Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gradio components in gr.Chatbot() #8131

Merged
merged 79 commits into from
Jun 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
79 commits
Select commit Hold shift + click to select a range
803a059
chatbot components
dawoodkhan82 Apr 24, 2024
eaf3737
demoi
dawoodkhan82 Apr 29, 2024
0e161e7
merge
dawoodkhan82 Apr 29, 2024
539ff05
add changeset
gradio-pr-bot Apr 29, 2024
fb2b107
preprocess fix
dawoodkhan82 Apr 29, 2024
54af1b5
Merge branch 'main' into chatbot-components
dawoodkhan82 Apr 29, 2024
d1b9604
add changeset
gradio-pr-bot Apr 29, 2024
838965f
Make guide for tailwind more verbose (#8152)
duerrsimon Apr 30, 2024
d3a11ca
Lite wheel optimization (#7855)
whitphx Apr 30, 2024
80b868e
Add ETag to `/custom_component` route to control browser caching (#8170)
freddyaboulton Apr 30, 2024
ce4d348
Implement JS Client tests (#8109)
hannahblair Apr 30, 2024
e4bd0c4
Remove hatch installation in js/app/package.json which is no longer n…
whitphx Apr 30, 2024
e94d7da
Update test-functional.yml - Fix vulnerability code injection (#8145)
h2oa May 1, 2024
9d8ead8
rework upload to be a class method + pass client into each component …
pngwn May 1, 2024
7d1c87b
chore(deps): update pnpm to v9 (#8123)
renovate[bot] May 1, 2024
1b3d2b6
Use workspace version for code in _website (#8189)
aliabd May 1, 2024
1f0483f
Pass Error status in /dev/reload stream (#8106)
freddyaboulton May 1, 2024
1b1ed31
Convert sse calls in client from async to sync (#8182)
abidlabs May 2, 2024
0430f79
run python reload only if python file changed (#8194)
jameszhou02 May 2, 2024
8e0d09d
fix: handling SIGINT correctly in reload.py, single entrance of block…
Tiger3018 May 2, 2024
1d7fc6f
Add eventsource polyfill for Node.js and browser environments (#8118)
hannahblair May 2, 2024
c5277a3
Ensure connectivity to private HF spaces with SSE protocol (#8181)
hannahblair May 2, 2024
6cac294
Support custom components in gr.load (#8200)
freddyaboulton May 2, 2024
6b102f8
Refactor analytics to not use api.gradio.app (#8180)
freddyaboulton May 3, 2024
7d1a125
Specify the fastapi version on Lite to avoid ujson installation which…
whitphx May 3, 2024
9533ea6
Set the show_api flag on Lite (#8205)
whitphx May 3, 2024
5678375
Extend Interface.from_pipeline() to support Transformers.js.py pipeli…
whitphx May 3, 2024
078df9c
merge
dawoodkhan82 May 6, 2024
7e65963
allow the canvas size to be set on the `ImageEditor` (#8127)
pngwn May 3, 2024
70783cf
Rename `eventSource_Factory` and `fetch_implementation` (#8209)
hannahblair May 3, 2024
4183dd8
remove redundant event source logic (#8211)
hannahblair May 3, 2024
c96ef0d
Only connect to heartbeat if needed (#8169)
freddyaboulton May 3, 2024
1b2fa59
chore: update versions (#8172)
pngwn May 3, 2024
68c70df
merge
dawoodkhan82 May 9, 2024
190edf7
fixes
dawoodkhan82 May 9, 2024
2b4c079
type fixes
dawoodkhan82 May 12, 2024
1a9318d
Merge branch 'main' into chatbot-components
dawoodkhan82 May 12, 2024
ba056cb
type fixes
dawoodkhan82 May 12, 2024
c3ba20a
Merge branch 'main' into chatbot-components
dawoodkhan82 May 13, 2024
5955494
notebook fix
dawoodkhan82 May 13, 2024
daeb642
type ignore
dawoodkhan82 May 13, 2024
2fc0ba9
data object model
dawoodkhan82 May 15, 2024
d179f7e
Merge branch 'main' into chatbot-components
dawoodkhan82 May 15, 2024
649c566
remove component in tuple
dawoodkhan82 May 15, 2024
42144cb
more fixes
dawoodkhan82 May 16, 2024
688e576
Merge branch 'main' into chatbot-components
dawoodkhan82 May 16, 2024
a7ca154
Merge branch 'main' into chatbot-components
dawoodkhan82 May 19, 2024
411e736
extend components
dawoodkhan82 May 22, 2024
5f3321b
merge
dawoodkhan82 May 23, 2024
80a3324
remove test var
dawoodkhan82 May 24, 2024
61ae7c4
extend to all components backend
dawoodkhan82 May 29, 2024
c0ed798
Merge branch 'main' into chatbot-components
dawoodkhan82 May 29, 2024
acc78b9
remove loading data models
dawoodkhan82 May 29, 2024
89540fb
merge
dawoodkhan82 Jun 4, 2024
620e7d9
conflict fix
dawoodkhan82 Jun 4, 2024
6ccc896
test and type fixes
dawoodkhan82 Jun 4, 2024
f8a1b2b
Merge branch 'main' into chatbot-components
dawoodkhan82 Jun 4, 2024
2ef7bd9
playwright test
dawoodkhan82 Jun 4, 2024
37bddec
PR fixes
dawoodkhan82 Jun 6, 2024
71d3d40
Merge branch 'main' into chatbot-components
dawoodkhan82 Jun 6, 2024
3433694
Merge branch 'main' into chatbot-components
freddyaboulton Jun 10, 2024
82220e2
final changes
freddyaboulton Jun 10, 2024
a713691
Merge branch 'main' into chatbot-components
freddyaboulton Jun 10, 2024
825ee2b
Add pltly for 2e2 test
freddyaboulton Jun 10, 2024
60dd746
pass loader to Gradio helper class
pngwn Jun 12, 2024
448dad1
fix things
pngwn Jun 12, 2024
95ef23a
add changeset
gradio-pr-bot Jun 12, 2024
af62d2c
checks
pngwn Jun 12, 2024
e5e7e7b
Merge branch 'main' into chatbot-components
pngwn Jun 12, 2024
247f1e8
more fixy
pngwn Jun 12, 2024
57962c8
more fixy
pngwn Jun 12, 2024
e3075d3
more fixy
pngwn Jun 12, 2024
bb76e5e
guess what? more fixy
pngwn Jun 12, 2024
d8e44fc
fix storybook
pngwn Jun 13, 2024
e83e688
add changeset
gradio-pr-bot Jun 13, 2024
8cb6a3d
formatting
pngwn Jun 13, 2024
95fd6b0
timeout
pngwn Jun 13, 2024
ea43e95
Merge branch 'main' into chatbot-components
pngwn Jun 14, 2024
f4282fb
fixyfixfix
pngwn Jun 14, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions .changeset/bitter-goats-chew.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
"@gradio/app": minor
"@gradio/audio": minor
"@gradio/chatbot": minor
"@gradio/gallery": minor
"@gradio/image": minor
"@gradio/multimodaltextbox": minor
"@gradio/plot": minor
"@gradio/simpleimage": minor
"@gradio/storybook": minor
"@gradio/utils": minor
"@gradio/video": minor
"gradio": minor
---

feat:Gradio components in `gr.Chatbot()`
5 changes: 4 additions & 1 deletion .config/basevite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,10 @@ export default defineConfig(({ mode }) => {
build: {
sourcemap: false,
target: "esnext",
minify: production
minify: production,
rollupOptions: {
external: ["virtual:component-loader"]
}
},
define: {
BUILD_MODE: production ? JSON.stringify("prod") : JSON.stringify("dev"),
Expand Down
6 changes: 3 additions & 3 deletions .config/playwright.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const base = defineConfig({
},
expect: { timeout: 15000 },
timeout: 30000,
testMatch: /.*.spec.ts/,
testMatch: /.*\.spec\.ts/,
testDir: "..",
workers: process.env.CI ? 1 : undefined,
retries: 3
Expand All @@ -37,13 +37,13 @@ const lite = defineConfig(base, {
},
testMatch: [
"**/file_component_events.spec.ts",
"**/chatbot_multimodal.spec.ts",
"**/kitchen_sink.spec.ts",
"**/gallery_component_events.spec.ts",
"**/image_remote_url.spec.ts" // To detect the bugs on Lite fixed in https://github.com/gradio-app/gradio/pull/8011 and https://github.com/gradio-app/gradio/pull/8026
],
workers: 1,
retries: 3
retries: 3,
timeout: 60000
});

lite.projects = undefined; // Explicitly unset this field due to https://github.com/microsoft/playwright/issues/28795
Expand Down
Binary file added demo/chatbot_core_components/files/audio.wav
Binary file not shown.
Binary file added demo/chatbot_core_components/files/avatar.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions demo/chatbot_core_components/files/sample.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
hello friends
Binary file added demo/chatbot_core_components/files/world.mp4
Binary file not shown.
1 change: 1 addition & 0 deletions demo/chatbot_core_components/run.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +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 "]}, {"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/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": ["import gradio as gr\n", "import os\n", "import plotly.express as px\n", "\n", "# Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text.\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", "\n", "def print_like_dislike(x: gr.LikeData):\n", " print(x.index, x.value, x.liked)\n", "\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, factor_mark\n", "\n", " classes = list(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", "\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", "\n", "def add_message(history, message):\n", " for x in message[\"files\"]:\n", " history.append(((x,), None))\n", " if message[\"text\"] is not None:\n", " history.append((message[\"text\"], None))\n", " return history, gr.MultimodalTextbox(value=None, interactive=False)\n", "\n", "\n", "def bot(history, response_type):\n", " if response_type == \"plot\":\n", " history[-1][1] = gr.Plot(random_plot())\n", " elif response_type == \"bokeh_plot\":\n", " history[-1][1] = gr.Plot(random_bokeh_plot())\n", " elif response_type == \"matplotlib_plot\":\n", " history[-1][1] = gr.Plot(random_matplotlib_plot())\n", " elif response_type == \"gallery\":\n", " history[-1][1] = gr.Gallery(\n", " [os.path.join(\"files\", \"avatar.png\"), os.path.join(\"files\", \"avatar.png\")]\n", " )\n", " elif response_type == \"image\":\n", " history[-1][1] = gr.Image(os.path.join(\"files\", \"avatar.png\"))\n", " elif response_type == \"video\":\n", " history[-1][1] = gr.Video(os.path.join(\"files\", \"world.mp4\"))\n", " elif response_type == \"audio\":\n", " history[-1][1] = gr.Audio(os.path.join(\"files\", \"audio.wav\"))\n", " elif response_type == \"audio_file\":\n", " history[-1][1] = (os.path.join(\"files\", \"audio.wav\"), \"description\")\n", " elif response_type == \"image_file\":\n", " history[-1][1] = (os.path.join(\"files\", \"avatar.png\"), \"description\")\n", " elif response_type == \"video_file\":\n", " history[-1][1] = (os.path.join(\"files\", \"world.mp4\"), \"description\")\n", " elif response_type == \"txt_file\":\n", " history[-1][1] = (os.path.join(\"files\", \"sample.txt\"), \"description\")\n", " else:\n", " history[-1][1] = \"Cool!\"\n", " return history\n", "\n", "\n", "fig = random_plot()\n", "\n", "with gr.Blocks(fill_height=True) as demo:\n", " chatbot = gr.Chatbot(\n", " elem_id=\"chatbot\",\n", " bubble_full_width=False,\n", " scale=1,\n", " )\n", " response_type = gr.Radio(\n", " [\n", " \"audio_file\",\n", " \"image_file\",\n", " \"video_file\",\n", " \"txt_file\",\n", " \"plot\",\n", " \"matplotlib_plot\",\n", " \"bokeh_plot\",\n", " \"image\",\n", " \"text\",\n", " \"gallery\",\n", " \"video\",\n", " \"audio\",\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", "demo.queue()\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
179 changes: 179 additions & 0 deletions demo/chatbot_core_components/run.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
import gradio as gr
import os
import plotly.express as px

# Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text.


def random_plot():
df = px.data.iris()
fig = px.scatter(
df,
x="sepal_width",
y="sepal_length",
color="species",
size="petal_length",
hover_data=["petal_width"],
)
return fig


def print_like_dislike(x: gr.LikeData):
print(x.index, x.value, x.liked)


def random_bokeh_plot():
from bokeh.models import ColumnDataSource, Whisker
from bokeh.plotting import figure
from bokeh.sampledata.autompg2 import autompg2 as df
from bokeh.transform import factor_cmap, jitter, factor_mark

classes = list(sorted(df["class"].unique()))

p = figure(
height=400,
x_range=classes,
background_fill_color="#efefef",
title="Car class vs HWY mpg with quintile ranges",
)
p.xgrid.grid_line_color = None

g = df.groupby("class")
upper = g.hwy.quantile(0.80)
lower = g.hwy.quantile(0.20)
source = ColumnDataSource(data=dict(base=classes, upper=upper, lower=lower))

error = Whisker(
base="base",
upper="upper",
lower="lower",
source=source,
level="annotation",
line_width=2,
)
error.upper_head.size = 20
error.lower_head.size = 20
p.add_layout(error)

p.circle(
jitter("class", 0.3, range=p.x_range),
"hwy",
source=df,
alpha=0.5,
size=13,
line_color="white",
color=factor_cmap("class", "Light6", classes),
)
return p


def random_matplotlib_plot():
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

countries = ["USA", "Canada", "Mexico", "UK"]
months = ["January", "February", "March", "April", "May"]
m = months.index("January")
r = 3.2
start_day = 30 * m
final_day = 30 * (m + 1)
x = np.arange(start_day, final_day + 1)
pop_count = {"USA": 350, "Canada": 40, "Mexico": 300, "UK": 120}
df = pd.DataFrame({"day": x})
for country in countries:
df[country] = x ** (r) * (pop_count[country] + 1)

fig = plt.figure()
plt.plot(df["day"], df[countries].to_numpy())
plt.title("Outbreak in " + "January")
plt.ylabel("Cases")
plt.xlabel("Days since Day 0")
plt.legend(countries)
return fig


def add_message(history, message):
for x in message["files"]:
history.append(((x,), None))
if message["text"] is not None:
history.append((message["text"], None))
return history, gr.MultimodalTextbox(value=None, interactive=False)


def bot(history, response_type):
if response_type == "plot":
history[-1][1] = gr.Plot(random_plot())
elif response_type == "bokeh_plot":
history[-1][1] = gr.Plot(random_bokeh_plot())
elif response_type == "matplotlib_plot":
history[-1][1] = gr.Plot(random_matplotlib_plot())
elif response_type == "gallery":
history[-1][1] = gr.Gallery(
[os.path.join("files", "avatar.png"), os.path.join("files", "avatar.png")]
)
elif response_type == "image":
history[-1][1] = gr.Image(os.path.join("files", "avatar.png"))
elif response_type == "video":
history[-1][1] = gr.Video(os.path.join("files", "world.mp4"))
elif response_type == "audio":
history[-1][1] = gr.Audio(os.path.join("files", "audio.wav"))
elif response_type == "audio_file":
history[-1][1] = (os.path.join("files", "audio.wav"), "description")
elif response_type == "image_file":
history[-1][1] = (os.path.join("files", "avatar.png"), "description")
elif response_type == "video_file":
history[-1][1] = (os.path.join("files", "world.mp4"), "description")
elif response_type == "txt_file":
history[-1][1] = (os.path.join("files", "sample.txt"), "description")
else:
history[-1][1] = "Cool!"
return history


fig = random_plot()

with gr.Blocks(fill_height=True) as demo:
chatbot = gr.Chatbot(
elem_id="chatbot",
bubble_full_width=False,
scale=1,
)
response_type = gr.Radio(
[
"audio_file",
"image_file",
"video_file",
"txt_file",
"plot",
"matplotlib_plot",
"bokeh_plot",
"image",
"text",
"gallery",
"video",
"audio",
],
value="text",
label="Response Type",
)

chat_input = gr.MultimodalTextbox(
interactive=True,
placeholder="Enter message or upload file...",
show_label=False,
)

chat_msg = chat_input.submit(
add_message, [chatbot, chat_input], [chatbot, chat_input]
)
bot_msg = chat_msg.then(
bot, [chatbot, response_type], chatbot, api_name="bot_response"
)
bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input])

chatbot.like(print_like_dislike, None, None)

demo.queue()
if __name__ == "__main__":
demo.launch()
Binary file removed demo/chatbot_multimodal/files/lion.jpg
Binary file not shown.
1 change: 1 addition & 0 deletions demo/chatbot_multimodal/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
plotly
2 changes: 1 addition & 1 deletion demo/chatbot_multimodal/run.ipynb
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: chatbot_multimodal"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio "]}, {"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/avatar.png https://github.com/gradio-app/gradio/raw/main/demo/chatbot_multimodal/files/avatar.png\n", "!wget -q -O files/lion.jpg https://github.com/gradio-app/gradio/raw/main/demo/chatbot_multimodal/files/lion.jpg"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "import time\n", "\n", "# Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text.\n", "\n", "\n", "def print_like_dislike(x: gr.LikeData):\n", " print(x.index, x.value, x.liked)\n", "\n", "def add_message(history, message):\n", " for x in message[\"files\"]:\n", " history.append(((x,), None))\n", " if message[\"text\"] is not None:\n", " history.append((message[\"text\"], None))\n", " return history, gr.MultimodalTextbox(value=None, interactive=False)\n", "\n", "def bot(history):\n", " response = \"**That's cool!**\"\n", " history[-1][1] = \"\"\n", " for character in response:\n", " history[-1][1] += character\n", " time.sleep(0.05)\n", " yield history\n", "\n", "with gr.Blocks() as demo:\n", " chatbot = gr.Chatbot(\n", " [],\n", " elem_id=\"chatbot\",\n", " bubble_full_width=False\n", " )\n", "\n", " chat_input = gr.MultimodalTextbox(interactive=True, file_types=[\"image\"], placeholder=\"Enter message or upload file...\", show_label=False)\n", "\n", " chat_msg = chat_input.submit(add_message, [chatbot, chat_input], [chatbot, chat_input])\n", " bot_msg = chat_msg.then(bot, chatbot, chatbot, api_name=\"bot_response\")\n", " bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input])\n", "\n", " chatbot.like(print_like_dislike, None, None)\n", "\n", "demo.queue()\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: chatbot_multimodal"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio plotly"]}, {"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/avatar.png https://github.com/gradio-app/gradio/raw/main/demo/chatbot_multimodal/files/avatar.png"]}, {"cell_type": "code", "execution_count": null, "id": "44380577570523278879349135829904343037", "metadata": {}, "outputs": [], "source": ["import gradio as gr\n", "import os\n", "import plotly.express as px\n", "\n", "# Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text.\n", "\n", "def random_plot():\n", " df = px.data.iris()\n", " fig = px.scatter(df, x=\"sepal_width\", y=\"sepal_length\", color=\"species\",\n", " size='petal_length', hover_data=['petal_width'])\n", " return fig\n", "\n", "def print_like_dislike(x: gr.LikeData):\n", " print(x.index, x.value, x.liked)\n", "\n", "def add_message(history, message):\n", " for x in message[\"files\"]:\n", " history.append(((x,), None))\n", " if message[\"text\"] is not None:\n", " history.append((message[\"text\"], None))\n", " return history, gr.MultimodalTextbox(value=None, interactive=False)\n", "\n", "def bot(history):\n", " history[-1][1] = \"Cool!\"\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", " bubble_full_width=False,\n", " scale=1,\n", " )\n", "\n", " chat_input = gr.MultimodalTextbox(interactive=True, placeholder=\"Enter message or upload file...\", show_label=False)\n", "\n", " chat_msg = chat_input.submit(add_message, [chatbot, chat_input], [chatbot, chat_input])\n", " bot_msg = chat_msg.then(bot, chatbot, chatbot, api_name=\"bot_response\")\n", " bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input])\n", "\n", " chatbot.like(print_like_dislike, None, None)\n", "\n", "demo.queue()\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
Loading