diff --git a/CHANGELOG.md b/CHANGELOG.md
index 17502aa7eae1d..668551f8bd08e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,4 +1,67 @@
-# Upcoming Release
+# Upcoming Release
+
+## New Features:
+
+### iOS image rotation fixed ๐
+
+Previously photos uploaded via iOS would be rotated after processing. This has been fixed by [@freddyaboulton](https://github.com/freddyaboulton) in [PR 3089](https://github.com/gradio-app/gradio/pull/3091)
+
+#### Before
+![image](https://user-images.githubusercontent.com/41651716/215846507-a36e9d05-1ac2-4867-8ab3-ce045a9415d9.png)
+
+#### After
+![image](https://user-images.githubusercontent.com/41651716/215846554-e41773ed-70f0-491a-9952-6a18babf91ef.png)
+
+<<<<<<< HEAD
+=======
+### Run on Kaggle kernels ๐งช
+
+A share link will automatically be created when running on Kaggle kernels (notebooks) so that
+the front-end is properly displayed.
+
+![image](https://user-images.githubusercontent.com/41651716/216104254-2cf55599-449c-436c-b57e-40f6a83f9eee.png)
+
+By [@freddyaboulton](https://github.com/freddyaboulton) in [PR 3101](https://github.com/gradio-app/gradio/pull/3101)
+
+>>>>>>> 42ad0cbe (Enable gradio to work on kaggle (#3101))
+## Bug Fixes:
+<<<<<<< HEAD
+<<<<<<< HEAD
+
+=======
+* Fix bug where examples were not rendered correctly for demos created with Blocks api that had multiple input compinents by [@freddyaboulton](https://github.com/freddyaboulton) in [PR 3090](https://github.com/gradio-app/gradio/pull/3090)
+>>>>>>> 792289cd (Fix example gallery mode (#3090))
+- Fix change event listener for JSON, HighlightedText, Chatbot by [@aliabid94](https://github.com/aliabid94) in [PR 3095](https://github.com/gradio-app/gradio/pull/3095)
+
+## Documentation Changes:
+<<<<<<< HEAD
+
+No changes to highlight.
+=======
+=======
+* Fix bug where examples were not rendered correctly for demos created with Blocks api that had multiple input compinents by [@freddyaboulton](https://github.com/freddyaboulton) in [PR 3090](https://github.com/gradio-app/gradio/pull/3090)
+- Fix change event listener for JSON, HighlightedText, Chatbot by [@aliabid94](https://github.com/aliabid94) in [PR 3095](https://github.com/gradio-app/gradio/pull/3095)
+- Fixes bug where video and file change event not working [@tomchang25](https://github.com/tomchang25) in [PR 3098](https://github.com/gradio-app/gradio/pull/3098)
+- Fixes bug where static_video play and pause event not working [@tomchang25](https://github.com/tomchang25) in [PR 3098](https://github.com/gradio-app/gradio/pull/3098)
+
+## Documentation Changes:
+>>>>>>> 2cf3e25c (fix changelog)
+- Fix a broken link in the Quick Start guide, by [@cakiki](https://github.com/cakiki) in [PR 3109](https://github.com/gradio-app/gradio/pull/3109)
+>>>>>>> 4d94d4b3 ([Minor] Correct link (#3109))
+
+## Testing and Infrastructure Changes:
+No changes to highlight.
+
+## Breaking Changes:
+No changes to highlight.
+
+## Full Changelog:
+* Set minimum `markdown-it-py` version to `2.0.0` so that the dollar math plugin is compatible by [@freddyaboulton](https://github.com/freddyaboulton) in [PR 3102](https://github.com/gradio-app/gradio/pull/3102)
+
+## Contributors Shoutout:
+No changes to highlight.
+
+# Version 3.17.0
## New Features:
@@ -25,7 +88,7 @@ chatbot.launch()
By [@freddyaboulton](https://github.com/freddyaboulton) in [PR 3011](https://github.com/gradio-app/gradio/pull/3011)
-### Download Button added to Model3D Output Component
+### Download Button added to Model3D Output Component ๐ฅ
No need for an additional file output component to enable model3d file downloads anymore. We now added a download button to the model3d component itself.
@@ -33,6 +96,14 @@ No need for an additional file output component to enable model3d file downloads
By [@dawoodkhan82](https://github.com/dawoodkhan82) in [PR 3014](https://github.com/gradio-app/gradio/pull/3014)
+### Fixing Auth on Spaces ๐
+
+Authentication on spaces works now! Third party cookies must be enabled on your browser to be able
+to log in. Some browsers disable third party cookies by default (Safari, Chrome Incognito).
+
+![auth_spaces](https://user-images.githubusercontent.com/41651716/215528417-09538933-0576-4d1d-b3b9-1e877ab01905.gif)
+
+
## Bug Fixes:
* Fixes bug where interpretation event was not configured correctly by [@freddyaboulton](https://github.com/freddyaboulton) in [PR 2993](https://github.com/gradio-app/gradio/pull/2993)
* Fix relative import bug in reload mode by [@freddyaboulton](https://github.com/freddyaboulton) in [PR 2992](https://github.com/gradio-app/gradio/pull/2992)
@@ -55,7 +126,14 @@ By [@dawoodkhan82](https://github.com/dawoodkhan82) in [PR 3014](https://github.
* Fix bug where the queue was not properly restarted after launching a `closed` app by [@freddyaboulton](https://github.com/freddyaboulton) in [PR 3022](https://github.com/gradio-app/gradio/pull/3022)
* Adding missing embedded components on docs by [@aliabd](https://github.com/aliabd) in [PR 3027](https://github.com/gradio-app/gradio/pull/3027)
* Fixes bug where app would crash if the `file_types` parameter of `gr.File` or `gr.UploadButton` was not a list by [@freddyaboulton](https://github.com/freddyaboulton) in [PR 3048](https://github.com/gradio-app/gradio/pull/3048)
+* Ensure CSS mounts correctly regardless of how many Gradio instances are on the page [@pngwn](https://github.com/pngwn) in [PR 3059](https://github.com/gradio-app/gradio/pull/3059).
* Fix bug where input component was not hidden in the frontend for `UploadButton` by [@freddyaboulton](https://github.com/freddyaboulton) in [PR 3053](https://github.com/gradio-app/gradio/pull/3053)
+* Fixes issue where after clicking submit or undo, the sketch output wouldn't clear. [@dawoodkhan82](https://github.com/dawoodkhan82) in [PR 3047](https://github.com/gradio-app/gradio/pull/3047)
+* Ensure spaces embedded via the web component always use the correct URLs for server requests and change ports for testing to avoid strange collisions when users are working with embedded apps locally by [@pngwn](https://github.com/pngwn) in [PR 3065](https://github.com/gradio-app/gradio/pull/3065)
+* Preserve selected image of Gallery through updated by [@freddyaboulton](https://github.com/freddyaboulton) in [PR 3061](https://github.com/gradio-app/gradio/pull/3061)
+* Fix bug where auth was not respected on HF spaces by [@freddyaboulton](https://github.com/freddyaboulton) and [@aliabid94](https://github.com/aliabid94) in [PR 3049](https://github.com/gradio-app/gradio/pull/3049)
+* Fixes bug where tabs selected attribute not working if manually change tab by [@tomchang25](https://github.com/tomchang25) in [3055](https://github.com/gradio-app/gradio/pull/3055)
+* Change chatbot to show dots on progress, and fix bug where chatbot would not stick to bottom in the case of images by [@aliabid94](https://github.com/aliabid94) in [PR 3067](https://github.com/gradio-app/gradio/pull/3079)
## Documentation Changes:
* SEO improvements to guides by[@aliabd](https://github.com/aliabd) in [PR 2915](https://github.com/gradio-app/gradio/pull/2915)
@@ -1895,4 +1973,4 @@ We've introduced a lot of new components in `3.0`, including `Model3D`, `Dataset
* [@NimaBoscarino](https://github.com/NimaBoscarino) made their first contribution in [PR 1000](https://github.com/gradio-app/gradio/pull/1000)
* [@ronvoluted](https://github.com/ronvoluted) made their first contribution in [PR 1050](https://github.com/gradio-app/gradio/pull/1050)
* [@radames](https://github.com/radames) made their first contribution in [PR 1074](https://github.com/gradio-app/gradio/pull/1074)
-* [@freddyaboulton](https://github.com/freddyaboulton) made their first contribution in [PR 1085](https://github.com/gradio-app/gradio/pull/1085)
+* [@freddyaboulton](https://github.com/freddyaboulton) made their first contribution in [PR 1085](https://github.com/gradio-app/gradio/pull/1085)
\ No newline at end of file
diff --git a/demo/event_trigger/img/a.jpg b/demo/event_trigger/img/a.jpg
new file mode 100644
index 0000000000000..765f840973dae
Binary files /dev/null and b/demo/event_trigger/img/a.jpg differ
diff --git a/demo/event_trigger/img/b.jpg b/demo/event_trigger/img/b.jpg
new file mode 100644
index 0000000000000..7774fb80bb4f0
Binary files /dev/null and b/demo/event_trigger/img/b.jpg differ
diff --git a/demo/event_trigger/mp4/a.mp4 b/demo/event_trigger/mp4/a.mp4
new file mode 100644
index 0000000000000..95a61f6b4a753
Binary files /dev/null and b/demo/event_trigger/mp4/a.mp4 differ
diff --git a/demo/event_trigger/mp4/b.mp4 b/demo/event_trigger/mp4/b.mp4
new file mode 100644
index 0000000000000..7b2d7c723ea53
Binary files /dev/null and b/demo/event_trigger/mp4/b.mp4 differ
diff --git a/demo/event_trigger/run.ipynb b/demo/event_trigger/run.ipynb
new file mode 100644
index 0000000000000..2a3131640f273
--- /dev/null
+++ b/demo/event_trigger/run.ipynb
@@ -0,0 +1 @@
+{"cells": [{"cell_type": "markdown", "id": 302934307671667531413257853548643485645, "metadata": {}, "source": ["# Gradio Demo: event_trigger"]}, {"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('img')\n", "!wget -q -O img/a.jpg https://github.com/gradio-app/gradio/raw/main/demo/event_trigger/img/a.jpg\n", "!wget -q -O img/b.jpg https://github.com/gradio-app/gradio/raw/main/demo/event_trigger/img/b.jpg\n", "os.mkdir('mp4')\n", "!wget -q -O mp4/a.mp4 https://github.com/gradio-app/gradio/raw/main/demo/event_trigger/mp4/a.mp4\n", "!wget -q -O mp4/b.mp4 https://github.com/gradio-app/gradio/raw/main/demo/event_trigger/mp4/b.mp4"]}, {"cell_type": "code", "execution_count": null, "id": 44380577570523278879349135829904343037, "metadata": {}, "outputs": [], "source": ["# %%\n", "import gradio as gr\n", "\n", "\n", "TEST_VIDEO_A = \"mp4/a.mp4\"\n", "TEST_VIDEO_B = \"mp4/b.mp4\"\n", "\n", "TEST_IMAGE_A = \"img/a.jpg\"\n", "TEST_IMAGE_B = \"img/b.jpg\"\n", "\n", "\n", "def alert_change(component, value):\n", " print(f\"Detected {component} change, {type(value)}\")\n", "\n", " if type(value) == list or type(value) == str:\n", " print(value)\n", "\n", "\n", "def change_interactive(state):\n", " return gr.update(interactive=not state), not state\n", "\n", "\n", "with gr.Blocks() as demo:\n", " with gr.Tab(label=\"Text change\"):\n", " with gr.Row():\n", " with gr.Column():\n", " textbox1 = gr.Textbox()\n", " textbox2 = gr.Textbox(interactive=True)\n", "\n", " with gr.Column():\n", " btn = gr.Button()\n", "\n", " def btn_click(state):\n", " return state\n", "\n", " def text_change(value):\n", " print(\"text_change\", value)\n", "\n", " btn.click(fn=btn_click, inputs=textbox1, outputs=textbox2)\n", " textbox2.change(fn=alert_change, inputs=[gr.State(\"Text\"), textbox2])\n", "\n", " with gr.Tab(label=\"Video change, play, pause\"):\n", " with gr.Row():\n", " with gr.Column():\n", " radio1 = gr.Radio(\n", " choices=[TEST_VIDEO_A, TEST_VIDEO_B],\n", " interactive=True,\n", " type=\"index\",\n", " )\n", "\n", " video_btn = gr.Button(\"Change interactive\")\n", "\n", " with gr.Column():\n", " video1 = gr.Video(value=TEST_VIDEO_A, interactive=False)\n", " video1_interactive = gr.State(value=False)\n", "\n", " def change_video(index):\n", " if index == 0:\n", " return TEST_VIDEO_A\n", " elif index == 1:\n", " return TEST_VIDEO_B\n", "\n", " def video_play():\n", " print(\"video_play\")\n", "\n", " def video_pause():\n", " print(\"video_pause\")\n", "\n", " def video_stop():\n", " print(\"video_stop\")\n", "\n", " video1.play(fn=video_play)\n", " video1.pause(fn=video_pause)\n", " video1.stop(fn=video_stop)\n", "\n", " radio1.change(fn=change_video, inputs=radio1, outputs=video1)\n", " video1.change(fn=alert_change, inputs=[gr.State(\"Video\"), video1])\n", "\n", " video_btn.click(\n", " fn=change_interactive,\n", " inputs=video1_interactive,\n", " outputs=[video1, video1_interactive],\n", " )\n", "\n", " with gr.Tab(label=\"Image change\"):\n", " with gr.Row():\n", " with gr.Column():\n", " radio2 = gr.Radio(\n", " choices=[TEST_IMAGE_A, TEST_IMAGE_B],\n", " interactive=True,\n", " type=\"index\",\n", " )\n", "\n", " with gr.Column():\n", " image1 = gr.Image(value=TEST_IMAGE_A, interactive=True)\n", "\n", " def change_image(index):\n", " if index == 0:\n", " return TEST_IMAGE_A\n", " elif index == 1:\n", " return TEST_IMAGE_B\n", "\n", " radio2.change(fn=change_image, inputs=radio2, outputs=image1)\n", " image1.change(fn=alert_change, inputs=[gr.State(\"Image\"), image1])\n", "\n", " with gr.Tab(label=\"File\"):\n", " with gr.Row():\n", " with gr.Column():\n", " radio3 = gr.Radio(\n", " choices=[\"A\", \"B\", \"AB\"],\n", " interactive=True,\n", " type=\"index\",\n", " )\n", "\n", " file_btn = gr.Button(\"Change interactive\")\n", "\n", " with gr.Column():\n", " file1 = gr.File(\n", " value=[TEST_IMAGE_A, TEST_IMAGE_B],\n", " interactive=False,\n", " file_count=\"multiple\",\n", " )\n", " file1_interactive = gr.State(value=False)\n", "\n", " def change_file(index):\n", " if index == 0:\n", " return [TEST_IMAGE_A]\n", " elif index == 1:\n", " return [TEST_IMAGE_A]\n", " elif index == 2:\n", " return [TEST_IMAGE_A, TEST_IMAGE_B]\n", "\n", " radio3.change(fn=change_file, inputs=radio3, outputs=file1)\n", " file1.change(fn=alert_change, inputs=[gr.State(\"File\"), file1])\n", "\n", " file_btn.click(\n", " fn=change_interactive,\n", " inputs=file1_interactive,\n", " outputs=[file1, file1_interactive],\n", " )\n", "\n", "demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}
\ No newline at end of file
diff --git a/demo/event_trigger/run.py b/demo/event_trigger/run.py
new file mode 100644
index 0000000000000..4b7d16707e923
--- /dev/null
+++ b/demo/event_trigger/run.py
@@ -0,0 +1,142 @@
+# %%
+import gradio as gr
+
+
+TEST_VIDEO_A = "mp4/a.mp4"
+TEST_VIDEO_B = "mp4/b.mp4"
+
+TEST_IMAGE_A = "img/a.jpg"
+TEST_IMAGE_B = "img/b.jpg"
+
+
+def alert_change(component, value):
+ print(f"Detected {component} change, {type(value)}")
+
+ if type(value) == list or type(value) == str:
+ print(value)
+
+
+def change_interactive(state):
+ return gr.update(interactive=not state), not state
+
+
+with gr.Blocks() as demo:
+ with gr.Tab(label="Text change"):
+ with gr.Row():
+ with gr.Column():
+ textbox1 = gr.Textbox()
+ textbox2 = gr.Textbox(interactive=True)
+
+ with gr.Column():
+ btn = gr.Button()
+
+ def btn_click(state):
+ return state
+
+ def text_change(value):
+ print("text_change", value)
+
+ btn.click(fn=btn_click, inputs=textbox1, outputs=textbox2)
+ textbox2.change(fn=alert_change, inputs=[gr.State("Text"), textbox2])
+
+ with gr.Tab(label="Video change, play, pause"):
+ with gr.Row():
+ with gr.Column():
+ radio1 = gr.Radio(
+ choices=[TEST_VIDEO_A, TEST_VIDEO_B],
+ interactive=True,
+ type="index",
+ )
+
+ video_btn = gr.Button("Change interactive")
+
+ with gr.Column():
+ video1 = gr.Video(value=TEST_VIDEO_A, interactive=False)
+ video1_interactive = gr.State(value=False)
+
+ def change_video(index):
+ if index == 0:
+ return TEST_VIDEO_A
+ elif index == 1:
+ return TEST_VIDEO_B
+
+ def video_play():
+ print("video_play")
+
+ def video_pause():
+ print("video_pause")
+
+ def video_stop():
+ print("video_stop")
+
+ video1.play(fn=video_play)
+ video1.pause(fn=video_pause)
+ video1.stop(fn=video_stop)
+
+ radio1.change(fn=change_video, inputs=radio1, outputs=video1)
+ video1.change(fn=alert_change, inputs=[gr.State("Video"), video1])
+
+ video_btn.click(
+ fn=change_interactive,
+ inputs=video1_interactive,
+ outputs=[video1, video1_interactive],
+ )
+
+ with gr.Tab(label="Image change"):
+ with gr.Row():
+ with gr.Column():
+ radio2 = gr.Radio(
+ choices=[TEST_IMAGE_A, TEST_IMAGE_B],
+ interactive=True,
+ type="index",
+ )
+
+ with gr.Column():
+ image1 = gr.Image(value=TEST_IMAGE_A, interactive=True)
+
+ def change_image(index):
+ if index == 0:
+ return TEST_IMAGE_A
+ elif index == 1:
+ return TEST_IMAGE_B
+
+ radio2.change(fn=change_image, inputs=radio2, outputs=image1)
+ image1.change(fn=alert_change, inputs=[gr.State("Image"), image1])
+
+ with gr.Tab(label="File"):
+ with gr.Row():
+ with gr.Column():
+ radio3 = gr.Radio(
+ choices=["A", "B", "AB"],
+ interactive=True,
+ type="index",
+ )
+
+ file_btn = gr.Button("Change interactive")
+
+ with gr.Column():
+ file1 = gr.File(
+ value=[TEST_IMAGE_A, TEST_IMAGE_B],
+ interactive=False,
+ file_count="multiple",
+ )
+ file1_interactive = gr.State(value=False)
+
+ def change_file(index):
+ if index == 0:
+ return [TEST_IMAGE_A]
+ elif index == 1:
+ return [TEST_IMAGE_A]
+ elif index == 2:
+ return [TEST_IMAGE_A, TEST_IMAGE_B]
+
+ radio3.change(fn=change_file, inputs=radio3, outputs=file1)
+ file1.change(fn=alert_change, inputs=[gr.State("File"), file1])
+
+ file_btn.click(
+ fn=change_interactive,
+ inputs=file1_interactive,
+ outputs=[file1, file1_interactive],
+ )
+
+demo.launch()
diff --git a/gradio/blocks.py b/gradio/blocks.py
index de88893269156..f9813f3609192 100644
--- a/gradio/blocks.py
+++ b/gradio/blocks.py
@@ -1383,6 +1383,7 @@ def reverse(text):
self.server = server
self.is_running = True
self.is_colab = utils.colab_check()
+ self.is_kaggle = utils.kaggle_check()
self.protocol = (
"https"
if self.local_url.startswith("https") or self.is_colab
@@ -1405,7 +1406,7 @@ def reverse(text):
share
if share is not None
else True
- if self.is_colab and self.enable_queue
+ if (self.is_colab and self.enable_queue) or self.is_kaggle
else False
)
diff --git a/gradio/processing_utils.py b/gradio/processing_utils.py
index 39ac6b5e7dca0..c181a9bef7c59 100644
--- a/gradio/processing_utils.py
+++ b/gradio/processing_utils.py
@@ -52,7 +52,12 @@ def to_binary(x: str | Dict) -> bytes:
def decode_base64_to_image(encoding: str) -> Image.Image:
content = encoding.split(";")[1]
image_encoded = content.split(",")[1]
- return Image.open(BytesIO(base64.b64decode(image_encoded)))
+ img = Image.open(BytesIO(base64.b64decode(image_encoded)))
+ exif = img.getexif()
+ # 274 is the code for image rotation and 1 means "correct orientation"
+ if exif.get(274, 1) != 1 and hasattr(ImageOps, "exif_transpose"):
+ img = ImageOps.exif_transpose(img)
+ return img
def encode_url_or_file_to_base64(path: str | Path, encryption_key: bytes | None = None):
diff --git a/gradio/routes.py b/gradio/routes.py
index c263c08b3e848..1a0d00c9cc7c5 100644
--- a/gradio/routes.py
+++ b/gradio/routes.py
@@ -184,8 +184,14 @@ def login(form_data: OAuth2PasswordRequestForm = Depends()):
) or (callable(app.auth) and app.auth.__call__(username, password)):
token = secrets.token_urlsafe(16)
app.tokens[token] = username
- response = RedirectResponse(url="/", status_code=status.HTTP_302_FOUND)
- response.set_cookie(key="access-token", value=token, httponly=True)
+ response = JSONResponse(content={"success": True})
+ response.set_cookie(
+ key="access-token",
+ value=token,
+ httponly=True,
+ samesite="none",
+ secure=True,
+ )
return response
else:
raise HTTPException(status_code=400, detail="Incorrect credentials.")
@@ -206,6 +212,7 @@ def main(request: fastapi.Request, user: str = Depends(get_current_user)):
config = {
"auth_required": True,
"auth_message": blocks.auth_message,
+ "is_space": app.get_blocks().is_space,
}
try:
diff --git a/gradio/utils.py b/gradio/utils.py
index 674154f4c311c..9ac48152e9946 100644
--- a/gradio/utils.py
+++ b/gradio/utils.py
@@ -189,6 +189,12 @@ def colab_check() -> bool:
return is_colab
+def kaggle_check() -> bool:
+ return bool(
+ os.environ.get("KAGGLE_KERNEL_RUN_TYPE") or os.environ.get("GFOOTBALL_DATA_DIR")
+ )
+
+
def ipython_check() -> bool:
"""
Check if interface is launching from iPython (not colab)
diff --git a/gradio/version.txt b/gradio/version.txt
index 21221d0e7a479..3f67e25cea13b 100644
--- a/gradio/version.txt
+++ b/gradio/version.txt
@@ -1 +1 @@
-3.16.2
+3.17.0
diff --git a/guides/01_getting-started/01_quickstart.md b/guides/01_getting-started/01_quickstart.md
index 170bd0a440a70..88ce233df2ef3 100644
--- a/guides/01_getting-started/01_quickstart.md
+++ b/guides/01_getting-started/01_quickstart.md
@@ -103,6 +103,6 @@ Here's an app to give you a taste of what's possible with `Blocks`:
$code_blocks_flipper
$demo_blocks_flipper
-A lot more going on here! We'll cover how to create complex `Blocks` apps like this in the [building with blocks](https://github.com/gradio-app/gradio/tree/main/guides/3\)building_with_blocks) section for you.
+A lot more going on here! We'll cover how to create complex `Blocks` apps like this in the [building with blocks](https://gradio.app/building_with_blocks) section for you.
Congrats, you're now familiar with the basics of Gradio! ๐ฅณ Go to our [next guide](https://gradio.app/key_features) to learn more about the key features of Gradio.
diff --git a/guides/01_getting-started/03_sharing-your-app.md b/guides/01_getting-started/03_sharing-your-app.md
index f32540797653e..51ab2dc74bfcc 100644
--- a/guides/01_getting-started/03_sharing-your-app.md
+++ b/guides/01_getting-started/03_sharing-your-app.md
@@ -77,6 +77,8 @@ fetch("https://pypi.org/pypi/gradio/json"
});
+_Note: While Gradio's CSS will never impact the embedding page, the embedding page can affect the style of the embedded Gradio app. Make sure that any CSS in the parent page isn't so general that it could also apply to the embedded Gradio app and cause the styling to break. Element selectors such as `header { ... }` and `footer { ... }` will be the most likely to cause issues._
+
### Embedding with IFrames
To embed with IFrames instead, simply add this element:
@@ -121,6 +123,9 @@ def same_auth(username, password):
demo.launch(auth=same_auth)
```
+For authentication to work properly, third party cookies must be enabled in your browser.
+This is not the case by default for Safari, Chrome Incognito Mode.
+
## Accessing the Network Request Directly
When a user makes a prediction to your app, you may need the underlying network request, in order to get the request headers (e.g. for advanced authentication), log the client's IP address, or for other reasons. Gradio supports this in a similar manner to FastAPI: simply add a function parameter whose type hint is `gr.Request` and Gradio will pass in the network request as that parameter. Here is an example:
diff --git a/guides/06_other-tutorials/creating-a-new-component.md b/guides/06_other-tutorials/creating-a-new-component.md
index 0bf0f855fe5af..6256cecdea5d6 100644
--- a/guides/06_other-tutorials/creating-a-new-component.md
+++ b/guides/06_other-tutorials/creating-a-new-component.md
@@ -385,7 +385,7 @@ You can take a look at the [demo](https://github.com/gradio-app/gradio/tree/main
To test the application:
- run on a terminal `python path/demo/run.py` which starts the backend at the address [http://localhost:7860](http://localhost:7860);
-- in another terminal, from the ui folder, run `pnpm dev` to start the frontend at [http://localhost:3000](http://localhost:3000) with hot reload functionalities.
+- in another terminal, from the ui folder, run `pnpm dev` to start the frontend at [http://localhost:9876](http://localhost:9876) with hot reload functionalities.
## Conclusion
diff --git a/requirements.txt b/requirements.txt
index 6cb909beaf096..14c6edb81d456 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -2,7 +2,7 @@ aiohttp
altair>=4.2.0
fastapi
ffmpy
-markdown-it-py[linkify,plugins]
+markdown-it-py[linkify,plugins]>=2.0.0
markupsafe
matplotlib
numpy
diff --git a/test/test_blocks.py b/test/test_blocks.py
index fe334ad51ada2..ea6df70c9ed70 100644
--- a/test/test_blocks.py
+++ b/test/test_blocks.py
@@ -1338,7 +1338,7 @@ async def say_hello(name):
data={"username": "abc", "password": "123"},
follow_redirects=False,
)
- assert resp.status_code == 302
+ assert resp.status_code == 200
token = resp.cookies.get("access-token")
assert token
diff --git a/test/test_processing_utils.py b/test/test_processing_utils.py
index 141bed35e7f58..07c6851eae8bc 100644
--- a/test/test_processing_utils.py
+++ b/test/test_processing_utils.py
@@ -73,6 +73,14 @@ def test_encode_pil_to_base64_keeps_pnginfo(self):
assert decoded_image.info == input_img.info
+ @patch("PIL.Image.Image.getexif", return_value={274: 3})
+ @patch("PIL.ImageOps.exif_transpose")
+ def test_base64_to_image_does_rotation(self, mock_rotate, mock_exif):
+ input_img = Image.open("gradio/test_data/test_image.png")
+ base64 = processing_utils.encode_pil_to_base64(input_img)
+ processing_utils.decode_base64_to_image(base64)
+ mock_rotate.assert_called_once()
+
def test_resize_and_crop(self):
img = Image.open("gradio/test_data/test_image.png")
new_img = processing_utils.resize_and_crop(img, (20, 20))
diff --git a/test/test_utils.py b/test/test_utils.py
index 9b4de02672ee0..cdbe453a5ca6d 100644
--- a/test/test_utils.py
+++ b/test/test_utils.py
@@ -29,6 +29,7 @@
format_ner_list,
get_local_ip_address,
ipython_check,
+ kaggle_check,
launch_analytics,
readme_to_html,
sanitize_list_for_csv,
@@ -103,6 +104,31 @@ def test_readme_to_html_doesnt_crash_on_connection_error(self, mock_get):
def test_readme_to_html_correct_parse(self):
readme_to_html("https://github.com/gradio-app/gradio/blob/master/README.md")
+ def test_kaggle_check_false(self):
+ assert not kaggle_check()
+
+ def test_kaggle_check_true_when_run_type_set(self):
+ with mock.patch.dict(
+ os.environ, {"KAGGLE_KERNEL_RUN_TYPE": "Interactive"}, clear=True
+ ):
+ assert kaggle_check()
+
+ def test_kaggle_check_true_when_both_set(self):
+ with mock.patch.dict(
+ os.environ,
+ {"KAGGLE_KERNEL_RUN_TYPE": "Interactive", "GFOOTBALL_DATA_DIR": "./"},
+ clear=True,
+ ):
+ assert kaggle_check()
+
+ def test_kaggle_check_false_when_neither_set(self):
+ with mock.patch.dict(
+ os.environ,
+ {"KAGGLE_KERNEL_RUN_TYPE": "", "GFOOTBALL_DATA_DIR": ""},
+ clear=True,
+ ):
+ assert not kaggle_check()
+
class TestIPAddress:
@pytest.mark.flaky
diff --git a/ui/package.json b/ui/package.json
index e2f12449a0488..1bed2031c0109 100644
--- a/ui/package.json
+++ b/ui/package.json
@@ -47,6 +47,7 @@
"postcss": "^8.4.6",
"postcss-custom-media": "8",
"postcss-nested": "^5.0.6",
+ "postcss-prefix-selector": "^1.16.0",
"prettier": "^2.6.2",
"prettier-plugin-css-order": "^1.3.0",
"prettier-plugin-svelte": "^2.7.0",
diff --git a/ui/packages/_cdn-test/index.html b/ui/packages/_cdn-test/index.html
index 59f774ae07b9e..6585ebe2a4e57 100644
--- a/ui/packages/_cdn-test/index.html
+++ b/ui/packages/_cdn-test/index.html
@@ -39,7 +39,7 @@
hello subtitle
Hello text. Hello text.
hello subtitle
diff --git a/ui/packages/app/build_plugins.ts b/ui/packages/app/build_plugins.ts
index 24e108ea52de3..dafe46f6bf6bf 100644
--- a/ui/packages/app/build_plugins.ts
+++ b/ui/packages/app/build_plugins.ts
@@ -110,17 +110,6 @@ export function handle_ce_css(): Plugin {
enforce: "post",
name: "custom-element-css",
- transform(code, id) {
- if (id === "vite/preload-helper") {
- return {
- code: code.replace(
- "document.head.appendChild(link);",
- "window.scoped_css_attach(link)"
- )
- };
- }
- },
-
writeBundle(config, bundle) {
let file_to_insert = {
filename: "",
diff --git a/ui/packages/app/package.json b/ui/packages/app/package.json
index 982140dfdb58c..72f4c473035a3 100644
--- a/ui/packages/app/package.json
+++ b/ui/packages/app/package.json
@@ -3,7 +3,7 @@
"version": "1.0.0",
"private": true,
"scripts": {
- "dev": "vite",
+ "dev": "vite --port 9876",
"build:cdn": "vite build --mode production:cdn --emptyOutDir",
"build:website": "vite build --mode production:website --emptyOutDir",
"build:local": "vite build --mode production:local --emptyOutDir",
@@ -42,6 +42,8 @@
"@gradio/video": "workspace:^0.0.1",
"d3-dsv": "^3.0.1",
"mime-types": "^2.1.34",
+ "postcss": "^8.4.21",
+ "postcss-prefix-selector": "^1.16.0",
"svelte": "^3.25.1",
"svelte-i18n": "^3.3.13"
}
diff --git a/ui/packages/app/postcss.config.js b/ui/packages/app/postcss.config.js
index 7a7249ddfb424..f053ebf7976e3 100644
--- a/ui/packages/app/postcss.config.js
+++ b/ui/packages/app/postcss.config.js
@@ -1,4 +1 @@
-module.exports = {
- extract: "themes.css",
- plugins: [custom_media]
-};
+module.exports = {};
diff --git a/ui/packages/app/snapshots/blocks_layout.spec.ts b/ui/packages/app/snapshots/blocks_layout.spec.ts
index 990f7f3e3bd9a..2ad031705e853 100644
--- a/ui/packages/app/snapshots/blocks_layout.spec.ts
+++ b/ui/packages/app/snapshots/blocks_layout.spec.ts
@@ -13,6 +13,6 @@ function mock_demo(page: Page, demo: string) {
test("blocks layout", async ({ page }) => {
await mock_demo(page, "blocks_layout");
- await page.goto("http://localhost:3000");
+ await page.goto("http://localhost:9876");
await expect(page).toHaveScreenshot();
});
diff --git a/ui/packages/app/snapshots/blocks_xray.spec.ts b/ui/packages/app/snapshots/blocks_xray.spec.ts
index 6b6cf16f14b41..00987bbbbf42c 100644
--- a/ui/packages/app/snapshots/blocks_xray.spec.ts
+++ b/ui/packages/app/snapshots/blocks_xray.spec.ts
@@ -13,6 +13,6 @@ function mock_demo(page: Page, demo: string) {
test("blocks xray", async ({ page }) => {
await mock_demo(page, "blocks_xray");
- await page.goto("http://localhost:3000");
+ await page.goto("http://localhost:9876");
await expect(page).toHaveScreenshot();
});
diff --git a/ui/packages/app/snapshots/kitchen_sink.spec.ts b/ui/packages/app/snapshots/kitchen_sink.spec.ts
index 16ec00df7844a..713e31cd71cc8 100644
--- a/ui/packages/app/snapshots/kitchen_sink.spec.ts
+++ b/ui/packages/app/snapshots/kitchen_sink.spec.ts
@@ -13,6 +13,6 @@ function mock_demo(page: Page, demo: string) {
test("kitchen sink", async ({ page }) => {
await mock_demo(page, "kitchen_sink");
- await page.goto("http://localhost:3000");
+ await page.goto("http://localhost:9876");
await expect(page).toHaveScreenshot();
});
diff --git a/ui/packages/app/src/Login.svelte b/ui/packages/app/src/Login.svelte
index 4b000e9e9a086..03067e23c9b82 100644
--- a/ui/packages/app/src/Login.svelte
+++ b/ui/packages/app/src/Login.svelte
@@ -6,6 +6,7 @@
export let id: number;
export let auth_message: string | null;
export let app_mode: boolean;
+ export let is_space: boolean;
window.__gradio_loader__[id].$set({ status: "complete" });
let username = "";
@@ -25,7 +26,7 @@
incorrect_credentials = true;
username = "";
password = "";
- } else {
+ } else if (response.status == 200) {
location.reload();
}
};
@@ -37,6 +38,12 @@
{#if auth_message}
{auth_message}
{/if}
+ {#if is_space}
+
+ If you are visiting a HuggingFace Space in Incognito mode, you must
+ enable third party cookies.
+
+ {/if}
{#if incorrect_credentials}
Incorrect Credentials
{/if}
@@ -62,7 +69,12 @@
/>
-
+
Login
@@ -80,6 +92,7 @@
.panel {
display: flex;
+ flex-direction: column;
flex-wrap: wrap;
gap: var(--size-4);
border-radius: var(--radius-lg);
@@ -89,14 +102,16 @@
}
h2 {
- margin-bottom: var(--size-6);
+ margin-bottom: var(--size-3);
+ color: var(--color-text-body);
font-weight: var(--weight-semibold);
font-size: var(--scale-2);
}
.auth {
- margin-top: var(--size-4);
- margin-bottom: var(--size-4);
+ margin-top: var(--size-1);
+ margin-bottom: var(--size-1);
+ color: var(--color-text-body);
}
.creds {
diff --git a/ui/packages/app/src/api.ts b/ui/packages/app/src/api.ts
index 7e53d23f96d2a..ce7605d900854 100644
--- a/ui/packages/app/src/api.ts
+++ b/ui/packages/app/src/api.ts
@@ -130,7 +130,7 @@ export const fn =
var ws_protocol = ws_endpoint.startsWith("https") ? "wss:" : "ws:";
var ws_path = location.pathname === "/" ? "/" : location.pathname;
var ws_host =
- BUILD_MODE === "dev" || location.origin === "http://localhost:3000"
+ BUILD_MODE === "dev" || location.origin === "http://localhost:9876"
? BACKEND_URL.replace("http://", "").slice(0, -1)
: location.host;
WS_ENDPOINT = `${ws_protocol}//${ws_host}${ws_path}queue/join`;
diff --git a/ui/packages/app/src/components/Chatbot/Chatbot.svelte b/ui/packages/app/src/components/Chatbot/Chatbot.svelte
index 464d677a68c96..f5ee85882d015 100644
--- a/ui/packages/app/src/components/Chatbot/Chatbot.svelte
+++ b/ui/packages/app/src/components/Chatbot/Chatbot.svelte
@@ -1,7 +1,6 @@
-
{#if show_label}
{/if}
-
+
diff --git a/ui/packages/app/src/components/Dataset/Dataset.svelte b/ui/packages/app/src/components/Dataset/Dataset.svelte
index 7808c411eae9d..ccbb2b32e59d5 100644
--- a/ui/packages/app/src/components/Dataset/Dataset.svelte
+++ b/ui/packages/app/src/components/Dataset/Dataset.svelte
@@ -18,7 +18,7 @@
let samples_dir: string = (root_url ?? root) + "file=";
let page = 0;
- $: gallery = headers.length < 2;
+ $: gallery = components.length < 2;
let paginate = samples.length > samples_per_page;
let selected_samples: Array>;
diff --git a/ui/packages/app/src/components/File/File.svelte b/ui/packages/app/src/components/File/File.svelte
index 5a725aed69824..88773ef74f1b3 100644
--- a/ui/packages/app/src/components/File/File.svelte
+++ b/ui/packages/app/src/components/File/File.svelte
@@ -1,7 +1,8 @@
(value = detail)}
on:drag={({ detail }) => (dragging = detail)}
- on:change
on:clear
on:upload
>
diff --git a/ui/packages/app/src/components/HighlightedText/HighlightedText.svelte b/ui/packages/app/src/components/HighlightedText/HighlightedText.svelte
index d45d95174916b..44048a20c11a7 100644
--- a/ui/packages/app/src/components/HighlightedText/HighlightedText.svelte
+++ b/ui/packages/app/src/components/HighlightedText/HighlightedText.svelte
@@ -10,6 +10,7 @@
export let elem_id: string = "";
export let visible: boolean = true;
export let value: Array<[string, string | number]>;
+ let old_value: Array<[string, string | number]>;
export let show_legend: boolean;
export let color_map: Record = {};
export let label: string;
@@ -23,7 +24,12 @@
const dispatch = createEventDispatcher<{ change: undefined }>();
- $: value, dispatch("change");
+ $: {
+ if (value !== old_value) {
+ old_value = value;
+ dispatch("change");
+ }
+ }
();
- $: value, dispatch("change");
+ $: {
+ if (value !== old_value) {
+ old_value = value;
+ dispatch("change");
+ }
+ }
+ import { createEventDispatcher } from "svelte";
import type { FileData } from "@gradio/upload";
import { normalise_file } from "@gradio/upload";
import { Block } from "@gradio/atoms";
@@ -13,6 +14,8 @@
export let elem_id: string = "";
export let visible: boolean = true;
export let value: FileData | null | string = null;
+ let old_value: FileData | null | string = null;
+
export let label: string;
export let source: string;
export let root: string;
@@ -29,6 +32,18 @@
$: _value = normalise_file(value, root_url ?? root);
let dragging = false;
+
+ const dispatch = createEventDispatcher<{
+ change: undefined;
+ }>();
+
+ $: {
+ if (value !== old_value) {
+ old_value = value;
+
+ dispatch("change");
+ }
+ }
{#if mode === "static"}
-
+
{:else}
{
}
async function get_config(source: string | null) {
- if (BUILD_MODE === "dev" || location.origin === "http://localhost:3000") {
+ if (BUILD_MODE === "dev" || location.origin === "http://localhost:9876") {
let config = await fetch(BACKEND_URL + "config");
const result = await config.json();
return result;
@@ -150,6 +151,7 @@ function mount_app(
props: {
auth_message: config.auth_message,
root: config.root,
+ is_space: config.is_space,
id,
app_mode
}
@@ -183,10 +185,10 @@ function mount_app(
function create_custom_element() {
//@ts-ignore
- FONTS.map((f) => mount_css(f, document.head));
+ typeof FONTS !== "string" && FONTS.map((f) => mount_css(f, document.head));
class GradioApp extends HTMLElement {
- root: ShadowRoot;
+ root: HTMLElement;
wrapper: HTMLDivElement;
_id: number;
theme: string;
@@ -195,15 +197,11 @@ function create_custom_element() {
super();
this._id = ++id;
-
- this.root = this.attachShadow({ mode: "open" });
-
- window.scoped_css_attach = (link) => {
- this.root.append(link);
- };
+ this.root = this;
this.wrapper = document.createElement("div");
this.wrapper.classList.add("gradio-container");
+ this.wrapper.classList.add(`gradio-container-${GRADIO_VERSION}`);
this.wrapper.style.position = "relative";
this.wrapper.style.width = "100%";
@@ -226,7 +224,7 @@ function create_custom_element() {
}
async connectedCallback() {
- await mount_css(ENTRY_CSS, this.root);
+ await mount_css(ENTRY_CSS, document.head);
this.root.append(this.wrapper);
const event = new CustomEvent("domchange", {
@@ -243,6 +241,7 @@ function create_custom_element() {
const host = this.getAttribute("host");
const space = this.getAttribute("space");
+ const src = this.getAttribute("src");
const source = host
? `https://${host}`
@@ -252,7 +251,10 @@ function create_custom_element() {
await fetch(`https://huggingface.co/api/spaces/${space}/host`)
).json()
).host
- : this.getAttribute("src");
+ : src;
+
+ const is_embed =
+ !!space || (source && new URL(source).host.endsWith("hf.space"));
const control_page_title = this.getAttribute("control_page_title");
const initial_height = this.getAttribute("initial_height");
@@ -277,7 +279,7 @@ function create_custom_element() {
this.wrapper,
this._id,
_autoscroll,
- !!space
+ is_embed
);
}
}
@@ -286,27 +288,6 @@ function create_custom_element() {
customElements.define("gradio-app", GradioApp);
}
-async function unscoped_mount() {
- const target = document.querySelector("#root")! as HTMLDivElement;
- target.classList.add("gradio-container");
- if (window.__gradio_mode__ !== "website") {
- handle_darkmode(target);
- }
-
- window.__gradio_loader__[0] = new Loader({
- target: target,
- props: {
- status: "pending",
- timer: false,
- queue_position: null,
- queue_size: null
- }
- });
-
- const config = await handle_config(target, null);
- mount_app({ ...config, control_page_title: true }, false, target, 0);
-}
-
function handle_darkmode(target: HTMLDivElement): string {
let url = new URL(window.location.toString());
let theme = "light";
@@ -357,11 +338,4 @@ function darkmode(target: HTMLDivElement): string {
return "dark";
}
-if (BUILD_MODE === "dev") {
- window.scoped_css_attach = (link) => {
- document.head.append(link);
- };
- unscoped_mount();
-} else {
- create_custom_element();
-}
+create_custom_element();
diff --git a/ui/packages/app/test/blocks_inputs.spec.ts b/ui/packages/app/test/blocks_inputs.spec.ts
index 9eb3401d4da26..a7caf02251e89 100644
--- a/ui/packages/app/test/blocks_inputs.spec.ts
+++ b/ui/packages/app/test/blocks_inputs.spec.ts
@@ -28,7 +28,7 @@ function mock_api(page: Page, body: Array) {
test("renders the correct elements", async ({ page }) => {
await mock_demo(page, "blocks_inputs");
await mock_api(page, [["hi dawood"]]);
- await page.goto("http://localhost:3000");
+ await page.goto("http://localhost:9876");
const textboxes = await page.getByLabel("Input");
diff --git a/ui/packages/app/test/blocks_kinematics.spec.ts b/ui/packages/app/test/blocks_kinematics.spec.ts
index 7943152b9e21a..306a832f48a77 100644
--- a/ui/packages/app/test/blocks_kinematics.spec.ts
+++ b/ui/packages/app/test/blocks_kinematics.spec.ts
@@ -28,7 +28,7 @@ function mock_api(page: Page, body: Array) {
test("renders the correct elements", async ({ page }) => {
await mock_demo(page, "blocks_kinematics");
await mock_api(page, [[25, 45]]);
- await page.goto("http://localhost:3000");
+ await page.goto("http://localhost:9876");
await Promise.all([
page.click("button:has-text('Run')"),
diff --git a/ui/packages/app/test/blocks_page_load.spec.ts b/ui/packages/app/test/blocks_page_load.spec.ts
index 38cf8d1a01fb1..f92be22228cbd 100644
--- a/ui/packages/app/test/blocks_page_load.spec.ts
+++ b/ui/packages/app/test/blocks_page_load.spec.ts
@@ -28,7 +28,7 @@ function mock_api(page: Page, body: Array) {
test("renders the correct elements", async ({ page }) => {
await mock_demo(page, "blocks_page_load");
await mock_api(page, [["Welcome! This page has loaded for Frank"]]);
- await page.goto("http://localhost:3000");
+ await page.goto("http://localhost:9876");
const textbox = await page.getByLabel("Name");
diff --git a/ui/packages/app/test/blocks_xray.spec.ts b/ui/packages/app/test/blocks_xray.spec.ts
index 966f0dc38e125..63a46f0f6de56 100644
--- a/ui/packages/app/test/blocks_xray.spec.ts
+++ b/ui/packages/app/test/blocks_xray.spec.ts
@@ -27,7 +27,7 @@ function mock_api(page: Page, body: Array) {
test("renders the correct elements", async ({ page }) => {
await mock_demo(page, "blocks_xray");
- await page.goto("http://localhost:3000");
+ await page.goto("http://localhost:9876");
const description = await page.getByTestId("markdown");
await expect(description).toContainText("Detect Disease From Scan");
@@ -56,7 +56,7 @@ test("can run an api request and display the data", async ({ page }) => {
]
]);
- await page.goto("http://localhost:3000");
+ await page.goto("http://localhost:9876");
await page.getByLabel("Covid").check();
await page.getByLabel("Lung Cancer").check();
diff --git a/ui/packages/app/test/input_output.spec.ts b/ui/packages/app/test/input_output.spec.ts
index 65104590ed89e..26f97f1cfe3a0 100644
--- a/ui/packages/app/test/input_output.spec.ts
+++ b/ui/packages/app/test/input_output.spec.ts
@@ -28,7 +28,7 @@ function mock_api(page: Page, body: Array) {
test("a component acts as both input and output", async ({ page }) => {
await mock_demo(page, "input_output");
await mock_api(page, [["tset"]]);
- await page.goto("http://localhost:3000");
+ await page.goto("http://localhost:9876");
const textbox = await page.getByLabel("Input-Output");
diff --git a/ui/packages/app/test/kitchen_sink.spec.ts b/ui/packages/app/test/kitchen_sink.spec.ts
index c3cec72fad504..5d74d85de2ab8 100644
--- a/ui/packages/app/test/kitchen_sink.spec.ts
+++ b/ui/packages/app/test/kitchen_sink.spec.ts
@@ -28,7 +28,7 @@ function mock_api(page: Page, body: Array) {
test("test inputs", async ({ page }) => {
await mock_demo(page, "kitchen_sink");
- await page.goto("http://localhost:3000");
+ await page.goto("http://localhost:9876");
const textbox = await page.getByLabel("Textbox").nth(0);
await expect(textbox).toHaveValue("Lorem ipsum");
@@ -209,7 +209,7 @@ test("test outputs", async ({ page }) => {
]
]);
- await page.goto("http://localhost:3000");
+ await page.goto("http://localhost:9876");
const submit_button = await page.locator("button", { hasText: /Submit/ });
diff --git a/ui/packages/app/test/outbreak_forecast.spec.ts b/ui/packages/app/test/outbreak_forecast.spec.ts
index 60f50b46015bc..3184d83bec37e 100644
--- a/ui/packages/app/test/outbreak_forecast.spec.ts
+++ b/ui/packages/app/test/outbreak_forecast.spec.ts
@@ -29,7 +29,7 @@ function mock_api(page: Page, body: Array) {
test("matplotlib", async ({ page }) => {
await mock_demo(page, "outbreak_forecast");
await mock_api(page, [[{ type: "matplotlib", plot: BASE64_PLOT_IMG }]]);
- await page.goto("http://localhost:3000");
+ await page.goto("http://localhost:9876");
await page.getByLabel("Plot Type").selectOption("Matplotlib");
await page.getByLabel("Month").selectOption("January");
@@ -55,7 +55,7 @@ test("plotly", async ({ page }) => {
}
]
]);
- await page.goto("http://localhost:3000");
+ await page.goto("http://localhost:9876");
await page.getByLabel("Plot Type").selectOption("Plotly");
await page.getByLabel("Month").selectOption("January");
diff --git a/ui/packages/app/vite.config.js b/ui/packages/app/vite.config.js
index 2916e57469a17..929231df39645 100644
--- a/ui/packages/app/vite.config.js
+++ b/ui/packages/app/vite.config.js
@@ -3,6 +3,15 @@ import { svelte } from "@sveltejs/vite-plugin-svelte";
import sveltePreprocess from "svelte-preprocess";
// @ts-ignore
import custom_media from "postcss-custom-media";
+// @ts-ignore
+import prefixer from "postcss-prefix-selector";
+import { readFileSync } from "fs";
+import { join } from "path";
+
+const version_path = join(__dirname, "..", "..", "..", "gradio", "version.txt");
+const version = readFileSync(version_path, { encoding: "utf-8" })
+ .trim()
+ .replace(/\./g, "-");
import {
inject_ejs,
@@ -30,24 +39,43 @@ export default defineConfig(({ mode }) => {
base: is_cdn ? CDN_URL : "./",
server: {
- port: 3000
+ port: 9876
},
build: {
sourcemap: true,
target: "esnext",
minify: production,
+ // minify: false,
outDir: `../../../gradio/templates/${is_cdn ? "cdn" : "frontend"}`
},
define: {
BUILD_MODE: production ? JSON.stringify("prod") : JSON.stringify("dev"),
BACKEND_URL: production
? JSON.stringify("")
- : JSON.stringify("http://localhost:7860/")
+ : JSON.stringify("http://localhost:7860/"),
+ GRADIO_VERSION: JSON.stringify(version)
},
css: {
postcss: {
plugins: [
+ prefixer({
+ prefix: `.gradio-container-${version}`,
+ // @ts-ignore
+ transform(prefix, selector, prefixedSelector, fileName) {
+ if (selector.indexOf("gradio-container") > -1) {
+ return prefix;
+ } else if (
+ selector.indexOf(":root") > -1 ||
+ selector.indexOf("dark") > -1 ||
+ fileName.indexOf(".svelte") > -1
+ ) {
+ return selector;
+ } else {
+ return prefixedSelector;
+ }
+ }
+ }),
custom_media({
importFrom: [
{
@@ -74,7 +102,9 @@ export default defineConfig(({ mode }) => {
},
hot: !process.env.VITEST && !production,
preprocess: sveltePreprocess({
- postcss: { plugins: [custom_media()] }
+ postcss: {
+ plugins: [custom_media()]
+ }
})
}),
inject_ejs(),
diff --git a/ui/packages/chatbot/src/ChatBot.svelte b/ui/packages/chatbot/src/ChatBot.svelte
index 4e2c1e3ec4a57..dc47074335b0c 100644
--- a/ui/packages/chatbot/src/ChatBot.svelte
+++ b/ui/packages/chatbot/src/ChatBot.svelte
@@ -3,24 +3,39 @@
import { colors } from "@gradio/theme";
import type { Styles } from "@gradio/utils";
- export let value: Array<[string, string]>;
+ export let value: Array<[string, string]> | null;
+ let old_value: Array<[string, string]> | null;
export let style: Styles = {};
+ export let pending_message: boolean = false;
let div: HTMLDivElement;
let autoscroll: Boolean;
const dispatch = createEventDispatcher<{ change: undefined }>();
+ $: _value = value || [];
beforeUpdate(() => {
autoscroll =
div && div.offsetHeight + div.scrollTop > div.scrollHeight - 20;
});
afterUpdate(() => {
- if (autoscroll) div.scrollTo(0, div.scrollHeight);
+ if (autoscroll) {
+ div.scrollTo(0, div.scrollHeight);
+ div.querySelectorAll("img").forEach((n) => {
+ n.addEventListener("load", () => {
+ div.scrollTo(0, div.scrollHeight);
+ });
+ });
+ }
});
- $: value && dispatch("change");
+ $: {
+ if (value !== old_value) {
+ old_value = value;
+ dispatch("change");
+ }
+ }
$: _colors = get_colors();
@@ -43,10 +58,10 @@
- {#each value as message, i}
+ {#each _value as message, i}
@@ -54,13 +69,26 @@
{@html message[1]}
{/each}
+ {#if pending_message}
+
+ {/if}
@@ -120,4 +148,37 @@
background: var(--chatbot-bot-background-latest);
color: var(--chatbot-bot-text-color-latest);
}
+
+ .pending {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ gap: 2px;
+ }
+ .dot-flashing {
+ animation: dot-flashing 1s infinite linear alternate;
+ border-radius: 5px;
+ background-color: white;
+ width: 5px;
+ height: 5px;
+ color: white;
+ }
+ .dot-flashing:nth-child(2) {
+ animation-delay: 0.33s;
+ }
+ .dot-flashing:nth-child(3) {
+ animation-delay: 0.66s;
+ }
+
+ @keyframes dot-flashing {
+ 0% {
+ opacity: 0.8;
+ }
+ 50% {
+ opacity: 0.5;
+ }
+ 100% {
+ opacity: 0.8;
+ }
+ }
diff --git a/ui/packages/gallery/src/Gallery.svelte b/ui/packages/gallery/src/Gallery.svelte
index 1b1c8bd195e78..6ad38941e8653 100644
--- a/ui/packages/gallery/src/Gallery.svelte
+++ b/ui/packages/gallery/src/Gallery.svelte
@@ -28,7 +28,11 @@
let prevValue: string[] | FileData[] | null = null;
let selected_image: number | null = null;
$: if (prevValue !== value) {
- selected_image = null;
+ // so that gallery preserves selected image after update
+ selected_image =
+ selected_image !== null && value !== null && selected_image < value.length
+ ? selected_image
+ : null;
prevValue = value;
}
diff --git a/ui/packages/image/src/Image.svelte b/ui/packages/image/src/Image.svelte
index 97a711de9a2d2..85139eb166d0e 100644
--- a/ui/packages/image/src/Image.svelte
+++ b/ui/packages/image/src/Image.svelte
@@ -103,7 +103,7 @@
container_height = element.getBoundingClientRect().height;
}
- async function handle_mask_clear() {
+ async function handle_sketch_clear() {
sketch.clear();
await tick();
value = null;
@@ -214,7 +214,7 @@
/>
sketch.undo()}
- on:clear={handle_mask_clear}
+ on:clear={handle_sketch_clear}
/>
{#if tool === "color-sketch" || tool === "sketch"}
sketch.undo()}
- on:clear={() => sketch.clear()}
+ on:clear={handle_sketch_clear}
/>
{#if tool === "color-sketch"}
sketch.undo()}
- on:clear={handle_mask_clear}
+ on:clear={handle_sketch_clear}
/>
{#if tool === "color-sketch" || tool === "sketch"}
{
return {
- selector: ":host, :root",
+ selector: ":root",
output: "./src/pollen.css",
modules: {
line: {
diff --git a/ui/packages/upload/src/utils.ts b/ui/packages/upload/src/utils.ts
index a8e697707f547..477a6cdcdfdcc 100644
--- a/ui/packages/upload/src/utils.ts
+++ b/ui/packages/upload/src/utils.ts
@@ -10,12 +10,32 @@ export function normalise_file(
name: "file_data",
data: file
};
+ } else if (Array.isArray(file)) {
+ for (const x of file) {
+ normalise_file(x, root);
+ }
} else if (file.is_file) {
file.data = root + "file=" + file.name;
+ }
+ return file;
+}
+
+export function normalise_files(
+ file: string | FileData | Array | null,
+ root: string
+): FileData | Array | null {
+ if (file == null) return null;
+ if (typeof file === "string") {
+ return {
+ name: "file_data",
+ data: file
+ };
} else if (Array.isArray(file)) {
for (const x of file) {
normalise_file(x, root);
}
+ } else if (file.is_file) {
+ file.data = root + "file=" + file.name;
}
return file;
}
diff --git a/ui/playwright-setup.js b/ui/playwright-setup.js
index dd78747558536..40bec486c4188 100644
--- a/ui/playwright-setup.js
+++ b/ui/playwright-setup.js
@@ -11,8 +11,8 @@ export default async function global_setup() {
const serve = sirv(template);
const app = polka()
.use(serve)
- .listen("3000", () => {
- console.log(`> Running on localhost: 3000`);
+ .listen("9876", () => {
+ console.log(`> Running on localhost: 9876`);
});
return () => {
diff --git a/ui/pnpm-lock.yaml b/ui/pnpm-lock.yaml
index 1a5b0b69bc596..d5bcaa227d14e 100644
--- a/ui/pnpm-lock.yaml
+++ b/ui/pnpm-lock.yaml
@@ -1,4 +1,4 @@
-lockfileVersion: 5.3
+lockfileVersion: 5.4
importers:
@@ -25,6 +25,7 @@ importers:
postcss: ^8.4.6
postcss-custom-media: '8'
postcss-nested: ^5.0.6
+ postcss-prefix-selector: ^1.16.0
prettier: ^2.6.2
prettier-plugin-css-order: ^1.3.0
prettier-plugin-svelte: ^2.7.0
@@ -46,7 +47,7 @@ importers:
'@tailwindcss/forms': 0.5.0_tailwindcss@3.1.6
'@testing-library/dom': 8.11.3
'@testing-library/svelte': 3.1.0_svelte@3.49.0
- '@testing-library/user-event': 13.5.0_@testing-library+dom@8.11.3
+ '@testing-library/user-event': 13.5.0_gzufz4q333be4gqfrvipwvqt6a
autoprefixer: 10.4.4_postcss@8.4.6
babylonjs: 5.18.0
babylonjs-loaders: 5.18.0
@@ -60,16 +61,17 @@ importers:
postcss: 8.4.6
postcss-custom-media: 8.0.2_postcss@8.4.6
postcss-nested: 5.0.6_postcss@8.4.6
+ postcss-prefix-selector: 1.16.0_postcss@8.4.6
prettier: 2.6.2
- prettier-plugin-css-order: 1.3.0_postcss@8.4.6+prettier@2.6.2
- prettier-plugin-svelte: 2.7.0_prettier@2.6.2+svelte@3.49.0
+ prettier-plugin-css-order: 1.3.0_ob5okuz2s5mlecytbeo2erc43a
+ prettier-plugin-svelte: 2.7.0_3cyj5wbackxvw67rnaarcmbw7y
sirv: 2.0.2
sirv-cli: 2.0.2
svelte: 3.49.0
- svelte-check: 2.8.0_postcss@8.4.6+svelte@3.49.0
+ svelte-check: 2.8.0_mgmdnb6x5rpawk37gozc2sbtta
svelte-i18n: 3.3.13_svelte@3.49.0
- svelte-preprocess: 4.10.6_62d50a01257de5eec5be08cad9d3ed66
- tailwindcss: 3.1.6
+ svelte-preprocess: 4.10.6_mlkquajfpxs65rn6bdfntu7nmy
+ tailwindcss: 3.1.6_postcss@8.4.6
tinyspy: 0.3.0
typescript: 4.7.4
vite: 2.9.9
@@ -115,6 +117,8 @@ importers:
'@gradio/video': workspace:^0.0.1
d3-dsv: ^3.0.1
mime-types: ^2.1.34
+ postcss: ^8.4.21
+ postcss-prefix-selector: ^1.16.0
svelte: ^3.25.1
svelte-i18n: ^3.3.13
dependencies:
@@ -145,6 +149,8 @@ importers:
'@gradio/video': link:../video
d3-dsv: 3.0.1
mime-types: 2.1.34
+ postcss: 8.4.21
+ postcss-prefix-selector: 1.16.0_postcss@8.4.21
svelte: 3.49.0
svelte-i18n: 3.3.13_svelte@3.49.0
@@ -322,7 +328,7 @@ importers:
'@gradio/utils': link:../utils
'@rollup/plugin-json': 5.0.2
plotly.js-dist-min: 2.11.1
- svelte-vega: 1.2.0_vega-lite@5.6.0+vega@5.22.1
+ svelte-vega: 1.2.0_36sthfwhgi34qytpvkzggbhnle
vega: 5.22.1
vega-lite: 5.6.0_vega@5.22.1
@@ -452,14 +458,14 @@ importers:
'@gradio/video': link:../video
svelte: 3.49.0
devDependencies:
- '@sveltejs/adapter-auto': 1.0.0-next.91_@sveltejs+kit@1.0.0-next.318
+ '@sveltejs/adapter-auto': 1.0.0-next.91_b2bjiolq6much32vueqoio7eoy
'@sveltejs/kit': 1.0.0-next.318_svelte@3.49.0
autoprefixer: 10.4.2_postcss@8.4.6
postcss: 8.4.6
postcss-load-config: 3.1.1
- svelte-check: 2.4.1_736abba5ed1eb6f8ecf70b1d49ead14b
- svelte-preprocess: 4.10.2_d50790bb30dd88cc44babe7efa52bace
- tailwindcss: 3.1.6
+ svelte-check: 2.4.1_onvlxjpnd23pr3hxbmout2wrjm
+ svelte-preprocess: 4.10.2_2udzbozq3wemyrf2xz7puuv2zy
+ tailwindcss: 3.1.6_postcss@8.4.6
tslib: 2.3.1
typescript: 4.5.5
@@ -633,7 +639,7 @@ packages:
picomatch: 2.3.1
dev: false
- /@sveltejs/adapter-auto/1.0.0-next.91_@sveltejs+kit@1.0.0-next.318:
+ /@sveltejs/adapter-auto/1.0.0-next.91_b2bjiolq6much32vueqoio7eoy:
resolution: {integrity: sha512-U57tQdzTfFINim8tzZSARC9ztWPzwOoHwNOpGdb2o6XrD0mEQwU9DsII7dBblvzg+xCnmd0pw7PDtXz5c5t96w==}
peerDependencies:
'@sveltejs/kit': ^1.0.0-next.587
@@ -689,7 +695,7 @@ packages:
tailwindcss: '>=3.0.0 || >= 3.0.0-alpha.1'
dependencies:
mini-svg-data-uri: 1.4.4
- tailwindcss: 3.1.6
+ tailwindcss: 3.1.6_postcss@8.4.6
dev: false
/@testing-library/dom/7.31.2:
@@ -730,7 +736,7 @@ packages:
svelte: 3.49.0
dev: false
- /@testing-library/user-event/13.5.0_@testing-library+dom@8.11.3:
+ /@testing-library/user-event/13.5.0_gzufz4q333be4gqfrvipwvqt6a:
resolution: {integrity: sha512-5Kwtbo3Y/NowpkbRuSepbyMFkZmHgD+vPzYB/RJ4oxt5Gj/avFFBYjhw27cqSVPVw/3a67NK1PbiIr9k4Gwmdg==}
engines: {node: '>=10', npm: '>=6'}
peerDependencies:
@@ -2612,25 +2618,25 @@ packages:
postcss-value-parser: 4.2.0
dev: false
- /postcss-import/14.1.0_postcss@8.4.14:
+ /postcss-import/14.1.0_postcss@8.4.6:
resolution: {integrity: sha512-flwI+Vgm4SElObFVPpTIT7SU7R3qk2L7PyduMcokiaVKuWv9d/U+Gm/QAd8NDLuykTWTkcrjOeD2Pp1rMeBTGw==}
engines: {node: '>=10.0.0'}
peerDependencies:
postcss: ^8.0.0
dependencies:
- postcss: 8.4.14
+ postcss: 8.4.6
postcss-value-parser: 4.2.0
read-cache: 1.0.0
resolve: 1.22.1
- /postcss-js/4.0.0_postcss@8.4.14:
+ /postcss-js/4.0.0_postcss@8.4.6:
resolution: {integrity: sha512-77QESFBwgX4irogGVPgQ5s07vLvFqWr228qZY+w6lW599cRlK/HmnlivnnVUxkjHnCu4J16PDMHcH+e+2HbvTQ==}
engines: {node: ^12 || ^14 || >= 16}
peerDependencies:
postcss: ^8.3.3
dependencies:
camelcase-css: 2.0.1
- postcss: 8.4.14
+ postcss: 8.4.6
/postcss-less/6.0.0_postcss@8.4.6:
resolution: {integrity: sha512-FPX16mQLyEjLzEuuJtxA8X3ejDLNGGEG503d2YGZR5Ask1SpDN8KmZUMpzCvyalWRywAn1n1VOA5dcqfCLo5rg==}
@@ -2654,7 +2660,7 @@ packages:
yaml: 1.10.2
dev: true
- /postcss-load-config/3.1.4_postcss@8.4.14:
+ /postcss-load-config/3.1.4_postcss@8.4.6:
resolution: {integrity: sha512-6DiM4E7v4coTE4uzA8U//WhtPwyhiim3eyjEMFCnUpzbrkK9wJHgKDT2mR+HbtSrd/NubVaYTOpSpjUl8NQeRg==}
engines: {node: '>= 10'}
peerDependencies:
@@ -2667,26 +2673,32 @@ packages:
optional: true
dependencies:
lilconfig: 2.0.6
- postcss: 8.4.14
+ postcss: 8.4.6
yaml: 1.10.2
- /postcss-nested/5.0.6_postcss@8.4.14:
+ /postcss-nested/5.0.6_postcss@8.4.6:
resolution: {integrity: sha512-rKqm2Fk0KbA8Vt3AdGN0FB9OBOMDVajMG6ZCf/GoHgdxUJ4sBFp0A/uMIRm+MJUdo33YXEtjqIz8u7DAp8B7DA==}
engines: {node: '>=12.0'}
peerDependencies:
postcss: ^8.2.14
dependencies:
- postcss: 8.4.14
+ postcss: 8.4.6
postcss-selector-parser: 6.0.9
- /postcss-nested/5.0.6_postcss@8.4.6:
- resolution: {integrity: sha512-rKqm2Fk0KbA8Vt3AdGN0FB9OBOMDVajMG6ZCf/GoHgdxUJ4sBFp0A/uMIRm+MJUdo33YXEtjqIz8u7DAp8B7DA==}
- engines: {node: '>=12.0'}
+ /postcss-prefix-selector/1.16.0_postcss@8.4.21:
+ resolution: {integrity: sha512-rdVMIi7Q4B0XbXqNUEI+Z4E+pueiu/CS5E6vRCQommzdQ/sgsS4dK42U7GX8oJR+TJOtT+Qv3GkNo6iijUMp3Q==}
peerDependencies:
- postcss: ^8.2.14
+ postcss: '>4 <9'
+ dependencies:
+ postcss: 8.4.21
+ dev: false
+
+ /postcss-prefix-selector/1.16.0_postcss@8.4.6:
+ resolution: {integrity: sha512-rdVMIi7Q4B0XbXqNUEI+Z4E+pueiu/CS5E6vRCQommzdQ/sgsS4dK42U7GX8oJR+TJOtT+Qv3GkNo6iijUMp3Q==}
+ peerDependencies:
+ postcss: '>4 <9'
dependencies:
postcss: 8.4.6
- postcss-selector-parser: 6.0.9
dev: false
/postcss-scss/4.0.6_postcss@8.4.6:
@@ -2723,6 +2735,15 @@ packages:
picocolors: 1.0.0
source-map-js: 1.0.2
+ /postcss/8.4.21:
+ resolution: {integrity: sha512-tP7u/Sn/dVxK2NnruI4H9BG+x+Wxz6oeZ1cJ8P6G/PZY0IKk4k/63TDsQf2kQq3+qoJeLm2kIBUNlZe3zgb4Zg==}
+ engines: {node: ^10 || ^12 || >=14}
+ dependencies:
+ nanoid: 3.3.4
+ picocolors: 1.0.0
+ source-map-js: 1.0.2
+ dev: false
+
/postcss/8.4.6:
resolution: {integrity: sha512-OovjwIzs9Te46vlEx7+uXB0PLijpwjXGKXjVGGPIGubGpq7uh5Xgf6D6FiJ/SzJMBosHDp6a2hiXOS97iBXcaA==}
engines: {node: ^10 || ^12 || >=14}
@@ -2731,7 +2752,7 @@ packages:
picocolors: 1.0.0
source-map-js: 1.0.2
- /prettier-plugin-css-order/1.3.0_postcss@8.4.6+prettier@2.6.2:
+ /prettier-plugin-css-order/1.3.0_ob5okuz2s5mlecytbeo2erc43a:
resolution: {integrity: sha512-wOS4qlbUARCoiiuOG0TiB/j751soC3+gUnMMva5HVWKvHJdLNYqh+jXK3MvvixR6xkJVPxHSF7rIIhkHIuHTFg==}
engines: {node: '>=14'}
peerDependencies:
@@ -2746,7 +2767,7 @@ packages:
- postcss
dev: false
- /prettier-plugin-svelte/2.7.0_prettier@2.6.2+svelte@3.49.0:
+ /prettier-plugin-svelte/2.7.0_3cyj5wbackxvw67rnaarcmbw7y:
resolution: {integrity: sha512-fQhhZICprZot2IqEyoiUYLTRdumULGRvw0o4dzl5jt0jfzVWdGqeYW27QTWAeXhoupEZJULmNoH3ueJwUWFLIA==}
peerDependencies:
prettier: ^1.16.4 || ^2.0.0
@@ -3158,7 +3179,7 @@ packages:
resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}
engines: {node: '>= 0.4'}
- /svelte-check/2.4.1_736abba5ed1eb6f8ecf70b1d49ead14b:
+ /svelte-check/2.4.1_onvlxjpnd23pr3hxbmout2wrjm:
resolution: {integrity: sha512-xhf3ShP5rnRwBokrgTBJ/0cO9QIc1DAVu1NWNRTfCDsDBNjGmkS3HgitgUadRuoMKj1+irZR/yHJ+Uqobnkbrw==}
hasBin: true
peerDependencies:
@@ -3172,7 +3193,7 @@ packages:
sade: 1.8.1
source-map: 0.7.3
svelte: 3.49.0
- svelte-preprocess: 4.10.2_d50790bb30dd88cc44babe7efa52bace
+ svelte-preprocess: 4.10.2_2udzbozq3wemyrf2xz7puuv2zy
typescript: 4.5.5
transitivePeerDependencies:
- '@babel/core'
@@ -3187,7 +3208,7 @@ packages:
- sugarss
dev: true
- /svelte-check/2.8.0_postcss@8.4.6+svelte@3.49.0:
+ /svelte-check/2.8.0_mgmdnb6x5rpawk37gozc2sbtta:
resolution: {integrity: sha512-HRL66BxffMAZusqe5I5k26mRWQ+BobGd9Rxm3onh7ZVu0nTk8YTKJ9vu3LVPjUGLU9IX7zS+jmwPVhJYdXJ8vg==}
hasBin: true
peerDependencies:
@@ -3200,7 +3221,7 @@ packages:
picocolors: 1.0.0
sade: 1.8.1
svelte: 3.49.0
- svelte-preprocess: 4.10.6_62d50a01257de5eec5be08cad9d3ed66
+ svelte-preprocess: 4.10.6_mlkquajfpxs65rn6bdfntu7nmy
typescript: 4.7.4
transitivePeerDependencies:
- '@babel/core'
@@ -3238,7 +3259,7 @@ packages:
tiny-glob: 0.2.9
dev: false
- /svelte-preprocess/4.10.2_d50790bb30dd88cc44babe7efa52bace:
+ /svelte-preprocess/4.10.2_2udzbozq3wemyrf2xz7puuv2zy:
resolution: {integrity: sha512-aPpkCreSo8EL/y8kJSa1trhiX0oyAtTjlNNM7BNjRAsMJ8Yy2LtqHt0zyd4pQPXt+D4PzbO3qTjjio3kwOxDlA==}
engines: {node: '>= 9.11.2'}
requiresBuild: true
@@ -3291,7 +3312,7 @@ packages:
typescript: 4.5.5
dev: true
- /svelte-preprocess/4.10.6_62d50a01257de5eec5be08cad9d3ed66:
+ /svelte-preprocess/4.10.6_mlkquajfpxs65rn6bdfntu7nmy:
resolution: {integrity: sha512-I2SV1w/AveMvgIQlUF/ZOO3PYVnhxfcpNyGt8pxpUVhPfyfL/CZBkkw/KPfuFix5FJ9TnnNYMhACK3DtSaYVVQ==}
engines: {node: '>= 9.11.2'}
requiresBuild: true
@@ -3347,7 +3368,7 @@ packages:
resolution: {integrity: sha512-VTWHOdwDyWbndGZnI0PQJY9DO7hgQlNubtCcCL6Wlypv5dU4vEsc4A1sX9TWMuvebEe4332SgsQQHzOdZ+guhQ==}
dev: false
- /svelte-vega/1.2.0_vega-lite@5.6.0+vega@5.22.1:
+ /svelte-vega/1.2.0_36sthfwhgi34qytpvkzggbhnle:
resolution: {integrity: sha512-MsDdO+l7o/d9d4mVkh8MBDhqZvJ45lpuprBaTj0V/ZilIG902QERHFQlam3ZFcR9C9OIKSpmPqINssWNPkDdcA==}
peerDependencies:
vega: '*'
@@ -3355,7 +3376,7 @@ packages:
dependencies:
fast-deep-equal: 3.1.3
vega: 5.22.1
- vega-embed: 6.21.0_vega-lite@5.6.0+vega@5.22.1
+ vega-embed: 6.21.0_36sthfwhgi34qytpvkzggbhnle
vega-lite: 5.6.0_vega@5.22.1
dev: false
@@ -3382,10 +3403,12 @@ packages:
resolution: {integrity: sha512-hIdwt/c/e1ONnr2RJmfBxEAj/J6KQQWKdToF3Qw8ZNRsTNNteGkOe63rQy9I7J5UNlr8Yl0wkzIr9wgLY94x0Q==}
dev: false
- /tailwindcss/3.1.6:
+ /tailwindcss/3.1.6_postcss@8.4.6:
resolution: {integrity: sha512-7skAOY56erZAFQssT1xkpk+kWt2NrO45kORlxFPXUt3CiGsVPhH1smuH5XoDH6sGPXLyBv+zgCKA2HWBsgCytg==}
engines: {node: '>=12.13.0'}
hasBin: true
+ peerDependencies:
+ postcss: ^8.0.9
dependencies:
arg: 5.0.2
chokidar: 3.5.3
@@ -3400,11 +3423,11 @@ packages:
normalize-path: 3.0.0
object-hash: 3.0.0
picocolors: 1.0.0
- postcss: 8.4.14
- postcss-import: 14.1.0_postcss@8.4.14
- postcss-js: 4.0.0_postcss@8.4.14
- postcss-load-config: 3.1.4_postcss@8.4.14
- postcss-nested: 5.0.6_postcss@8.4.14
+ postcss: 8.4.6
+ postcss-import: 14.1.0_postcss@8.4.6
+ postcss-js: 4.0.0_postcss@8.4.6
+ postcss-load-config: 3.1.4_postcss@8.4.6
+ postcss-nested: 5.0.6_postcss@8.4.6
postcss-selector-parser: 6.0.10
postcss-value-parser: 4.2.0
quick-lru: 5.1.1
@@ -3556,7 +3579,7 @@ packages:
- encoding
dev: false
- /vega-embed/6.21.0_vega-lite@5.6.0+vega@5.22.1:
+ /vega-embed/6.21.0_36sthfwhgi34qytpvkzggbhnle:
resolution: {integrity: sha512-Tzo9VAfgNRb6XpxSFd7uphSeK2w5OxDY2wDtmpsQ+rQlPSEEI9TE6Jsb2nHRLD5J4FrmXKLrTcORqidsNQSXEg==}
peerDependencies:
vega: ^5.21.0
@@ -3570,7 +3593,7 @@ packages:
vega-interpreter: 1.0.4
vega-lite: 5.6.0_vega@5.22.1
vega-schema-url-parser: 2.2.0
- vega-themes: 2.12.0_vega-lite@5.6.0+vega@5.22.1
+ vega-themes: 2.12.0_36sthfwhgi34qytpvkzggbhnle
vega-tooltip: 0.28.0
dev: false
bundledDependencies:
@@ -3789,7 +3812,7 @@ packages:
d3-array: 3.1.1
dev: false
- /vega-themes/2.12.0_vega-lite@5.6.0+vega@5.22.1:
+ /vega-themes/2.12.0_36sthfwhgi34qytpvkzggbhnle:
resolution: {integrity: sha512-gHNYCzDgexSQDmGzQsxH57OYgFVbAOmvhIYN3MPOvVucyI+zhbUawBVIVNzG9ftucRp0MaaMVXi6ctC5HLnBsg==}
peerDependencies:
vega: '*'
diff --git a/website/homepage/src/docs/v3.17.0_template.html b/website/homepage/src/docs/v3.17.0_template.html
new file mode 100644
index 0000000000000..d28fe186b6843
--- /dev/null
+++ b/website/homepage/src/docs/v3.17.0_template.html
@@ -0,0 +1,41936 @@
+
+
+
+
+ Gradio Docs
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ v3.17.0
+
+
+ main
+
+
+
+
+
+
+
+
+
+
+ โก Quickstart
+
+ โ๏ธ Docs
+
+ ๐ก Guides
+ ๐ข Demos
+
+
๐ Community
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Building Demos
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ hello_world
+
+ hello_world_3
+
+ gpt_j
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+def greet(name):
+ return "Hello " + name + "!"
+
+demo = gr.Interface(fn=greet, inputs="text", outputs="text")
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+def greet(name, is_morning, temperature):
+ salutation = "Good morning" if is_morning else "Good evening"
+ greeting = f"{salutation} {name}. It is {temperature} degrees today"
+ celsius = (temperature - 32) * 5 / 9
+ return greeting, round(celsius, 2)
+
+demo = gr.Interface(
+ fn=greet,
+ inputs=["text", "checkbox", gr.Slider(0, 100)],
+ outputs=["text", "number"],
+)
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+title = "GPT-J-6B"
+
+examples = [
+ ["The tower is 324 metres (1,063 ft) tall,"],
+ ["The Moon's orbit around Earth has"],
+ ["The smooth Borealis basin in the Northern Hemisphere covers 40%"],
+]
+
+demo = gr.Interface.load(
+ "huggingface/EleutherAI/gpt-j-6B",
+ inputs=gr.Textbox(lines=5, max_lines=6, label="Input Text"),
+ title=title,
+ examples=examples,
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
gradio.Interface( fn, inputs, outputs, ยทยทยท)
+
+
+
Interface is Gradio's main high-level class, and allows you to create a web-based GUI / demo around a machine learning model (or any Python function) in a few lines of code. You must specify three parameters: (1) the function to create a GUI for (2) the desired input components and (3) the desired output components. Additional parameters can be used to control the appearance and behavior of the demo.
+
+
+
+
+
Example Usage
+
+
import gradio as gr
+
+def image_classifier(inp):
+ return {'cat': 0.3, 'dog': 0.7}
+
+demo = gr.Interface(fn=image_classifier, inputs="image", outputs="label")
+demo.launch()
+
+
+
+ More Examples โ
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ str | IOComponent | List[str | IOComponent] | None
+
+ required
+
+
+
+ a single Gradio component, or list of Gradio components. Components can either be passed as instantiated objects, or referred to by their string shortcuts. The number of input components should match the number of parameters in fn. If set to None, then only the output components will be displayed.
+
+
+
+
+
+
+
+
+ outputs
+
+ str | IOComponent | List[str | IOComponent] | None
+
+ required
+
+
+
+ a single Gradio component, or list of Gradio components. Components can either be passed as instantiated objects, or referred to by their string shortcuts. The number of output components should match the number of values returned by fn. If set to None, then only the input components will be displayed.
+
+
+
+
+
+
+
+
+ examples
+
+ List[Any] | List[List[Any]] | str | None
+
+ default: None
+
+
+
+ sample inputs for the function; if provided, appear below the UI components and can be clicked to populate the interface. Should be nested list, in which the outer list consists of samples and each inner list consists of an input corresponding to each input component. A string path to a directory of examples can also be provided, but it should be within the directory with the python file running the gradio app. If there are multiple input components and a directory is provided, a log.csv file must be present in the directory to link corresponding inputs.
+
+
+
+
+
+
+
+
+ cache_examples
+
+ bool | None
+
+ default: None
+
+
+
+ If True, caches examples in the server for fast runtime in examples. The default option in HuggingFace Spaces is True. The default option elsewhere is False.
+
+
+
+
+
+
+
+
+ examples_per_page
+
+ int
+
+ default: 10
+
+
+
+ If examples are provided, how many to display per page.
+
+
+
+
+
+
+
+
+ live
+
+ bool
+
+ default: False
+
+
+
+ whether the interface should automatically rerun if any of the inputs change.
+
+
+
+
+
+
+
+
+ interpretation
+
+ Callable | str | None
+
+ default: None
+
+
+
+ function that provides interpretation explaining prediction output. Pass "default" to use simple built-in interpreter, "shap" to use a built-in shapley-based interpreter, or your own custom interpretation function. For more information on the different interpretation methods, see the Advanced Interface Features guide.
+
+
+
+
+
+
+
+
+ num_shap
+
+ float
+
+ default: 2.0
+
+
+
+ a multiplier that determines how many examples are computed for shap-based interpretation. Increasing this value will increase shap runtime, but improve results. Only applies if interpretation is "shap".
+
+
+
+
+
+
+
+
+ title
+
+ str | None
+
+ default: None
+
+
+
+ a title for the interface; if provided, appears above the input and output components in large font. Also used as the tab title when opened in a browser window.
+
+
+
+
+
+
+
+
+ description
+
+ str | None
+
+ default: None
+
+
+
+ a description for the interface; if provided, appears above the input and output components and beneath the title in regular font. Accepts Markdown and HTML content.
+
+
+
+
+
+
+
+
+ article
+
+ str | None
+
+ default: None
+
+
+
+ an expanded article explaining the interface; if provided, appears below the input and output components in regular font. Accepts Markdown and HTML content.
+
+
+
+
+
+
+
+
+ thumbnail
+
+ str | None
+
+ default: None
+
+
+
+ path or url to image to use as display image when the web demo is shared on social media.
+
+
+
+
+
+
+
+
+ theme
+
+ str
+
+ default: "default"
+
+
+
+ Theme to use - right now, only "default" is supported. Can be set with the GRADIO_THEME environment variable.
+
+
+
+
+
+
+
+
+ css
+
+ str | None
+
+ default: None
+
+
+
+ custom css or path to custom css file to use with interface.
+
+
+
+
+
+
+
+
+ allow_flagging
+
+ str | None
+
+ default: None
+
+
+
+ one of "never", "auto", or "manual". If "never" or "auto", users will not see a button to flag an input and output. If "manual", users will see a button to flag. If "auto", every input the user submits will be automatically flagged (outputs are not flagged). If "manual", both the input and outputs are flagged when the user clicks flag button. This parameter can be set with environmental variable GRADIO_ALLOW_FLAGGING; otherwise defaults to "manual".
+
+
+
+
+
+
+
+
+ flagging_options
+
+ List[str] | None
+
+ default: None
+
+
+
+ if provided, allows user to select from the list of options when flagging. Only applies if allow_flagging is "manual".
+
+
+
+
+
+
+
+
+ flagging_dir
+
+ str
+
+ default: "flagged"
+
+
+
+ what to name the directory where flagged data is stored.
+
+
+
+
+
+
+
+
+ flagging_callback
+
+ FlaggingCallback
+
+ default: CSVLogger()
+
+
+
+ An instance of a subclass of FlaggingCallback which will be called when a sample is flagged. By default logs to a local CSV file.
+
+
+
+
+
+
+
+
+ analytics_enabled
+
+ bool | None
+
+ default: None
+
+
+
+ Whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable if defined, or default to True.
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Interface.launch( ยทยทยท)
+
+
+
Launches a simple web server that serves the demo. Can also be used to create a public link used by anyone to access the demo from their browser by setting share=True.
+
+
+
+
+
Example Usage
+
+
import gradio as gr
+def reverse(text):
+ return text[::-1]
+demo = gr.Interface(reverse, "text", "text")
+demo.launch(share=True, auth=("username", "password"))
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ inline
+
+ bool | None
+
+ default: None
+
+
+
+ whether to display in the interface inline in an iframe. Defaults to True in python notebooks; False otherwise.
+
+
+
+
+
+
+
+
+ inbrowser
+
+ bool
+
+ default: False
+
+
+
+ whether to automatically launch the interface in a new tab on the default browser.
+
+
+
+
+
+
+
+
+ share
+
+ bool | None
+
+ default: None
+
+
+
+ whether to create a publicly shareable link for the interface. Creates an SSH tunnel to make your UI accessible from anywhere. If not provided, it is set to False by default every time, except when running in Google Colab. When localhost is not accessible (e.g. Google Colab), setting share=False is not supported.
+
+
+
+
+
+
+
+
+ debug
+
+ bool
+
+ default: False
+
+
+
+ if True, blocks the main thread from running. If running in Google Colab, this is needed to print the errors in the cell output.
+
+
+
+
+
+
+
+
+ enable_queue
+
+ bool | None
+
+ default: None
+
+
+
+ DEPRECATED (use .queue() method instead.) if True, inference requests will be served through a queue instead of with parallel threads. Required for longer inference times (> 1min) to prevent timeout. The default option in HuggingFace Spaces is True. The default option elsewhere is False.
+
+
+
+
+
+
+
+
+ max_threads
+
+ int
+
+ default: 40
+
+
+
+ the maximum number of total threads that the Gradio app can generate in parallel. The default is inherited from the starlette library (currently 40). Applies whether the queue is enabled or not. But if queuing is enabled, this parameter is increaseed to be at least the concurrency_count of the queue.
+
+
+
+
+
+
+
+
+ auth
+
+ Callable | Tuple[str, str] | List[Tuple[str, str]] | None
+
+ default: None
+
+
+
+ If provided, username and password (or list of username-password tuples) required to access interface. Can also provide function that takes username and password and returns True if valid login.
+
+
+
+
+
+
+
+
+ auth_message
+
+ str | None
+
+ default: None
+
+
+
+ If provided, HTML message provided on login page.
+
+
+
+
+
+
+
+
+ prevent_thread_lock
+
+ bool
+
+ default: False
+
+
+
+ If True, the interface will block the main thread while the server is running.
+
+
+
+
+
+
+
+
+ show_error
+
+ bool
+
+ default: False
+
+
+
+ If True, any errors in the interface will be displayed in an alert modal and printed in the browser console log
+
+
+
+
+
+
+
+
+ server_name
+
+ str | None
+
+ default: None
+
+
+
+ to make app accessible on local network, set this to "0.0.0.0". Can be set by environment variable GRADIO_SERVER_NAME. If None, will use "127.0.0.1".
+
+
+
+
+
+
+
+
+ server_port
+
+ int | None
+
+ default: None
+
+
+
+ will start gradio app on this port (if available). Can be set by environment variable GRADIO_SERVER_PORT. If None, will search for an available port starting at 7860.
+
+
+
+
+
+
+
+
+ show_tips
+
+ bool
+
+ default: False
+
+
+
+ if True, will occasionally show tips about new Gradio features
+
+
+
+
+
+
+
+
+ height
+
+ int
+
+ default: 500
+
+
+
+ The height in pixels of the iframe element containing the interface (used if inline=True)
+
+
+
+
+
+
+
+
+ width
+
+ int | str
+
+ default: "100%"
+
+
+
+ The width in pixels of the iframe element containing the interface (used if inline=True)
+
+
+
+
+
+
+
+
+ encrypt
+
+ bool
+
+ default: False
+
+
+
+ If True, flagged data will be encrypted by key provided by creator at launch
+
+
+
+
+
+
+
+
+ favicon_path
+
+ str | None
+
+ default: None
+
+
+
+ If a path to a file (.png, .gif, or .ico) is provided, it will be used as the favicon for the web page.
+
+
+
+
+
+
+
+
+ ssl_keyfile
+
+ str | None
+
+ default: None
+
+
+
+ If a path to a file is provided, will use this as the private key file to create a local server running on https.
+
+
+
+
+
+
+
+
+ ssl_certfile
+
+ str | None
+
+ default: None
+
+
+
+ If a path to a file is provided, will use this as the signed certificate for https. Needs to be provided if ssl_keyfile is provided.
+
+
+
+
+
+
+
+
+ ssl_keyfile_password
+
+ str | None
+
+ default: None
+
+
+
+ If a password is provided, will use this with the ssl certificate for https.
+
+
+
+
+
+
+
+
+ quiet
+
+ bool
+
+ default: False
+
+
+
+ If True, suppresses most print statements.
+
+
+
+
+
+
+
+
+ show_api
+
+ bool
+
+ default: True
+
+
+
+ If True, shows the api docs in the footer of the app. Default True. If the queue is enabled, then api_open parameter of .queue() will determine if the api docs are shown, independent of the value of show_api.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Interface.load( name, ยทยทยท)
+
+
+
Class method that constructs an Interface from a Hugging Face repo. Can accept model repos (if src is "models") or Space repos (if src is "spaces"). The input and output components are automatically loaded from the repo.
+
+
+
+
+
Example Usage
+
+
import gradio as gr
+description = "Story generation with GPT"
+examples = [["An adventurer is approached by a mysterious stranger in the tavern for a new quest."]]
+demo = gr.Interface.load("models/EleutherAI/gpt-neo-1.3B", description=description, examples=examples)
+demo.launch()
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+ name
+
+ str
+
+ required
+
+
+
+ the name of the model (e.g. "gpt2" or "facebook/bart-base") or space (e.g. "flax-community/spanish-gpt2"), can include the `src` as prefix (e.g. "models/facebook/bart-base")
+
+
+
+
+
+
+
+
+ src
+
+ str | None
+
+ default: None
+
+
+
+ the source of the model: `models` or `spaces` (or leave empty if source is provided as a prefix in `name`)
+
+
+
+
+
+
+
+
+ api_key
+
+ str | None
+
+ default: None
+
+
+
+ optional access token for loading private Hugging Face Hub models or spaces. Find your token here: https://huggingface.co/settings/tokens
+
+
+
+
+
+
+
+
+ alias
+
+ str | None
+
+ default: None
+
+
+
+ optional string used as the name of the loaded model instead of the default name (only applies if loading a Space running Gradio 2.x)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Interface.from_pipeline( pipeline, ยทยทยท)
+
+
+
Class method that constructs an Interface from a Hugging Face transformers.Pipeline object. The input and output components are automatically determined from the pipeline.
+
+
+
+
+
Example Usage
+
+
import gradio as gr
+from transformers import pipeline
+pipe = pipeline("image-classification")
+gr.Interface.from_pipeline(pipe).launch()
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+ pipeline
+
+ Pipeline
+
+ required
+
+
+
+ the pipeline object to use.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Interface.integrate( ยทยทยท)
+
+
+
A catch-all method for integrating with other libraries. This method should be run after launch()
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ comet_ml
+
+ comet_ml.Experiment | None
+
+ default: None
+
+
+
+ If a comet_ml Experiment object is provided, will integrate with the experiment and appear on Comet dashboard
+
+
+
+
+
+
+
+
+ wandb
+
+ ModuleType | None
+
+ default: None
+
+
+
+ If the wandb module is provided, will integrate with it and appear on WandB dashboard
+
+
+
+
+
+
+
+
+ mlflow
+
+ ModuleType | None
+
+ default: None
+
+
+
+ If the mlflow module is provided, will integrate with the experiment and appear on ML Flow dashboard
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Interface.queue( ยทยทยท)
+
+
+
You can control the rate of processed requests by creating a queue. This will allow you to set the number of requests to be processed at one time, and will let users know their position in the queue.
+
+
+
+
+
Example Usage
+
+
demo = gr.Interface(gr.Textbox(), gr.Image(), image_generator)
+demo.queue(concurrency_count=3)
+demo.launch()
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ concurrency_count
+
+ int
+
+ default: 1
+
+
+
+ Number of worker threads that will be processing requests from the queue concurrently. Increasing this number will increase the rate at which requests are processed, but will also increase the memory usage of the queue.
+
+
+
+
+
+
+
+
+ status_update_rate
+
+ float | Literal['auto']
+
+ default: "auto"
+
+
+
+ If "auto", Queue will send status estimations to all clients whenever a job is finished. Otherwise Queue will send status at regular intervals set by this parameter as the number of seconds.
+
+
+
+
+
+
+
+
+ client_position_to_load_data
+
+ int | None
+
+ default: None
+
+
+
+ DEPRECATED. This parameter is deprecated and has no effect.
+
+
+
+
+
+
+
+
+ default_enabled
+
+ bool | None
+
+ default: None
+
+
+
+ Deprecated and has no effect.
+
+
+
+
+
+
+
+
+ api_open
+
+ bool
+
+ default: True
+
+
+
+ If True, the REST routes of the backend will be open, allowing requests made directly to those endpoints to skip the queue.
+
+
+
+
+
+
+
+
+ max_size
+
+ int | None
+
+ default: None
+
+
+
+ The maximum number of events the queue will store at any given moment. If the queue is full, new events will not be added and a user will receive a message saying that the queue is full. If None, the queue size will be unlimited.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
+
+
+
+
+
+
+
+
+
+ Flagging
+
+
+ A Gradio Interface includes a "Flag" button that appears
+ underneath the output. By default, clicking on the Flag button sends the input and output
+ data back to the machine where the gradio demo is running, and saves it to a CSV log file.
+ But this default behavior can be changed. To set what happens when the Flag button is clicked,
+ you pass an instance of a subclass of FlaggingCallback to the flagging_callback parameter
+ in the Interface constructor. You can use one of the FlaggingCallback subclasses
+ that are listed below, or you can create your own, which lets you do whatever
+ you want with the data that is being flagged.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.SimpleCSVLogger( ยทยทยท)
+
+
+
A simplified implementation of the FlaggingCallback abstract class provided for illustrative purposes. Each flagged sample (both the input and output data) is logged to a CSV file on the machine running the gradio app.
+
+
+
+
+
Example Usage
+
+
import gradio as gr
+def image_classifier(inp):
+ return {'cat': 0.3, 'dog': 0.7}
+demo = gr.Interface(fn=image_classifier, inputs="image", outputs="label",
+ flagging_callback=SimpleCSVLogger())
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about SimpleCSVLogger
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
The default implementation of the FlaggingCallback abstract class. Each flagged sample (both the input and output data) is logged to a CSV file with headers on the machine running the gradio app.
+
+
+
+
+
Example Usage
+
+
import gradio as gr
+def image_classifier(inp):
+ return {'cat': 0.3, 'dog': 0.7}
+demo = gr.Interface(fn=image_classifier, inputs="image", outputs="label",
+ flagging_callback=CSVLogger())
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about CSVLogger
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.HuggingFaceDatasetSaver( hf_token, dataset_name, ยทยทยท)
+
+
+
A callback that saves each flagged sample (both the input and output data) to a HuggingFace dataset.
+
+
+
+
+
Example Usage
+
+
import gradio as gr
+hf_writer = gr.HuggingFaceDatasetSaver(HF_API_TOKEN, "image-classification-mistakes")
+def image_classifier(inp):
+ return {'cat': 0.3, 'dog': 0.7}
+demo = gr.Interface(fn=image_classifier, inputs="image", outputs="label",
+ allow_flagging="manual", flagging_callback=hf_writer)
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ hf_token
+
+ str
+
+ required
+
+
+
+ The HuggingFace token to use to create (and write the flagged sample to) the HuggingFace dataset.
+
+
+
+
+
+
+
+
+ dataset_name
+
+ str
+
+ required
+
+
+
+ The name of the dataset to save the data to, e.g. "image-classifier-1"
+
+
+
+
+
+
+
+
+ organization
+
+ str | None
+
+ default: None
+
+
+
+ The organization to save the dataset under. The hf_token must provide write access to this organization. If not provided, saved under the name of the user corresponding to the hf_token.
+
+
+
+
+
+
+
+
+ private
+
+ bool
+
+ default: False
+
+
+
+ Whether the dataset should be private (defaults to False).
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about HuggingFaceDatasetSaver
+
+
+
+
+
+
+
+
+
+
+
+ Combining Interfaces
+
+
+ Once you have created several Interfaces, we provide several classes that let you
+ start combining them together. For example, you can chain them in Series
+ or compare their outputs in Parallel if the inputs and outputs match accordingly.
+ You can also display arbitrary Interfaces together in a tabbed layout using TabbedInterface .
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ stt_or_tts
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+title = "GPT-J-6B"
+
+tts_examples = [
+ "I love learning machine learning",
+ "How do you do?",
+]
+
+tts_demo = gr.Interface.load(
+ "huggingface/facebook/fastspeech2-en-ljspeech",
+ title=None,
+ examples=tts_examples,
+ description="Give me something to say!",
+)
+
+stt_demo = gr.Interface.load(
+ "huggingface/facebook/wav2vec2-base-960h",
+ title=None,
+ inputs="mic",
+ description="Let me try to guess what you're saying!",
+)
+
+demo = gr.TabbedInterface([tts_demo, stt_demo], ["Text-to-speech", "Speech-to-text"])
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
gradio.TabbedInterface( interface_list, ยทยทยท)
+
+
+
A TabbedInterface is created by providing a list of Interfaces, each of which gets rendered in a separate tab.
+
+
+
+
+
+
+
import gradio as gr
+
+title = "GPT-J-6B"
+
+tts_examples = [
+ "I love learning machine learning",
+ "How do you do?",
+]
+
+tts_demo = gr.Interface.load(
+ "huggingface/facebook/fastspeech2-en-ljspeech",
+ title=None,
+ examples=tts_examples,
+ description="Give me something to say!",
+)
+
+stt_demo = gr.Interface.load(
+ "huggingface/facebook/wav2vec2-base-960h",
+ title=None,
+ inputs="mic",
+ description="Let me try to guess what you're saying!",
+)
+
+demo = gr.TabbedInterface([tts_demo, stt_demo], ["Text-to-speech", "Speech-to-text"])
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ interface_list
+
+ List[Interface]
+
+ required
+
+
+
+ a list of interfaces to be rendered in tabs.
+
+
+
+
+
+
+
+
+ tab_names
+
+ List[str] | None
+
+ default: None
+
+
+
+ a list of tab names. If None, the tab names will be "Tab 1", "Tab 2", etc.
+
+
+
+
+
+
+
+
+ title
+
+ str | None
+
+ default: None
+
+
+
+ a title for the interface; if provided, appears above the input and output components in large font. Also used as the tab title when opened in a browser window.
+
+
+
+
+
+
+
+
+ theme
+
+ str
+
+ default: "default"
+
+
+
+ which theme to use - right now, only "default" is supported.
+
+
+
+
+
+
+
+
+ analytics_enabled
+
+ bool | None
+
+ default: None
+
+
+
+ whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable or default to True.
+
+
+
+
+
+
+
+
+ css
+
+ str | None
+
+ default: None
+
+
+
+ custom css or path to custom css file to apply to entire Blocks
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ interface_parallel
+
+ interface_parallel_load
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+greeter_1 = gr.Interface(lambda name: f"Hello {name}!", inputs="textbox", outputs=gr.Textbox(label="Greeter 1"))
+greeter_2 = gr.Interface(lambda name: f"Greetings {name}!", inputs="textbox", outputs=gr.Textbox(label="Greeter 2"))
+demo = gr.Parallel(greeter_1, greeter_2)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+generator1 = gr.Interface.load("huggingface/gpt2")
+generator2 = gr.Interface.load("huggingface/EleutherAI/gpt-neo-2.7B")
+generator3 = gr.Interface.load("huggingface/EleutherAI/gpt-j-6B")
+
+demo = gr.Parallel(generator1, generator2, generator3)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
gradio.Parallel( interfaces, ยทยทยท)
+
+
+
Creates a new Interface consisting of multiple Interfaces in parallel (comparing their outputs). The Interfaces to put in Parallel must share the same input components (but can have different output components).
+
+
+
+
+
+
+
import gradio as gr
+
+greeter_1 = gr.Interface(lambda name: f"Hello {name}!", inputs="textbox", outputs=gr.Textbox(label="Greeter 1"))
+greeter_2 = gr.Interface(lambda name: f"Greetings {name}!", inputs="textbox", outputs=gr.Textbox(label="Greeter 2"))
+demo = gr.Parallel(greeter_1, greeter_2)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ interfaces
+
+
+
+ required
+
+
+
+ any number of Interface objects that are to be compared in parallel
+
+
+
+
+
+
+
+
+ options
+
+
+
+
+
+ additional kwargs that are passed into the new Interface object to customize it
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Parallel
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ interface_series
+
+ interface_series_load
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+get_name = gr.Interface(lambda name: name, inputs="textbox", outputs="textbox")
+prepend_hello = gr.Interface(lambda name: f"Hello {name}!", inputs="textbox", outputs="textbox")
+append_nice = gr.Interface(lambda greeting: f"{greeting} Nice to meet you!",
+ inputs="textbox", outputs=gr.Textbox(label="Greeting"))
+demo = gr.Series(get_name, prepend_hello, append_nice)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+generator = gr.Interface.load("huggingface/gpt2")
+translator = gr.Interface.load("huggingface/t5-small")
+
+demo = gr.Series(generator, translator, description="This demo combines two Spaces: a text generator (`huggingface/gpt2`) and a text translator (`huggingface/t5-small`). The first Space takes a prompt as input and generates a text. The second Space takes the generated text as input and translates it into another language.")
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
gradio.Series( interfaces, ยทยทยท)
+
+
+
Creates a new Interface from multiple Interfaces in series (the output of one is fed as the input to the next, and so the input and output components must agree between the interfaces).
+
+
+
+
+
+
+
import gradio as gr
+
+get_name = gr.Interface(lambda name: name, inputs="textbox", outputs="textbox")
+prepend_hello = gr.Interface(lambda name: f"Hello {name}!", inputs="textbox", outputs="textbox")
+append_nice = gr.Interface(lambda greeting: f"{greeting} Nice to meet you!",
+ inputs="textbox", outputs=gr.Textbox(label="Greeting"))
+demo = gr.Series(get_name, prepend_hello, append_nice)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ interfaces
+
+
+
+ required
+
+
+
+ any number of Interface objects that are to be connected in series
+
+
+
+
+
+
+
+
+ options
+
+
+
+
+
+ additional kwargs that are passed into the new Interface object to customize it
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Series
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ blocks_hello
+
+ blocks_flipper
+
+ blocks_speech_text_sentiment
+
+ generate_english_german
+
+ sound_alert
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+def welcome(name):
+ return f"Welcome to Gradio, {name}!"
+
+with gr.Blocks() as demo:
+ gr.Markdown(
+ """
+ # Hello World!
+ Start typing below to see the output.
+ """)
+ inp = gr.Textbox(placeholder="What is your name?")
+ out = gr.Textbox()
+ inp.change(welcome, inp, out)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
import numpy as np
+import gradio as gr
+
+def flip_text(x):
+ return x[::-1]
+
+def flip_image(x):
+ return np.fliplr(x)
+
+with gr.Blocks() as demo:
+ gr.Markdown("Flip text or image files using this demo.")
+ with gr.Tab("Flip Text"):
+ text_input = gr.Textbox()
+ text_output = gr.Textbox()
+ text_button = gr.Button("Flip")
+ with gr.Tab("Flip Image"):
+ with gr.Row():
+ image_input = gr.Image()
+ image_output = gr.Image()
+ image_button = gr.Button("Flip")
+
+ with gr.Accordion("Open for More!"):
+ gr.Markdown("Look at me...")
+
+ text_button.click(flip_text, inputs=text_input, outputs=text_output)
+ image_button.click(flip_image, inputs=image_input, outputs=image_output)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
from transformers import pipeline
+
+import gradio as gr
+
+asr = pipeline("automatic-speech-recognition", "facebook/wav2vec2-base-960h")
+classifier = pipeline("text-classification")
+
+
+def speech_to_text(speech):
+ text = asr(speech)["text"]
+ return text
+
+
+def text_to_sentiment(text):
+ return classifier(text)[0]["label"]
+
+
+demo = gr.Blocks()
+
+with demo:
+ audio_file = gr.Audio(type="filepath")
+ text = gr.Textbox()
+ label = gr.Label()
+
+ b1 = gr.Button("Recognize Speech")
+ b2 = gr.Button("Classify Sentiment")
+
+ b1.click(speech_to_text, inputs=audio_file, outputs=text)
+ b2.click(text_to_sentiment, inputs=text, outputs=label)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+from transformers import pipeline
+
+english_translator = gr.Blocks.load(name="spaces/gradio/english_translator")
+english_generator = pipeline("text-generation", model="distilgpt2")
+
+
+def generate_text(text):
+ english_text = english_generator(text)[0]["generated_text"]
+ german_text = english_translator(english_text)
+ return english_text, german_text
+
+
+with gr.Blocks() as demo:
+ with gr.Row():
+ with gr.Column():
+ seed = gr.Text(label="Input Phrase")
+ with gr.Column():
+ english = gr.Text(label="Generated English Text")
+ german = gr.Text(label="Generated German Text")
+ btn = gr.Button("Generate")
+ btn.click(generate_text, inputs=[seed], outputs=[english, german])
+ gr.Examples(["My name is Clara and I am"], inputs=[seed])
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
import time
+import gradio as gr
+
+
+js_function = "() => {new Audio('file=beep.mp3').play();}"
+
+def task(x):
+ time.sleep(2)
+ return "Hello, " + x
+
+with gr.Blocks() as demo:
+ name = gr.Textbox(label="name")
+ greeting = gr.Textbox(label="greeting")
+ name.blur(task, name, greeting)
+ greeting.change(None, [], [], _js=js_function) # Note that _js is a special arugment whose usage may change in the future
+
+demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
Blocks is Gradio's low-level API that allows you to create more custom web applications and demos than Interfaces (yet still entirely in Python). Compared to the Interface class, Blocks offers more flexibility and control over: (1) the layout of components (2) the events that trigger the execution of functions (3) data flows (e.g. inputs can trigger outputs, which can trigger the next level of outputs). Blocks also offers ways to group together related demos such as with tabs. The basic usage of Blocks is as follows: create a Blocks object, then use it as a context (with the "with" statement), and then define layouts, components, or events within the Blocks context. Finally, call the launch() method to launch the demo.
+
+
+
+
+
Example Usage
+
+
import gradio as gr
+def update(name):
+ return f"Welcome to Gradio, {name}!"
+
+with gr.Blocks() as demo:
+ gr.Markdown("Start typing below and then click **Run** to see the output.")
+ with gr.Row():
+ inp = gr.Textbox(placeholder="What is your name?")
+ out = gr.Textbox()
+ btn = gr.Button("Run")
+ btn.click(fn=update, inputs=inp, outputs=out)
+
+demo.launch()
+
+
+
+ More Examples โ
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ theme
+
+ str
+
+ default: "default"
+
+
+
+ which theme to use - right now, only "default" is supported.
+
+
+
+
+
+
+
+
+ analytics_enabled
+
+ bool | None
+
+ default: None
+
+
+
+ whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable or default to True.
+
+
+
+
+
+
+
+
+ mode
+
+ str
+
+ default: "blocks"
+
+
+
+ a human-friendly name for the kind of Blocks or Interface being created.
+
+
+
+
+
+
+
+
+ title
+
+ str
+
+ default: "Gradio"
+
+
+
+ The tab title to display when this is opened in a browser window.
+
+
+
+
+
+
+
+
+ css
+
+ str | None
+
+ default: None
+
+
+
+ custom css or path to custom css file to apply to entire Blocks
+
+
+
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Blocks.load( ยทยทยท)
+
+
+
For reverse compatibility reasons, this is both a class method and an instance method, the two of which, confusingly, do two completely different things. Class method: loads a demo from a Hugging Face Spaces repo and creates it locally and returns a block instance. Equivalent to gradio.Interface.load() Instance method: adds event that runs as soon as the demo loads in the browser. Example usage below.
+
+
+
+
+
Example Usage
+
+
import gradio as gr
+import datetime
+with gr.Blocks() as demo:
+ def get_time():
+ return datetime.datetime.now().time()
+ dt = gr.Textbox(label="Current time")
+ demo.load(get_time, inputs=None, outputs=dt)
+demo.launch()
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ default: None
+
+
+
+ Instance Method - the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ List[Component] | None
+
+ default: None
+
+
+
+ Instance Method - List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ List[Component] | None
+
+ default: None
+
+
+
+ Instance Method - List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Instance Method - Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ Instance Method - If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ Instance Method - If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+
+
+ default: None
+
+
+
+ Instance Method - If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ Instance Method - If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Instance Method - Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ Instance Method - If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ Instance Method - If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Instance Method - Run this event 'every' number of seconds. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+ name
+
+ str | None
+
+ default: None
+
+
+
+ Class Method - the name of the model (e.g. "gpt2" or "facebook/bart-base") or space (e.g. "flax-community/spanish-gpt2"), can include the `src` as prefix (e.g. "models/facebook/bart-base")
+
+
+
+
+
+
+
+
+ src
+
+ str | None
+
+ default: None
+
+
+
+ Class Method - the source of the model: `models` or `spaces` (or leave empty if source is provided as a prefix in `name`)
+
+
+
+
+
+
+
+
+ api_key
+
+ str | None
+
+ default: None
+
+
+
+ Class Method - optional access token for loading private Hugging Face Hub models or spaces. Find your token here: https://huggingface.co/settings/tokens
+
+
+
+
+
+
+
+
+ alias
+
+ str | None
+
+ default: None
+
+
+
+ Class Method - optional string used as the name of the loaded model instead of the default name (only applies if loading a Space running Gradio 2.x)
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Blocks
+
+
+
+
+
+
+
+
+
+
+ Block Layouts
+
+
+ Customize the layout of your Blocks UI with the layout classes below.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Row is a layout element within Blocks that renders all children horizontally.
+
+
+
+
+
Example Usage
+
+
with gradio.Blocks() as demo:
+ with gradio.Row():
+ gr.Image("lion.jpg")
+ gr.Image("tiger.jpg")
+demo.launch()
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ variant
+
+ str
+
+ default: "default"
+
+
+
+ row type, 'default' (no background), 'panel' (gray background color and rounded corners), or 'compact' (rounded corners and no internal gap).
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, row will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Row
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Column
+
+
+
+
+
+
+
+
+
Column is a layout element within Blocks that renders all children vertically. The widths of columns can be set through the `scale` and `min_width` parameters. If a certain scale results in a column narrower than min_width, the min_width parameter will win.
+
+
+
+
+
Example Usage
+
+
with gradio.Blocks() as demo:
+ with gradio.Row():
+ with gradio.Column(scale=1):
+ text1 = gr.Textbox()
+ text2 = gr.Textbox()
+ with gradio.Column(scale=4):
+ btn1 = gr.Button("Button 1")
+ btn2 = gr.Button("Button 2")
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ scale
+
+ int
+
+ default: 1
+
+
+
+ relative width compared to adjacent Columns. For example, if Column A has scale=2, and Column B has scale=1, A will be twice as wide as B.
+
+
+
+
+
+
+
+
+ min_width
+
+ int
+
+ default: 320
+
+
+
+ minimum pixel width of Column, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in a column narrower than min_width, the min_width parameter will be respected first.
+
+
+
+
+
+
+
+
+ variant
+
+ str
+
+ default: "default"
+
+
+
+ column type, 'default' (no background), 'panel' (gray background color and rounded corners), or 'compact' (rounded corners and no internal gap).
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, column will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Column
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Tab (or its alias TabItem) is a layout element. Components defined within the Tab will be visible when this tab is selected tab.
+
+
+
+
+
Example Usage
+
+
with gradio.Blocks() as demo:
+ with gradio.Tab("Lion"):
+ gr.Image("lion.jpg")
+ gr.Button("New Lion")
+ with gradio.Tab("Tiger"):
+ gr.Image("tiger.jpg")
+ gr.Button("New Tiger")
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ label
+
+ str
+
+ required
+
+
+
+ The visual label for the tab
+
+
+
+
+
+
+
+
+ id
+
+ int | str | None
+
+ default: None
+
+
+
+ An optional identifier for the tab, required if you wish to control the selected tab from a predict function.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Tab
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Box is a a layout element which places children in a box with rounded corners and some padding around them.
+
+
+
+
+
Example Usage
+
+
with gradio.Box():
+ gr.Textbox(label="First")
+ gr.Textbox(label="Last")
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, box will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Box
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Accordion( label, ยทยทยท)
+
+
+
Accordion is a layout element which can be toggled to show/hide the contained content.
+
+
+
+
+
Example Usage
+
+
with gradio.Accordion("See Details"):
+ gr.Markdown("lorem ipsum")
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ label
+
+
+
+ required
+
+
+
+ name of accordion section.
+
+
+
+
+
+
+
+
+ open
+
+ bool
+
+ default: True
+
+
+
+ if True, accordion is open by default.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Accordion
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Gradio includes pre-built components that can be used as
+ inputs or outputs in your Interface or Blocks with a single line of code. Components
+ include preprocessing steps that convert user data submitted through browser
+ to something that be can used by a Python function, and postprocessing
+ steps to convert values returned by a Python function into something that can be displayed in a browser.
+
+
+ Consider an example with three inputs (Textbox, Number, and Image) and two outputs
+ (Number and Gallery), below is a diagram of what our preprocessing will send to the function and what
+ our postprocessing will require from it.
+
+
+
+ Components also come with certain events that they support. These are methods that are triggered with user actions.
+ Below is a table showing which events are supported for each component. All events are also listed (with parameters) in the component's docs.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ hello_world
+
+ diff_texts
+
+ sentence_builder
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+def greet(name):
+ return "Hello " + name + "!"
+
+demo = gr.Interface(fn=greet, inputs="text", outputs="text")
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
from difflib import Differ
+
+import gradio as gr
+
+
+def diff_texts(text1, text2):
+ d = Differ()
+ return [
+ (token[2:], token[0] if token[0] != " " else None)
+ for token in d.compare(text1, text2)
+ ]
+
+
+demo = gr.Interface(
+ diff_texts,
+ [
+ gr.Textbox(
+ label="Initial text",
+ lines=3,
+ value="The quick brown fox jumped over the lazy dogs.",
+ ),
+ gr.Textbox(
+ label="Text to compare",
+ lines=3,
+ value="The fast brown fox jumps over lazy dogs.",
+ ),
+ ],
+ gr.HighlightedText(
+ label="Diff",
+ combine_adjacent=True,
+ ).style(color_map={"+": "red", "-": "green"}),
+)
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+
+def sentence_builder(quantity, animal, place, activity_list, morning):
+ return f"""The {quantity} {animal}s went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""
+
+
+demo = gr.Interface(
+ sentence_builder,
+ [
+ gr.Slider(2, 20, value=4),
+ gr.Dropdown(["cat", "dog", "bird"]),
+ gr.Radio(["park", "zoo", "road"]),
+ gr.Dropdown(["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True),
+ gr.Checkbox(label="Is it the morning?"),
+ ],
+ "text",
+ examples=[
+ [2, "cat", "park", ["ran", "swam"], True],
+ [4, "dog", "zoo", ["ate", "swam"], False],
+ [10, "bird", "road", ["ran"], False],
+ [8, "cat", "zoo", ["ate"], True],
+ ],
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Creates a textarea for user to enter string input or display string output.
+
+
+
As input: passes textarea value as a str into the function.
+
As output: expects a str returned from function and sets textarea value to it.
+
+
Format expected for examples: a str representing the textbox input.
+
+
+
Supported events: change(), submit(), blur()
+
+
+
+
+
+
+
import gradio as gr
+
+def greet(name):
+ return "Hello " + name + "!"
+
+demo = gr.Interface(fn=greet, inputs="text", outputs="text")
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ value
+
+ str | Callable | None
+
+ default: ""
+
+
+
+ default text to provide in textarea. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ lines
+
+ int
+
+ default: 1
+
+
+
+ minimum number of line rows to provide in textarea.
+
+
+
+
+
+
+
+
+ max_lines
+
+ int
+
+ default: 20
+
+
+
+ maximum number of line rows to provide in textarea.
+
+
+
+
+
+
+
+
+ placeholder
+
+ str | None
+
+ default: None
+
+
+
+ placeholder hint to provide behind textarea.
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ component name in interface.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ if True, will display label.
+
+
+
+
+
+
+
+
+ interactive
+
+ bool | None
+
+ default: None
+
+
+
+ if True, will be rendered as an editable textbox; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+ type
+
+ str
+
+ default: "text"
+
+
+
+ The type of textbox. One of: 'text', 'password', 'email', Default is 'text'.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.Textbox
+
+
+ "textbox"
+
+
+ Uses default values
+
+
+
+
+
+ gradio.TextArea
+
+
+ "textarea"
+
+
+ Uses lines=7
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Textbox.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Textbox.submit( fn, ยทยทยท)
+
+
+
This event is triggered when the user presses the Enter key while the component (e.g. a textbox) is focused. This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Textbox.blur( fn, ยทยทยท)
+
+
+
This event is triggered when the component's is unfocused/blurred (e.g. when the user clicks outside of a textbox). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ Callable function
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Textbox.style( ยทยทยท)
+
+
+
This method can be used to change the appearance of the component.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ container
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the component in a container - providing some extra padding around the border.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Textbox
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ tax_calculator
+
+ titanic_survival
+
+ blocks_simple_squares
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+def tax_calculator(income, marital_status, assets):
+ tax_brackets = [(10, 0), (25, 8), (60, 12), (120, 20), (250, 30)]
+ total_deductible = sum(assets["Cost"])
+ taxable_income = income - total_deductible
+
+ total_tax = 0
+ for bracket, rate in tax_brackets:
+ if taxable_income > bracket:
+ total_tax += (taxable_income - bracket) * rate / 100
+
+ if marital_status == "Married":
+ total_tax *= 0.75
+ elif marital_status == "Divorced":
+ total_tax *= 0.8
+
+ return round(total_tax)
+
+demo = gr.Interface(
+ tax_calculator,
+ [
+ "number",
+ gr.Radio(["Single", "Married", "Divorced"]),
+ gr.Dataframe(
+ headers=["Item", "Cost"],
+ datatype=["str", "number"],
+ label="Assets Purchased this Year",
+ ),
+ ],
+ "number",
+ examples=[
+ [10000, "Married", [["Suit", 5000], ["Laptop", 800], ["Car", 1800]]],
+ [80000, "Single", [["Suit", 800], ["Watch", 1800], ["Car", 800]]],
+ ],
+)
+
+demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import os
+
+import pandas as pd
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.model_selection import train_test_split
+
+import gradio as gr
+
+current_dir = os.path.dirname(os.path.realpath(__file__))
+data = pd.read_csv(os.path.join(current_dir, "files/titanic.csv"))
+
+
+def encode_age(df):
+ df.Age = df.Age.fillna(-0.5)
+ bins = (-1, 0, 5, 12, 18, 25, 35, 60, 120)
+ categories = pd.cut(df.Age, bins, labels=False)
+ df.Age = categories
+ return df
+
+
+def encode_fare(df):
+ df.Fare = df.Fare.fillna(-0.5)
+ bins = (-1, 0, 8, 15, 31, 1000)
+ categories = pd.cut(df.Fare, bins, labels=False)
+ df.Fare = categories
+ return df
+
+
+def encode_df(df):
+ df = encode_age(df)
+ df = encode_fare(df)
+ sex_mapping = {"male": 0, "female": 1}
+ df = df.replace({"Sex": sex_mapping})
+ embark_mapping = {"S": 1, "C": 2, "Q": 3}
+ df = df.replace({"Embarked": embark_mapping})
+ df.Embarked = df.Embarked.fillna(0)
+ df["Company"] = 0
+ df.loc[(df["SibSp"] > 0), "Company"] = 1
+ df.loc[(df["Parch"] > 0), "Company"] = 2
+ df.loc[(df["SibSp"] > 0) & (df["Parch"] > 0), "Company"] = 3
+ df = df[
+ [
+ "PassengerId",
+ "Pclass",
+ "Sex",
+ "Age",
+ "Fare",
+ "Embarked",
+ "Company",
+ "Survived",
+ ]
+ ]
+ return df
+
+
+train = encode_df(data)
+
+X_all = train.drop(["Survived", "PassengerId"], axis=1)
+y_all = train["Survived"]
+
+num_test = 0.20
+X_train, X_test, y_train, y_test = train_test_split(
+ X_all, y_all, test_size=num_test, random_state=23
+)
+
+clf = RandomForestClassifier()
+clf.fit(X_train, y_train)
+predictions = clf.predict(X_test)
+
+
+def predict_survival(passenger_class, is_male, age, company, fare, embark_point):
+ if passenger_class is None or embark_point is None:
+ return None
+ df = pd.DataFrame.from_dict(
+ {
+ "Pclass": [passenger_class + 1],
+ "Sex": [0 if is_male else 1],
+ "Age": [age],
+ "Company": [
+ (1 if "Sibling" in company else 0) + (2 if "Child" in company else 0)
+ ],
+ "Fare": [fare],
+ "Embarked": [embark_point + 1],
+ }
+ )
+ df = encode_age(df)
+ df = encode_fare(df)
+ pred = clf.predict_proba(df)[0]
+ return {"Perishes": float(pred[0]), "Survives": float(pred[1])}
+
+
+demo = gr.Interface(
+ predict_survival,
+ [
+ gr.Dropdown(["first", "second", "third"], type="index"),
+ "checkbox",
+ gr.Slider(0, 80, value=25),
+ gr.CheckboxGroup(["Sibling", "Child"], label="Travelling with (select all)"),
+ gr.Number(value=20),
+ gr.Radio(["S", "C", "Q"], type="index"),
+ ],
+ "label",
+ examples=[
+ ["first", True, 30, [], 50, "S"],
+ ["second", False, 40, ["Sibling", "Child"], 10, "Q"],
+ ["third", True, 30, ["Child"], 20, "S"],
+ ],
+ interpretation="default",
+ live=True,
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+demo = gr.Blocks(css="#btn {color: red}")
+
+with demo:
+ default_json = {"a": "a"}
+
+ num = gr.State(value=0)
+ squared = gr.Number(value=0)
+ btn = gr.Button("Next Square", elem_id="btn").style(rounded=False)
+
+ stats = gr.State(value=default_json)
+ table = gr.JSON()
+
+ def increase(var, stats_history):
+ var += 1
+ stats_history[str(var)] = var**2
+ return var, var**2, stats_history, stats_history
+
+ btn.click(increase, [num, stats], [num, squared, stats, table])
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Creates a numeric field for user to enter numbers as input or display numeric output.
+
+
+
As input: passes field value as a float or int into the function, depending on `precision`.
+
As output: expects an int or float returned from the function and sets field value to it.
+
+
Format expected for examples: a float or int representing the number's value.
+
+
+
Supported events: change(), submit(), blur()
+
+
+
+
+
+
+
import gradio as gr
+
+def tax_calculator(income, marital_status, assets):
+ tax_brackets = [(10, 0), (25, 8), (60, 12), (120, 20), (250, 30)]
+ total_deductible = sum(assets["Cost"])
+ taxable_income = income - total_deductible
+
+ total_tax = 0
+ for bracket, rate in tax_brackets:
+ if taxable_income > bracket:
+ total_tax += (taxable_income - bracket) * rate / 100
+
+ if marital_status == "Married":
+ total_tax *= 0.75
+ elif marital_status == "Divorced":
+ total_tax *= 0.8
+
+ return round(total_tax)
+
+demo = gr.Interface(
+ tax_calculator,
+ [
+ "number",
+ gr.Radio(["Single", "Married", "Divorced"]),
+ gr.Dataframe(
+ headers=["Item", "Cost"],
+ datatype=["str", "number"],
+ label="Assets Purchased this Year",
+ ),
+ ],
+ "number",
+ examples=[
+ [10000, "Married", [["Suit", 5000], ["Laptop", 800], ["Car", 1800]]],
+ [80000, "Single", [["Suit", 800], ["Watch", 1800], ["Car", 800]]],
+ ],
+)
+
+demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ value
+
+ float | Callable | None
+
+ default: None
+
+
+
+ default value. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ component name in interface.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ if True, will display label.
+
+
+
+
+
+
+
+
+ interactive
+
+ bool | None
+
+ default: None
+
+
+
+ if True, will be editable; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+ precision
+
+ int | None
+
+ default: None
+
+
+
+ Precision to round input/output to. If set to 0, will round to nearest integer and covert type to int. If None, no rounding happens.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.Number
+
+
+ "number"
+
+
+ Uses default values
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Number.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Number.submit( fn, ยทยทยท)
+
+
+
This event is triggered when the user presses the Enter key while the component (e.g. a textbox) is focused. This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Number.style( ยทยทยท)
+
+
+
This method can be used to change the appearance of the component.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ container
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the component in a container - providing some extra padding around the border.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Number
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ sentence_builder
+
+ generate_tone
+
+ titanic_survival
+
+ interface_random_slider
+
+ blocks_random_slider
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+
+def sentence_builder(quantity, animal, place, activity_list, morning):
+ return f"""The {quantity} {animal}s went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""
+
+
+demo = gr.Interface(
+ sentence_builder,
+ [
+ gr.Slider(2, 20, value=4),
+ gr.Dropdown(["cat", "dog", "bird"]),
+ gr.Radio(["park", "zoo", "road"]),
+ gr.Dropdown(["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True),
+ gr.Checkbox(label="Is it the morning?"),
+ ],
+ "text",
+ examples=[
+ [2, "cat", "park", ["ran", "swam"], True],
+ [4, "dog", "zoo", ["ate", "swam"], False],
+ [10, "bird", "road", ["ran"], False],
+ [8, "cat", "zoo", ["ate"], True],
+ ],
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import numpy as np
+import gradio as gr
+
+notes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
+
+def generate_tone(note, octave, duration):
+ sr = 48000
+ a4_freq, tones_from_a4 = 440, 12 * (octave - 4) + (note - 9)
+ frequency = a4_freq * 2 ** (tones_from_a4 / 12)
+ duration = int(duration)
+ audio = np.linspace(0, duration, duration * sr)
+ audio = (20000 * np.sin(audio * (2 * np.pi * frequency))).astype(np.int16)
+ return sr, audio
+
+demo = gr.Interface(
+ generate_tone,
+ [
+ gr.Dropdown(notes, type="index"),
+ gr.Slider(4, 6, step=1),
+ gr.Textbox(value=1, label="Duration in seconds"),
+ ],
+ "audio",
+)
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import os
+
+import pandas as pd
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.model_selection import train_test_split
+
+import gradio as gr
+
+current_dir = os.path.dirname(os.path.realpath(__file__))
+data = pd.read_csv(os.path.join(current_dir, "files/titanic.csv"))
+
+
+def encode_age(df):
+ df.Age = df.Age.fillna(-0.5)
+ bins = (-1, 0, 5, 12, 18, 25, 35, 60, 120)
+ categories = pd.cut(df.Age, bins, labels=False)
+ df.Age = categories
+ return df
+
+
+def encode_fare(df):
+ df.Fare = df.Fare.fillna(-0.5)
+ bins = (-1, 0, 8, 15, 31, 1000)
+ categories = pd.cut(df.Fare, bins, labels=False)
+ df.Fare = categories
+ return df
+
+
+def encode_df(df):
+ df = encode_age(df)
+ df = encode_fare(df)
+ sex_mapping = {"male": 0, "female": 1}
+ df = df.replace({"Sex": sex_mapping})
+ embark_mapping = {"S": 1, "C": 2, "Q": 3}
+ df = df.replace({"Embarked": embark_mapping})
+ df.Embarked = df.Embarked.fillna(0)
+ df["Company"] = 0
+ df.loc[(df["SibSp"] > 0), "Company"] = 1
+ df.loc[(df["Parch"] > 0), "Company"] = 2
+ df.loc[(df["SibSp"] > 0) & (df["Parch"] > 0), "Company"] = 3
+ df = df[
+ [
+ "PassengerId",
+ "Pclass",
+ "Sex",
+ "Age",
+ "Fare",
+ "Embarked",
+ "Company",
+ "Survived",
+ ]
+ ]
+ return df
+
+
+train = encode_df(data)
+
+X_all = train.drop(["Survived", "PassengerId"], axis=1)
+y_all = train["Survived"]
+
+num_test = 0.20
+X_train, X_test, y_train, y_test = train_test_split(
+ X_all, y_all, test_size=num_test, random_state=23
+)
+
+clf = RandomForestClassifier()
+clf.fit(X_train, y_train)
+predictions = clf.predict(X_test)
+
+
+def predict_survival(passenger_class, is_male, age, company, fare, embark_point):
+ if passenger_class is None or embark_point is None:
+ return None
+ df = pd.DataFrame.from_dict(
+ {
+ "Pclass": [passenger_class + 1],
+ "Sex": [0 if is_male else 1],
+ "Age": [age],
+ "Company": [
+ (1 if "Sibling" in company else 0) + (2 if "Child" in company else 0)
+ ],
+ "Fare": [fare],
+ "Embarked": [embark_point + 1],
+ }
+ )
+ df = encode_age(df)
+ df = encode_fare(df)
+ pred = clf.predict_proba(df)[0]
+ return {"Perishes": float(pred[0]), "Survives": float(pred[1])}
+
+
+demo = gr.Interface(
+ predict_survival,
+ [
+ gr.Dropdown(["first", "second", "third"], type="index"),
+ "checkbox",
+ gr.Slider(0, 80, value=25),
+ gr.CheckboxGroup(["Sibling", "Child"], label="Travelling with (select all)"),
+ gr.Number(value=20),
+ gr.Radio(["S", "C", "Q"], type="index"),
+ ],
+ "label",
+ examples=[
+ ["first", True, 30, [], 50, "S"],
+ ["second", False, 40, ["Sibling", "Child"], 10, "Q"],
+ ["third", True, 30, ["Child"], 20, "S"],
+ ],
+ interpretation="default",
+ live=True,
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+
+def func(slider_1, slider_2, *args):
+ return slider_1 + slider_2 * 5
+
+
+demo = gr.Interface(
+ func,
+ [
+ gr.Slider(minimum=1.5, maximum=250000.89, randomize=True, label="Random Big Range"),
+ gr.Slider(minimum=-1, maximum=1, randomize=True, step=0.05, label="Random only multiple of 0.05 allowed"),
+ gr.Slider(minimum=0, maximum=1, randomize=True, step=0.25, label="Random only multiples of 0.25 allowed"),
+ gr.Slider(minimum=-100, maximum=100, randomize=True, step=3, label="Random between -100 and 100 step 3"),
+ gr.Slider(minimum=-100, maximum=100, randomize=True, label="Random between -100 and 100"),
+ gr.Slider(value=0.25, minimum=5, maximum=30, step=-1),
+ ],
+ "number",
+ interpretation="default"
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+import gradio as gr
+
+
+def func(slider_1, slider_2):
+ return slider_1 * 5 + slider_2
+
+
+with gr.Blocks() as demo:
+ slider = gr.Slider(minimum=-10.2, maximum=15, label="Random Slider (Static)", randomize=True)
+ slider_1 = gr.Slider(minimum=100, maximum=200, label="Random Slider (Input 1)", randomize=True)
+ slider_2 = gr.Slider(minimum=10, maximum=23.2, label="Random Slider (Input 2)", randomize=True)
+ slider_3 = gr.Slider(value=3, label="Non random slider")
+ btn = gr.Button("Run")
+ btn.click(func, inputs=[slider_1, slider_2], outputs=gr.Number())
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Creates a slider that ranges from `minimum` to `maximum` with a step size of `step`.
+
+
+
As input: passes slider value as a float into the function.
+
As output: expects an int or float returned from function and sets slider value to it as long as it is within range.
+
+
Format expected for examples: A float or int representing the slider's value.
+
+
+
Supported events: change()
+
+
+
+
+
+
+
import gradio as gr
+
+
+def sentence_builder(quantity, animal, place, activity_list, morning):
+ return f"""The {quantity} {animal}s went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""
+
+
+demo = gr.Interface(
+ sentence_builder,
+ [
+ gr.Slider(2, 20, value=4),
+ gr.Dropdown(["cat", "dog", "bird"]),
+ gr.Radio(["park", "zoo", "road"]),
+ gr.Dropdown(["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True),
+ gr.Checkbox(label="Is it the morning?"),
+ ],
+ "text",
+ examples=[
+ [2, "cat", "park", ["ran", "swam"], True],
+ [4, "dog", "zoo", ["ate", "swam"], False],
+ [10, "bird", "road", ["ran"], False],
+ [8, "cat", "zoo", ["ate"], True],
+ ],
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ minimum
+
+ float
+
+ default: 0
+
+
+
+ minimum value for slider.
+
+
+
+
+
+
+
+
+ maximum
+
+ float
+
+ default: 100
+
+
+
+ maximum value for slider.
+
+
+
+
+
+
+
+
+ value
+
+ float | Callable | None
+
+ default: None
+
+
+
+ default value. If callable, the function will be called whenever the app loads to set the initial value of the component. Ignored if randomized=True.
+
+
+
+
+
+
+
+
+ step
+
+ float | None
+
+ default: None
+
+
+
+ increment between slider values.
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ component name in interface.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ if True, will display label.
+
+
+
+
+
+
+
+
+ interactive
+
+ bool | None
+
+ default: None
+
+
+
+ if True, slider will be adjustable; if False, adjusting will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+ randomize
+
+ bool
+
+ default: False
+
+
+
+ If True, the value of the slider when the app loads is taken uniformly at random from the range given by the minimum and maximum.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.Slider
+
+
+ "slider"
+
+
+ Uses default values
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Slider.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Slider.style( ยทยทยท)
+
+
+
This method can be used to change the appearance of the slider.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ container
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the component in a container - providing some extra padding around the border.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Slider
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ sentence_builder
+
+ titanic_survival
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+
+def sentence_builder(quantity, animal, place, activity_list, morning):
+ return f"""The {quantity} {animal}s went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""
+
+
+demo = gr.Interface(
+ sentence_builder,
+ [
+ gr.Slider(2, 20, value=4),
+ gr.Dropdown(["cat", "dog", "bird"]),
+ gr.Radio(["park", "zoo", "road"]),
+ gr.Dropdown(["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True),
+ gr.Checkbox(label="Is it the morning?"),
+ ],
+ "text",
+ examples=[
+ [2, "cat", "park", ["ran", "swam"], True],
+ [4, "dog", "zoo", ["ate", "swam"], False],
+ [10, "bird", "road", ["ran"], False],
+ [8, "cat", "zoo", ["ate"], True],
+ ],
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import os
+
+import pandas as pd
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.model_selection import train_test_split
+
+import gradio as gr
+
+current_dir = os.path.dirname(os.path.realpath(__file__))
+data = pd.read_csv(os.path.join(current_dir, "files/titanic.csv"))
+
+
+def encode_age(df):
+ df.Age = df.Age.fillna(-0.5)
+ bins = (-1, 0, 5, 12, 18, 25, 35, 60, 120)
+ categories = pd.cut(df.Age, bins, labels=False)
+ df.Age = categories
+ return df
+
+
+def encode_fare(df):
+ df.Fare = df.Fare.fillna(-0.5)
+ bins = (-1, 0, 8, 15, 31, 1000)
+ categories = pd.cut(df.Fare, bins, labels=False)
+ df.Fare = categories
+ return df
+
+
+def encode_df(df):
+ df = encode_age(df)
+ df = encode_fare(df)
+ sex_mapping = {"male": 0, "female": 1}
+ df = df.replace({"Sex": sex_mapping})
+ embark_mapping = {"S": 1, "C": 2, "Q": 3}
+ df = df.replace({"Embarked": embark_mapping})
+ df.Embarked = df.Embarked.fillna(0)
+ df["Company"] = 0
+ df.loc[(df["SibSp"] > 0), "Company"] = 1
+ df.loc[(df["Parch"] > 0), "Company"] = 2
+ df.loc[(df["SibSp"] > 0) & (df["Parch"] > 0), "Company"] = 3
+ df = df[
+ [
+ "PassengerId",
+ "Pclass",
+ "Sex",
+ "Age",
+ "Fare",
+ "Embarked",
+ "Company",
+ "Survived",
+ ]
+ ]
+ return df
+
+
+train = encode_df(data)
+
+X_all = train.drop(["Survived", "PassengerId"], axis=1)
+y_all = train["Survived"]
+
+num_test = 0.20
+X_train, X_test, y_train, y_test = train_test_split(
+ X_all, y_all, test_size=num_test, random_state=23
+)
+
+clf = RandomForestClassifier()
+clf.fit(X_train, y_train)
+predictions = clf.predict(X_test)
+
+
+def predict_survival(passenger_class, is_male, age, company, fare, embark_point):
+ if passenger_class is None or embark_point is None:
+ return None
+ df = pd.DataFrame.from_dict(
+ {
+ "Pclass": [passenger_class + 1],
+ "Sex": [0 if is_male else 1],
+ "Age": [age],
+ "Company": [
+ (1 if "Sibling" in company else 0) + (2 if "Child" in company else 0)
+ ],
+ "Fare": [fare],
+ "Embarked": [embark_point + 1],
+ }
+ )
+ df = encode_age(df)
+ df = encode_fare(df)
+ pred = clf.predict_proba(df)[0]
+ return {"Perishes": float(pred[0]), "Survives": float(pred[1])}
+
+
+demo = gr.Interface(
+ predict_survival,
+ [
+ gr.Dropdown(["first", "second", "third"], type="index"),
+ "checkbox",
+ gr.Slider(0, 80, value=25),
+ gr.CheckboxGroup(["Sibling", "Child"], label="Travelling with (select all)"),
+ gr.Number(value=20),
+ gr.Radio(["S", "C", "Q"], type="index"),
+ ],
+ "label",
+ examples=[
+ ["first", True, 30, [], 50, "S"],
+ ["second", False, 40, ["Sibling", "Child"], 10, "Q"],
+ ["third", True, 30, ["Child"], 20, "S"],
+ ],
+ interpretation="default",
+ live=True,
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Creates a checkbox that can be set to `True` or `False`.
+
+
+
As input: passes the status of the checkbox as a bool into the function.
+
As output: expects a bool returned from the function and, if it is True, checks the checkbox.
+
+
Format expected for examples: a bool representing whether the box is checked.
+
+
+
Supported events: change()
+
+
+
+
+
+
+
import gradio as gr
+
+
+def sentence_builder(quantity, animal, place, activity_list, morning):
+ return f"""The {quantity} {animal}s went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""
+
+
+demo = gr.Interface(
+ sentence_builder,
+ [
+ gr.Slider(2, 20, value=4),
+ gr.Dropdown(["cat", "dog", "bird"]),
+ gr.Radio(["park", "zoo", "road"]),
+ gr.Dropdown(["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True),
+ gr.Checkbox(label="Is it the morning?"),
+ ],
+ "text",
+ examples=[
+ [2, "cat", "park", ["ran", "swam"], True],
+ [4, "dog", "zoo", ["ate", "swam"], False],
+ [10, "bird", "road", ["ran"], False],
+ [8, "cat", "zoo", ["ate"], True],
+ ],
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ value
+
+ bool | Callable
+
+ default: False
+
+
+
+ if True, checked by default. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ component name in interface.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ if True, will display label.
+
+
+
+
+
+
+
+
+ interactive
+
+ bool | None
+
+ default: None
+
+
+
+ if True, this checkbox can be checked; if False, checking will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.Checkbox
+
+
+ "checkbox"
+
+
+ Uses default values
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Checkbox.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Checkbox.style( ยทยทยท)
+
+
+
This method can be used to change the appearance of the component.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ container
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the component in a container - providing some extra padding around the border.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Checkbox
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ sentence_builder
+
+ titanic_survival
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+
+def sentence_builder(quantity, animal, place, activity_list, morning):
+ return f"""The {quantity} {animal}s went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""
+
+
+demo = gr.Interface(
+ sentence_builder,
+ [
+ gr.Slider(2, 20, value=4),
+ gr.Dropdown(["cat", "dog", "bird"]),
+ gr.Radio(["park", "zoo", "road"]),
+ gr.Dropdown(["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True),
+ gr.Checkbox(label="Is it the morning?"),
+ ],
+ "text",
+ examples=[
+ [2, "cat", "park", ["ran", "swam"], True],
+ [4, "dog", "zoo", ["ate", "swam"], False],
+ [10, "bird", "road", ["ran"], False],
+ [8, "cat", "zoo", ["ate"], True],
+ ],
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import os
+
+import pandas as pd
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.model_selection import train_test_split
+
+import gradio as gr
+
+current_dir = os.path.dirname(os.path.realpath(__file__))
+data = pd.read_csv(os.path.join(current_dir, "files/titanic.csv"))
+
+
+def encode_age(df):
+ df.Age = df.Age.fillna(-0.5)
+ bins = (-1, 0, 5, 12, 18, 25, 35, 60, 120)
+ categories = pd.cut(df.Age, bins, labels=False)
+ df.Age = categories
+ return df
+
+
+def encode_fare(df):
+ df.Fare = df.Fare.fillna(-0.5)
+ bins = (-1, 0, 8, 15, 31, 1000)
+ categories = pd.cut(df.Fare, bins, labels=False)
+ df.Fare = categories
+ return df
+
+
+def encode_df(df):
+ df = encode_age(df)
+ df = encode_fare(df)
+ sex_mapping = {"male": 0, "female": 1}
+ df = df.replace({"Sex": sex_mapping})
+ embark_mapping = {"S": 1, "C": 2, "Q": 3}
+ df = df.replace({"Embarked": embark_mapping})
+ df.Embarked = df.Embarked.fillna(0)
+ df["Company"] = 0
+ df.loc[(df["SibSp"] > 0), "Company"] = 1
+ df.loc[(df["Parch"] > 0), "Company"] = 2
+ df.loc[(df["SibSp"] > 0) & (df["Parch"] > 0), "Company"] = 3
+ df = df[
+ [
+ "PassengerId",
+ "Pclass",
+ "Sex",
+ "Age",
+ "Fare",
+ "Embarked",
+ "Company",
+ "Survived",
+ ]
+ ]
+ return df
+
+
+train = encode_df(data)
+
+X_all = train.drop(["Survived", "PassengerId"], axis=1)
+y_all = train["Survived"]
+
+num_test = 0.20
+X_train, X_test, y_train, y_test = train_test_split(
+ X_all, y_all, test_size=num_test, random_state=23
+)
+
+clf = RandomForestClassifier()
+clf.fit(X_train, y_train)
+predictions = clf.predict(X_test)
+
+
+def predict_survival(passenger_class, is_male, age, company, fare, embark_point):
+ if passenger_class is None or embark_point is None:
+ return None
+ df = pd.DataFrame.from_dict(
+ {
+ "Pclass": [passenger_class + 1],
+ "Sex": [0 if is_male else 1],
+ "Age": [age],
+ "Company": [
+ (1 if "Sibling" in company else 0) + (2 if "Child" in company else 0)
+ ],
+ "Fare": [fare],
+ "Embarked": [embark_point + 1],
+ }
+ )
+ df = encode_age(df)
+ df = encode_fare(df)
+ pred = clf.predict_proba(df)[0]
+ return {"Perishes": float(pred[0]), "Survives": float(pred[1])}
+
+
+demo = gr.Interface(
+ predict_survival,
+ [
+ gr.Dropdown(["first", "second", "third"], type="index"),
+ "checkbox",
+ gr.Slider(0, 80, value=25),
+ gr.CheckboxGroup(["Sibling", "Child"], label="Travelling with (select all)"),
+ gr.Number(value=20),
+ gr.Radio(["S", "C", "Q"], type="index"),
+ ],
+ "label",
+ examples=[
+ ["first", True, 30, [], 50, "S"],
+ ["second", False, 40, ["Sibling", "Child"], 10, "Q"],
+ ["third", True, 30, ["Child"], 20, "S"],
+ ],
+ interpretation="default",
+ live=True,
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
gradio.CheckboxGroup( ยทยทยท)
+
+
+
+
+
+
+
+
+
+
+
Creates a set of checkboxes of which a subset can be checked.
+
+
+
As input: passes the list of checked checkboxes as a List[str] or their indices as a List[int] into the function, depending on `type`.
+
As output: expects a List[str] , each element of which becomes a checked checkbox.
+
+
Format expected for examples: a List[str] representing the values to be checked.
+
+
+
Supported events: change()
+
+
+
+
+
+
+
import gradio as gr
+
+
+def sentence_builder(quantity, animal, place, activity_list, morning):
+ return f"""The {quantity} {animal}s went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""
+
+
+demo = gr.Interface(
+ sentence_builder,
+ [
+ gr.Slider(2, 20, value=4),
+ gr.Dropdown(["cat", "dog", "bird"]),
+ gr.Radio(["park", "zoo", "road"]),
+ gr.Dropdown(["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True),
+ gr.Checkbox(label="Is it the morning?"),
+ ],
+ "text",
+ examples=[
+ [2, "cat", "park", ["ran", "swam"], True],
+ [4, "dog", "zoo", ["ate", "swam"], False],
+ [10, "bird", "road", ["ran"], False],
+ [8, "cat", "zoo", ["ate"], True],
+ ],
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ choices
+
+ List[str] | None
+
+ default: None
+
+
+
+ list of options to select from.
+
+
+
+
+
+
+
+
+ value
+
+ List[str] | str | Callable | None
+
+ default: None
+
+
+
+ default selected list of options. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ type
+
+ str
+
+ default: "value"
+
+
+
+ Type of value to be returned by component. "value" returns the list of strings of the choices selected, "index" returns the list of indicies of the choices selected.
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ component name in interface.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ if True, will display label.
+
+
+
+
+
+
+
+
+ interactive
+
+ bool | None
+
+ default: None
+
+
+
+ if True, choices in this checkbox group will be checkable; if False, checking will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.CheckboxGroup
+
+
+ "checkboxgroup"
+
+
+ Uses default values
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.CheckboxGroup.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.CheckboxGroup.style( ยทยทยท)
+
+
+
This method can be used to change the appearance of the CheckboxGroup.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ item_container
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the items in a container.
+
+
+
+
+
+
+
+
+ container
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the component in a container - providing some extra padding around the border.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about CheckboxGroup
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ sentence_builder
+
+ titanic_survival
+
+ blocks_essay
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+
+def sentence_builder(quantity, animal, place, activity_list, morning):
+ return f"""The {quantity} {animal}s went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""
+
+
+demo = gr.Interface(
+ sentence_builder,
+ [
+ gr.Slider(2, 20, value=4),
+ gr.Dropdown(["cat", "dog", "bird"]),
+ gr.Radio(["park", "zoo", "road"]),
+ gr.Dropdown(["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True),
+ gr.Checkbox(label="Is it the morning?"),
+ ],
+ "text",
+ examples=[
+ [2, "cat", "park", ["ran", "swam"], True],
+ [4, "dog", "zoo", ["ate", "swam"], False],
+ [10, "bird", "road", ["ran"], False],
+ [8, "cat", "zoo", ["ate"], True],
+ ],
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import os
+
+import pandas as pd
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.model_selection import train_test_split
+
+import gradio as gr
+
+current_dir = os.path.dirname(os.path.realpath(__file__))
+data = pd.read_csv(os.path.join(current_dir, "files/titanic.csv"))
+
+
+def encode_age(df):
+ df.Age = df.Age.fillna(-0.5)
+ bins = (-1, 0, 5, 12, 18, 25, 35, 60, 120)
+ categories = pd.cut(df.Age, bins, labels=False)
+ df.Age = categories
+ return df
+
+
+def encode_fare(df):
+ df.Fare = df.Fare.fillna(-0.5)
+ bins = (-1, 0, 8, 15, 31, 1000)
+ categories = pd.cut(df.Fare, bins, labels=False)
+ df.Fare = categories
+ return df
+
+
+def encode_df(df):
+ df = encode_age(df)
+ df = encode_fare(df)
+ sex_mapping = {"male": 0, "female": 1}
+ df = df.replace({"Sex": sex_mapping})
+ embark_mapping = {"S": 1, "C": 2, "Q": 3}
+ df = df.replace({"Embarked": embark_mapping})
+ df.Embarked = df.Embarked.fillna(0)
+ df["Company"] = 0
+ df.loc[(df["SibSp"] > 0), "Company"] = 1
+ df.loc[(df["Parch"] > 0), "Company"] = 2
+ df.loc[(df["SibSp"] > 0) & (df["Parch"] > 0), "Company"] = 3
+ df = df[
+ [
+ "PassengerId",
+ "Pclass",
+ "Sex",
+ "Age",
+ "Fare",
+ "Embarked",
+ "Company",
+ "Survived",
+ ]
+ ]
+ return df
+
+
+train = encode_df(data)
+
+X_all = train.drop(["Survived", "PassengerId"], axis=1)
+y_all = train["Survived"]
+
+num_test = 0.20
+X_train, X_test, y_train, y_test = train_test_split(
+ X_all, y_all, test_size=num_test, random_state=23
+)
+
+clf = RandomForestClassifier()
+clf.fit(X_train, y_train)
+predictions = clf.predict(X_test)
+
+
+def predict_survival(passenger_class, is_male, age, company, fare, embark_point):
+ if passenger_class is None or embark_point is None:
+ return None
+ df = pd.DataFrame.from_dict(
+ {
+ "Pclass": [passenger_class + 1],
+ "Sex": [0 if is_male else 1],
+ "Age": [age],
+ "Company": [
+ (1 if "Sibling" in company else 0) + (2 if "Child" in company else 0)
+ ],
+ "Fare": [fare],
+ "Embarked": [embark_point + 1],
+ }
+ )
+ df = encode_age(df)
+ df = encode_fare(df)
+ pred = clf.predict_proba(df)[0]
+ return {"Perishes": float(pred[0]), "Survives": float(pred[1])}
+
+
+demo = gr.Interface(
+ predict_survival,
+ [
+ gr.Dropdown(["first", "second", "third"], type="index"),
+ "checkbox",
+ gr.Slider(0, 80, value=25),
+ gr.CheckboxGroup(["Sibling", "Child"], label="Travelling with (select all)"),
+ gr.Number(value=20),
+ gr.Radio(["S", "C", "Q"], type="index"),
+ ],
+ "label",
+ examples=[
+ ["first", True, 30, [], 50, "S"],
+ ["second", False, 40, ["Sibling", "Child"], 10, "Q"],
+ ["third", True, 30, ["Child"], 20, "S"],
+ ],
+ interpretation="default",
+ live=True,
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+
+def change_textbox(choice):
+ if choice == "short":
+ return gr.Textbox.update(lines=2, visible=True)
+ elif choice == "long":
+ return gr.Textbox.update(lines=8, visible=True)
+ else:
+ return gr.Textbox.update(visible=False)
+
+
+with gr.Blocks() as demo:
+ radio = gr.Radio(
+ ["short", "long", "none"], label="What kind of essay would you like to write?"
+ )
+ text = gr.Textbox(lines=2, interactive=True)
+
+ radio.change(fn=change_textbox, inputs=radio, outputs=text)
+
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Creates a set of radio buttons of which only one can be selected.
+
+
+
As input: passes the value of the selected radio button as a str or its index as an int into the function, depending on `type`.
+
As output: expects a str corresponding to the value of the radio button to be selected.
+
+
Format expected for examples: a str representing the radio option to select.
+
+
+
Supported events: change()
+
+
+
+
+
+
+
import gradio as gr
+
+
+def sentence_builder(quantity, animal, place, activity_list, morning):
+ return f"""The {quantity} {animal}s went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""
+
+
+demo = gr.Interface(
+ sentence_builder,
+ [
+ gr.Slider(2, 20, value=4),
+ gr.Dropdown(["cat", "dog", "bird"]),
+ gr.Radio(["park", "zoo", "road"]),
+ gr.Dropdown(["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True),
+ gr.Checkbox(label="Is it the morning?"),
+ ],
+ "text",
+ examples=[
+ [2, "cat", "park", ["ran", "swam"], True],
+ [4, "dog", "zoo", ["ate", "swam"], False],
+ [10, "bird", "road", ["ran"], False],
+ [8, "cat", "zoo", ["ate"], True],
+ ],
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ choices
+
+ List[str] | None
+
+ default: None
+
+
+
+ list of options to select from.
+
+
+
+
+
+
+
+
+ value
+
+ str | Callable | None
+
+ default: None
+
+
+
+ the button selected by default. If None, no button is selected by default. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ type
+
+ str
+
+ default: "value"
+
+
+
+ Type of value to be returned by component. "value" returns the string of the choice selected, "index" returns the index of the choice selected.
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ component name in interface.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ if True, will display label.
+
+
+
+
+
+
+
+
+ interactive
+
+ bool | None
+
+ default: None
+
+
+
+ if True, choices in this radio group will be selectable; if False, selection will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.Radio
+
+
+ "radio"
+
+
+ Uses default values
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Radio.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Radio.style( ยทยทยท)
+
+
+
This method can be used to change the appearance of the radio component.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ item_container
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place items in a container.
+
+
+
+
+
+
+
+
+ container
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the component in a container - providing some extra padding around the border.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Radio
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ sentence_builder
+
+ titanic_survival
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+
+def sentence_builder(quantity, animal, place, activity_list, morning):
+ return f"""The {quantity} {animal}s went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""
+
+
+demo = gr.Interface(
+ sentence_builder,
+ [
+ gr.Slider(2, 20, value=4),
+ gr.Dropdown(["cat", "dog", "bird"]),
+ gr.Radio(["park", "zoo", "road"]),
+ gr.Dropdown(["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True),
+ gr.Checkbox(label="Is it the morning?"),
+ ],
+ "text",
+ examples=[
+ [2, "cat", "park", ["ran", "swam"], True],
+ [4, "dog", "zoo", ["ate", "swam"], False],
+ [10, "bird", "road", ["ran"], False],
+ [8, "cat", "zoo", ["ate"], True],
+ ],
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import os
+
+import pandas as pd
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.model_selection import train_test_split
+
+import gradio as gr
+
+current_dir = os.path.dirname(os.path.realpath(__file__))
+data = pd.read_csv(os.path.join(current_dir, "files/titanic.csv"))
+
+
+def encode_age(df):
+ df.Age = df.Age.fillna(-0.5)
+ bins = (-1, 0, 5, 12, 18, 25, 35, 60, 120)
+ categories = pd.cut(df.Age, bins, labels=False)
+ df.Age = categories
+ return df
+
+
+def encode_fare(df):
+ df.Fare = df.Fare.fillna(-0.5)
+ bins = (-1, 0, 8, 15, 31, 1000)
+ categories = pd.cut(df.Fare, bins, labels=False)
+ df.Fare = categories
+ return df
+
+
+def encode_df(df):
+ df = encode_age(df)
+ df = encode_fare(df)
+ sex_mapping = {"male": 0, "female": 1}
+ df = df.replace({"Sex": sex_mapping})
+ embark_mapping = {"S": 1, "C": 2, "Q": 3}
+ df = df.replace({"Embarked": embark_mapping})
+ df.Embarked = df.Embarked.fillna(0)
+ df["Company"] = 0
+ df.loc[(df["SibSp"] > 0), "Company"] = 1
+ df.loc[(df["Parch"] > 0), "Company"] = 2
+ df.loc[(df["SibSp"] > 0) & (df["Parch"] > 0), "Company"] = 3
+ df = df[
+ [
+ "PassengerId",
+ "Pclass",
+ "Sex",
+ "Age",
+ "Fare",
+ "Embarked",
+ "Company",
+ "Survived",
+ ]
+ ]
+ return df
+
+
+train = encode_df(data)
+
+X_all = train.drop(["Survived", "PassengerId"], axis=1)
+y_all = train["Survived"]
+
+num_test = 0.20
+X_train, X_test, y_train, y_test = train_test_split(
+ X_all, y_all, test_size=num_test, random_state=23
+)
+
+clf = RandomForestClassifier()
+clf.fit(X_train, y_train)
+predictions = clf.predict(X_test)
+
+
+def predict_survival(passenger_class, is_male, age, company, fare, embark_point):
+ if passenger_class is None or embark_point is None:
+ return None
+ df = pd.DataFrame.from_dict(
+ {
+ "Pclass": [passenger_class + 1],
+ "Sex": [0 if is_male else 1],
+ "Age": [age],
+ "Company": [
+ (1 if "Sibling" in company else 0) + (2 if "Child" in company else 0)
+ ],
+ "Fare": [fare],
+ "Embarked": [embark_point + 1],
+ }
+ )
+ df = encode_age(df)
+ df = encode_fare(df)
+ pred = clf.predict_proba(df)[0]
+ return {"Perishes": float(pred[0]), "Survives": float(pred[1])}
+
+
+demo = gr.Interface(
+ predict_survival,
+ [
+ gr.Dropdown(["first", "second", "third"], type="index"),
+ "checkbox",
+ gr.Slider(0, 80, value=25),
+ gr.CheckboxGroup(["Sibling", "Child"], label="Travelling with (select all)"),
+ gr.Number(value=20),
+ gr.Radio(["S", "C", "Q"], type="index"),
+ ],
+ "label",
+ examples=[
+ ["first", True, 30, [], 50, "S"],
+ ["second", False, 40, ["Sibling", "Child"], 10, "Q"],
+ ["third", True, 30, ["Child"], 20, "S"],
+ ],
+ interpretation="default",
+ live=True,
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Creates a dropdown of choices from which entries can be selected.
+
+
+
As input: passes the value of the selected dropdown entry as a str or its index as an int into the function, depending on `type`.
+
As output: expects a str corresponding to the value of the dropdown entry to be selected.
+
+
Format expected for examples: a str representing the drop down value to select.
+
+
+
Supported events: change()
+
+
+
+
+
+
+
import gradio as gr
+
+
+def sentence_builder(quantity, animal, place, activity_list, morning):
+ return f"""The {quantity} {animal}s went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""
+
+
+demo = gr.Interface(
+ sentence_builder,
+ [
+ gr.Slider(2, 20, value=4),
+ gr.Dropdown(["cat", "dog", "bird"]),
+ gr.Radio(["park", "zoo", "road"]),
+ gr.Dropdown(["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True),
+ gr.Checkbox(label="Is it the morning?"),
+ ],
+ "text",
+ examples=[
+ [2, "cat", "park", ["ran", "swam"], True],
+ [4, "dog", "zoo", ["ate", "swam"], False],
+ [10, "bird", "road", ["ran"], False],
+ [8, "cat", "zoo", ["ate"], True],
+ ],
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ choices
+
+ str | List[str] | None
+
+ default: None
+
+
+
+ list of options to select from.
+
+
+
+
+
+
+
+
+ value
+
+ str | List[str] | Callable | None
+
+ default: None
+
+
+
+ default value(s) selected in dropdown. If None, no value is selected by default. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ type
+
+ str
+
+ default: "value"
+
+
+
+ Type of value to be returned by component. "value" returns the string of the choice selected, "index" returns the index of the choice selected.
+
+
+
+
+
+
+
+
+ multiselect
+
+ bool | None
+
+ default: None
+
+
+
+ if True, multiple choices can be selected.
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ component name in interface.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ if True, will display label.
+
+
+
+
+
+
+
+
+ interactive
+
+ bool | None
+
+ default: None
+
+
+
+ if True, choices in this dropdown will be selectable; if False, selection will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.Dropdown
+
+
+ "dropdown"
+
+
+ Uses default values
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Dropdown.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Dropdown.style( ยทยทยท)
+
+
+
This method can be used to change the appearance of the Dropdown.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ container
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the component in a container - providing some extra padding around the border.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Dropdown
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ image_mod
+
+ image_mod_default_image
+
+
+
+
+
+
+
+
+
import gradio as gr
+import os
+
+
+def image_mod(image):
+ return image.rotate(45)
+
+
+demo = gr.Interface(
+ image_mod,
+ gr.Image(type="pil"),
+ "image",
+ flagging_options=["blurry", "incorrect", "other"],
+ examples=[
+ os.path.join(os.path.dirname(__file__), "images/cheetah1.jpg"),
+ os.path.join(os.path.dirname(__file__), "images/lion.jpg"),
+ os.path.join(os.path.dirname(__file__), "images/logo.png"),
+ os.path.join(os.path.dirname(__file__), "images/tower.jpg"),
+ ],
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import gradio as gr
+import os
+
+
+def image_mod(image):
+ return image.rotate(45)
+
+
+cheetah = os.path.join(os.path.dirname(__file__), "images/cheetah1.jpg")
+
+demo = gr.Interface(image_mod, gr.Image(type="pil", value=cheetah), "image",
+ flagging_options=["blurry", "incorrect", "other"], examples=[
+ os.path.join(os.path.dirname(__file__), "images/lion.jpg"),
+ os.path.join(os.path.dirname(__file__), "images/logo.png")
+ ])
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Creates an image component that can be used to upload/draw images (as an input) or display images (as an output).
+
+
+
As input: passes the uploaded image as a numpy.array , PIL.Image or str filepath depending on `type` -- unless `tool` is `sketch` AND source is one of `upload` or `webcam`. In these cases, a dict with keys `image` and `mask` is passed, and the format of the corresponding values depends on `type`.
+
As output: expects a numpy.array , PIL.Image or str or pathlib.Path filepath to an image and displays the image.
+
+
Format expected for examples: a str filepath to a local file that contains the image.
+
+
+
Supported events: change(), edit(), clear(), stream(), upload()
+
+
+
+
+
+
+
import gradio as gr
+import os
+
+
+def image_mod(image):
+ return image.rotate(45)
+
+
+demo = gr.Interface(
+ image_mod,
+ gr.Image(type="pil"),
+ "image",
+ flagging_options=["blurry", "incorrect", "other"],
+ examples=[
+ os.path.join(os.path.dirname(__file__), "images/cheetah1.jpg"),
+ os.path.join(os.path.dirname(__file__), "images/lion.jpg"),
+ os.path.join(os.path.dirname(__file__), "images/logo.png"),
+ os.path.join(os.path.dirname(__file__), "images/tower.jpg"),
+ ],
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ value
+
+ str | _Image.Image | np.ndarray | None
+
+ default: None
+
+
+
+ A PIL Image, numpy array, path or URL for the default value that Image component is going to take. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ shape
+
+ Tuple[int, int] | None
+
+ default: None
+
+
+
+ (width, height) shape to crop and resize image to; if None, matches input image size. Pass None for either width or height to only crop and resize the other.
+
+
+
+
+
+
+
+
+ image_mode
+
+ str
+
+ default: "RGB"
+
+
+
+ "RGB" if color, or "L" if black and white.
+
+
+
+
+
+
+
+
+ invert_colors
+
+ bool
+
+ default: False
+
+
+
+ whether to invert the image as a preprocessing step.
+
+
+
+
+
+
+
+
+ source
+
+ str
+
+ default: "upload"
+
+
+
+ Source of image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "canvas" defaults to a white image that can be edited and drawn upon with tools.
+
+
+
+
+
+
+
+
+ tool
+
+ str | None
+
+ default: None
+
+
+
+ Tools used for editing. "editor" allows a full screen editor (and is the default if source is "upload" or "webcam"), "select" provides a cropping and zoom tool, "sketch" allows you to create a binary sketch (and is the default if source="canvas"), and "color-sketch" allows you to created a sketch in different colors. "color-sketch" can be used with source="upload" or "webcam" to allow sketching on an image. "sketch" can also be used with "upload" or "webcam" to create a mask over an image and in that case both the image and mask are passed into the function as a dictionary with keys "image" and "mask" respectively.
+
+
+
+
+
+
+
+
+ type
+
+ str
+
+ default: "numpy"
+
+
+
+ The format the image is converted to before being passed into the prediction function. "numpy" converts the image to a numpy array with shape (width, height, 3) and values from 0 to 255, "pil" converts the image to a PIL image object, "filepath" passes a str path to a temporary file containing the image.
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ component name in interface.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ if True, will display label.
+
+
+
+
+
+
+
+
+ interactive
+
+ bool | None
+
+ default: None
+
+
+
+ if True, will allow users to upload and edit an image; if False, can only be used to display images. If not provided, this is inferred based on whether the component is used as an input or output.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ streaming
+
+ bool
+
+ default: False
+
+
+
+ If True when used in a `live` interface, will automatically stream webcam feed. Only valid is source is 'webcam'.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+ mirror_webcam
+
+ bool
+
+ default: True
+
+
+
+ If True webcam will be mirrored. Default is True.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.Image
+
+
+ "image"
+
+
+ Uses default values
+
+
+
+
+
+ gradio.Webcam
+
+
+ "webcam"
+
+
+ Uses source="webcam", interactive=True
+
+
+
+
+
+ gradio.Sketchpad
+
+
+ "sketchpad"
+
+
+ Uses image_mode="L", source="canvas", shape=(28, 28), invert_colors=True, interactive=True
+
+
+
+
+
+ gradio.Paint
+
+
+ "paint"
+
+
+ Uses source="canvas", tool="color-sketch", interactive=True
+
+
+
+
+
+ gradio.ImageMask
+
+
+ "imagemask"
+
+
+ Uses source="upload", tool="sketch", interactive=True
+
+
+
+
+
+ gradio.ImagePaint
+
+
+ "imagepaint"
+
+
+ Uses source="upload", tool="color-sketch", interactive=True
+
+
+
+
+
+ gradio.Pil
+
+
+ "pil"
+
+
+ Uses type="pil"
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Image.edit( fn, ยทยทยท)
+
+
+
This event is triggered when the user edits the component (e.g. image) using the built-in editor. This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Image.clear( fn, ยทยทยท)
+
+
+
This event is triggered when the user clears the component (e.g. image or audio) using the X button for the component. This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Image.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Image.stream( fn, inputs, outputs, ยทยทยท)
+
+
+
This event is triggered when the user streams the component (e.g. a live webcam component)
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable
+
+ required
+
+
+
+ Callable function
+
+
+
+
+
+
+
+
+ inputs
+
+ List[Component]
+
+ required
+
+
+
+ List of inputs
+
+
+
+
+
+
+
+
+ outputs
+
+ List[Component]
+
+ required
+
+
+
+ List of outputs
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Image.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Image.style( ยทยทยท)
+
+
+
This method can be used to change the appearance of the Image component.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ height
+
+ int | None
+
+ default: None
+
+
+
+ Height of the image.
+
+
+
+
+
+
+
+
+ width
+
+ int | None
+
+ default: None
+
+
+
+ Width of the image.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Image
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ video_identity
+
+
+
+
+
+
+
+
+
import gradio as gr
+import os
+
+
+def video_identity(video):
+ return video
+
+
+demo = gr.Interface(video_identity,
+ gr.Video(),
+ "playable_video",
+ examples=[
+ os.path.join(os.path.dirname(__file__),
+ "video/video_sample.mp4")],
+ cache_examples=True)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Creates a video component that can be used to upload/record videos (as an input) or display videos (as an output). For the video to be playable in the browser it must have a compatible container and codec combination. Allowed combinations are .mp4 with h264 codec, .ogg with theora codec, and .webm with vp9 codec. If the component detects that the output video would not be playable in the browser it will attempt to convert it to a playable mp4 video. If the conversion fails, the original video is returned.
+
+
+
As input: passes the uploaded video as a str filepath or URL whose extension can be modified by `format`.
+
As output: expects a str filepath to a video which is displayed.
+
+
Format expected for examples: a str filepath to a local file that contains the video.
+
+
+
Supported events: change(), clear(), pause(), play(), stop(), upload()
+
+
+
+
+
+
+
import gradio as gr
+import os
+
+
+def video_identity(video):
+ return video
+
+
+demo = gr.Interface(video_identity,
+ gr.Video(),
+ "playable_video",
+ examples=[
+ os.path.join(os.path.dirname(__file__),
+ "video/video_sample.mp4")],
+ cache_examples=True)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ value
+
+ str | Callable | None
+
+ default: None
+
+
+
+ A path or URL for the default value that Video component is going to take. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ format
+
+ str | None
+
+ default: None
+
+
+
+ Format of video format to be returned by component, such as 'avi' or 'mp4'. Use 'mp4' to ensure browser playability. If set to None, video will keep uploaded format.
+
+
+
+
+
+
+
+
+ source
+
+ str
+
+ default: "upload"
+
+
+
+ Source of video. "upload" creates a box where user can drop an video file, "webcam" allows user to record a video from their webcam.
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ component name in interface.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ if True, will display label.
+
+
+
+
+
+
+
+
+ interactive
+
+ bool | None
+
+ default: None
+
+
+
+ if True, will allow users to upload a video; if False, can only be used to display videos. If not provided, this is inferred based on whether the component is used as an input or output.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+ mirror_webcam
+
+ bool
+
+ default: True
+
+
+
+ If True webcam will be mirrored. Default is True.
+
+
+
+
+
+
+
+
+ include_audio
+
+ bool | None
+
+ default: None
+
+
+
+ Whether the component should record/retain the audio track for a video. By default, audio is excluded for webcam videos and included for uploaded videos.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.Video
+
+
+ "video"
+
+
+ Uses default values
+
+
+
+
+
+ gradio.PlayableVideo
+
+
+ "playablevideo"
+
+
+ Uses format="mp4"
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Video.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Video.clear( fn, ยทยทยท)
+
+
+
This event is triggered when the user clears the component (e.g. image or audio) using the X button for the component. This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Video.play( fn, ยทยทยท)
+
+
+
This event is triggered when the user plays the component (e.g. audio or video). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Video.pause( fn, ยทยทยท)
+
+
+
This event is triggered when the user pauses the component (e.g. audio or video). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Video.stop( fn, ยทยทยท)
+
+
+
This event is triggered when the user stops the component (e.g. audio or video). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Video.style( ยทยทยท)
+
+
+
This method can be used to change the appearance of the video component.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ height
+
+ int | None
+
+ default: None
+
+
+
+ Height of the video.
+
+
+
+
+
+
+
+
+ width
+
+ int | None
+
+ default: None
+
+
+
+ Width of the video.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Video
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ main_note
+
+ generate_tone
+
+ reverse_audio
+
+
+
+
+
+
+
+
+
from math import log2, pow
+import os
+
+import numpy as np
+from scipy.fftpack import fft
+
+import gradio as gr
+
+A4 = 440
+C0 = A4 * pow(2, -4.75)
+name = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
+
+
+def get_pitch(freq):
+ h = round(12 * log2(freq / C0))
+ n = h % 12
+ return name[n]
+
+
+def main_note(audio):
+ rate, y = audio
+ if len(y.shape) == 2:
+ y = y.T[0]
+ N = len(y)
+ T = 1.0 / rate
+ x = np.linspace(0.0, N * T, N)
+ yf = fft(y)
+ yf2 = 2.0 / N * np.abs(yf[0 : N // 2])
+ xf = np.linspace(0.0, 1.0 / (2.0 * T), N // 2)
+
+ volume_per_pitch = {}
+ total_volume = np.sum(yf2)
+ for freq, volume in zip(xf, yf2):
+ if freq == 0:
+ continue
+ pitch = get_pitch(freq)
+ if pitch not in volume_per_pitch:
+ volume_per_pitch[pitch] = 0
+ volume_per_pitch[pitch] += 1.0 * volume / total_volume
+ volume_per_pitch = {k: float(v) for k, v in volume_per_pitch.items()}
+ return volume_per_pitch
+
+
+demo = gr.Interface(
+ main_note,
+ gr.Audio(source="microphone"),
+ gr.Label(num_top_classes=4),
+ examples=[
+ [os.path.join(os.path.dirname(__file__),"audio/recording1.wav")],
+ [os.path.join(os.path.dirname(__file__),"audio/cantina.wav")],
+ ],
+ interpretation="default",
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import numpy as np
+import gradio as gr
+
+notes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
+
+def generate_tone(note, octave, duration):
+ sr = 48000
+ a4_freq, tones_from_a4 = 440, 12 * (octave - 4) + (note - 9)
+ frequency = a4_freq * 2 ** (tones_from_a4 / 12)
+ duration = int(duration)
+ audio = np.linspace(0, duration, duration * sr)
+ audio = (20000 * np.sin(audio * (2 * np.pi * frequency))).astype(np.int16)
+ return sr, audio
+
+demo = gr.Interface(
+ generate_tone,
+ [
+ gr.Dropdown(notes, type="index"),
+ gr.Slider(4, 6, step=1),
+ gr.Textbox(value=1, label="Duration in seconds"),
+ ],
+ "audio",
+)
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import os
+
+import numpy as np
+
+import gradio as gr
+
+
+def reverse_audio(audio):
+ sr, data = audio
+ return (sr, np.flipud(data))
+
+
+demo = gr.Interface(fn=reverse_audio,
+ inputs="microphone",
+ outputs="audio",
+ examples=[
+ "https://samplelib.com/lib/preview/mp3/sample-3s.mp3",
+ os.path.join(os.path.dirname(__file__), "audio/recording1.wav")
+ ], cache_examples=True)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Creates an audio component that can be used to upload/record audio (as an input) or display audio (as an output).
+
+
+
As input: passes the uploaded audio as a Tuple(int, numpy.array) corresponding to (sample rate, data) or as a str filepath, depending on `type`
+
As output: expects a Tuple(int, numpy.array) corresponding to (sample rate, data) or as a str filepath or URL to an audio file, which gets displayed
+
+
Format expected for examples: a str filepath to a local file that contains audio.
+
+
+
Supported events: change(), clear(), pause(), play(), stop(), stream(), upload()
+
+
+
+
+
+
+
from math import log2, pow
+import os
+
+import numpy as np
+from scipy.fftpack import fft
+
+import gradio as gr
+
+A4 = 440
+C0 = A4 * pow(2, -4.75)
+name = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
+
+
+def get_pitch(freq):
+ h = round(12 * log2(freq / C0))
+ n = h % 12
+ return name[n]
+
+
+def main_note(audio):
+ rate, y = audio
+ if len(y.shape) == 2:
+ y = y.T[0]
+ N = len(y)
+ T = 1.0 / rate
+ x = np.linspace(0.0, N * T, N)
+ yf = fft(y)
+ yf2 = 2.0 / N * np.abs(yf[0 : N // 2])
+ xf = np.linspace(0.0, 1.0 / (2.0 * T), N // 2)
+
+ volume_per_pitch = {}
+ total_volume = np.sum(yf2)
+ for freq, volume in zip(xf, yf2):
+ if freq == 0:
+ continue
+ pitch = get_pitch(freq)
+ if pitch not in volume_per_pitch:
+ volume_per_pitch[pitch] = 0
+ volume_per_pitch[pitch] += 1.0 * volume / total_volume
+ volume_per_pitch = {k: float(v) for k, v in volume_per_pitch.items()}
+ return volume_per_pitch
+
+
+demo = gr.Interface(
+ main_note,
+ gr.Audio(source="microphone"),
+ gr.Label(num_top_classes=4),
+ examples=[
+ [os.path.join(os.path.dirname(__file__),"audio/recording1.wav")],
+ [os.path.join(os.path.dirname(__file__),"audio/cantina.wav")],
+ ],
+ interpretation="default",
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ value
+
+ str | Tuple[int, np.ndarray] | Callable | None
+
+ default: None
+
+
+
+ A path, URL, or [sample_rate, numpy array] tuple for the default value that Audio component is going to take. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ source
+
+ str
+
+ default: "upload"
+
+
+
+ Source of audio. "upload" creates a box where user can drop an audio file, "microphone" creates a microphone input.
+
+
+
+
+
+
+
+
+ type
+
+ str
+
+ default: "numpy"
+
+
+
+ The format the audio file is converted to before being passed into the prediction function. "numpy" converts the audio to a tuple consisting of: (int sample rate, numpy.array for the data), "filepath" passes a str path to a temporary file containing the audio.
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ component name in interface.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ if True, will display label.
+
+
+
+
+
+
+
+
+ interactive
+
+ bool | None
+
+ default: None
+
+
+
+ if True, will allow users to upload and edit a audio file; if False, can only be used to play audio. If not provided, this is inferred based on whether the component is used as an input or output.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ streaming
+
+ bool
+
+ default: False
+
+
+
+ If set to True when used in a `live` interface, will automatically stream webcam feed. Only valid is source is 'microphone'.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.Audio
+
+
+ "audio"
+
+
+ Uses default values
+
+
+
+
+
+ gradio.Microphone
+
+
+ "microphone"
+
+
+ Uses source="microphone"
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Audio.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Audio.clear( fn, ยทยทยท)
+
+
+
This event is triggered when the user clears the component (e.g. image or audio) using the X button for the component. This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Audio.play( fn, ยทยทยท)
+
+
+
This event is triggered when the user plays the component (e.g. audio or video). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Audio.pause( fn, ยทยทยท)
+
+
+
This event is triggered when the user pauses the component (e.g. audio or video). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Audio.stop( fn, ยทยทยท)
+
+
+
This event is triggered when the user stops the component (e.g. audio or video). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Audio.stream( fn, inputs, outputs, ยทยทยท)
+
+
+
This event is triggered when the user streams the component (e.g. a live webcam component)
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable
+
+ required
+
+
+
+ Callable function
+
+
+
+
+
+
+
+
+ inputs
+
+ List[Component]
+
+ required
+
+
+
+ List of inputs
+
+
+
+
+
+
+
+
+ outputs
+
+ List[Component]
+
+ required
+
+
+
+ List of outputs
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Audio.style( ยทยทยท)
+
+
+
This method can be used to change the appearance of the audio component.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Audio
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ zip_to_json
+
+ zip_files
+
+
+
+
+
+
+
+
+
from zipfile import ZipFile
+
+import gradio as gr
+
+
+def zip_to_json(file_obj):
+ files = []
+ with ZipFile(file_obj.name) as zfile:
+ for zinfo in zfile.infolist():
+ files.append(
+ {
+ "name": zinfo.filename,
+ "file_size": zinfo.file_size,
+ "compressed_size": zinfo.compress_size,
+ }
+ )
+ return files
+
+
+demo = gr.Interface(zip_to_json, "file", "json")
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import os
+from zipfile import ZipFile
+
+import gradio as gr
+
+
+def zip_files(files):
+ with ZipFile("tmp.zip", "w") as zipObj:
+ for idx, file in enumerate(files):
+ zipObj.write(file.name, "file" + str(idx))
+ return "tmp.zip"
+
+demo = gr.Interface(
+ zip_files,
+ gr.File(file_count="multiple", file_types=["text", ".json", ".csv"]),
+ "file",
+ examples=[[[os.path.join(os.path.dirname(__file__),"files/titanic.csv"),
+ os.path.join(os.path.dirname(__file__),"files/titanic.csv"),
+ os.path.join(os.path.dirname(__file__),"files/titanic.csv")]]],
+ cache_examples=True
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Creates a file component that allows uploading generic file (when used as an input) and or displaying generic files (output).
+
+
+
As input: passes the uploaded file as a file-object or List[file-object] depending on `file_count` (or a bytes /Listbytes depending on `type`)
+
As output: expects function to return a str path to a file, or List[str] consisting of paths to files.
+
+
Format expected for examples: a str path to a local file that populates the component.
+
+
+
Supported events: change(), clear(), upload()
+
+
+
+
+
+
+
from zipfile import ZipFile
+
+import gradio as gr
+
+
+def zip_to_json(file_obj):
+ files = []
+ with ZipFile(file_obj.name) as zfile:
+ for zinfo in zfile.infolist():
+ files.append(
+ {
+ "name": zinfo.filename,
+ "file_size": zinfo.file_size,
+ "compressed_size": zinfo.compress_size,
+ }
+ )
+ return files
+
+
+demo = gr.Interface(zip_to_json, "file", "json")
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ value
+
+ str | List[str] | Callable | None
+
+ default: None
+
+
+
+ Default file to display, given as str file path. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ file_count
+
+ str
+
+ default: "single"
+
+
+
+ if single, allows user to upload one file. If "multiple", user uploads multiple files. If "directory", user uploads all files in selected directory. Return type will be list for each file in case of "multiple" or "directory".
+
+
+
+
+
+
+
+
+ file_types
+
+ List[str] | None
+
+ default: None
+
+
+
+ List of file extensions or types of files to be uploaded (e.g. ['image', '.json', '.mp4']). "file" allows any file to be uploaded, "image" allows only image files to be uploaded, "audio" allows only audio files to be uploaded, "video" allows only video files to be uploaded, "text" allows only text files to be uploaded.
+
+
+
+
+
+
+
+
+ type
+
+ str
+
+ default: "file"
+
+
+
+ Type of value to be returned by component. "file" returns a temporary file object whose path can be retrieved by file_obj.name and original filename can be retrieved with file_obj.orig_name, "binary" returns an bytes object.
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ component name in interface.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ if True, will display label.
+
+
+
+
+
+
+
+
+ interactive
+
+ bool | None
+
+ default: None
+
+
+
+ if True, will allow users to upload a file; if False, can only be used to display files. If not provided, this is inferred based on whether the component is used as an input or output.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.File
+
+
+ "file"
+
+
+ Uses default values
+
+
+
+
+
+ gradio.Files
+
+
+ "files"
+
+
+ Uses file_count="multiple"
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.File.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.File.clear( fn, ยทยทยท)
+
+
+
This event is triggered when the user clears the component (e.g. image or audio) using the X button for the component. This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.File.style( ยทยทยท)
+
+
+
This method can be used to change the appearance of the file component.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about File
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ filter_records
+
+ matrix_transpose
+
+ tax_calculator
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+
+def filter_records(records, gender):
+ return records[records["gender"] == gender]
+
+
+demo = gr.Interface(
+ filter_records,
+ [
+ gr.Dataframe(
+ headers=["name", "age", "gender"],
+ datatype=["str", "number", "str"],
+ row_count=5,
+ col_count=(3, "fixed"),
+ ),
+ gr.Dropdown(["M", "F", "O"]),
+ ],
+ "dataframe",
+ description="Enter gender as 'M', 'F', or 'O' for other.",
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import numpy as np
+
+import gradio as gr
+
+
+def transpose(matrix):
+ return matrix.T
+
+
+demo = gr.Interface(
+ transpose,
+ gr.Dataframe(type="numpy", datatype="number", row_count=5, col_count=3),
+ "numpy",
+ examples=[
+ [np.zeros((3, 3)).tolist()],
+ [np.ones((2, 2)).tolist()],
+ [np.random.randint(0, 10, (3, 10)).tolist()],
+ [np.random.randint(0, 10, (10, 3)).tolist()],
+ [np.random.randint(0, 10, (10, 10)).tolist()],
+ ],
+ cache_examples=False
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+def tax_calculator(income, marital_status, assets):
+ tax_brackets = [(10, 0), (25, 8), (60, 12), (120, 20), (250, 30)]
+ total_deductible = sum(assets["Cost"])
+ taxable_income = income - total_deductible
+
+ total_tax = 0
+ for bracket, rate in tax_brackets:
+ if taxable_income > bracket:
+ total_tax += (taxable_income - bracket) * rate / 100
+
+ if marital_status == "Married":
+ total_tax *= 0.75
+ elif marital_status == "Divorced":
+ total_tax *= 0.8
+
+ return round(total_tax)
+
+demo = gr.Interface(
+ tax_calculator,
+ [
+ "number",
+ gr.Radio(["Single", "Married", "Divorced"]),
+ gr.Dataframe(
+ headers=["Item", "Cost"],
+ datatype=["str", "number"],
+ label="Assets Purchased this Year",
+ ),
+ ],
+ "number",
+ examples=[
+ [10000, "Married", [["Suit", 5000], ["Laptop", 800], ["Car", 1800]]],
+ [80000, "Single", [["Suit", 800], ["Watch", 1800], ["Car", 800]]],
+ ],
+)
+
+demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Accepts or displays 2D input through a spreadsheet-like component for dataframes.
+
+
+
As input: passes the uploaded spreadsheet data as a pandas.DataFrame , numpy.array , List[List] , or List depending on `type`
+
As output: expects a pandas.DataFrame , numpy.array , List[List] , List , a Dict with keys `data` (and optionally `headers`), or str path to a csv, which is rendered in the spreadsheet.
+
+
Format expected for examples: a str filepath to a csv with data, a pandas dataframe, or a list of lists (excluding headers) where each sublist is a row of data.
+
+
+
Supported events: change()
+
+
+
+
+
+
+
import gradio as gr
+
+
+def filter_records(records, gender):
+ return records[records["gender"] == gender]
+
+
+demo = gr.Interface(
+ filter_records,
+ [
+ gr.Dataframe(
+ headers=["name", "age", "gender"],
+ datatype=["str", "number", "str"],
+ row_count=5,
+ col_count=(3, "fixed"),
+ ),
+ gr.Dropdown(["M", "F", "O"]),
+ ],
+ "dataframe",
+ description="Enter gender as 'M', 'F', or 'O' for other.",
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ value
+
+ List[List[Any]] | Callable | None
+
+ default: None
+
+
+
+ Default value as a 2-dimensional list of values. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ headers
+
+ List[str] | None
+
+ default: None
+
+
+
+ List of str header names. If None, no headers are shown.
+
+
+
+
+
+
+
+
+ row_count
+
+ int | Tuple[int, str]
+
+ default: (1, 'dynamic')
+
+
+
+ Limit number of rows for input and decide whether user can create new rows. The first element of the tuple is an `int`, the row count; the second should be 'fixed' or 'dynamic', the new row behaviour. If an `int` is passed the rows default to 'dynamic'
+
+
+
+
+
+
+
+
+ col_count
+
+ int | Tuple[int, str] | None
+
+ default: None
+
+
+
+ Limit number of columns for input and decide whether user can create new columns. The first element of the tuple is an `int`, the number of columns; the second should be 'fixed' or 'dynamic', the new column behaviour. If an `int` is passed the columns default to 'dynamic'
+
+
+
+
+
+
+
+
+ datatype
+
+ str | List[str]
+
+ default: "str"
+
+
+
+ Datatype of values in sheet. Can be provided per column as a list of strings, or for the entire sheet as a single string. Valid datatypes are "str", "number", "bool", "date", and "markdown".
+
+
+
+
+
+
+
+
+ type
+
+ str
+
+ default: "pandas"
+
+
+
+ Type of value to be returned by component. "pandas" for pandas dataframe, "numpy" for numpy array, or "array" for a Python array.
+
+
+
+
+
+
+
+
+ max_rows
+
+ int | None
+
+ default: 20
+
+
+
+ Maximum number of rows to display at once. Set to None for infinite.
+
+
+
+
+
+
+
+
+ max_cols
+
+ int | None
+
+ default: None
+
+
+
+ Maximum number of columns to display at once. Set to None for infinite.
+
+
+
+
+
+
+
+
+ overflow_row_behaviour
+
+ str
+
+ default: "paginate"
+
+
+
+ If set to "paginate", will create pages for overflow rows. If set to "show_ends", will show initial and final rows and truncate middle rows.
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ component name in interface.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ if True, will display label.
+
+
+
+
+
+
+
+
+ interactive
+
+ bool | None
+
+ default: None
+
+
+
+ if True, will allow users to edit the dataframe; if False, can only be used to display data. If not provided, this is inferred based on whether the component is used as an input or output.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+ wrap
+
+ bool
+
+ default: False
+
+
+
+ if True text in table cells will wrap when appropriate, if False the table will scroll horiztonally. Defaults to False.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.Dataframe
+
+
+ "dataframe"
+
+
+ Uses default values
+
+
+
+
+
+ gradio.Numpy
+
+
+ "numpy"
+
+
+ Uses type="numpy"
+
+
+
+
+
+ gradio.Matrix
+
+
+ "matrix"
+
+
+ Uses type="array"
+
+
+
+
+
+ gradio.List
+
+
+ "list"
+
+
+ Uses type="array", col_count=1
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Dataframe.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Dataframe.style( ยทยทยท)
+
+
+
This method can be used to change the appearance of the DataFrame component.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Dataframe
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ fraud_detector
+
+
+
+
+
+
+
+
+
import random
+import os
+import gradio as gr
+
+
+def fraud_detector(card_activity, categories, sensitivity):
+ activity_range = random.randint(0, 100)
+ drop_columns = [
+ column for column in ["retail", "food", "other"] if column not in categories
+ ]
+ if len(drop_columns):
+ card_activity.drop(columns=drop_columns, inplace=True)
+ return (
+ card_activity,
+ card_activity,
+ {"fraud": activity_range / 100.0, "not fraud": 1 - activity_range / 100.0},
+ )
+
+
+demo = gr.Interface(
+ fraud_detector,
+ [
+ gr.Timeseries(x="time", y=["retail", "food", "other"]),
+ gr.CheckboxGroup(
+ ["retail", "food", "other"], value=["retail", "food", "other"]
+ ),
+ gr.Slider(1, 3),
+ ],
+ [
+ "dataframe",
+ gr.Timeseries(x="time", y=["retail", "food", "other"]),
+ gr.Label(label="Fraud Level"),
+ ],
+ examples=[
+ [os.path.join(os.path.dirname(__file__), "fraud.csv"), ["retail", "food", "other"], 1.0],
+ ],
+)
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
gradio.Timeseries( ยทยทยท)
+
+
+
+
+
+
+
+
+
+
+
Creates a component that can be used to upload/preview timeseries csv files or display a dataframe consisting of a time series graphically.
+
+
+
As input: passes the uploaded timeseries data as a pandas.DataFrame into the function
+
As output: expects a pandas.DataFrame or str path to a csv to be returned, which is then displayed as a timeseries graph
+
+
Format expected for examples: a str filepath of csv data with time series data.
+
+
+
Supported events: change()
+
+
+
+
+
+
+
import random
+import os
+import gradio as gr
+
+
+def fraud_detector(card_activity, categories, sensitivity):
+ activity_range = random.randint(0, 100)
+ drop_columns = [
+ column for column in ["retail", "food", "other"] if column not in categories
+ ]
+ if len(drop_columns):
+ card_activity.drop(columns=drop_columns, inplace=True)
+ return (
+ card_activity,
+ card_activity,
+ {"fraud": activity_range / 100.0, "not fraud": 1 - activity_range / 100.0},
+ )
+
+
+demo = gr.Interface(
+ fraud_detector,
+ [
+ gr.Timeseries(x="time", y=["retail", "food", "other"]),
+ gr.CheckboxGroup(
+ ["retail", "food", "other"], value=["retail", "food", "other"]
+ ),
+ gr.Slider(1, 3),
+ ],
+ [
+ "dataframe",
+ gr.Timeseries(x="time", y=["retail", "food", "other"]),
+ gr.Label(label="Fraud Level"),
+ ],
+ examples=[
+ [os.path.join(os.path.dirname(__file__), "fraud.csv"), ["retail", "food", "other"], 1.0],
+ ],
+)
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ value
+
+ str | Callable | None
+
+ default: None
+
+
+
+ File path for the timeseries csv file. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ x
+
+ str | None
+
+ default: None
+
+
+
+ Column name of x (time) series. None if csv has no headers, in which case first column is x series.
+
+
+
+
+
+
+
+
+ y
+
+ str | List[str] | None
+
+ default: None
+
+
+
+ Column name of y series, or list of column names if multiple series. None if csv has no headers, in which case every column after first is a y series.
+
+
+
+
+
+
+
+
+ colors
+
+ List[str] | None
+
+ default: None
+
+
+
+ an ordered list of colors to use for each line plot
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ component name in interface.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ if True, will display label.
+
+
+
+
+
+
+
+
+ interactive
+
+ bool | None
+
+ default: None
+
+
+
+ if True, will allow users to upload a timeseries csv; if False, can only be used to display timeseries data. If not provided, this is inferred based on whether the component is used as an input or output.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.Timeseries
+
+
+ "timeseries"
+
+
+ Uses default values
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Timeseries.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Timeseries.style( ยทยทยท)
+
+
+
This method can be used to change the appearance of the TimeSeries component.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Timeseries
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ chatbot_demo
+
+ blocks_simple_squares
+
+
+
+
+
+
+
+
+
import random
+import gradio as gr
+
+def chat(message, history):
+ history = history or []
+ message = message.lower()
+ if message.startswith("how many"):
+ response = str(random.randint(1, 10))
+ elif message.startswith("how"):
+ response = random.choice(["Great", "Good", "Okay", "Bad"])
+ elif message.startswith("where"):
+ response = random.choice(["Here", "There", "Somewhere"])
+ else:
+ response = "I don't know"
+ history.append((message, response))
+ return history, history
+
+chatbot = gr.Chatbot().style(color_map=("green", "pink"))
+demo = gr.Interface(
+ chat,
+ ["text", "state"],
+ [chatbot, "state"],
+ allow_flagging="never",
+)
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+demo = gr.Blocks(css="#btn {color: red}")
+
+with demo:
+ default_json = {"a": "a"}
+
+ num = gr.State(value=0)
+ squared = gr.Number(value=0)
+ btn = gr.Button("Next Square", elem_id="btn").style(rounded=False)
+
+ stats = gr.State(value=default_json)
+ table = gr.JSON()
+
+ def increase(var, stats_history):
+ var += 1
+ stats_history[str(var)] = var**2
+ return var, var**2, stats_history, stats_history
+
+ btn.click(increase, [num, stats], [num, squared, stats, table])
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
Special hidden component that stores session state across runs of the demo by the same user. The value of the State variable is cleared when the user refreshes the page.
+
+
+
As input: No preprocessing is performed
+
As output: No postprocessing is performed
+
+
+
+
+
+
+
+
import random
+import gradio as gr
+
+def chat(message, history):
+ history = history or []
+ message = message.lower()
+ if message.startswith("how many"):
+ response = str(random.randint(1, 10))
+ elif message.startswith("how"):
+ response = random.choice(["Great", "Good", "Okay", "Bad"])
+ elif message.startswith("where"):
+ response = random.choice(["Here", "There", "Somewhere"])
+ else:
+ response = "I don't know"
+ history.append((message, response))
+ return history, history
+
+chatbot = gr.Chatbot().style(color_map=("green", "pink"))
+demo = gr.Interface(
+ chat,
+ ["text", "state"],
+ [chatbot, "state"],
+ allow_flagging="never",
+)
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ value
+
+ Any
+
+ default: None
+
+
+
+ the initial value of the state. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about State
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ color_picker
+
+ color_generator
+
+
+
+
+
+
+
+
+
import gradio as gr
+import numpy as np
+import os
+from PIL import Image, ImageColor
+
+
+def change_color(icon, color):
+
+ """
+ Function that given an icon in .png format changes its color
+ Args:
+ icon: Icon whose color needs to be changed.
+ color: Chosen color with which to edit the input icon.
+ Returns:
+ edited_image: Edited icon.
+ """
+ img = icon.convert("LA")
+ img = img.convert("RGBA")
+ image_np = np.array(icon)
+ _, _, _, alpha = image_np.T
+ mask = alpha > 0
+ image_np[..., :-1][mask.T] = ImageColor.getcolor(color, "RGB")
+ edited_image = Image.fromarray(image_np)
+ return edited_image
+
+
+inputs = [
+ gr.Image(label="icon", type="pil", image_mode="RGBA"),
+ gr.ColorPicker(label="color"),
+]
+outputs = gr.Image(label="colored icon")
+
+demo = gr.Interface(
+ fn=change_color,
+ inputs=inputs,
+ outputs=outputs,
+ examples=[
+ [os.path.join(os.path.dirname(__file__), "rabbit.png"), "#ff0000"],
+ [os.path.join(os.path.dirname(__file__), "rabbit.png"), "#0000FF"],
+ ],
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import gradio as gr
+import cv2
+import numpy as np
+import random
+
+
+# Convert decimal color to hexadecimal color
+def RGB_to_Hex(rgb):
+ color = "#"
+ for i in rgb:
+ num = int(i)
+ color += str(hex(num))[-2:].replace("x", "0").upper()
+ return color
+
+
+# Randomly generate light or dark colors
+def random_color(is_light=True):
+ return (
+ random.randint(0, 127) + int(is_light) * 128,
+ random.randint(0, 127) + int(is_light) * 128,
+ random.randint(0, 127) + int(is_light) * 128,
+ )
+
+
+def switch_color(color_style):
+ if color_style == "light":
+ is_light = True
+ elif color_style == "dark":
+ is_light = False
+ back_color_ = random_color(is_light) # Randomly generate colors
+ back_color = RGB_to_Hex(back_color_) # Convert to hexadecimal
+
+ # Draw color pictures.
+ w, h = 50, 50
+ img = np.zeros((h, w, 3), np.uint8)
+ cv2.rectangle(img, (0, 0), (w, h), back_color_, thickness=-1)
+
+ return back_color, back_color, img
+
+
+inputs = [gr.Radio(["light", "dark"], value="light")]
+
+outputs = [
+ gr.ColorPicker(label="color"),
+ gr.Textbox(label="hexadecimal color"),
+ gr.Image(type="numpy", label="color picture"),
+]
+
+title = "Color Generator"
+description = (
+ "Click the Submit button, and a dark or light color will be randomly generated."
+)
+
+demo = gr.Interface(
+ fn=switch_color,
+ inputs=inputs,
+ outputs=outputs,
+ title=title,
+ description=description,
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
gradio.ColorPicker( ยทยทยท)
+
+
+
+
+
+
+
+
+
+
+
Creates a color picker for user to select a color as string input.
+
+
+
As input: passes selected color value as a str into the function.
+
As output: expects a str returned from function and sets color picker value to it.
+
+
Format expected for examples: a str with a hexadecimal representation of a color, e.g. "#ff0000" for red.
+
+
+
Supported events: change(), submit()
+
+
+
+
+
+
+
import gradio as gr
+import numpy as np
+import os
+from PIL import Image, ImageColor
+
+
+def change_color(icon, color):
+
+ """
+ Function that given an icon in .png format changes its color
+ Args:
+ icon: Icon whose color needs to be changed.
+ color: Chosen color with which to edit the input icon.
+ Returns:
+ edited_image: Edited icon.
+ """
+ img = icon.convert("LA")
+ img = img.convert("RGBA")
+ image_np = np.array(icon)
+ _, _, _, alpha = image_np.T
+ mask = alpha > 0
+ image_np[..., :-1][mask.T] = ImageColor.getcolor(color, "RGB")
+ edited_image = Image.fromarray(image_np)
+ return edited_image
+
+
+inputs = [
+ gr.Image(label="icon", type="pil", image_mode="RGBA"),
+ gr.ColorPicker(label="color"),
+]
+outputs = gr.Image(label="colored icon")
+
+demo = gr.Interface(
+ fn=change_color,
+ inputs=inputs,
+ outputs=outputs,
+ examples=[
+ [os.path.join(os.path.dirname(__file__), "rabbit.png"), "#ff0000"],
+ [os.path.join(os.path.dirname(__file__), "rabbit.png"), "#0000FF"],
+ ],
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ value
+
+ str | Callable | None
+
+ default: None
+
+
+
+ default text to provide in color picker. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ component name in interface.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ if True, will display label.
+
+
+
+
+
+
+
+
+ interactive
+
+ bool | None
+
+ default: None
+
+
+
+ if True, will be rendered as an editable color picker; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.ColorPicker
+
+
+ "colorpicker"
+
+
+ Uses default values
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.ColorPicker.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.ColorPicker.submit( fn, ยทยทยท)
+
+
+
This event is triggered when the user presses the Enter key while the component (e.g. a textbox) is focused. This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.ColorPicker.style( ยทยทยท)
+
+
+
This method can be used to change the appearance of the component.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ container
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the component in a container - providing some extra padding around the border.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about ColorPicker
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ main_note
+
+ titanic_survival
+
+
+
+
+
+
+
+
+
from math import log2, pow
+import os
+
+import numpy as np
+from scipy.fftpack import fft
+
+import gradio as gr
+
+A4 = 440
+C0 = A4 * pow(2, -4.75)
+name = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
+
+
+def get_pitch(freq):
+ h = round(12 * log2(freq / C0))
+ n = h % 12
+ return name[n]
+
+
+def main_note(audio):
+ rate, y = audio
+ if len(y.shape) == 2:
+ y = y.T[0]
+ N = len(y)
+ T = 1.0 / rate
+ x = np.linspace(0.0, N * T, N)
+ yf = fft(y)
+ yf2 = 2.0 / N * np.abs(yf[0 : N // 2])
+ xf = np.linspace(0.0, 1.0 / (2.0 * T), N // 2)
+
+ volume_per_pitch = {}
+ total_volume = np.sum(yf2)
+ for freq, volume in zip(xf, yf2):
+ if freq == 0:
+ continue
+ pitch = get_pitch(freq)
+ if pitch not in volume_per_pitch:
+ volume_per_pitch[pitch] = 0
+ volume_per_pitch[pitch] += 1.0 * volume / total_volume
+ volume_per_pitch = {k: float(v) for k, v in volume_per_pitch.items()}
+ return volume_per_pitch
+
+
+demo = gr.Interface(
+ main_note,
+ gr.Audio(source="microphone"),
+ gr.Label(num_top_classes=4),
+ examples=[
+ [os.path.join(os.path.dirname(__file__),"audio/recording1.wav")],
+ [os.path.join(os.path.dirname(__file__),"audio/cantina.wav")],
+ ],
+ interpretation="default",
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import os
+
+import pandas as pd
+from sklearn.ensemble import RandomForestClassifier
+from sklearn.model_selection import train_test_split
+
+import gradio as gr
+
+current_dir = os.path.dirname(os.path.realpath(__file__))
+data = pd.read_csv(os.path.join(current_dir, "files/titanic.csv"))
+
+
+def encode_age(df):
+ df.Age = df.Age.fillna(-0.5)
+ bins = (-1, 0, 5, 12, 18, 25, 35, 60, 120)
+ categories = pd.cut(df.Age, bins, labels=False)
+ df.Age = categories
+ return df
+
+
+def encode_fare(df):
+ df.Fare = df.Fare.fillna(-0.5)
+ bins = (-1, 0, 8, 15, 31, 1000)
+ categories = pd.cut(df.Fare, bins, labels=False)
+ df.Fare = categories
+ return df
+
+
+def encode_df(df):
+ df = encode_age(df)
+ df = encode_fare(df)
+ sex_mapping = {"male": 0, "female": 1}
+ df = df.replace({"Sex": sex_mapping})
+ embark_mapping = {"S": 1, "C": 2, "Q": 3}
+ df = df.replace({"Embarked": embark_mapping})
+ df.Embarked = df.Embarked.fillna(0)
+ df["Company"] = 0
+ df.loc[(df["SibSp"] > 0), "Company"] = 1
+ df.loc[(df["Parch"] > 0), "Company"] = 2
+ df.loc[(df["SibSp"] > 0) & (df["Parch"] > 0), "Company"] = 3
+ df = df[
+ [
+ "PassengerId",
+ "Pclass",
+ "Sex",
+ "Age",
+ "Fare",
+ "Embarked",
+ "Company",
+ "Survived",
+ ]
+ ]
+ return df
+
+
+train = encode_df(data)
+
+X_all = train.drop(["Survived", "PassengerId"], axis=1)
+y_all = train["Survived"]
+
+num_test = 0.20
+X_train, X_test, y_train, y_test = train_test_split(
+ X_all, y_all, test_size=num_test, random_state=23
+)
+
+clf = RandomForestClassifier()
+clf.fit(X_train, y_train)
+predictions = clf.predict(X_test)
+
+
+def predict_survival(passenger_class, is_male, age, company, fare, embark_point):
+ if passenger_class is None or embark_point is None:
+ return None
+ df = pd.DataFrame.from_dict(
+ {
+ "Pclass": [passenger_class + 1],
+ "Sex": [0 if is_male else 1],
+ "Age": [age],
+ "Company": [
+ (1 if "Sibling" in company else 0) + (2 if "Child" in company else 0)
+ ],
+ "Fare": [fare],
+ "Embarked": [embark_point + 1],
+ }
+ )
+ df = encode_age(df)
+ df = encode_fare(df)
+ pred = clf.predict_proba(df)[0]
+ return {"Perishes": float(pred[0]), "Survives": float(pred[1])}
+
+
+demo = gr.Interface(
+ predict_survival,
+ [
+ gr.Dropdown(["first", "second", "third"], type="index"),
+ "checkbox",
+ gr.Slider(0, 80, value=25),
+ gr.CheckboxGroup(["Sibling", "Child"], label="Travelling with (select all)"),
+ gr.Number(value=20),
+ gr.Radio(["S", "C", "Q"], type="index"),
+ ],
+ "label",
+ examples=[
+ ["first", True, 30, [], 50, "S"],
+ ["second", False, 40, ["Sibling", "Child"], 10, "Q"],
+ ["third", True, 30, ["Child"], 20, "S"],
+ ],
+ interpretation="default",
+ live=True,
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Displays a classification label, along with confidence scores of top categories, if provided.
+
+
+
As input: this component does *not* accept input.
+
As output: expects a Dict[str, float] of classes and confidences, or str with just the class or an int /float for regression outputs, or a str path to a .json file containing a json dictionary in the structure produced by Label.postprocess().
+
+
+
Supported events: change()
+
+
+
+
+
+
+
from math import log2, pow
+import os
+
+import numpy as np
+from scipy.fftpack import fft
+
+import gradio as gr
+
+A4 = 440
+C0 = A4 * pow(2, -4.75)
+name = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
+
+
+def get_pitch(freq):
+ h = round(12 * log2(freq / C0))
+ n = h % 12
+ return name[n]
+
+
+def main_note(audio):
+ rate, y = audio
+ if len(y.shape) == 2:
+ y = y.T[0]
+ N = len(y)
+ T = 1.0 / rate
+ x = np.linspace(0.0, N * T, N)
+ yf = fft(y)
+ yf2 = 2.0 / N * np.abs(yf[0 : N // 2])
+ xf = np.linspace(0.0, 1.0 / (2.0 * T), N // 2)
+
+ volume_per_pitch = {}
+ total_volume = np.sum(yf2)
+ for freq, volume in zip(xf, yf2):
+ if freq == 0:
+ continue
+ pitch = get_pitch(freq)
+ if pitch not in volume_per_pitch:
+ volume_per_pitch[pitch] = 0
+ volume_per_pitch[pitch] += 1.0 * volume / total_volume
+ volume_per_pitch = {k: float(v) for k, v in volume_per_pitch.items()}
+ return volume_per_pitch
+
+
+demo = gr.Interface(
+ main_note,
+ gr.Audio(source="microphone"),
+ gr.Label(num_top_classes=4),
+ examples=[
+ [os.path.join(os.path.dirname(__file__),"audio/recording1.wav")],
+ [os.path.join(os.path.dirname(__file__),"audio/cantina.wav")],
+ ],
+ interpretation="default",
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ value
+
+ Dict[str, float] | str | float | Callable | None
+
+ default: None
+
+
+
+ Default value to show in the component. If a str or number is provided, simply displays the string or number. If a {Dict[str, float]} of classes and confidences is provided, displays the top class on top and the `num_top_classes` below, along with their confidence bars. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ num_top_classes
+
+ int | None
+
+ default: None
+
+
+
+ number of most confident classes to show.
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ component name in interface.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ if True, will display label.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+ color
+
+ str | None
+
+ default: None
+
+
+
+ The background color of the label (either a valid css color name or hexadecimal string).
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.Label
+
+
+ "label"
+
+
+ Uses default values
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Label.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Label.style( ยทยทยท)
+
+
+
This method can be used to change the appearance of the label component.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ container
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will add a container to the label - providing some extra padding around the border.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Label
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ diff_texts
+
+ text_analysis
+
+
+
+
+
+
+
+
+
from difflib import Differ
+
+import gradio as gr
+
+
+def diff_texts(text1, text2):
+ d = Differ()
+ return [
+ (token[2:], token[0] if token[0] != " " else None)
+ for token in d.compare(text1, text2)
+ ]
+
+
+demo = gr.Interface(
+ diff_texts,
+ [
+ gr.Textbox(
+ label="Initial text",
+ lines=3,
+ value="The quick brown fox jumped over the lazy dogs.",
+ ),
+ gr.Textbox(
+ label="Text to compare",
+ lines=3,
+ value="The fast brown fox jumps over lazy dogs.",
+ ),
+ ],
+ gr.HighlightedText(
+ label="Diff",
+ combine_adjacent=True,
+ ).style(color_map={"+": "red", "-": "green"}),
+)
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import gradio as gr
+import os
+os.system('python -m spacy download en_core_web_sm')
+import spacy
+from spacy import displacy
+
+nlp = spacy.load("en_core_web_sm")
+
+def text_analysis(text):
+ doc = nlp(text)
+ html = displacy.render(doc, style="dep", page=True)
+ html = (
+ ""
+ + html
+ + "
"
+ )
+ pos_count = {
+ "char_count": len(text),
+ "token_count": 0,
+ }
+ pos_tokens = []
+
+ for token in doc:
+ pos_tokens.extend([(token.text, token.pos_), (" ", None)])
+
+ return pos_tokens, pos_count, html
+
+demo = gr.Interface(
+ text_analysis,
+ gr.Textbox(placeholder="Enter sentence here..."),
+ ["highlight", "json", "html"],
+ examples=[
+ ["What a beautiful morning for a walk!"],
+ ["It was the best of times, it was the worst of times."],
+ ],
+)
+
+demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
gradio.HighlightedText( ยทยทยท)
+
+
+
+
+
+
+
+
+
+
+
Displays text that contains spans that are highlighted by category or numerical value.
+
+
+
As input: this component does *not* accept input.
+
As output: expects a List[Tuple[str, float | str]]] consisting of spans of text and their associated labels, or a Dict with two keys: (1) "text" whose value is the complete text, and "entities", which is a list of dictionaries, each of which have the keys: "entity" (consisting of the entity label), "start" (the character index where the label starts), and "end" (the character index where the label ends). Entities should not overlap.
+
+
+
Supported events: change()
+
+
+
+
+
+
+
from difflib import Differ
+
+import gradio as gr
+
+
+def diff_texts(text1, text2):
+ d = Differ()
+ return [
+ (token[2:], token[0] if token[0] != " " else None)
+ for token in d.compare(text1, text2)
+ ]
+
+
+demo = gr.Interface(
+ diff_texts,
+ [
+ gr.Textbox(
+ label="Initial text",
+ lines=3,
+ value="The quick brown fox jumped over the lazy dogs.",
+ ),
+ gr.Textbox(
+ label="Text to compare",
+ lines=3,
+ value="The fast brown fox jumps over lazy dogs.",
+ ),
+ ],
+ gr.HighlightedText(
+ label="Diff",
+ combine_adjacent=True,
+ ).style(color_map={"+": "red", "-": "green"}),
+)
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ value
+
+ List[Tuple[str, str | float | None]] | Dict | Callable | None
+
+ default: None
+
+
+
+ Default value to show. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ color_map
+
+ Dict[str, str] | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ show_legend
+
+ bool
+
+ default: False
+
+
+
+ whether to show span categories in a separate legend or inline.
+
+
+
+
+
+
+
+
+ combine_adjacent
+
+ bool
+
+ default: False
+
+
+
+ If True, will merge the labels of adjacent tokens belonging to the same category.
+
+
+
+
+
+
+
+
+ adjacent_separator
+
+ str
+
+ default: ""
+
+
+
+ Specifies the separator to be used between tokens if combine_adjacent is True.
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ component name in interface.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ if True, will display label.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.HighlightedText
+
+
+ "highlightedtext"
+
+
+ Uses default values
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.HighlightedText.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.HighlightedText.style( ยทยทยท)
+
+
+
This method can be used to change the appearance of the HighlightedText component.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ color_map
+
+ Dict[str, str] | None
+
+ default: None
+
+
+
+ Map between category and respective colors.
+
+
+
+
+
+
+
+
+ container
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the component in a container - providing some extra padding around the border.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about HighlightedText
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ zip_to_json
+
+ blocks_xray
+
+
+
+
+
+
+
+
+
from zipfile import ZipFile
+
+import gradio as gr
+
+
+def zip_to_json(file_obj):
+ files = []
+ with ZipFile(file_obj.name) as zfile:
+ for zinfo in zfile.infolist():
+ files.append(
+ {
+ "name": zinfo.filename,
+ "file_size": zinfo.file_size,
+ "compressed_size": zinfo.compress_size,
+ }
+ )
+ return files
+
+
+demo = gr.Interface(zip_to_json, "file", "json")
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import gradio as gr
+import random
+import time
+
+
+def xray_model(diseases, img):
+ time.sleep(4)
+ return [{disease: random.random() for disease in diseases}]
+
+
+def ct_model(diseases, img):
+ time.sleep(3)
+ return [{disease: 0.1 for disease in diseases}]
+
+with gr.Blocks() as demo:
+ gr.Markdown(
+ """
+# Detect Disease From Scan
+With this model you can lorem ipsum
+- ipsum 1
+- ipsum 2
+"""
+ )
+ disease = gr.CheckboxGroup(
+ choices=["Covid", "Malaria", "Lung Cancer"], label="Disease to Scan For"
+ )
+
+ with gr.Tab("X-ray") as x_tab:
+ with gr.Row():
+ xray_scan = gr.Image()
+ xray_results = gr.JSON()
+ xray_run = gr.Button("Run")
+ xray_run.click(
+ xray_model,
+ inputs=[disease, xray_scan],
+ outputs=xray_results,
+ api_name="xray_model"
+ )
+
+ with gr.Tab("CT Scan"):
+ with gr.Row():
+ ct_scan = gr.Image()
+ ct_results = gr.JSON()
+ ct_run = gr.Button("Run")
+ ct_run.click(
+ ct_model,
+ inputs=[disease, ct_scan],
+ outputs=ct_results,
+ api_name="ct_model"
+ )
+
+ upload_btn = gr.Button("Upload Results")
+ upload_btn.click(
+ lambda ct, xr: time.sleep(5),
+ inputs=[ct_results, xray_results],
+ outputs=[],
+ )
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Used to display arbitrary JSON output prettily.
+
+
+
As input: this component does *not* accept input.
+
As output: expects a valid JSON str -- or a list or dict that is JSON serializable.
+
+
+
Supported events: change()
+
+
+
+
+
+
+
from zipfile import ZipFile
+
+import gradio as gr
+
+
+def zip_to_json(file_obj):
+ files = []
+ with ZipFile(file_obj.name) as zfile:
+ for zinfo in zfile.infolist():
+ files.append(
+ {
+ "name": zinfo.filename,
+ "file_size": zinfo.file_size,
+ "compressed_size": zinfo.compress_size,
+ }
+ )
+ return files
+
+
+demo = gr.Interface(zip_to_json, "file", "json")
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ value
+
+ str | Callable | None
+
+ default: None
+
+
+
+ Default value. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ component name in interface.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ if True, will display label.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.JSON
+
+
+ "json"
+
+
+ Uses default values
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.JSON.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.JSON.style( ยทยทยท)
+
+
+
This method can be used to change the appearance of the JSON component.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ container
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the JSON in a container - providing some extra padding around the border.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about JSON
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ text_analysis
+
+
+
+
+
+
+
+
+
import gradio as gr
+import os
+os.system('python -m spacy download en_core_web_sm')
+import spacy
+from spacy import displacy
+
+nlp = spacy.load("en_core_web_sm")
+
+def text_analysis(text):
+ doc = nlp(text)
+ html = displacy.render(doc, style="dep", page=True)
+ html = (
+ ""
+ + html
+ + "
"
+ )
+ pos_count = {
+ "char_count": len(text),
+ "token_count": 0,
+ }
+ pos_tokens = []
+
+ for token in doc:
+ pos_tokens.extend([(token.text, token.pos_), (" ", None)])
+
+ return pos_tokens, pos_count, html
+
+demo = gr.Interface(
+ text_analysis,
+ gr.Textbox(placeholder="Enter sentence here..."),
+ ["highlight", "json", "html"],
+ examples=[
+ ["What a beautiful morning for a walk!"],
+ ["It was the best of times, it was the worst of times."],
+ ],
+)
+
+demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Used to display arbitrary HTML output.
+
+
+
As input: this component does *not* accept input.
+
As output: expects a valid HTML str .
+
+
+
Supported events: change()
+
+
+
+
+
+
+
import gradio as gr
+import os
+os.system('python -m spacy download en_core_web_sm')
+import spacy
+from spacy import displacy
+
+nlp = spacy.load("en_core_web_sm")
+
+def text_analysis(text):
+ doc = nlp(text)
+ html = displacy.render(doc, style="dep", page=True)
+ html = (
+ ""
+ + html
+ + "
"
+ )
+ pos_count = {
+ "char_count": len(text),
+ "token_count": 0,
+ }
+ pos_tokens = []
+
+ for token in doc:
+ pos_tokens.extend([(token.text, token.pos_), (" ", None)])
+
+ return pos_tokens, pos_count, html
+
+demo = gr.Interface(
+ text_analysis,
+ gr.Textbox(placeholder="Enter sentence here..."),
+ ["highlight", "json", "html"],
+ examples=[
+ ["What a beautiful morning for a walk!"],
+ ["It was the best of times, it was the worst of times."],
+ ],
+)
+
+demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ value
+
+ str | Callable
+
+ default: ""
+
+
+
+ Default value. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ component name in interface.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ if True, will display label.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.HTML
+
+
+ "html"
+
+
+ Uses default values
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.HTML.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about HTML
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ fake_gan
+
+
+
+
+
+
+
+
+
# This demo needs to be run from the repo folder.
+# python demo/fake_gan/run.py
+import os
+import random
+
+import gradio as gr
+
+
+def fake_gan():
+ images = [
+ (random.choice(
+ [
+ "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80",
+ "https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=386&q=80",
+ "https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW4lMjBmYWNlfGVufDB8fDB8fA%3D%3D&w=1000&q=80",
+ "https://images.unsplash.com/photo-1546456073-92b9f0a8d413?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80",
+ "https://images.unsplash.com/photo-1601412436009-d964bd02edbc?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=464&q=80",
+ ]
+ ), f"label {i}" if i != 0 else "label" * 50)
+ for i in range(3)
+ ]
+ return images
+
+
+with gr.Blocks() as demo:
+ with gr.Column(variant="panel"):
+ with gr.Row(variant="compact"):
+ text = gr.Textbox(
+ label="Enter your prompt",
+ show_label=False,
+ max_lines=1,
+ placeholder="Enter your prompt",
+ ).style(
+ container=False,
+ )
+ btn = gr.Button("Generate image").style(full_width=False)
+
+ gallery = gr.Gallery(
+ label="Generated images", show_label=False, elem_id="gallery"
+ ).style(grid=[2], height="auto")
+
+ btn.click(fake_gan, None, gallery)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Used to display a list of images as a gallery that can be scrolled through.
+
+
+
As input: this component does *not* accept input.
+
As output: expects a list of images in any format, List[numpy.array | PIL.Image | str] , or a List of (image, str caption) tuples and displays them.
+
+
+
+
+
+
+
+
# This demo needs to be run from the repo folder.
+# python demo/fake_gan/run.py
+import os
+import random
+
+import gradio as gr
+
+
+def fake_gan():
+ images = [
+ (random.choice(
+ [
+ "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80",
+ "https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=386&q=80",
+ "https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW4lMjBmYWNlfGVufDB8fDB8fA%3D%3D&w=1000&q=80",
+ "https://images.unsplash.com/photo-1546456073-92b9f0a8d413?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80",
+ "https://images.unsplash.com/photo-1601412436009-d964bd02edbc?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=464&q=80",
+ ]
+ ), f"label {i}" if i != 0 else "label" * 50)
+ for i in range(3)
+ ]
+ return images
+
+
+with gr.Blocks() as demo:
+ with gr.Column(variant="panel"):
+ with gr.Row(variant="compact"):
+ text = gr.Textbox(
+ label="Enter your prompt",
+ show_label=False,
+ max_lines=1,
+ placeholder="Enter your prompt",
+ ).style(
+ container=False,
+ )
+ btn = gr.Button("Generate image").style(full_width=False)
+
+ gallery = gr.Gallery(
+ label="Generated images", show_label=False, elem_id="gallery"
+ ).style(grid=[2], height="auto")
+
+ btn.click(fake_gan, None, gallery)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ value
+
+ List[np.ndarray | _Image.Image | str] | Callable | None
+
+ default: None
+
+
+
+ List of images to display in the gallery by default. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ component name in interface.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ if True, will display label.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.Gallery
+
+
+ "gallery"
+
+
+ Uses default values
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Gallery.style( ยทยทยท)
+
+
+
This method can be used to change the appearance of the gallery component.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ grid
+
+ int | Tuple | None
+
+ default: None
+
+
+
+ Represents the number of images that should be shown in one row, for each of the six standard screen sizes (<576px, <768px, <992px, <1200px, <1400px, >1400px). if fewer that 6 are given then the last will be used for all subsequent breakpoints
+
+
+
+
+
+
+
+
+ height
+
+ str | None
+
+ default: None
+
+
+
+ Height of the gallery.
+
+
+
+
+
+
+
+
+ container
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place gallery in a container - providing some extra padding around the border.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Gallery
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ chatbot_demo
+
+
+
+
+
+
+
+
+
import random
+import gradio as gr
+
+def chat(message, history):
+ history = history or []
+ message = message.lower()
+ if message.startswith("how many"):
+ response = str(random.randint(1, 10))
+ elif message.startswith("how"):
+ response = random.choice(["Great", "Good", "Okay", "Bad"])
+ elif message.startswith("where"):
+ response = random.choice(["Here", "There", "Somewhere"])
+ else:
+ response = "I don't know"
+ history.append((message, response))
+ return history, history
+
+chatbot = gr.Chatbot().style(color_map=("green", "pink"))
+demo = gr.Interface(
+ chat,
+ ["text", "state"],
+ [chatbot, "state"],
+ allow_flagging="never",
+)
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Displays a chatbot output showing both user submitted messages and responses. Supports a subset of Markdown including bold, italics, code, and images.
+
+
+
As input: this component does *not* accept input.
+
As output: expects a List[Tuple[str, str]] , a list of tuples with user inputs and responses as strings of HTML.
+
+
+
Supported events: change()
+
+
+
+
+
+
+
import random
+import gradio as gr
+
+def chat(message, history):
+ history = history or []
+ message = message.lower()
+ if message.startswith("how many"):
+ response = str(random.randint(1, 10))
+ elif message.startswith("how"):
+ response = random.choice(["Great", "Good", "Okay", "Bad"])
+ elif message.startswith("where"):
+ response = random.choice(["Here", "There", "Somewhere"])
+ else:
+ response = "I don't know"
+ history.append((message, response))
+ return history, history
+
+chatbot = gr.Chatbot().style(color_map=("green", "pink"))
+demo = gr.Interface(
+ chat,
+ ["text", "state"],
+ [chatbot, "state"],
+ allow_flagging="never",
+)
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ value
+
+ List[Tuple[str, str]] | Callable | None
+
+ default: None
+
+
+
+ Default value to show in chatbot. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ color_map
+
+ Dict[str, str] | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ component name in interface.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ if True, will display label.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.Chatbot
+
+
+ "chatbot"
+
+
+ Uses default values
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Chatbot.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Chatbot.style( ยทยทยท)
+
+
+
This method can be used to change the appearance of the Chatbot component.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ color_map
+
+ Tuple[str, str] | None
+
+ default: None
+
+
+
+ Tuple containing colors to apply to user and response chat bubbles.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Chatbot
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ model3D
+
+
+
+
+
+
+
+
+
import gradio as gr
+import os
+
+
+def load_mesh(mesh_file_name):
+ return mesh_file_name
+
+
+demo = gr.Interface(
+ fn=load_mesh,
+ inputs=gr.Model3D(),
+ outputs=gr.Model3D(
+ clear_color=[0.0, 0.0, 0.0, 0.0], label="3D Model"),
+ examples=[
+ [os.path.join(os.path.dirname(__file__), "files/Bunny.obj")],
+ [os.path.join(os.path.dirname(__file__), "files/Duck.glb")],
+ [os.path.join(os.path.dirname(__file__), "files/Fox.gltf")],
+ [os.path.join(os.path.dirname(__file__), "files/face.obj")],
+ ],
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Component allows users to upload or view 3D Model files (.obj, .glb, or .gltf).
+
+
+
As input: This component passes the uploaded file as a str filepath.
+
As output: expects function to return a str path to a file of type (.obj, glb, or .gltf)
+
+
+
Supported events: change(), edit(), clear()
+
+
+
+
+
+
+
import gradio as gr
+import os
+
+
+def load_mesh(mesh_file_name):
+ return mesh_file_name
+
+
+demo = gr.Interface(
+ fn=load_mesh,
+ inputs=gr.Model3D(),
+ outputs=gr.Model3D(
+ clear_color=[0.0, 0.0, 0.0, 0.0], label="3D Model"),
+ examples=[
+ [os.path.join(os.path.dirname(__file__), "files/Bunny.obj")],
+ [os.path.join(os.path.dirname(__file__), "files/Duck.glb")],
+ [os.path.join(os.path.dirname(__file__), "files/Fox.gltf")],
+ [os.path.join(os.path.dirname(__file__), "files/face.obj")],
+ ],
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ value
+
+ str | Callable | None
+
+ default: None
+
+
+
+ path to (.obj, glb, or .gltf) file to show in model3D viewer. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ clear_color
+
+ List[float] | None
+
+ default: None
+
+
+
+ background color of scene
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ component name in interface.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ if True, will display label.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.Model3D
+
+
+ "model3d"
+
+
+ Uses default values
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Model3D.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Model3D.edit( fn, ยทยทยท)
+
+
+
This event is triggered when the user edits the component (e.g. image) using the built-in editor. This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Model3D.clear( fn, ยทยทยท)
+
+
+
This event is triggered when the user clears the component (e.g. image or audio) using the X button for the component. This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Model3D.style( ยทยทยท)
+
+
+
This method can be used to change the appearance of the Model3D component.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Model3D
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ altair_plot
+
+ outbreak_forecast
+
+ blocks_kinematics
+
+ stock_forecast
+
+ map_airbnb
+
+
+
+
+
+
+
+
+
import altair as alt
+import gradio as gr
+import numpy as np
+import pandas as pd
+from vega_datasets import data
+
+
+def make_plot(plot_type):
+ if plot_type == "scatter_plot":
+ cars = data.cars()
+ return alt.Chart(cars).mark_point().encode(
+ x='Horsepower',
+ y='Miles_per_Gallon',
+ color='Origin',
+ )
+ elif plot_type == "heatmap":
+ # Compute x^2 + y^2 across a 2D grid
+ x, y = np.meshgrid(range(-5, 5), range(-5, 5))
+ z = x ** 2 + y ** 2
+
+ # Convert this grid to columnar data expected by Altair
+ source = pd.DataFrame({'x': x.ravel(),
+ 'y': y.ravel(),
+ 'z': z.ravel()})
+ return alt.Chart(source).mark_rect().encode(
+ x='x:O',
+ y='y:O',
+ color='z:Q'
+ )
+ elif plot_type == "us_map":
+ states = alt.topo_feature(data.us_10m.url, 'states')
+ source = data.income.url
+
+ return alt.Chart(source).mark_geoshape().encode(
+ shape='geo:G',
+ color='pct:Q',
+ tooltip=['name:N', 'pct:Q'],
+ facet=alt.Facet('group:N', columns=2),
+ ).transform_lookup(
+ lookup='id',
+ from_=alt.LookupData(data=states, key='id'),
+ as_='geo'
+ ).properties(
+ width=300,
+ height=175,
+ ).project(
+ type='albersUsa'
+ )
+ elif plot_type == "interactive_barplot":
+ source = data.movies.url
+
+ pts = alt.selection(type="single", encodings=['x'])
+
+ rect = alt.Chart(data.movies.url).mark_rect().encode(
+ alt.X('IMDB_Rating:Q', bin=True),
+ alt.Y('Rotten_Tomatoes_Rating:Q', bin=True),
+ alt.Color('count()',
+ scale=alt.Scale(scheme='greenblue'),
+ legend=alt.Legend(title='Total Records')
+ )
+ )
+
+ circ = rect.mark_point().encode(
+ alt.ColorValue('grey'),
+ alt.Size('count()',
+ legend=alt.Legend(title='Records in Selection')
+ )
+ ).transform_filter(
+ pts
+ )
+
+ bar = alt.Chart(source).mark_bar().encode(
+ x='Major_Genre:N',
+ y='count()',
+ color=alt.condition(pts, alt.ColorValue("steelblue"), alt.ColorValue("grey"))
+ ).properties(
+ width=550,
+ height=200
+ ).add_selection(pts)
+
+ plot = alt.vconcat(
+ rect + circ,
+ bar
+ ).resolve_legend(
+ color="independent",
+ size="independent"
+ )
+ return plot
+ elif plot_type == "radial":
+ source = pd.DataFrame({"values": [12, 23, 47, 6, 52, 19]})
+
+ base = alt.Chart(source).encode(
+ theta=alt.Theta("values:Q", stack=True),
+ radius=alt.Radius("values", scale=alt.Scale(type="sqrt", zero=True, rangeMin=20)),
+ color="values:N",
+ )
+
+ c1 = base.mark_arc(innerRadius=20, stroke="#fff")
+
+ c2 = base.mark_text(radiusOffset=10).encode(text="values:Q")
+
+ return c1 + c2
+ elif plot_type == "multiline":
+ source = data.stocks()
+
+ highlight = alt.selection(type='single', on='mouseover',
+ fields=['symbol'], nearest=True)
+
+ base = alt.Chart(source).encode(
+ x='date:T',
+ y='price:Q',
+ color='symbol:N'
+ )
+
+ points = base.mark_circle().encode(
+ opacity=alt.value(0)
+ ).add_selection(
+ highlight
+ ).properties(
+ width=600
+ )
+
+ lines = base.mark_line().encode(
+ size=alt.condition(~highlight, alt.value(1), alt.value(3))
+ )
+
+ return points + lines
+
+
+with gr.Blocks() as demo:
+ button = gr.Radio(label="Plot type",
+ choices=['scatter_plot', 'heatmap', 'us_map',
+ 'interactive_barplot', "radial", "multiline"], value='scatter_plot')
+ plot = gr.Plot(label="Plot")
+ button.change(make_plot, inputs=button, outputs=[plot])
+ demo.load(make_plot, inputs=[button], outputs=[plot])
+
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import altair
+
+import gradio as gr
+from math import sqrt
+import matplotlib
+
+matplotlib.use("Agg")
+
+import matplotlib.pyplot as plt
+import numpy as np
+import plotly.express as px
+import pandas as pd
+
+
+def outbreak(plot_type, r, month, countries, social_distancing):
+ months = ["January", "February", "March", "April", "May"]
+ m = months.index(month)
+ 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}
+ if social_distancing:
+ r = sqrt(r)
+ df = pd.DataFrame({"day": x})
+ for country in countries:
+ df[country] = x ** (r) * (pop_count[country] + 1)
+
+ if plot_type == "Matplotlib":
+ fig = plt.figure()
+ plt.plot(df["day"], df[countries].to_numpy())
+ plt.title("Outbreak in " + month)
+ plt.ylabel("Cases")
+ plt.xlabel("Days since Day 0")
+ plt.legend(countries)
+ return fig
+ elif plot_type == "Plotly":
+ fig = px.line(df, x="day", y=countries)
+ fig.update_layout(
+ title="Outbreak in " + month,
+ xaxis_title="Cases",
+ yaxis_title="Days Since Day 0",
+ )
+ return fig
+ elif plot_type == "Altair":
+ df = df.melt(id_vars="day").rename(columns={"variable": "country"})
+ fig = altair.Chart(df).mark_line().encode(x="day", y='value', color='country')
+ return fig
+ else:
+ raise ValueError("A plot type must be selected")
+
+
+inputs = [
+ gr.Dropdown(["Matplotlib", "Plotly", "Altair"], label="Plot Type"),
+ gr.Slider(1, 4, 3.2, label="R"),
+ gr.Dropdown(["January", "February", "March", "April", "May"], label="Month"),
+ gr.CheckboxGroup(
+ ["USA", "Canada", "Mexico", "UK"], label="Countries", value=["USA", "Canada"]
+ ),
+ gr.Checkbox(label="Social Distancing?"),
+]
+outputs = gr.Plot()
+
+demo = gr.Interface(
+ fn=outbreak,
+ inputs=inputs,
+ outputs=outputs,
+ examples=[
+ ["Matplotlib", 2, "March", ["Mexico", "UK"], True],
+ ["Altair", 2, "March", ["Mexico", "Canada"], True],
+ ["Plotly", 3.6, "February", ["Canada", "Mexico", "UK"], False],
+ ],
+ cache_examples=True,
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import pandas as pd
+import numpy as np
+
+import gradio as gr
+
+
+def plot(v, a):
+ g = 9.81
+ theta = a / 180 * 3.14
+ tmax = ((2 * v) * np.sin(theta)) / g
+ timemat = tmax * np.linspace(0, 1, 40)
+
+ x = (v * timemat) * np.cos(theta)
+ y = ((v * timemat) * np.sin(theta)) - ((0.5 * g) * (timemat**2))
+ df = pd.DataFrame({"x": x, "y": y})
+ return df
+
+
+demo = gr.Blocks()
+
+with demo:
+ gr.Markdown(
+ r"Let's do some kinematics! Choose the speed and angle to see the trajectory. Remember that the range $R = v_0^2 \cdot \frac{\sin(2\theta)}{g}$"
+ )
+
+ with gr.Row():
+ speed = gr.Slider(1, 30, 25, label="Speed")
+ angle = gr.Slider(0, 90, 45, label="Angle")
+ output = gr.LinePlot(
+ x="x",
+ y="y",
+ overlay_point=True,
+ tooltip=["x", "y"],
+ x_lim=[0, 100],
+ y_lim=[0, 60],
+ width=350,
+ height=300,
+ )
+ btn = gr.Button(value="Run")
+ btn.click(plot, [speed, angle], output)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import matplotlib
+matplotlib.use('Agg')
+import matplotlib.pyplot as plt
+import numpy as np
+
+import gradio as gr
+
+
+def plot_forecast(final_year, companies, noise, show_legend, point_style):
+ start_year = 2020
+ x = np.arange(start_year, final_year + 1)
+ year_count = x.shape[0]
+ plt_format = ({"cross": "X", "line": "-", "circle": "o--"})[point_style]
+ fig = plt.figure()
+ ax = fig.add_subplot(111)
+ for i, company in enumerate(companies):
+ series = np.arange(0, year_count, dtype=float)
+ series = series**2 * (i + 1)
+ series += np.random.rand(year_count) * noise
+ ax.plot(x, series, plt_format)
+ if show_legend:
+ plt.legend(companies)
+ return fig
+
+
+demo = gr.Interface(
+ plot_forecast,
+ [
+ gr.Radio([2025, 2030, 2035, 2040], label="Project to:"),
+ gr.CheckboxGroup(["Google", "Microsoft", "Gradio"], label="Company Selection"),
+ gr.Slider(1, 100, label="Noise Level"),
+ gr.Checkbox(label="Show Legend"),
+ gr.Dropdown(["cross", "line", "circle"], label="Style"),
+ ],
+ gr.Plot(label="forecast"),
+)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import gradio as gr
+import pandas as pd
+import plotly.graph_objects as go
+from datasets import load_dataset
+
+dataset = load_dataset("gradio/NYC-Airbnb-Open-Data", split="train")
+df = dataset.to_pandas()
+
+def filter_map(min_price, max_price, boroughs):
+
+ filtered_df = df[(df['neighbourhood_group'].isin(boroughs)) &
+ (df['price'] > min_price) & (df['price'] < max_price)]
+ names = filtered_df["name"].tolist()
+ prices = filtered_df["price"].tolist()
+ text_list = [(names[i], prices[i]) for i in range(0, len(names))]
+ fig = go.Figure(go.Scattermapbox(
+ customdata=text_list,
+ lat=filtered_df['latitude'].tolist(),
+ lon=filtered_df['longitude'].tolist(),
+ mode='markers',
+ marker=go.scattermapbox.Marker(
+ size=6
+ ),
+ hoverinfo="text",
+ hovertemplate='Name : %{customdata[0]}Price : $%{customdata[1]}'
+ ))
+
+ fig.update_layout(
+ mapbox_style="open-street-map",
+ hovermode='closest',
+ mapbox=dict(
+ bearing=0,
+ center=go.layout.mapbox.Center(
+ lat=40.67,
+ lon=-73.90
+ ),
+ pitch=0,
+ zoom=9
+ ),
+ )
+
+ return fig
+
+with gr.Blocks() as demo:
+ with gr.Column():
+ with gr.Row():
+ min_price = gr.Number(value=250, label="Minimum Price")
+ max_price = gr.Number(value=1000, label="Maximum Price")
+ boroughs = gr.CheckboxGroup(choices=["Queens", "Brooklyn", "Manhattan", "Bronx", "Staten Island"], value=["Queens", "Brooklyn"], label="Select Boroughs:")
+ btn = gr.Button(value="Update Filter")
+ map = gr.Plot().style()
+ demo.load(filter_map, [min_price, max_price, boroughs], map)
+ btn.click(filter_map, [min_price, max_price, boroughs], map)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Used to display various kinds of plots (matplotlib, plotly, or bokeh are supported)
+
+
+
As input: this component does *not* accept input.
+
As output: expects either a matplotlib.figure.Figure , a plotly.graph_objects._figure.Figure , or a dict corresponding to a bokeh plot (json_item format)
+
+
+
Supported events: change(), clear()
+
+
+
+
+
+
+
import altair as alt
+import gradio as gr
+import numpy as np
+import pandas as pd
+from vega_datasets import data
+
+
+def make_plot(plot_type):
+ if plot_type == "scatter_plot":
+ cars = data.cars()
+ return alt.Chart(cars).mark_point().encode(
+ x='Horsepower',
+ y='Miles_per_Gallon',
+ color='Origin',
+ )
+ elif plot_type == "heatmap":
+ # Compute x^2 + y^2 across a 2D grid
+ x, y = np.meshgrid(range(-5, 5), range(-5, 5))
+ z = x ** 2 + y ** 2
+
+ # Convert this grid to columnar data expected by Altair
+ source = pd.DataFrame({'x': x.ravel(),
+ 'y': y.ravel(),
+ 'z': z.ravel()})
+ return alt.Chart(source).mark_rect().encode(
+ x='x:O',
+ y='y:O',
+ color='z:Q'
+ )
+ elif plot_type == "us_map":
+ states = alt.topo_feature(data.us_10m.url, 'states')
+ source = data.income.url
+
+ return alt.Chart(source).mark_geoshape().encode(
+ shape='geo:G',
+ color='pct:Q',
+ tooltip=['name:N', 'pct:Q'],
+ facet=alt.Facet('group:N', columns=2),
+ ).transform_lookup(
+ lookup='id',
+ from_=alt.LookupData(data=states, key='id'),
+ as_='geo'
+ ).properties(
+ width=300,
+ height=175,
+ ).project(
+ type='albersUsa'
+ )
+ elif plot_type == "interactive_barplot":
+ source = data.movies.url
+
+ pts = alt.selection(type="single", encodings=['x'])
+
+ rect = alt.Chart(data.movies.url).mark_rect().encode(
+ alt.X('IMDB_Rating:Q', bin=True),
+ alt.Y('Rotten_Tomatoes_Rating:Q', bin=True),
+ alt.Color('count()',
+ scale=alt.Scale(scheme='greenblue'),
+ legend=alt.Legend(title='Total Records')
+ )
+ )
+
+ circ = rect.mark_point().encode(
+ alt.ColorValue('grey'),
+ alt.Size('count()',
+ legend=alt.Legend(title='Records in Selection')
+ )
+ ).transform_filter(
+ pts
+ )
+
+ bar = alt.Chart(source).mark_bar().encode(
+ x='Major_Genre:N',
+ y='count()',
+ color=alt.condition(pts, alt.ColorValue("steelblue"), alt.ColorValue("grey"))
+ ).properties(
+ width=550,
+ height=200
+ ).add_selection(pts)
+
+ plot = alt.vconcat(
+ rect + circ,
+ bar
+ ).resolve_legend(
+ color="independent",
+ size="independent"
+ )
+ return plot
+ elif plot_type == "radial":
+ source = pd.DataFrame({"values": [12, 23, 47, 6, 52, 19]})
+
+ base = alt.Chart(source).encode(
+ theta=alt.Theta("values:Q", stack=True),
+ radius=alt.Radius("values", scale=alt.Scale(type="sqrt", zero=True, rangeMin=20)),
+ color="values:N",
+ )
+
+ c1 = base.mark_arc(innerRadius=20, stroke="#fff")
+
+ c2 = base.mark_text(radiusOffset=10).encode(text="values:Q")
+
+ return c1 + c2
+ elif plot_type == "multiline":
+ source = data.stocks()
+
+ highlight = alt.selection(type='single', on='mouseover',
+ fields=['symbol'], nearest=True)
+
+ base = alt.Chart(source).encode(
+ x='date:T',
+ y='price:Q',
+ color='symbol:N'
+ )
+
+ points = base.mark_circle().encode(
+ opacity=alt.value(0)
+ ).add_selection(
+ highlight
+ ).properties(
+ width=600
+ )
+
+ lines = base.mark_line().encode(
+ size=alt.condition(~highlight, alt.value(1), alt.value(3))
+ )
+
+ return points + lines
+
+
+with gr.Blocks() as demo:
+ button = gr.Radio(label="Plot type",
+ choices=['scatter_plot', 'heatmap', 'us_map',
+ 'interactive_barplot', "radial", "multiline"], value='scatter_plot')
+ plot = gr.Plot(label="Plot")
+ button.change(make_plot, inputs=button, outputs=[plot])
+ demo.load(make_plot, inputs=[button], outputs=[plot])
+
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ value
+
+ Callable | None | pd.DataFrame
+
+ default: None
+
+
+
+ Optionally, supply a default plot object to display, must be a matplotlib, plotly, altair, or bokeh figure, or a callable. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ component name in interface.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ if True, will display label.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.Plot
+
+
+ "plot"
+
+
+ Uses default values
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Plot.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Plot.clear( fn, ยทยทยท)
+
+
+
This event is triggered when the user clears the component (e.g. image or audio) using the X button for the component. This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Plot
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ native_plots
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+from scatter_plot_demo import scatter_plot
+from line_plot_demo import line_plot
+
+
+with gr.Blocks() as demo:
+ with gr.Tabs():
+ with gr.TabItem("Scatter Plot"):
+ scatter_plot.render()
+ with gr.TabItem("Line Plot"):
+ line_plot.render()
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
gradio.ScatterPlot( ยทยทยท)
+
+
+
+
+
+
+
+
+
+
+
Create a scatter plot.
+
+
+
As input: this component does *not* accept input.
+
As output: expects a pandas dataframe with the data to plot.
+
+
+
Supported events: change(), clear()
+
+
+
+
+
+
+
import gradio as gr
+
+from scatter_plot_demo import scatter_plot
+from line_plot_demo import line_plot
+
+
+with gr.Blocks() as demo:
+ with gr.Tabs():
+ with gr.TabItem("Scatter Plot"):
+ scatter_plot.render()
+ with gr.TabItem("Line Plot"):
+ line_plot.render()
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ value
+
+ pd.DataFrame | Callable | None
+
+ default: None
+
+
+
+ The pandas dataframe containing the data to display in a scatter plot, or a callable. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ x
+
+ str | None
+
+ default: None
+
+
+
+ Column corresponding to the x axis.
+
+
+
+
+
+
+
+
+ y
+
+ str | None
+
+ default: None
+
+
+
+ Column corresponding to the y axis.
+
+
+
+
+
+
+
+
+ color
+
+ str | None
+
+ default: None
+
+
+
+ The column to determine the point color. If the column contains numeric data, gradio will interpolate the column data so that small values correspond to light colors and large values correspond to dark values.
+
+
+
+
+
+
+
+
+ size
+
+ str | None
+
+ default: None
+
+
+
+ The column used to determine the point size. Should contain numeric data so that gradio can map the data to the point size.
+
+
+
+
+
+
+
+
+ shape
+
+ str | None
+
+ default: None
+
+
+
+ The column used to determine the point shape. Should contain categorical data. Gradio will map each unique value to a different shape.
+
+
+
+
+
+
+
+
+ title
+
+ str | None
+
+ default: None
+
+
+
+ The title to display on top of the chart.
+
+
+
+
+
+
+
+
+ tooltip
+
+ List[str] | str | None
+
+ default: None
+
+
+
+ The column (or list of columns) to display on the tooltip when a user hovers a point on the plot.
+
+
+
+
+
+
+
+
+ x_title
+
+ str | None
+
+ default: None
+
+
+
+ The title given to the x axis. By default, uses the value of the x parameter.
+
+
+
+
+
+
+
+
+ y_title
+
+ str | None
+
+ default: None
+
+
+
+ The title given to the y axis. By default, uses the value of the y parameter.
+
+
+
+
+
+
+
+
+ color_legend_title
+
+ str | None
+
+ default: None
+
+
+
+ The title given to the color legend. By default, uses the value of color parameter.
+
+
+
+
+
+
+
+
+ size_legend_title
+
+ str | None
+
+ default: None
+
+
+
+ The title given to the size legend. By default, uses the value of the size parameter.
+
+
+
+
+
+
+
+
+ shape_legend_title
+
+ str | None
+
+ default: None
+
+
+
+ The title given to the shape legend. By default, uses the value of the shape parameter.
+
+
+
+
+
+
+
+
+ color_legend_position
+
+ str | None
+
+ default: None
+
+
+
+ The position of the color legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation.
+
+
+
+
+
+
+
+
+ size_legend_position
+
+ str | None
+
+ default: None
+
+
+
+ The position of the size legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation.
+
+
+
+
+
+
+
+
+ shape_legend_position
+
+ str | None
+
+ default: None
+
+
+
+ The position of the shape legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation.
+
+
+
+
+
+
+
+
+ height
+
+ int | None
+
+ default: None
+
+
+
+ The height of the plot in pixels.
+
+
+
+
+
+
+
+
+ width
+
+ int | None
+
+ default: None
+
+
+
+ The width of the plot in pixels.
+
+
+
+
+
+
+
+
+ x_lim
+
+ List[int | float] | None
+
+ default: None
+
+
+
+ A tuple or list containing the limits for the x-axis, specified as [x_min, x_max].
+
+
+
+
+
+
+
+
+ y_lim
+
+ List[int | float] | None
+
+ default: None
+
+
+
+ A tuple of list containing the limits for the y-axis, specified as [y_min, y_max].
+
+
+
+
+
+
+
+
+ caption
+
+ str | None
+
+ default: None
+
+
+
+ The (optional) caption to display below the plot.
+
+
+
+
+
+
+
+
+ interactive
+
+ bool | None
+
+ default: True
+
+
+
+ Whether users should be able to interact with the plot by panning or zooming with their mouse or trackpad.
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ The (optional) label to display on the top left corner of the plot.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ Whether the label should be displayed.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ Whether the plot should be visible.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ Unique id used for custom css targetting.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.ScatterPlot
+
+
+ "scatterplot"
+
+
+ Uses default values
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.ScatterPlot.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.ScatterPlot.clear( fn, ยทยทยท)
+
+
+
This event is triggered when the user clears the component (e.g. image or audio) using the X button for the component. This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about ScatterPlot
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ native_plots
+
+ live_dashboard
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+from scatter_plot_demo import scatter_plot
+from line_plot_demo import line_plot
+
+
+with gr.Blocks() as demo:
+ with gr.Tabs():
+ with gr.TabItem("Scatter Plot"):
+ scatter_plot.render()
+ with gr.TabItem("Line Plot"):
+ line_plot.render()
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import math
+
+import pandas as pd
+
+import gradio as gr
+import datetime
+import numpy as np
+
+
+def get_time():
+ return datetime.datetime.now()
+
+
+plot_end = 2 * math.pi
+
+
+def get_plot(period=1):
+ global plot_end
+ x = np.arange(plot_end - 2 * math.pi, plot_end, 0.02)
+ y = np.sin(2 * math.pi * period * x)
+ update = gr.LinePlot.update(
+ value=pd.DataFrame({"x": x, "y": y}),
+ x="x",
+ y="y",
+ title="Plot (updates every second)",
+ width=600,
+ height=350,
+ )
+ plot_end += 2 * math.pi
+ if plot_end > 1000:
+ plot_end = 2 * math.pi
+ return update
+
+
+with gr.Blocks() as demo:
+ with gr.Row():
+ with gr.Column():
+ c_time2 = gr.Textbox(label="Current Time refreshed every second")
+ gr.Textbox(
+ "Change the value of the slider to automatically update the plot",
+ label="",
+ )
+ period = gr.Slider(
+ label="Period of plot", value=1, minimum=0, maximum=10, step=1
+ )
+ plot = gr.LinePlot(show_label=False)
+ with gr.Column():
+ name = gr.Textbox(label="Enter your name")
+ greeting = gr.Textbox(label="Greeting")
+ button = gr.Button(value="Greet")
+ button.click(lambda s: f"Hello {s}", name, greeting)
+
+ demo.load(lambda: datetime.datetime.now(), None, c_time2, every=1)
+ dep = demo.load(get_plot, None, plot, every=1)
+ period.change(get_plot, period, plot, every=1, cancels=[dep])
+
+if __name__ == "__main__":
+ demo.queue().launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Create a line plot.
+
+
+
As input: this component does *not* accept input.
+
As output: expects a pandas dataframe with the data to plot.
+
+
+
Supported events: change(), clear()
+
+
+
+
+
+
+
import gradio as gr
+
+from scatter_plot_demo import scatter_plot
+from line_plot_demo import line_plot
+
+
+with gr.Blocks() as demo:
+ with gr.Tabs():
+ with gr.TabItem("Scatter Plot"):
+ scatter_plot.render()
+ with gr.TabItem("Line Plot"):
+ line_plot.render()
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ value
+
+ pd.DataFrame | Callable | None
+
+ default: None
+
+
+
+ The pandas dataframe containing the data to display in a scatter plot.
+
+
+
+
+
+
+
+
+ x
+
+ str | None
+
+ default: None
+
+
+
+ Column corresponding to the x axis.
+
+
+
+
+
+
+
+
+ y
+
+ str | None
+
+ default: None
+
+
+
+ Column corresponding to the y axis.
+
+
+
+
+
+
+
+
+ color
+
+ str | None
+
+ default: None
+
+
+
+ The column to determine the point color. If the column contains numeric data, gradio will interpolate the column data so that small values correspond to light colors and large values correspond to dark values.
+
+
+
+
+
+
+
+
+ stroke_dash
+
+ str | None
+
+ default: None
+
+
+
+ The column to determine the symbol used to draw the line, e.g. dashed lines, dashed lines with points.
+
+
+
+
+
+
+
+
+ overlay_point
+
+ bool | None
+
+ default: None
+
+
+
+ Whether to draw a point on the line for each (x, y) coordinate pair.
+
+
+
+
+
+
+
+
+ title
+
+ str | None
+
+ default: None
+
+
+
+ The title to display on top of the chart.
+
+
+
+
+
+
+
+
+ tooltip
+
+ List[str] | str | None
+
+ default: None
+
+
+
+ The column (or list of columns) to display on the tooltip when a user hovers a point on the plot.
+
+
+
+
+
+
+
+
+ x_title
+
+ str | None
+
+ default: None
+
+
+
+ The title given to the x axis. By default, uses the value of the x parameter.
+
+
+
+
+
+
+
+
+ y_title
+
+ str | None
+
+ default: None
+
+
+
+ The title given to the y axis. By default, uses the value of the y parameter.
+
+
+
+
+
+
+
+
+ color_legend_title
+
+ str | None
+
+ default: None
+
+
+
+ The title given to the color legend. By default, uses the value of color parameter.
+
+
+
+
+
+
+
+
+ stroke_dash_legend_title
+
+ str | None
+
+ default: None
+
+
+
+ The title given to the stroke_dash legend. By default, uses the value of the stroke_dash parameter.
+
+
+
+
+
+
+
+
+ color_legend_position
+
+ str | None
+
+ default: None
+
+
+
+ The position of the color legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation.
+
+
+
+
+
+
+
+
+ stroke_dash_legend_position
+
+ str | None
+
+ default: None
+
+
+
+ The position of the stoke_dash legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation.
+
+
+
+
+
+
+
+
+ height
+
+ int | None
+
+ default: None
+
+
+
+ The height of the plot in pixels.
+
+
+
+
+
+
+
+
+ width
+
+ int | None
+
+ default: None
+
+
+
+ The width of the plot in pixels.
+
+
+
+
+
+
+
+
+ x_lim
+
+ List[int] | None
+
+ default: None
+
+
+
+ A tuple or list containing the limits for the x-axis, specified as [x_min, x_max].
+
+
+
+
+
+
+
+
+ y_lim
+
+ List[int] | None
+
+ default: None
+
+
+
+ A tuple of list containing the limits for the y-axis, specified as [y_min, y_max].
+
+
+
+
+
+
+
+
+ caption
+
+ str | None
+
+ default: None
+
+
+
+ The (optional) caption to display below the plot.
+
+
+
+
+
+
+
+
+ interactive
+
+ bool | None
+
+ default: True
+
+
+
+ Whether users should be able to interact with the plot by panning or zooming with their mouse or trackpad.
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+ The (optional) label to display on the top left corner of the plot.
+
+
+
+
+
+
+
+
+ show_label
+
+ bool
+
+ default: True
+
+
+
+ Whether the label should be displayed.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ Whether the plot should be visible.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ Unique id used for custom css targetting.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.LinePlot
+
+
+ "lineplot"
+
+
+ Uses default values
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.LinePlot.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.LinePlot.clear( fn, ยทยทยท)
+
+
+
This event is triggered when the user clears the component (e.g. image or audio) using the X button for the component. This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about LinePlot
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ blocks_hello
+
+ blocks_kinematics
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+def welcome(name):
+ return f"Welcome to Gradio, {name}!"
+
+with gr.Blocks() as demo:
+ gr.Markdown(
+ """
+ # Hello World!
+ Start typing below to see the output.
+ """)
+ inp = gr.Textbox(placeholder="What is your name?")
+ out = gr.Textbox()
+ inp.change(welcome, inp, out)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
import pandas as pd
+import numpy as np
+
+import gradio as gr
+
+
+def plot(v, a):
+ g = 9.81
+ theta = a / 180 * 3.14
+ tmax = ((2 * v) * np.sin(theta)) / g
+ timemat = tmax * np.linspace(0, 1, 40)
+
+ x = (v * timemat) * np.cos(theta)
+ y = ((v * timemat) * np.sin(theta)) - ((0.5 * g) * (timemat**2))
+ df = pd.DataFrame({"x": x, "y": y})
+ return df
+
+
+demo = gr.Blocks()
+
+with demo:
+ gr.Markdown(
+ r"Let's do some kinematics! Choose the speed and angle to see the trajectory. Remember that the range $R = v_0^2 \cdot \frac{\sin(2\theta)}{g}$"
+ )
+
+ with gr.Row():
+ speed = gr.Slider(1, 30, 25, label="Speed")
+ angle = gr.Slider(0, 90, 45, label="Angle")
+ output = gr.LinePlot(
+ x="x",
+ y="y",
+ overlay_point=True,
+ tooltip=["x", "y"],
+ x_lim=[0, 100],
+ y_lim=[0, 60],
+ width=350,
+ height=300,
+ )
+ btn = gr.Button(value="Run")
+ btn.click(plot, [speed, angle], output)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Used to render arbitrary Markdown output. Can also render latex enclosed by dollar signs.
+
+
+
As input: this component does *not* accept input.
+
As output: expects a valid str that can be rendered as Markdown.
+
+
+
Supported events: change()
+
+
+
+
+
+
+
import gradio as gr
+
+def welcome(name):
+ return f"Welcome to Gradio, {name}!"
+
+with gr.Blocks() as demo:
+ gr.Markdown(
+ """
+ # Hello World!
+ Start typing below to see the output.
+ """)
+ inp = gr.Textbox(placeholder="What is your name?")
+ out = gr.Textbox()
+ inp.change(welcome, inp, out)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ value
+
+ str | Callable
+
+ default: ""
+
+
+
+ Value to show in Markdown component. If callable, the function will be called whenever the app loads to set the initial value of the component.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.Markdown
+
+
+ "markdown"
+
+
+ Uses default values
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Markdown.change( fn, ยทยทยท)
+
+
+
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+ bool | None
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Markdown
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gr.Dataset(components, samples)
+
+
+
+
+
+
+
+
+
+
+
Used to create an output widget for showing datasets. Used to render the examples box.
+
+
+
As input: passes the selected sample either as a list of data (if type="value") or as an int index (if type="index")
+
As output: expects a list of lists corresponding to the dataset data.
+
+
+
Supported events: click()
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ components
+
+ List[IOComponent] | List[str]
+
+ required
+
+
+
+ Which component types to show in this dataset widget, can be passed in as a list of string names or Components instances. The following components are supported in a Dataset: Audio, Checkbox, CheckboxGroup, ColorPicker, Dataframe, Dropdown, File, HTML, Image, Markdown, Model3D, Number, Radio, Slider, Textbox, TimeSeries, Video
+
+
+
+
+
+
+
+
+ samples
+
+ List[List[Any]] | None
+
+ default: None
+
+
+
+ a nested list of samples. Each sublist within the outer list represents a data sample, and each element within the sublist represents an value for each component
+
+
+
+
+
+
+
+
+ headers
+
+ List[str] | None
+
+ default: None
+
+
+
+ Column headers in the Dataset widget, should be the same len as components. If not provided, inferred from component labels
+
+
+
+
+
+
+
+
+ type
+
+ str
+
+ default: "values"
+
+
+
+ 'values' if clicking on a sample should pass the value of the sample, or "index" if it should pass the index of the sample
+
+
+
+
+
+
+
+
+ samples_per_page
+
+ int
+
+ default: 10
+
+
+
+ how many examples to show per page.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ If False, component will be hidden.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.Dataset
+
+
+ "dataset"
+
+
+ Uses default values
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Dataset.click( fn, ยทยทยท)
+
+
+
This event is triggered when the component (e.g. a button) is clicked. This method can be used when this component is in a Gradio Blocks.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ required
+
+
+
+ the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ inputs
+
+ Component | List[Component] | Set[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ outputs
+
+ Component | List[Component] | None
+
+ default: None
+
+
+
+ List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.
+
+
+
+
+
+
+
+
+ api_name
+
+ str | None
+
+ default: None
+
+
+
+ Defining this parameter exposes the endpoint in the api docs
+
+
+
+
+
+
+
+
+ status_tracker
+
+ StatusTracker | None
+
+ default: None
+
+
+
+
+
+
+
+
+
+
+
+
+ scroll_to_output
+
+ bool
+
+ default: False
+
+
+
+ If True, will scroll to output component on completion
+
+
+
+
+
+
+
+
+ show_progress
+
+ bool
+
+ default: True
+
+
+
+ If True, will show progress animation while pending
+
+
+
+
+
+
+
+
+ queue
+
+
+
+ default: None
+
+
+
+ If True, will place the request on the queue, if the queue exists
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
+
+
+
+
+
+
+
+
+ max_batch_size
+
+ int
+
+ default: 4
+
+
+
+ Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ If False, will not run postprocessing of component data before returning 'fn' output to the browser.
+
+
+
+
+
+
+
+
+ cancels
+
+ Dict[str, Any] | List[Dict[str, Any]] | None
+
+ default: None
+
+
+
+ A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.
+
+
+
+
+
+
+
+
+ every
+
+ float | None
+
+ default: None
+
+
+
+ Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Dataset.style( ยทยทยท)
+
+
+
This method can be used to change the appearance of the Dataset component.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Dataset
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Interpretation( component, ยทยทยท)
+
+
+
+
+
+
+
+
+
+
+
Used to create an interpretation widget for a component.
+
+
+
As input: this component does *not* accept input.
+
As output: expects a dict with keys "original" and "interpretation".
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ component
+
+ Component
+
+ required
+
+
+
+ Which component to show in the interpretation widget.
+
+
+
+
+
+
+
+
+ visible
+
+ bool
+
+ default: True
+
+
+
+ Whether or not the interpretation is visible.
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
+
+
+
+
+
+
+
+
+
+
+
+
+ Class
+ Interface String Shortcut
+ Initialization
+
+
+
+
+
+
+ gradio.Interpretation
+
+
+ "interpretation"
+
+
+ Uses default values
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Interpretation
+
+
+
+
+
+
+
+
+
+
+
+
+ Gradio includes helper classes and methods that interact with existing components. The goal of these classes and methods is to help you
+ add common functionality to your app without having to rewrite common functions.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ blocks_inputs
+
+ fake_gan
+
+
+
+
+
+
+
+
+
import gradio as gr
+import os
+
+
+def combine(a, b):
+ return a + " " + b
+
+
+def mirror(x):
+ return x
+
+
+with gr.Blocks() as demo:
+
+ txt = gr.Textbox(label="Input", lines=2)
+ txt_2 = gr.Textbox(label="Input 2")
+ txt_3 = gr.Textbox(value="", label="Output")
+ btn = gr.Button(value="Submit")
+ btn.click(combine, inputs=[txt, txt_2], outputs=[txt_3])
+
+ with gr.Row():
+ im = gr.Image()
+ im_2 = gr.Image()
+
+ btn = gr.Button(value="Mirror Image")
+ btn.click(mirror, inputs=[im], outputs=[im_2])
+
+ gr.Markdown("## Text Examples")
+ gr.Examples(
+ [["hi", "Adam"], ["hello", "Eve"]],
+ [txt, txt_2],
+ txt_3,
+ combine,
+ cache_examples=True,
+ )
+ gr.Markdown("## Image Examples")
+ gr.Examples(
+ examples=[os.path.join(os.path.dirname(__file__), "lion.jpg")],
+ inputs=im,
+ outputs=im_2,
+ fn=mirror,
+ cache_examples=True,
+ )
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
# This demo needs to be run from the repo folder.
+# python demo/fake_gan/run.py
+import os
+import random
+
+import gradio as gr
+
+
+def fake_gan():
+ images = [
+ (random.choice(
+ [
+ "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80",
+ "https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=386&q=80",
+ "https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW4lMjBmYWNlfGVufDB8fDB8fA%3D%3D&w=1000&q=80",
+ "https://images.unsplash.com/photo-1546456073-92b9f0a8d413?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80",
+ "https://images.unsplash.com/photo-1601412436009-d964bd02edbc?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=464&q=80",
+ ]
+ ), f"label {i}" if i != 0 else "label" * 50)
+ for i in range(3)
+ ]
+ return images
+
+
+with gr.Blocks() as demo:
+ with gr.Column(variant="panel"):
+ with gr.Row(variant="compact"):
+ text = gr.Textbox(
+ label="Enter your prompt",
+ show_label=False,
+ max_lines=1,
+ placeholder="Enter your prompt",
+ ).style(
+ container=False,
+ )
+ btn = gr.Button("Generate image").style(full_width=False)
+
+ gallery = gr.Gallery(
+ label="Generated images", show_label=False, elem_id="gallery"
+ ).style(grid=[2], height="auto")
+
+ btn.click(fake_gan, None, gallery)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
gradio.Examples( examples, inputs, ยทยทยท)
+
+
+
+
+
+
+
+
+
+
+
This class is a wrapper over the Dataset component and can be used to create Examples for Blocks / Interfaces. Populates the Dataset component with examples and assigns event listener so that clicking on an example populates the input/output components. Optionally handles example caching for fast inference.
+
+
+
+
+
+
+
import gradio as gr
+import os
+
+
+def combine(a, b):
+ return a + " " + b
+
+
+def mirror(x):
+ return x
+
+
+with gr.Blocks() as demo:
+
+ txt = gr.Textbox(label="Input", lines=2)
+ txt_2 = gr.Textbox(label="Input 2")
+ txt_3 = gr.Textbox(value="", label="Output")
+ btn = gr.Button(value="Submit")
+ btn.click(combine, inputs=[txt, txt_2], outputs=[txt_3])
+
+ with gr.Row():
+ im = gr.Image()
+ im_2 = gr.Image()
+
+ btn = gr.Button(value="Mirror Image")
+ btn.click(mirror, inputs=[im], outputs=[im_2])
+
+ gr.Markdown("## Text Examples")
+ gr.Examples(
+ [["hi", "Adam"], ["hello", "Eve"]],
+ [txt, txt_2],
+ txt_3,
+ combine,
+ cache_examples=True,
+ )
+ gr.Markdown("## Image Examples")
+ gr.Examples(
+ examples=[os.path.join(os.path.dirname(__file__), "lion.jpg")],
+ inputs=im,
+ outputs=im_2,
+ fn=mirror,
+ cache_examples=True,
+ )
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ examples
+
+ List[Any] | List[List[Any]] | str
+
+ required
+
+
+
+ example inputs that can be clicked to populate specific components. Should be nested list, in which the outer list consists of samples and each inner list consists of an input corresponding to each input component. A string path to a directory of examples can also be provided but it should be within the directory with the python file running the gradio app. If there are multiple input components and a directory is provided, a log.csv file must be present in the directory to link corresponding inputs.
+
+
+
+
+
+
+
+
+ inputs
+
+ IOComponent | List[IOComponent]
+
+ required
+
+
+
+ the component or list of components corresponding to the examples
+
+
+
+
+
+
+
+
+ outputs
+
+ IOComponent | List[IOComponent] | None
+
+ default: None
+
+
+
+ optionally, provide the component or list of components corresponding to the output of the examples. Required if `cache` is True.
+
+
+
+
+
+
+
+
+ fn
+
+ Callable | None
+
+ default: None
+
+
+
+ optionally, provide the function to run to generate the outputs corresponding to the examples. Required if `cache` is True.
+
+
+
+
+
+
+
+
+ cache_examples
+
+ bool
+
+ default: False
+
+
+
+ if True, caches examples for fast runtime. If True, then `fn` and `outputs` need to be provided
+
+
+
+
+
+
+
+
+ examples_per_page
+
+ int
+
+ default: 10
+
+
+
+ how many examples to show per page.
+
+
+
+
+
+
+
+
+ label
+
+ str | None
+
+ default: "Examples"
+
+
+
+ the label to use for the examples component (by default, "Examples")
+
+
+
+
+
+
+
+
+ elem_id
+
+ str | None
+
+ default: None
+
+
+
+ an optional string that is assigned as the id of this component in the HTML DOM.
+
+
+
+
+
+
+
+
+ run_on_click
+
+ bool
+
+ default: False
+
+
+
+ if cache_examples is False, clicking on an example does not run the function when an example is clicked. Set this to True to run the function when an example is clicked. Has no effect if cache_examples is True.
+
+
+
+
+
+
+
+
+ preprocess
+
+ bool
+
+ default: True
+
+
+
+ if True, preprocesses the example input before running the prediction function and caching the output. Only applies if cache_examples is True.
+
+
+
+
+
+
+
+
+ postprocess
+
+ bool
+
+ default: True
+
+
+
+ if True, postprocesses the example output after running the prediction function and before caching. Only applies if cache_examples is True.
+
+
+
+
+
+
+
+
+ batch
+
+ bool
+
+ default: False
+
+
+
+ If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. Used only if cache_examples is True.
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Examples
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ progress
+
+
+
+
+
+
+
+
+
import gradio as gr
+import random
+import time
+import tqdm
+from datasets import load_dataset
+import shutil
+from uuid import uuid4
+
+with gr.Blocks() as demo:
+ with gr.Row():
+ text = gr.Textbox()
+ textb = gr.Textbox()
+ with gr.Row():
+ load_set_btn = gr.Button("Load Set")
+ load_nested_set_btn = gr.Button("Load Nested Set")
+ load_random_btn = gr.Button("Load Random")
+ clean_imgs_btn = gr.Button("Clean Images")
+ wait_btn = gr.Button("Wait")
+ do_all_btn = gr.Button("Do All")
+ track_tqdm_btn = gr.Button("Bind TQDM")
+ bind_internal_tqdm_btn = gr.Button("Bind Internal TQDM")
+
+ text2 = gr.Textbox()
+
+ # track list
+ def load_set(text, text2, progress=gr.Progress()):
+ imgs = [None] * 24
+ for img in progress.tqdm(imgs, desc="Loading from list"):
+ time.sleep(0.1)
+ return "done"
+ load_set_btn.click(load_set, [text, textb], text2)
+
+ # track nested list
+ def load_nested_set(text, text2, progress=gr.Progress()):
+ imgs = [[None] * 8] * 3
+ for img_set in progress.tqdm(imgs, desc="Nested list"):
+ time.sleep(2)
+ for img in progress.tqdm(img_set, desc="inner list"):
+ time.sleep(0.1)
+ return "done"
+ load_nested_set_btn.click(load_nested_set, [text, textb], text2)
+
+ # track iterable of unknown length
+ def load_random(data, progress=gr.Progress()):
+ def yielder():
+ for i in range(0, random.randint(15, 20)):
+ time.sleep(0.1)
+ yield None
+ for img in progress.tqdm(yielder()):
+ pass
+ return "done"
+ load_random_btn.click(load_random, {text, textb}, text2)
+
+ # manual progress
+ def clean_imgs(text, progress=gr.Progress()):
+ progress(0.2, desc="Collecting Images")
+ time.sleep(1)
+ progress(0.5, desc="Cleaning Images")
+ time.sleep(1.5)
+ progress(0.8, desc="Sending Images")
+ time.sleep(1.5)
+ return "done"
+ clean_imgs_btn.click(clean_imgs, text, text2)
+
+ # no progress
+ def wait(text):
+ time.sleep(4)
+ return "done"
+ wait_btn.click(wait, text, text2)
+
+ # multiple progressions
+ def do_all(data, progress=gr.Progress()):
+ load_set(data[text], data[textb], progress)
+ load_random(data, progress)
+ clean_imgs(data[text], progress)
+ progress(None)
+ wait(text)
+ return "done"
+ do_all_btn.click(do_all, {text, textb}, text2)
+
+ def track_tqdm(data, progress=gr.Progress(track_tqdm=True)):
+ for i in tqdm.tqdm(range(5), desc="outer"):
+ for j in tqdm.tqdm(range(4), desc="inner"):
+ time.sleep(1)
+ return "done"
+ track_tqdm_btn.click(track_tqdm, {text, textb}, text2)
+
+ def bind_internal_tqdm(data, progress=gr.Progress(track_tqdm=True)):
+ outdir = "__tmp/" + str(uuid4())
+ dataset = load_dataset("beans", split="train", cache_dir=outdir)
+ shutil.rmtree(outdir)
+ return "done"
+ bind_internal_tqdm_btn.click(bind_internal_tqdm, {text, textb}, text2)
+
+
+if __name__ == "__main__":
+ demo.queue(concurrency_count=20).launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
The Progress class provides a custom progress tracker that is used in a function signature. To attach a Progress tracker to a function, simply add a parameter right after the input parameters that has a default value set to a `gradio.Progress()` instance. The Progress tracker can then be updated in the function by calling the Progress object or using the `tqdm` method on an Iterable. The Progress tracker is currently only available with `queue()`.
+
+
+
+
+
Example Usage
+
+
import gradio as gr
+import time
+def my_function(x, progress=gr.Progress()):
+ progress(0, desc="Starting...")
+ time.sleep(1)
+ for i in progress.tqdm(range(100)):
+ time.sleep(0.1)
+ return x
+gr.Interface(my_function, gr.Textbox(), gr.Textbox()).queue().launch()
+
+
+
+ More Examples โ
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ track_tqdm
+
+ bool
+
+ default: False
+
+
+
+ If True, the Progress object will track any tqdm.tqdm iterations with the tqdm library in the function.
+
+
+
+
+
+
+
+
+
+
+
Methods
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Progress(progress, ยทยทยท)
+
+
+
Updates progress tracker with progress and message text.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ progress
+
+ float | Tuple[int, int | None] | None
+
+ required
+
+
+
+ If float, should be between 0 and 1 representing completion. If Tuple, first number represents steps completed, and second value represents total steps or None if unknown. If None, hides progress bar.
+
+
+
+
+
+
+
+
+ desc
+
+ str | None
+
+ default: None
+
+
+
+ description to display.
+
+
+
+
+
+
+
+
+ total
+
+ int | None
+
+ default: None
+
+
+
+ estimated total number of steps.
+
+
+
+
+
+
+
+
+ unit
+
+ str
+
+ default: "steps"
+
+
+
+ unit of iterations.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.Progress.tqdm( iterable, args, ยทยทยท)
+
+
+
Attaches progress tracker to iterable, like tqdm.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ iterable
+
+ Iterable | None
+
+ required
+
+
+
+ iterable to attach progress tracker to.
+
+
+
+
+
+
+
+
+ desc
+
+ str | None
+
+ default: None
+
+
+
+ description to display.
+
+
+
+
+
+
+
+
+ total
+
+ int | None
+
+ default: None
+
+
+
+ estimated total number of steps.
+
+
+
+
+
+
+
+
+ unit
+
+ str
+
+ default: "steps"
+
+
+
+ unit of iterations.
+
+
+
+
+
+
+
+
+ args
+
+
+
+ required
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about Progress
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ blocks_essay
+
+ blocks_update
+
+ blocks_essay_update
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+
+def change_textbox(choice):
+ if choice == "short":
+ return gr.Textbox.update(lines=2, visible=True)
+ elif choice == "long":
+ return gr.Textbox.update(lines=8, visible=True)
+ else:
+ return gr.Textbox.update(visible=False)
+
+
+with gr.Blocks() as demo:
+ radio = gr.Radio(
+ ["short", "long", "none"], label="What kind of essay would you like to write?"
+ )
+ text = gr.Textbox(lines=2, interactive=True)
+
+ radio.change(fn=change_textbox, inputs=radio, outputs=text)
+
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+with gr.Blocks() as demo:
+ gr.Markdown(
+ """
+ # Animal Generator
+ Once you select a species, the detail panel should be visible.
+ """
+ )
+
+ species = gr.Radio(label="Animal Class", choices=["Mammal", "Fish", "Bird"])
+ animal = gr.Dropdown(label="Animal", choices=[])
+
+ with gr.Column(visible=False) as details_col:
+ weight = gr.Slider(0, 20)
+ details = gr.Textbox(label="Extra Details")
+ generate_btn = gr.Button("Generate")
+ output = gr.Textbox(label="Output")
+
+ species_map = {
+ "Mammal": ["Elephant", "Giraffe", "Hamster"],
+ "Fish": ["Shark", "Salmon", "Tuna"],
+ "Bird": ["Chicken", "Eagle", "Hawk"],
+ }
+
+ def filter_species(species):
+ return gr.Dropdown.update(
+ choices=species_map[species], value=species_map[species][1]
+ ), gr.update(visible=True)
+
+ species.change(filter_species, species, [animal, details_col])
+
+ def filter_weight(animal):
+ if animal in ("Elephant", "Shark", "Giraffe"):
+ return gr.update(maximum=100)
+ else:
+ return gr.update(maximum=20)
+
+ animal.change(filter_weight, animal, weight)
+ weight.change(lambda w: gr.update(lines=int(w / 10) + 1), weight, details)
+
+ generate_btn.click(lambda x: x, details, output)
+
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
import gradio as gr
+
+def change_textbox(choice):
+ if choice == "short":
+ return gr.update(lines=2, visible=True, value="Short story: ")
+ elif choice == "long":
+ return gr.update(lines=8, visible=True, value="Long story...")
+ else:
+ return gr.update(visible=False)
+
+with gr.Blocks() as demo:
+ radio = gr.Radio(
+ ["short", "long", "none"], label="Essay Length to Write?"
+ )
+ text = gr.Textbox(lines=2, interactive=True)
+ radio.change(fn=change_textbox, inputs=radio, outputs=text)
+
+if __name__ == "__main__":
+ demo.launch()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Try Examples
+
+
+
+
+
gradio.update( kwargs, ยทยทยท)
+
+
+
Updates component properties. When a function passed into a Gradio Interface or a Blocks events returns a typical value, it updates the value of the output component. But it is also possible to update the properties of an output component (such as the number of lines of a `Textbox` or the visibility of an `Image`) by returning the component's `update()` function, which takes as parameters any of the constructor parameters for that component. This is a shorthand for using the update method on a component. For example, rather than using gr.Number.update(...) you can just use gr.update(...). Note that your editor's autocompletion will suggest proper parameters if you use the update method on the component.
+
+
+
+
+
Example Usage
+
+
# Blocks Example
+import gradio as gr
+with gr.Blocks() as demo:
+ radio = gr.Radio([1, 2, 4], label="Set the value of the number")
+ number = gr.Number(value=2, interactive=True)
+ radio.change(fn=lambda value: gr.update(value=value), inputs=radio, outputs=number)
+demo.launch()
+
+# Interface example
+import gradio as gr
+def change_textbox(choice):
+ if choice == "short":
+ return gr.Textbox.update(lines=2, visible=True)
+ elif choice == "long":
+ return gr.Textbox.update(lines=8, visible=True)
+ else:
+ return gr.Textbox.update(visible=False)
+gr.Interface(
+ change_textbox,
+ gr.Radio(
+ ["short", "long", "none"], label="What kind of essay would you like to write?"
+ ),
+ gr.Textbox(lines=2),
+ live=True,
+).launch()
+
+
+
+ More Examples โ
+
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+ kwargs
+
+
+
+ required
+
+
+
+ Key-word arguments used to update the component's properties.
+
+
+
+
+
+
+
+
+
+
+
+
Step-by-step Guides
+
+
No guides yet, contribute a guide about update
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Gradio includes some helper functions for exposing and interacting with the FastAPI app
+ used to run your demo.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
A Gradio request object that can be used to access the request headers, cookies, query parameters and other information about the request from within the prediction function. The class is a thin wrapper around the fastapi.Request class. Attributes of this class include: `headers`, `client`, `query_params`, and `path_params`,
+
+
+
+
+
Example Usage
+
+
import gradio as gr
+def echo(name, request: gr.Request):
+ print("Request headers dictionary:", request.headers)
+ print("IP address:", request.client.host)
+ return name
+io = gr.Interface(echo, "textbox", "textbox").launch()
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+
+
+ request
+
+ fastapi.Request | None
+
+ default: None
+
+
+
+ A fastapi.Request
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
gradio.mount_gradio_app( app, blocks, path, ยทยทยท)
+
+
+
Mount a gradio.Blocks to an existing FastAPI application.
+
+
+
+
+
Example Usage
+
+
from fastapi import FastAPI
+import gradio as gr
+app = FastAPI()
+@app.get("/")
+def read_main():
+ return {"message": "This is your main app"}
+io = gr.Interface(lambda x: "Hello, " + x + "!", "textbox", "textbox")
+app = gr.mount_gradio_app(app, io, path="/gradio")
+# Then run `uvicorn run:app` from the terminal and navigate to http://localhost:8000/gradio.
+
+
+
+
+
+
+
+
+
+ Parameter
+ Description
+
+
+
+
+
+
+
+
+ app
+
+ fastapi.FastAPI
+
+ required
+
+
+
+ The parent FastAPI application.
+
+
+
+
+
+
+
+
+ blocks
+
+ gradio.Blocks
+
+ required
+
+
+
+ The blocks object we want to mount to the parent app.
+
+
+
+
+
+
+
+
+ path
+
+ str
+
+ required
+
+
+
+ The path at which the gradio application will be mounted.
+
+
+
+
+
+
+
+
+ gradio_api_url
+
+ str | None
+
+ default: None
+
+
+
+ The full url at which the gradio app will run. This is only needed if deploying to Huggingface spaces of if the websocket endpoints of your deployed app are on a different network location than the gradio app. If deploying to spaces, set gradio_api_url to 'http://localhost:7860/'
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file