freddyaboulton HF Staff commited on
Commit
acd94a2
·
verified ·
1 Parent(s): db44343

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. requirements.txt +2 -2
  2. run.ipynb +1 -1
  3. run.py +13 -10
requirements.txt CHANGED
@@ -1,5 +1,5 @@
1
- gradio-client @ git+https://github.com/gradio-app/gradio@327015b7dca90f17f174baee9f3c966a48fe4775#subdirectory=client/python
2
- https://gradio-pypi-previews.s3.amazonaws.com/327015b7dca90f17f174baee9f3c966a48fe4775/gradio-5.47.2-py3-none-any.whl
3
  plotly
4
  numpy
5
  pandas
 
1
+ gradio-client @ git+https://github.com/gradio-app/gradio@070463cf85f75f1a327a2c0daa6eea81467ad749#subdirectory=client/python
2
+ https://gradio-pypi-previews.s3.amazonaws.com/070463cf85f75f1a327a2c0daa6eea81467ad749/gradio-5.47.2-py3-none-any.whl
3
  plotly
4
  numpy
5
  pandas
run.ipynb CHANGED
@@ -1 +1 @@
1
- {"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: chatbot_core_components"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio plotly numpy pandas matplotlib "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('files')\n", "!wget -q -O files/Duck.glb https://github.com/gradio-app/gradio/raw/main/demo/chatbot_core_components/files/Duck.glb\n", "!wget -q -O files/audio.wav https://github.com/gradio-app/gradio/raw/main/demo/chatbot_core_components/files/audio.wav\n", "!wget -q -O files/avatar.png https://github.com/gradio-app/gradio/raw/main/demo/chatbot_core_components/files/avatar.png\n", "!wget -q -O files/sample.txt https://github.com/gradio-app/gradio/raw/main/demo/chatbot_core_components/files/sample.txt\n", "!wget -q -O files/world.mp4 https://github.com/gradio-app/gradio/raw/main/demo/chatbot_core_components/files/world.mp4"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["# type: ignore\n", "import gradio as gr\n", "import os\n", "import plotly.express as px # type: ignore\n", "import random\n", "\n", "# Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, video, & model3d). Plus shows support for streaming text.\n", "\n", "txt = \"\"\"\n", "Absolutely! The mycorrhizal network, often referred to as the \"Wood Wide Web,\" is a symbiotic association between fungi and the roots of most plant species. Here\u2019s a deeper dive into how it works and its implications:\n", "\n", "### How It Works\n", "\n", "1. **Symbiosis**: Mycorrhizal fungi attach to plant roots, extending far into the soil. The plant provides the fungi with carbohydrates produced via photosynthesis. In return, the fungi help the plant absorb water and essential nutrients like phosphorus and nitrogen from the soil.\n", "\n", "2. **Network Formation**: The fungal hyphae (thread-like structures) connect individual plants, creating an extensive underground network. This network can link many plants together, sometimes spanning entire forests.\n", "\n", "3. **Communication**: Trees and plants use this network to communicate and share resources. For example, a tree under attack by pests can send chemical signals through the mycorrhizal network to warn neighboring trees. These trees can then produce defensive chemicals to prepare for the impending threat.\n", "\n", "### Benefits and Functions\n", "\n", "1. **Resource Sharing**: The network allows for the redistribution of resources among plants. For instance, a large, established tree might share excess nutrients and water with smaller, younger trees, promoting overall forest health.\n", "\n", "2. **Defense Mechanism**: The ability to share information about pests and diseases enhances the resilience of plant communities. This early warning system helps plants activate their defenses before they are directly affected.\n", "\n", "3. **Support for Seedlings**: Young seedlings, which have limited root systems, benefit immensely from the mycorrhizal network. They receive nutrients and water from larger plants, increasing their chances of survival and growth.\n", "\n", "### Ecological Impact\n", "\n", "1. **Biodiversity**: The mycorrhizal network supports biodiversity by fostering a cooperative environment. Plants of different species can coexist and thrive because of the shared resources and information.\n", "\n", "2. **Forest Health**: The network enhances the overall health of forests. By enabling efficient nutrient cycling and supporting plant defenses, it contributes to the stability and longevity of forest ecosystems.\n", "\n", "3. **Climate Change Mitigation**: Healthy forests act as significant carbon sinks, absorbing carbon dioxide from the atmosphere. The mycorrhizal network plays a critical role in maintaining forest health and, consequently, in mitigating climate change.\n", "\n", "### Research and Discoveries\n", "\n", "1. **Suzanne Simard's Work**: Ecologist Suzanne Simard\u2019s research has been pivotal in uncovering the complexities of the mycorrhizal network. She demonstrated that trees of different species can share resources and that \"mother trees\" (large, older trees) play a crucial role in nurturing younger plants.\n", "\n", "2. **Implications for Conservation**: Understanding the mycorrhizal network has significant implications for conservation efforts. It highlights the importance of preserving not just individual trees but entire ecosystems, including the fungal networks that sustain them.\n", "\n", "### Practical Applications\n", "\n", "1. **Agriculture**: Farmers and horticulturists are exploring the use of mycorrhizal fungi to improve crop yields and soil health. By incorporating these fungi into agricultural practices, they can reduce the need for chemical fertilizers and enhance plant resilience.\n", "\n", "2. **Reforestation**: In reforestation projects, introducing mycorrhizal fungi can accelerate the recovery of degraded lands. The fungi help establish healthy plant communities, ensuring the success of newly planted trees.\n", "\n", "The \"Wood Wide Web\" exemplifies the intricate and often hidden connections that sustain life on Earth. It\u2019s a reminder of the profound interdependence within natural systems and the importance of preserving these delicate relationships.\n", "\"\"\"\n", "\n", "def random_plot():\n", " df = px.data.iris()\n", " fig = px.scatter(\n", " df,\n", " x=\"sepal_width\",\n", " y=\"sepal_length\",\n", " color=\"species\",\n", " size=\"petal_length\",\n", " hover_data=[\"petal_width\"],\n", " )\n", " return fig\n", "\n", "color_map = {\n", " \"harmful\": \"crimson\",\n", " \"neutral\": \"gray\",\n", " \"beneficial\": \"green\",\n", "}\n", "\n", "def html_src(harm_level):\n", " return f\"\"\"\n", "<div style=\"display: flex; gap: 5px;\">\n", " <div style=\"background-color: {color_map[harm_level]}; padding: 2px; border-radius: 5px;\">\n", " {harm_level}\n", " </div>\n", "</div>\n", "\"\"\"\n", "\n", "def print_like_dislike(x: gr.LikeData):\n", " print(x.index, x.value, x.liked)\n", "\n", "def random_bokeh_plot():\n", " from bokeh.models import ColumnDataSource, Whisker\n", " from bokeh.plotting import figure\n", " from bokeh.sampledata.autompg2 import autompg2 as df\n", " from bokeh.transform import factor_cmap, jitter\n", "\n", " classes = sorted(df[\"class\"].unique())\n", "\n", " p = figure(\n", " height=400,\n", " x_range=classes,\n", " background_fill_color=\"#efefef\",\n", " title=\"Car class vs HWY mpg with quintile ranges\",\n", " )\n", " p.xgrid.grid_line_color = None\n", "\n", " g = df.groupby(\"class\")\n", " upper = g.hwy.quantile(0.80)\n", " lower = g.hwy.quantile(0.20)\n", " source = ColumnDataSource(data=dict(base=classes, upper=upper, lower=lower))\n", "\n", " error = Whisker(\n", " base=\"base\",\n", " upper=\"upper\",\n", " lower=\"lower\",\n", " source=source,\n", " level=\"annotation\",\n", " line_width=2,\n", " )\n", " error.upper_head.size = 20\n", " error.lower_head.size = 20\n", " p.add_layout(error)\n", "\n", " p.circle(\n", " jitter(\"class\", 0.3, range=p.x_range),\n", " \"hwy\",\n", " source=df,\n", " alpha=0.5,\n", " size=13,\n", " line_color=\"white\",\n", " color=factor_cmap(\"class\", \"Light6\", classes),\n", " )\n", " return p\n", "\n", "def random_matplotlib_plot():\n", " import numpy as np\n", " import pandas as pd\n", " import matplotlib.pyplot as plt\n", "\n", " countries = [\"USA\", \"Canada\", \"Mexico\", \"UK\"]\n", " months = [\"January\", \"February\", \"March\", \"April\", \"May\"]\n", " m = months.index(\"January\")\n", " r = 3.2\n", " start_day = 30 * m\n", " final_day = 30 * (m + 1)\n", " x = np.arange(start_day, final_day + 1)\n", " pop_count = {\"USA\": 350, \"Canada\": 40, \"Mexico\": 300, \"UK\": 120}\n", " df = pd.DataFrame({\"day\": x})\n", " for country in countries:\n", " df[country] = x ** (r) * (pop_count[country] + 1)\n", "\n", " fig = plt.figure()\n", " plt.plot(df[\"day\"], df[countries].to_numpy())\n", " plt.title(\"Outbreak in \" + \"January\")\n", " plt.ylabel(\"Cases\")\n", " plt.xlabel(\"Days since Day 0\")\n", " plt.legend(countries)\n", " return fig\n", "\n", "def add_message(history, message):\n", " for x in message[\"files\"]:\n", " history.append({\"role\": \"user\", \"content\": {\"path\": x}})\n", " if message[\"text\"] is not None:\n", " history.append({\"role\": \"user\", \"content\": message[\"text\"]})\n", " return history, gr.MultimodalTextbox(value=None, interactive=False)\n", "\n", "def bot(history, response_type):\n", " msg = {\"role\": \"assistant\", \"content\": \"\"}\n", " if response_type == \"plot\":\n", " content = gr.Plot(random_plot())\n", " elif response_type == \"bokeh_plot\":\n", " content = gr.Plot(random_bokeh_plot())\n", " elif response_type == \"matplotlib_plot\":\n", " content = gr.Plot(random_matplotlib_plot())\n", " elif response_type == \"gallery\":\n", " content = gr.Gallery(\n", " [os.path.join(\"files\", \"avatar.png\"), os.path.join(\"files\", \"avatar.png\")]\n", " )\n", " elif response_type == \"dataframe\":\n", " content = gr.Dataframe(\n", " interactive=True,\n", " headers=[\"One\", \"Two\", \"Three\"],\n", " col_count=(3, \"fixed\"),\n", " row_count=(3, \"fixed\"),\n", " value=[[1, 2, 3], [4, 5, 6], [7, 8, 9]],\n", " label=\"Dataframe\",\n", " )\n", " elif response_type == \"image\":\n", " content = gr.Image(os.path.join(\"files\", \"avatar.png\"))\n", " elif response_type == \"video\":\n", " content = gr.Video(os.path.join(\"files\", \"world.mp4\"))\n", " elif response_type == \"audio\":\n", " content = gr.Audio(os.path.join(\"files\", \"audio.wav\"))\n", " elif response_type == \"audio_file\":\n", " content = {\"path\": os.path.join(\"files\", \"audio.wav\"), \"alt_text\": \"description\"}\n", " elif response_type == \"image_file\":\n", " content = {\"path\": os.path.join(\"files\", \"avatar.png\"), \"alt_text\": \"description\"}\n", " elif response_type == \"video_file\":\n", " content = {\"path\": os.path.join(\"files\", \"world.mp4\"), \"alt_text\": \"description\"}\n", " elif response_type == \"txt_file\":\n", " content = {\"path\": os.path.join(\"files\", \"sample.txt\"), \"alt_text\": \"description\"}\n", " elif response_type == \"model3d_file\":\n", " content = {\"path\": os.path.join(\"files\", \"Duck.glb\"), \"alt_text\": \"description\"}\n", " elif response_type == \"html\":\n", " content = gr.HTML(\n", " html_src(random.choice([\"harmful\", \"neutral\", \"beneficial\"]))\n", " )\n", " elif response_type == \"model3d\":\n", " content = gr.Model3D(os.path.join(\"files\", \"Duck.glb\"))\n", " else:\n", " content = txt\n", " msg[\"content\"] = content # type: ignore\n", " history.append(msg)\n", " return history\n", "\n", "fig = random_plot()\n", "\n", "with gr.Blocks(fill_height=True) as demo:\n", " chatbot = gr.Chatbot(\n", " elem_id=\"chatbot\",\n", " type=\"messages\",\n", " bubble_full_width=False,\n", " scale=1,\n", " show_copy_button=True,\n", " avatar_images=(\n", " None, # os.path.join(\"files\", \"avatar.png\"),\n", " os.path.join(\"files\", \"avatar.png\"),\n", " ),\n", " )\n", " response_type = gr.Radio(\n", " [\n", " \"audio_file\",\n", " \"image_file\",\n", " \"video_file\",\n", " \"txt_file\",\n", " \"model3d_file\",\n", " \"plot\",\n", " \"matplotlib_plot\",\n", " \"bokeh_plot\",\n", " \"image\",\n", " \"text\",\n", " \"gallery\",\n", " \"dataframe\",\n", " \"video\",\n", " \"audio\",\n", " \"html\",\n", " \"model3d\",\n", " ],\n", " value=\"text\",\n", " label=\"Response Type\",\n", " )\n", "\n", " chat_input = gr.MultimodalTextbox(\n", " interactive=True,\n", " placeholder=\"Enter message or upload file...\",\n", " show_label=False,\n", " )\n", "\n", " chat_msg = chat_input.submit(\n", " add_message, [chatbot, chat_input], [chatbot, chat_input]\n", " )\n", " bot_msg = chat_msg.then(\n", " bot, [chatbot, response_type], chatbot, api_name=\"bot_response\"\n", " )\n", " bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input])\n", "\n", " chatbot.like(print_like_dislike, None, None)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
 
1
+ {"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: chatbot_core_components"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio plotly numpy pandas matplotlib "]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["# Downloading files from the demo repo\n", "import os\n", "os.mkdir('files')\n", "!wget -q -O files/sample.txt https://github.com/gradio-app/gradio/raw/main/demo/chatbot_core_components/files/sample.txt"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["# type: ignore\n", "import gradio as gr\n", "import os\n", "import plotly.express as px # type: ignore\n", "import random\n", "\n", "# Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, video, & model3d). Plus shows support for streaming text.\n", "\n", "txt = \"\"\"\n", "Absolutely! The mycorrhizal network, often referred to as the \"Wood Wide Web,\" is a symbiotic association between fungi and the roots of most plant species. Here\u2019s a deeper dive into how it works and its implications:\n", "\n", "### How It Works\n", "\n", "1. **Symbiosis**: Mycorrhizal fungi attach to plant roots, extending far into the soil. The plant provides the fungi with carbohydrates produced via photosynthesis. In return, the fungi help the plant absorb water and essential nutrients like phosphorus and nitrogen from the soil.\n", "\n", "2. **Network Formation**: The fungal hyphae (thread-like structures) connect individual plants, creating an extensive underground network. This network can link many plants together, sometimes spanning entire forests.\n", "\n", "3. **Communication**: Trees and plants use this network to communicate and share resources. For example, a tree under attack by pests can send chemical signals through the mycorrhizal network to warn neighboring trees. These trees can then produce defensive chemicals to prepare for the impending threat.\n", "\n", "### Benefits and Functions\n", "\n", "1. **Resource Sharing**: The network allows for the redistribution of resources among plants. For instance, a large, established tree might share excess nutrients and water with smaller, younger trees, promoting overall forest health.\n", "\n", "2. **Defense Mechanism**: The ability to share information about pests and diseases enhances the resilience of plant communities. This early warning system helps plants activate their defenses before they are directly affected.\n", "\n", "3. **Support for Seedlings**: Young seedlings, which have limited root systems, benefit immensely from the mycorrhizal network. They receive nutrients and water from larger plants, increasing their chances of survival and growth.\n", "\n", "### Ecological Impact\n", "\n", "1. **Biodiversity**: The mycorrhizal network supports biodiversity by fostering a cooperative environment. Plants of different species can coexist and thrive because of the shared resources and information.\n", "\n", "2. **Forest Health**: The network enhances the overall health of forests. By enabling efficient nutrient cycling and supporting plant defenses, it contributes to the stability and longevity of forest ecosystems.\n", "\n", "3. **Climate Change Mitigation**: Healthy forests act as significant carbon sinks, absorbing carbon dioxide from the atmosphere. The mycorrhizal network plays a critical role in maintaining forest health and, consequently, in mitigating climate change.\n", "\n", "### Research and Discoveries\n", "\n", "1. **Suzanne Simard's Work**: Ecologist Suzanne Simard\u2019s research has been pivotal in uncovering the complexities of the mycorrhizal network. She demonstrated that trees of different species can share resources and that \"mother trees\" (large, older trees) play a crucial role in nurturing younger plants.\n", "\n", "2. **Implications for Conservation**: Understanding the mycorrhizal network has significant implications for conservation efforts. It highlights the importance of preserving not just individual trees but entire ecosystems, including the fungal networks that sustain them.\n", "\n", "### Practical Applications\n", "\n", "1. **Agriculture**: Farmers and horticulturists are exploring the use of mycorrhizal fungi to improve crop yields and soil health. By incorporating these fungi into agricultural practices, they can reduce the need for chemical fertilizers and enhance plant resilience.\n", "\n", "2. **Reforestation**: In reforestation projects, introducing mycorrhizal fungi can accelerate the recovery of degraded lands. The fungi help establish healthy plant communities, ensuring the success of newly planted trees.\n", "\n", "The \"Wood Wide Web\" exemplifies the intricate and often hidden connections that sustain life on Earth. It\u2019s a reminder of the profound interdependence within natural systems and the importance of preserving these delicate relationships.\n", "\"\"\"\n", "\n", "def random_plot():\n", " df = px.data.iris()\n", " fig = px.scatter(\n", " df,\n", " x=\"sepal_width\",\n", " y=\"sepal_length\",\n", " color=\"species\",\n", " size=\"petal_length\",\n", " hover_data=[\"petal_width\"],\n", " )\n", " return fig\n", "\n", "color_map = {\n", " \"harmful\": \"crimson\",\n", " \"neutral\": \"gray\",\n", " \"beneficial\": \"green\",\n", "}\n", "\n", "def html_src(harm_level):\n", " return f\"\"\"\n", "<div style=\"display: flex; gap: 5px;\">\n", " <div style=\"background-color: {color_map[harm_level]}; padding: 2px; border-radius: 5px;\">\n", " {harm_level}\n", " </div>\n", "</div>\n", "\"\"\"\n", "\n", "def print_like_dislike(x: gr.LikeData):\n", " print(x.index, x.value, x.liked)\n", "\n", "def random_bokeh_plot():\n", " from bokeh.models import ColumnDataSource, Whisker\n", " from bokeh.plotting import figure\n", " from bokeh.sampledata.autompg2 import autompg2 as df\n", " from bokeh.transform import factor_cmap, jitter\n", "\n", " classes = sorted(df[\"class\"].unique())\n", "\n", " p = figure(\n", " height=400,\n", " x_range=classes,\n", " background_fill_color=\"#efefef\",\n", " title=\"Car class vs HWY mpg with quintile ranges\",\n", " )\n", " p.xgrid.grid_line_color = None\n", "\n", " g = df.groupby(\"class\")\n", " upper = g.hwy.quantile(0.80)\n", " lower = g.hwy.quantile(0.20)\n", " source = ColumnDataSource(data=dict(base=classes, upper=upper, lower=lower))\n", "\n", " error = Whisker(\n", " base=\"base\",\n", " upper=\"upper\",\n", " lower=\"lower\",\n", " source=source,\n", " level=\"annotation\",\n", " line_width=2,\n", " )\n", " error.upper_head.size = 20\n", " error.lower_head.size = 20\n", " p.add_layout(error)\n", "\n", " p.circle(\n", " jitter(\"class\", 0.3, range=p.x_range),\n", " \"hwy\",\n", " source=df,\n", " alpha=0.5,\n", " size=13,\n", " line_color=\"white\",\n", " color=factor_cmap(\"class\", \"Light6\", classes),\n", " )\n", " return p\n", "\n", "# get_file(), get_image(), get_model3d(), get_video() return file paths to sample media included with Gradio\n", "from gradio.media import get_file, get_image, get_model3d, get_video\n", "\n", "def random_matplotlib_plot():\n", " import numpy as np\n", " import pandas as pd\n", " import matplotlib.pyplot as plt\n", "\n", " countries = [\"USA\", \"Canada\", \"Mexico\", \"UK\"]\n", " months = [\"January\", \"February\", \"March\", \"April\", \"May\"]\n", " m = months.index(\"January\")\n", " r = 3.2\n", " start_day = 30 * m\n", " final_day = 30 * (m + 1)\n", " x = np.arange(start_day, final_day + 1)\n", " pop_count = {\"USA\": 350, \"Canada\": 40, \"Mexico\": 300, \"UK\": 120}\n", " df = pd.DataFrame({\"day\": x})\n", " for country in countries:\n", " df[country] = x ** (r) * (pop_count[country] + 1)\n", "\n", " fig = plt.figure()\n", " plt.plot(df[\"day\"], df[countries].to_numpy())\n", " plt.title(\"Outbreak in \" + \"January\")\n", " plt.ylabel(\"Cases\")\n", " plt.xlabel(\"Days since Day 0\")\n", " plt.legend(countries)\n", " return fig\n", "\n", "def add_message(history, message):\n", " for x in message[\"files\"]:\n", " history.append({\"role\": \"user\", \"content\": {\"path\": x}})\n", " if message[\"text\"] is not None:\n", " history.append({\"role\": \"user\", \"content\": message[\"text\"]})\n", " return history, gr.MultimodalTextbox(value=None, interactive=False)\n", "\n", "def bot(history, response_type):\n", " msg = {\"role\": \"assistant\", \"content\": \"\"}\n", " if response_type == \"plot\":\n", " content = gr.Plot(random_plot())\n", " elif response_type == \"bokeh_plot\":\n", " content = gr.Plot(random_bokeh_plot())\n", " elif response_type == \"matplotlib_plot\":\n", " content = gr.Plot(random_matplotlib_plot())\n", " elif response_type == \"gallery\":\n", " content = gr.Gallery(\n", " [get_image(\"avatar.png\"), get_image(\"avatar.png\")]\n", " )\n", " elif response_type == \"dataframe\":\n", " content = gr.Dataframe(\n", " interactive=True,\n", " headers=[\"One\", \"Two\", \"Three\"],\n", " col_count=(3, \"fixed\"),\n", " row_count=(3, \"fixed\"),\n", " value=[[1, 2, 3], [4, 5, 6], [7, 8, 9]],\n", " label=\"Dataframe\",\n", " )\n", " elif response_type == \"image\":\n", " content = gr.Image(get_image(\"avatar.png\"))\n", " elif response_type == \"video\":\n", " content = gr.Video(get_video(\"world.mp4\"))\n", " elif response_type == \"audio\":\n", " content = gr.Audio(os.path.join(\"files\", \"audio.wav\"))\n", " elif response_type == \"audio_file\":\n", " content = {\"path\": os.path.join(\"files\", \"audio.wav\"), \"alt_text\": \"description\"}\n", " elif response_type == \"image_file\":\n", " content = {\"path\": get_image(\"avatar.png\"), \"alt_text\": \"description\"}\n", " elif response_type == \"video_file\":\n", " content = {\"path\": get_video(\"world.mp4\"), \"alt_text\": \"description\"}\n", " elif response_type == \"txt_file\":\n", " content = {\"path\": get_file(\"sample.txt\"), \"alt_text\": \"description\"}\n", " elif response_type == \"model3d_file\":\n", " content = {\"path\": get_model3d(\"Duck.glb\"), \"alt_text\": \"description\"}\n", " elif response_type == \"html\":\n", " content = gr.HTML(\n", " html_src(random.choice([\"harmful\", \"neutral\", \"beneficial\"]))\n", " )\n", " elif response_type == \"model3d\":\n", " content = gr.Model3D(get_model3d(\"Duck.glb\"))\n", " else:\n", " content = txt\n", " msg[\"content\"] = content # type: ignore\n", " history.append(msg)\n", " return history\n", "\n", "fig = random_plot()\n", "\n", "with gr.Blocks(fill_height=True) as demo:\n", " chatbot = gr.Chatbot(\n", " elem_id=\"chatbot\",\n", " type=\"messages\",\n", " bubble_full_width=False,\n", " scale=1,\n", " show_copy_button=True,\n", " avatar_images=(\n", " None,\n", " get_image(\"avatar.png\"),\n", " ),\n", " )\n", " response_type = gr.Radio(\n", " [\n", " \"audio_file\",\n", " \"image_file\",\n", " \"video_file\",\n", " \"txt_file\",\n", " \"model3d_file\",\n", " \"plot\",\n", " \"matplotlib_plot\",\n", " \"bokeh_plot\",\n", " \"image\",\n", " \"text\",\n", " \"gallery\",\n", " \"dataframe\",\n", " \"video\",\n", " \"audio\",\n", " \"html\",\n", " \"model3d\",\n", " ],\n", " value=\"text\",\n", " label=\"Response Type\",\n", " )\n", "\n", " chat_input = gr.MultimodalTextbox(\n", " interactive=True,\n", " placeholder=\"Enter message or upload file...\",\n", " show_label=False,\n", " )\n", "\n", " chat_msg = chat_input.submit(\n", " add_message, [chatbot, chat_input], [chatbot, chat_input]\n", " )\n", " bot_msg = chat_msg.then(\n", " bot, [chatbot, response_type], chatbot, api_name=\"bot_response\"\n", " )\n", " bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input])\n", "\n", " chatbot.like(print_like_dislike, None, None)\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
run.py CHANGED
@@ -122,6 +122,9 @@ def random_bokeh_plot():
122
  )
123
  return p
124
 
 
 
 
125
  def random_matplotlib_plot():
126
  import numpy as np
127
  import pandas as pd
@@ -164,7 +167,7 @@ def bot(history, response_type):
164
  content = gr.Plot(random_matplotlib_plot())
165
  elif response_type == "gallery":
166
  content = gr.Gallery(
167
- [os.path.join("files", "avatar.png"), os.path.join("files", "avatar.png")]
168
  )
169
  elif response_type == "dataframe":
170
  content = gr.Dataframe(
@@ -176,27 +179,27 @@ def bot(history, response_type):
176
  label="Dataframe",
177
  )
178
  elif response_type == "image":
179
- content = gr.Image(os.path.join("files", "avatar.png"))
180
  elif response_type == "video":
181
- content = gr.Video(os.path.join("files", "world.mp4"))
182
  elif response_type == "audio":
183
  content = gr.Audio(os.path.join("files", "audio.wav"))
184
  elif response_type == "audio_file":
185
  content = {"path": os.path.join("files", "audio.wav"), "alt_text": "description"}
186
  elif response_type == "image_file":
187
- content = {"path": os.path.join("files", "avatar.png"), "alt_text": "description"}
188
  elif response_type == "video_file":
189
- content = {"path": os.path.join("files", "world.mp4"), "alt_text": "description"}
190
  elif response_type == "txt_file":
191
- content = {"path": os.path.join("files", "sample.txt"), "alt_text": "description"}
192
  elif response_type == "model3d_file":
193
- content = {"path": os.path.join("files", "Duck.glb"), "alt_text": "description"}
194
  elif response_type == "html":
195
  content = gr.HTML(
196
  html_src(random.choice(["harmful", "neutral", "beneficial"]))
197
  )
198
  elif response_type == "model3d":
199
- content = gr.Model3D(os.path.join("files", "Duck.glb"))
200
  else:
201
  content = txt
202
  msg["content"] = content # type: ignore
@@ -213,8 +216,8 @@ with gr.Blocks(fill_height=True) as demo:
213
  scale=1,
214
  show_copy_button=True,
215
  avatar_images=(
216
- None, # os.path.join("files", "avatar.png"),
217
- os.path.join("files", "avatar.png"),
218
  ),
219
  )
220
  response_type = gr.Radio(
 
122
  )
123
  return p
124
 
125
+ # get_file(), get_image(), get_model3d(), get_video() return file paths to sample media included with Gradio
126
+ from gradio.media import get_file, get_image, get_model3d, get_video
127
+
128
  def random_matplotlib_plot():
129
  import numpy as np
130
  import pandas as pd
 
167
  content = gr.Plot(random_matplotlib_plot())
168
  elif response_type == "gallery":
169
  content = gr.Gallery(
170
+ [get_image("avatar.png"), get_image("avatar.png")]
171
  )
172
  elif response_type == "dataframe":
173
  content = gr.Dataframe(
 
179
  label="Dataframe",
180
  )
181
  elif response_type == "image":
182
+ content = gr.Image(get_image("avatar.png"))
183
  elif response_type == "video":
184
+ content = gr.Video(get_video("world.mp4"))
185
  elif response_type == "audio":
186
  content = gr.Audio(os.path.join("files", "audio.wav"))
187
  elif response_type == "audio_file":
188
  content = {"path": os.path.join("files", "audio.wav"), "alt_text": "description"}
189
  elif response_type == "image_file":
190
+ content = {"path": get_image("avatar.png"), "alt_text": "description"}
191
  elif response_type == "video_file":
192
+ content = {"path": get_video("world.mp4"), "alt_text": "description"}
193
  elif response_type == "txt_file":
194
+ content = {"path": get_file("sample.txt"), "alt_text": "description"}
195
  elif response_type == "model3d_file":
196
+ content = {"path": get_model3d("Duck.glb"), "alt_text": "description"}
197
  elif response_type == "html":
198
  content = gr.HTML(
199
  html_src(random.choice(["harmful", "neutral", "beneficial"]))
200
  )
201
  elif response_type == "model3d":
202
+ content = gr.Model3D(get_model3d("Duck.glb"))
203
  else:
204
  content = txt
205
  msg["content"] = content # type: ignore
 
216
  scale=1,
217
  show_copy_button=True,
218
  avatar_images=(
219
+ None,
220
+ get_image("avatar.png"),
221
  ),
222
  )
223
  response_type = gr.Radio(