text
stringlengths 0
2k
| heading1
stringlengths 4
79
| source_page_url
stringclasses 180
values | source_page_title
stringclasses 180
values |
|---|---|---|---|
--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\(Commercial%20License\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)
import gradio as gr
with gr.Blocks() as demo:
gr.Markdown("When you close the tab, hello will be printed to the console")
demo.unload(lambda: print("hello"))
demo.launch()
Parameters ▼
fn: Callable[..., Any]
Callable function to run to clear resources. The function should not take any
arguments and the output is not used.
|
unload
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
ources. The function should not take any
arguments and the output is not used.
|
unload
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
Creates a button, that when clicked, allows a user to download a single
file of arbitrary type.
|
Description
|
https://gradio.app/docs/gradio/downloadbutton
|
Gradio - Downloadbutton Docs
|
**As input component** : (Rarely used) passes the file as a `str` into the
function.
Your function should accept one of these types:
def predict(
value: str | None
)
...
**As output component** : Expects a `str` or `pathlib.Path` filepath
Your function should return one of these types:
def predict(···) -> str | Path | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/downloadbutton
|
Gradio - Downloadbutton Docs
|
Parameters ▼
label: str
default `= "Download"`
Text to display on the button. Defaults to "Download".
value: str | Path | Callable | None
default `= None`
A str or pathlib.Path filepath or URL to download, or a Callable that returns
a str or pathlib.Path filepath or URL to download.
every: Timer | float | None
default `= None`
Continously calls `value` to recalculate it if `value` is a function (has no
effect otherwise). Can provide a Timer whose tick resets `value`, or a float
that provides the regular interval for the reset Timer.
inputs: Component | list[Component] | set[Component] | None
default `= None`
Components that are used as inputs to calculate `value` if `value` is a
function (has no effect otherwise). `value` is recalculated any time the
inputs change.
variant: Literal['primary', 'secondary', 'stop']
default `= "secondary"`
'primary' for main call-to-action, 'secondary' for a more subdued style,
'stop' for a stop button.
visible: bool | Literal['hidden']
default `= True`
If False, component will be hidden. If "hidden", component will be visually
hidden and not take up space in the layout but still exist in the DOM
size: Literal['sm', 'md', 'lg']
default `= "lg"`
size of the button. Can be "sm", "md", or "lg".
icon: str | None
default `= None`
URL or path to the icon file to display within the button. If None, no icon
will be displayed.
scale: int | None
default `= None`
relative size compared to adjacent Components. For example if Components A and
B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide
as B. Should be an integer. scale applies in Rows, and to top-level Components
in Blocks where fill_height=True.
min_width: int | None
default `= None`
minimum pixel width, will wrap if not sufficient screen space to satisfy this
value. If a certain scale v
|
Initialization
|
https://gradio.app/docs/gradio/downloadbutton
|
Gradio - Downloadbutton Docs
|
nts
in Blocks where fill_height=True.
min_width: int | None
default `= None`
minimum pixel width, will wrap if not sufficient screen space to satisfy this
value. If a certain scale value results in this Component being narrower than
min_width, the min_width parameter will be respected first.
interactive: bool
default `= True`
If False, the UploadButton will be in a disabled state.
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.
elem_classes: list[str] | str | None
default `= None`
An optional list of strings that are assigned as the classes of this component
in the HTML DOM. Can be used for targeting CSS styles.
render: bool
default `= True`
If False, component will not render be rendered in the Blocks context. Should
be used if the intention is to assign event listeners now but render the
component later.
key: int | str | tuple[int | str, ...] | None
default `= None`
in a gr.render, Components with the same key across re-renders are treated as
the same component, not a new component. Properties set in 'preserved_by_key'
are not reset across a re-render.
preserved_by_key: list[str] | str | None
default `= "value"`
A list of parameters from this component's constructor. Inside a gr.render()
function, if a component is re-rendered with the same key, these (and only
these) parameters will be preserved in the UI (if they have been changed by
the user or an event listener) instead of re-rendered based on the values
provided during constructor.
|
Initialization
|
https://gradio.app/docs/gradio/downloadbutton
|
Gradio - Downloadbutton Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.DownloadButton` | "downloadbutton" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/downloadbutton
|
Gradio - Downloadbutton Docs
|
upload_and_download
Open in 🎢 ↗ from pathlib import Path import gradio as gr def
upload_file(filepath): name = Path(filepath).name return
[gr.UploadButton(visible=False), gr.DownloadButton(label=f"Download {name}",
value=filepath, visible=True)] def download_file(): return
[gr.UploadButton(visible=True), gr.DownloadButton(visible=False)] with
gr.Blocks() as demo: gr.Markdown("First upload a file and and then you'll be
able download it (but only once!)") with gr.Row(): u = gr.UploadButton("Upload
a file", file_count="single") d = gr.DownloadButton("Download the file",
visible=False) u.upload(upload_file, u, [u, d]) d.click(download_file, None,
[u, d]) if __name__ == "__main__": demo.launch()
from pathlib import Path
import gradio as gr
def upload_file(filepath):
name = Path(filepath).name
return [gr.UploadButton(visible=False), gr.DownloadButton(label=f"Download {name}", value=filepath, visible=True)]
def download_file():
return [gr.UploadButton(visible=True), gr.DownloadButton(visible=False)]
with gr.Blocks() as demo:
gr.Markdown("First upload a file and and then you'll be able download it (but only once!)")
with gr.Row():
u = gr.UploadButton("Upload a file", file_count="single")
d = gr.DownloadButton("Download the file", visible=False)
u.upload(upload_file, u, [u, d])
d.click(download_file, None, [u, d])
if __name__ == "__main__":
demo.launch()
|
Demos
|
https://gradio.app/docs/gradio/downloadbutton
|
Gradio - Downloadbutton Docs
|
Description
Event listeners allow you to respond to user interactions with the UI
components you've defined in a Gradio Blocks app. When a user interacts with
an element, such as changing a slider value or uploading an image, a function
is called.
Supported Event Listeners
The DownloadButton component supports the following event listeners. Each
event listener takes the same parameters, which are listed in the Event
Parameters table below.
Listener | Description
---|---
`DownloadButton.click(fn, ···)` | Triggered when the DownloadButton is clicked.
Event Parameters
Parameters ▼
fn: Callable | None | Literal['decorator']
default `= "decorator"`
the function to call when this event is triggered. 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 | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | 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 | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as outputs. If the function returns no
outputs, this should be an empty list.
api_name: str | None | Literal[False]
default `= None`
defines how the endpoint appears in the API docs. Can be a string, None, or
False. If set to a string, the endpoint will be exposed in the API docs with
the given name. If None (default), the name of the function will be used as
the API endpoint. If False, the endpoint will not be exposed in the API docs
and downstream apps (including those that `gr.load` this app) will not be able
to use this event.
|
Event Listeners
|
https://gradio.app/docs/gradio/downloadbutton
|
Gradio - Downloadbutton Docs
|
e used as
the API endpoint. If False, the endpoint will not be exposed in the API docs
and downstream apps (including those that `gr.load` this app) will not be able
to use this event.
api_description: str | None | Literal[False]
default `= None`
Description of the API endpoint. Can be a string, None, or False. If set to a
string, the endpoint will be exposed in the API docs with the given
description. If None, the function's docstring will be used as the API
endpoint description. If False, then no description will be displayed in the
API docs.
scroll_to_output: bool
default `= False`
If True, will scroll to output component on completion
show_progress: Literal['full', 'minimal', 'hidden']
default `= "full"`
how to show the progress animation while event is running: "full" shows a
spinner which covers the output component area as well as a runtime display in
the upper right corner, "minimal" only shows the runtime display, "hidden"
shows no progress animation at all
show_progress_on: Component | list[Component] | None
default `= None`
Component or list of components to show the progress animation on. If None,
will show the progress animation on all of the output components.
queue: bool
default `= True`
If True, will place the request on the queue, if the queue has been enabled.
If False, will not put this event on the queue, even if the queue has been
enabled. If None, will use the queue setting of the gradio app.
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
|
Event Listeners
|
https://gradio.app/docs/gradio/downloadbutton
|
Gradio - Downloadbutton Docs
|
s 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 listener 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. Functions that have
not yet run (or generators that are iterating) will be cancelled, but
functions that are currently running will be allowed to finish.
trigger_mode: Literal['once', 'multiple', 'always_last'] | None
default `= None`
If "once" (default for all events except `.change()`) would not allow any
submissions while an event is pending. If set to "multiple", unlimited
submissions are allowed while pending, and "always_last" (default for
`.change()` and `.key_up()` events) would allow a second submission after the
pending event is complete.
js: str | Literal[True] | None
default `= None`
Optional frontend js method to run before running 'fn'. Input arguments for js
method are values of 'inputs' and 'outputs', return should be a list of values
for output components.
concurrency_limit: int | None | Literal['default']
default `= "default"`
If set, this is the maximum number of this event that can be running
simultaneously. Can be set to Non
|
Event Listeners
|
https://gradio.app/docs/gradio/downloadbutton
|
Gradio - Downloadbutton Docs
|
nents.
concurrency_limit: int | None | Literal['default']
default `= "default"`
If set, this is the maximum number of this event that can be running
simultaneously. Can be set to None to mean no concurrency_limit (any number of
this event can be running simultaneously). Set to "default" to use the default
concurrency limit (defined by the `default_concurrency_limit` parameter in
`Blocks.queue()`, which itself is 1 by default).
concurrency_id: str | None
default `= None`
If set, this is the id of the concurrency group. Events with the same
concurrency_id will be limited by the lowest set concurrency_limit.
show_api: bool
default `= True`
whether to show this event in the "view API" page of the Gradio app, or in the
".view_api()" method of the Gradio clients. Unlike setting api_name to False,
setting show_api to False will still allow downstream apps as well as the
Clients to use this event. If fn is None, show_api will automatically be set
to False.
time_limit: int | None
default `= None`
stream_every: float
default `= 0.5`
like_user_message: bool
default `= False`
key: int | str | tuple[int | str, ...] | None
default `= None`
A unique key for this event listener to be used in @gr.render(). If set, this
value identifies an event as identical across re-renders when the key is
identical.
validator: Callable | None
default `= None`
Optional validation function to run before the main function. If provided,
this function will be executed first with queue=False, and only if it
completes successfully will the main function be called. The validator
receives the same inputs as the main function and should return a
`gr.validate()` for each input value.
|
Event Listeners
|
https://gradio.app/docs/gradio/downloadbutton
|
Gradio - Downloadbutton Docs
|
put value.
|
Event Listeners
|
https://gradio.app/docs/gradio/downloadbutton
|
Gradio - Downloadbutton Docs
|
Creates a component to displays a base image and colored annotations on top
of that image. Annotations can take the from of rectangles (e.g. object
detection) or masks (e.g. image segmentation). As this component does not
accept user input, it is rarely used as an input component.
|
Description
|
https://gradio.app/docs/gradio/annotatedimage
|
Gradio - Annotatedimage Docs
|
**As input component** : Passes its value as a `tuple` consisting of a
`str` filepath to a base image and `list` of annotations. Each annotation
itself is `tuple` of a mask (as a `str` filepath to image) and a `str` label.
Your function should accept one of these types:
def predict(
value: tuple[str, list[tuple[str, str]]] | None
)
...
**As output component** : Expects a a tuple of a base image and list of
annotations: a `tuple[Image, list[Annotation]]`. The `Image` itself can be
`str` filepath, `numpy.ndarray`, or `PIL.Image`. Each `Annotation` is a
`tuple[Mask, str]`. The `Mask` can be either a `tuple` of 4 `int`'s
representing the bounding box coordinates (x1, y1, x2, y2), or 0-1 confidence
mask in the form of a `numpy.ndarray` of the same shape as the image, while
the second element of the `Annotation` tuple is a `str` label.
Your function should return one of these types:
def predict(···) -> tuple[np.ndarray | PIL.Image.Image | str, list[tuple[np.ndarray | tuple[int, int, int, int], str]]] | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/annotatedimage
|
Gradio - Annotatedimage Docs
|
Parameters ▼
value: tuple[np.ndarray | PIL.Image.Image | str, list[tuple[np.ndarray | tuple[int, int, int, int], str]]] | None
default `= None`
Tuple of base image and list of (annotation, label) pairs.
format: str
default `= "webp"`
Format used to save images before it is returned to the front end, such as
'jpeg' or 'png'. This parameter only takes effect when the base image is
returned from the prediction function as a numpy array or a PIL Image. The
format should be supported by the PIL library.
show_legend: bool
default `= True`
If True, will show a legend of the annotations.
height: int | str | None
default `= None`
The height of the component, specified in pixels if a number is passed, or in
CSS units if a string is passed. This has no effect on the preprocessed image
file or numpy array, but will affect the displayed image.
width: int | str | None
default `= None`
The width of the component, specified in pixels if a number is passed, or in
CSS units if a string is passed. This has no effect on the preprocessed image
file or numpy array, but will affect the displayed image.
color_map: dict[str, str] | None
default `= None`
A dictionary mapping labels to colors. The colors must be specified as hex
codes.
label: str | I18nData | None
default `= None`
the label for this component. Appears above the component and is also used as
the header if there are a table of examples for this component. If None and
used in a `gr.Interface`, the label will be the name of the parameter this
component is assigned to.
every: Timer | float | None
default `= None`
Continously calls `value` to recalculate it if `value` is a function (has no
effect otherwise). Can provide a Timer whose tick resets `value`, or a float
that provides the regular interval for the reset Timer.
inputs: Component | list[Component] | set[Component] |
|
Initialization
|
https://gradio.app/docs/gradio/annotatedimage
|
Gradio - Annotatedimage Docs
|
ct otherwise). Can provide a Timer whose tick resets `value`, or a float
that provides the regular interval for the reset Timer.
inputs: Component | list[Component] | set[Component] | None
default `= None`
Components that are used as inputs to calculate `value` if `value` is a
function (has no effect otherwise). `value` is recalculated any time the
inputs change.
show_label: bool | None
default `= None`
if True, will display label.
container: bool
default `= True`
If True, will place the component in a container - providing some extra
padding around the border.
scale: int | None
default `= None`
Relative width compared to adjacent Components in a Row. For example, if
Component A has scale=2, and Component B has scale=1, A will be twice as wide
as B. Should be an integer.
min_width: int
default `= 160`
Minimum pixel width, will wrap if not sufficient screen space to satisfy this
value. If a certain scale value results in this Component being narrower than
min_width, the min_width parameter will be respected first.
visible: bool | Literal['hidden']
default `= True`
If False, component will be hidden. If "hidden", component will be visually
hidden and not take up space in the layout but still exist in the DOM
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.
elem_classes: list[str] | str | None
default `= None`
An optional list of strings that are assigned as the classes of this component
in the HTML DOM. Can be used for targeting CSS styles.
render: bool
default `= True`
If False, component will not render be rendered in the Blocks context. Should
be used if the intention is to assign event listeners now but render the
component later.
key: int | str | tuple[int | str, ...] | None
default
|
Initialization
|
https://gradio.app/docs/gradio/annotatedimage
|
Gradio - Annotatedimage Docs
|
rendered in the Blocks context. Should
be used if the intention is to assign event listeners now but render the
component later.
key: int | str | tuple[int | str, ...] | None
default `= None`
in a gr.render, Components with the same key across re-renders are treated as
the same component, not a new component. Properties set in 'preserved_by_key'
are not reset across a re-render.
preserved_by_key: list[str] | str | None
default `= "value"`
A list of parameters from this component's constructor. Inside a gr.render()
function, if a component is re-rendered with the same key, these (and only
these) parameters will be preserved in the UI (if they have been changed by
the user or an event listener) instead of re-rendered based on the values
provided during constructor.
show_fullscreen_button: bool
default `= True`
If True, will show a button to allow the image to be viewed in fullscreen
mode.
|
Initialization
|
https://gradio.app/docs/gradio/annotatedimage
|
Gradio - Annotatedimage Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.AnnotatedImage` | "annotatedimage" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/annotatedimage
|
Gradio - Annotatedimage Docs
|
image_segmentation
Open in 🎢 ↗ import gradio as gr import numpy as np import random with
gr.Blocks() as demo: section_labels = [ "apple", "banana", "carrot", "donut",
"eggplant", "fish", "grapes", "hamburger", "ice cream", "juice", ] with
gr.Row(): num_boxes = gr.Slider(0, 5, 2, step=1, label="Number of boxes")
num_segments = gr.Slider(0, 5, 1, step=1, label="Number of segments") with
gr.Row(): img_input = gr.Image() img_output = gr.AnnotatedImage(
color_map={"banana": "a89a00", "carrot": "ffae00"} ) section_btn =
gr.Button("Identify Sections") selected_section = gr.Textbox(label="Selected
Section") def section(img, num_boxes, num_segments): sections = [] for a in
range(num_boxes): x = random.randint(0, img.shape[1]) y = random.randint(0,
img.shape[0]) w = random.randint(0, img.shape[1] - x) h = random.randint(0,
img.shape[0] - y) sections.append(((x, y, x + w, y + h), section_labels[a]))
for b in range(num_segments): x = random.randint(0, img.shape[1]) y =
random.randint(0, img.shape[0]) r = random.randint(0, min(x, y, img.shape[1] -
x, img.shape[0] - y)) mask = np.zeros(img.shape[:2]) for i in
range(img.shape[0]): for j in range(img.shape[1]): dist_square = (i - y) ** 2
+ (j - x) ** 2 if dist_square < r**2: mask[i, j] = round((r**2 - dist_square)
/ r**2 * 4) / 4 sections.append((mask, section_labels[b + num_boxes])) return
(img, sections) section_btn.click(section, [img_input, num_boxes,
num_segments], img_output) def select_section(evt: gr.SelectData): return
section_labels[evt.index] img_output.select(select_section, None,
selected_section) if __name__ == "__main__": demo.launch()
import gradio as gr
import numpy as np
import random
with gr.Blocks() as demo:
section_labels = [
"apple",
"banana",
"carrot",
"donut",
"eggplant",
"fish",
"grapes",
"hamburger",
"ice cream",
"juice",
]
w
|
Demos
|
https://gradio.app/docs/gradio/annotatedimage
|
Gradio - Annotatedimage Docs
|
"carrot",
"donut",
"eggplant",
"fish",
"grapes",
"hamburger",
"ice cream",
"juice",
]
with gr.Row():
num_boxes = gr.Slider(0, 5, 2, step=1, label="Number of boxes")
num_segments = gr.Slider(0, 5, 1, step=1, label="Number of segments")
with gr.Row():
img_input = gr.Image()
img_output = gr.AnnotatedImage(
color_map={"banana": "a89a00", "carrot": "ffae00"}
)
section_btn = gr.Button("Identify Sections")
selected_section = gr.Textbox(label="Selected Section")
def section(img, num_boxes, num_segments):
sections = []
for a in range(num_boxes):
x = random.randint(0, img.shape[1])
y = random.randint(0, img.shape[0])
w = random.randint(0, img.shape[1] - x)
h = random.randint(0, img.shape[0] - y)
sections.append(((x, y, x + w, y + h), section_labels[a]))
for b in range(num_segments):
x = random.randint(0, img.shape[1])
y = random.randint(0, img.shape[0])
r = random.randint(0, min(x, y, img.shape[1] - x, img.shape[0] - y))
mask = np.zeros(img.shape[:2])
for i in range(img.shape[0]):
for j in range(img.shape[1]):
dist_square = (i - y) ** 2 + (j - x) ** 2
if dist_square < r**2:
mask[i, j] = round((r**2 - dist_square) / r**2 * 4) / 4
sections.append((mask, section_labels[b + num_boxes]))
return (img, sections)
section_btn.click(section, [img_input, num_boxes, num_segments], img_output)
def select_section(evt: gr.SelectData):
return section_labels[evt.index]
img_output.select(select_s
|
Demos
|
https://gradio.app/docs/gradio/annotatedimage
|
Gradio - Annotatedimage Docs
|
ick(section, [img_input, num_boxes, num_segments], img_output)
def select_section(evt: gr.SelectData):
return section_labels[evt.index]
img_output.select(select_section, None, selected_section)
if __name__ == "__main__":
demo.launch()
|
Demos
|
https://gradio.app/docs/gradio/annotatedimage
|
Gradio - Annotatedimage Docs
|
Description
Event listeners allow you to respond to user interactions with the UI
components you've defined in a Gradio Blocks app. When a user interacts with
an element, such as changing a slider value or uploading an image, a function
is called.
Supported Event Listeners
The AnnotatedImage component supports the following event listeners. Each
event listener takes the same parameters, which are listed in the Event
Parameters table below.
Listener | Description
---|---
`AnnotatedImage.select(fn, ···)` | Event listener for when the user selects or deselects the AnnotatedImage. Uses event data gradio.SelectData to carry `value` referring to the label of the AnnotatedImage, and `selected` to refer to state of the AnnotatedImage. See EventData documentation on how to use this event data
Event Parameters
Parameters ▼
fn: Callable | None | Literal['decorator']
default `= "decorator"`
the function to call when this event is triggered. 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 | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | 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 | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as outputs. If the function returns no
outputs, this should be an empty list.
api_name: str | None | Literal[False]
default `= None`
defines how the endpoint appears in the API docs. Can be a string, None, or
False. If set to a string, the endpoint will be exposed in the API docs with
the given name. If None (d
|
Event Listeners
|
https://gradio.app/docs/gradio/annotatedimage
|
Gradio - Annotatedimage Docs
|
]
default `= None`
defines how the endpoint appears in the API docs. Can be a string, None, or
False. If set to a string, the endpoint will be exposed in the API docs with
the given name. If None (default), the name of the function will be used as
the API endpoint. If False, the endpoint will not be exposed in the API docs
and downstream apps (including those that `gr.load` this app) will not be able
to use this event.
api_description: str | None | Literal[False]
default `= None`
Description of the API endpoint. Can be a string, None, or False. If set to a
string, the endpoint will be exposed in the API docs with the given
description. If None, the function's docstring will be used as the API
endpoint description. If False, then no description will be displayed in the
API docs.
scroll_to_output: bool
default `= False`
If True, will scroll to output component on completion
show_progress: Literal['full', 'minimal', 'hidden']
default `= "full"`
how to show the progress animation while event is running: "full" shows a
spinner which covers the output component area as well as a runtime display in
the upper right corner, "minimal" only shows the runtime display, "hidden"
shows no progress animation at all
show_progress_on: Component | list[Component] | None
default `= None`
Component or list of components to show the progress animation on. If None,
will show the progress animation on all of the output components.
queue: bool
default `= True`
If True, will place the request on the queue, if the queue has been enabled.
If False, will not put this event on the queue, even if the queue has been
enabled. If None, will use the queue setting of the gradio app.
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
|
Event Listeners
|
https://gradio.app/docs/gradio/annotatedimage
|
Gradio - Annotatedimage Docs
|
ault `= 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 listener 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. Functions that have
not yet run (or generators that are iterating) will be cancelled, but
functions that are currently running will be allowed to finish.
trigger_mode: Literal['once', 'multiple', 'always_last'] | None
default `= None`
If "once" (default for all events except `.change()`) would not allow any
submissions while an event is pending. If set to "multiple", unlimited
submissions are allowed while pending, and "always_last" (default for
`.change()` and `.key_up()` events) would allow a second submission after the
pending event is complete.
js: str | Literal[True] | None
default `= None`
Optional frontend js method to run before running 'fn'. Input arguments for js
method are values of 'inputs' and 'outputs', return sho
|
Event Listeners
|
https://gradio.app/docs/gradio/annotatedimage
|
Gradio - Annotatedimage Docs
|
js: str | Literal[True] | None
default `= None`
Optional frontend js method to run before running 'fn'. Input arguments for js
method are values of 'inputs' and 'outputs', return should be a list of values
for output components.
concurrency_limit: int | None | Literal['default']
default `= "default"`
If set, this is the maximum number of this event that can be running
simultaneously. Can be set to None to mean no concurrency_limit (any number of
this event can be running simultaneously). Set to "default" to use the default
concurrency limit (defined by the `default_concurrency_limit` parameter in
`Blocks.queue()`, which itself is 1 by default).
concurrency_id: str | None
default `= None`
If set, this is the id of the concurrency group. Events with the same
concurrency_id will be limited by the lowest set concurrency_limit.
show_api: bool
default `= True`
whether to show this event in the "view API" page of the Gradio app, or in the
".view_api()" method of the Gradio clients. Unlike setting api_name to False,
setting show_api to False will still allow downstream apps as well as the
Clients to use this event. If fn is None, show_api will automatically be set
to False.
time_limit: int | None
default `= None`
stream_every: float
default `= 0.5`
like_user_message: bool
default `= False`
key: int | str | tuple[int | str, ...] | None
default `= None`
A unique key for this event listener to be used in @gr.render(). If set, this
value identifies an event as identical across re-renders when the key is
identical.
validator: Callable | None
default `= None`
Optional validation function to run before the main function. If provided,
this function will be executed first with queue=False, and only if it
completes successfully will the main function be called. The validator
receives the same inputs as the main function and sho
|
Event Listeners
|
https://gradio.app/docs/gradio/annotatedimage
|
Gradio - Annotatedimage Docs
|
ided,
this function will be executed first with queue=False, and only if it
completes successfully will the main function be called. The validator
receives the same inputs as the main function and should return a
`gr.validate()` for each input value.
|
Event Listeners
|
https://gradio.app/docs/gradio/annotatedimage
|
Gradio - Annotatedimage Docs
|
Load a chat interface from an OpenAI API chat compatible endpoint.
|
Description
|
https://gradio.app/docs/gradio/load_chat
|
Gradio - Load_Chat Docs
|
import gradio as gr
demo = gr.load_chat("http://localhost:11434/v1", model="deepseek-r1")
demo.launch()
|
Example Usage
|
https://gradio.app/docs/gradio/load_chat
|
Gradio - Load_Chat Docs
|
Parameters ▼
base_url: str
The base URL of the endpoint, e.g. "http://localhost:11434/v1/"
model: str
The name of the model you are loading, e.g. "llama3.2"
token: str | None
default `= None`
The API token or a placeholder string if you are using a local model, e.g.
"ollama"
file_types: Literal['text_encoded', 'image'] | list[Literal['text_encoded', 'image']] | None
default `= "text_encoded"`
The file types allowed to be uploaded by the user. "text_encoded" allows
uploading any text-encoded file (which is simply appended to the prompt), and
"image" adds image upload support. Set to None to disable file uploads.
system_message: str | None
default `= None`
The system message to use for the conversation, if any.
streaming: bool
default `= True`
Whether the response should be streamed.
kwargs: <class 'inspect._empty'>
Additional keyword arguments to pass into ChatInterface for customization.
|
Initialization
|
https://gradio.app/docs/gradio/load_chat
|
Gradio - Load_Chat Docs
|
Any code in a `if gr.NO_RELOAD` code-block will not be re-evaluated when
the source file is reloaded. This is helpful for importing modules that do not
like to be reloaded (tiktoken, numpy) as well as database connections and long
running set up code.
|
Description
|
https://gradio.app/docs/gradio/NO_RELOAD
|
Gradio - No_Reload Docs
|
import gradio as gr
if gr.NO_RELOAD:
from transformers import pipeline
pipe = pipeline("text-classification", model="cardiffnlp/twitter-roberta-base-sentiment-latest")
gr.Interface.from_pipeline(pipe).launch()
|
Example Usage
|
https://gradio.app/docs/gradio/NO_RELOAD
|
Gradio - No_Reload Docs
|
The gr.RetryData class is a subclass of gr.Event data that specifically
carries information about the `.retry()` event. When gr.RetryData is added as
a type hint to an argument of an event listener method, a gr.RetryData object
will automatically be passed as the value of that argument. The attributes of
this object contains information about the event that triggered the listener.
|
Description
|
https://gradio.app/docs/gradio/retrydata
|
Gradio - Retrydata Docs
|
import gradio as gr
def retry(retry_data: gr.RetryData, history: list[gr.MessageDict]):
history_up_to_retry = history[:retry_data.index]
new_response = ""
for token in api.chat_completion(history):
new_response += token
yield history + [new_response]
with gr.Blocks() as demo:
chatbot = gr.Chatbot()
chatbot.retry(retry, chatbot, chatbot)
demo.launch()
|
Example Usage
|
https://gradio.app/docs/gradio/retrydata
|
Gradio - Retrydata Docs
|
Parameters ▼
index: int | tuple[int, int]
The index of the user message that should be retried.
value: Any
The value of the user message that should be retried.
|
Attributes
|
https://gradio.app/docs/gradio/retrydata
|
Gradio - Retrydata Docs
|
Creates a scatter plot component to display data from a pandas DataFrame.
|
Description
|
https://gradio.app/docs/gradio/scatterplot
|
Gradio - Scatterplot Docs
|
**As input component** : The data to display in a line plot.
Your function should accept one of these types:
def predict(
value: AltairPlotData | None
)
...
**As output component** : Expects a pandas DataFrame containing the data to
display in the line plot. The DataFrame should contain at least two columns,
one for the x-axis (corresponding to this component's `x` argument) and one
for the y-axis (corresponding to `y`).
Your function should return one of these types:
def predict(···) -> pd.DataFrame | dict | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/scatterplot
|
Gradio - Scatterplot Docs
|
Parameters ▼
value: pd.DataFrame | Callable | None
default `= None`
The pandas dataframe containing the data to display in the plot.
x: str | None
default `= None`
Column corresponding to the x axis. Column can be numeric, datetime, or
string/category.
y: str | None
default `= None`
Column corresponding to the y axis. Column must be numeric.
color: str | None
default `= None`
Column corresponding to series, visualized by color. Column must be
string/category.
title: str | None
default `= None`
The title to display on top of the chart.
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_title: str | None
default `= None`
The title given to the color legend. By default, uses the value of color
parameter.
x_bin: str | float | None
default `= None`
Grouping used to cluster x values. If x column is numeric, should be number to
bin the x values. If x column is datetime, should be string such as "1h",
"15m", "10s", using "s", "m", "h", "d" suffixes.
y_aggregate: Literal['sum', 'mean', 'median', 'min', 'max', 'count'] | None
default `= None`
Aggregation function used to aggregate y values, used if x_bin is provided or
x is a string/category. Must be one of "sum", "mean", "median", "min", "max".
color_map: dict[str, str] | None
default `= None`
Mapping of series to color names or codes. For example, {"success": "green",
"fail": "FF8888"}.
x_lim: list[float] | None
default `= None`
A tuple or list containing the limits for the x-axis, specified as [x_min,
x_max]. If x column is datetime type, x_lim should be timestamps.
y_lim: list[float | None]
default `= None`
A
|
Initialization
|
https://gradio.app/docs/gradio/scatterplot
|
Gradio - Scatterplot Docs
|
ple or list containing the limits for the x-axis, specified as [x_min,
x_max]. If x column is datetime type, x_lim should be timestamps.
y_lim: list[float | None]
default `= None`
A tuple of list containing the limits for the y-axis, specified as [y_min,
y_max]. To fix only one of these values, set the other to None, e.g. [0, None]
to scale from 0 to the maximum to value.
x_label_angle: float
default `= 0`
The angle of the x-axis labels in degrees offset clockwise.
y_label_angle: float
default `= 0`
The angle of the y-axis labels in degrees offset clockwise.
x_axis_labels_visible: bool | Literal['hidden']
default `= True`
Whether the x-axis labels should be visible. Can be hidden when many x-axis
labels are present.
caption: str | I18nData | None
default `= None`
The (optional) caption to display below the plot.
sort: Literal['x', 'y', '-x', '-y'] | list[str] | None
default `= None`
The sorting order of the x values, if x column is type string/category. Can be
"x", "y", "-x", "-y", or list of strings that represent the order of the
categories.
tooltip: Literal['axis', 'none', 'all'] | list[str]
default `= "axis"`
The tooltip to display when hovering on a point. "axis" shows the values for
the axis columns, "all" shows all column values, and "none" shows no tooltips.
Can also provide a list of strings representing columns to show in the
tooltip, which will be displayed along with axis values.
height: int | None
default `= None`
The height of the plot in pixels.
label: str | I18nData | None
default `= None`
The (optional) label to display on the top left corner of the plot.
show_label: bool | None
default `= None`
Whether the label should be displayed.
container: bool
default `= True`
If True, will place the component in a container - providing some extra
padding around the
|
Initialization
|
https://gradio.app/docs/gradio/scatterplot
|
Gradio - Scatterplot Docs
|
default `= None`
Whether the label should be displayed.
container: bool
default `= True`
If True, will place the component in a container - providing some extra
padding around the border.
scale: int | None
default `= None`
relative size compared to adjacent Components. For example if Components A and
B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide
as B. Should be an integer. scale applies in Rows, and to top-level Components
in Blocks where fill_height=True.
min_width: int
default `= 160`
minimum pixel width, will wrap if not sufficient screen space to satisfy this
value. If a certain scale value results in this Component being narrower than
min_width, the min_width parameter will be respected first.
every: Timer | float | None
default `= None`
Continously calls `value` to recalculate it if `value` is a function (has no
effect otherwise). Can provide a Timer whose tick resets `value`, or a float
that provides the regular interval for the reset Timer.
inputs: Component | list[Component] | Set[Component] | None
default `= None`
Components that are used as inputs to calculate `value` if `value` is a
function (has no effect otherwise). `value` is recalculated any time the
inputs change.
visible: bool | Literal['hidden']
default `= True`
Whether the plot should be 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.
elem_classes: list[str] | str | None
default `= None`
An optional list of strings that are assigned as the classes of this component
in the HTML DOM. Can be used for targeting CSS styles.
render: bool
default `= True`
If False, component will not render be rendered in the Blocks context. Should
be used if the intention is to assign event listeners now but re
|
Initialization
|
https://gradio.app/docs/gradio/scatterplot
|
Gradio - Scatterplot Docs
|
S styles.
render: bool
default `= True`
If False, component will not render be rendered in the Blocks context. Should
be used if the intention is to assign event listeners now but render the
component later.
show_fullscreen_button: bool
default `= False`
If True, will show a button to make plot visible in fullscreen mode.
show_export_button: bool
default `= False`
If True, will show a button to export and download the current view of the
plot as a PNG image.
key: int | str | tuple[int | str, ...] | None
default `= None`
in a gr.render, Components with the same key across re-renders are treated as
the same component, not a new component. Properties set in 'preserved_by_key'
are not reset across a re-render.
preserved_by_key: list[str] | str | None
default `= "value"`
A list of parameters from this component's constructor. Inside a gr.render()
function, if a component is re-rendered with the same key, these (and only
these) parameters will be preserved in the UI (if they have been changed by
the user or an event listener) instead of re-rendered based on the values
provided during constructor.
|
Initialization
|
https://gradio.app/docs/gradio/scatterplot
|
Gradio - Scatterplot Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.ScatterPlot` | "scatterplot" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/scatterplot
|
Gradio - Scatterplot Docs
|
scatter_plot_demo
Open in 🎢 ↗ import pandas as pd from random import randint, random import
gradio as gr temp_sensor_data = pd.DataFrame( { "time":
pd.date_range("2021-01-01", end="2021-01-05", periods=200), "temperature":
[randint(50 + 10 * (i % 2), 65 + 15 * (i % 2)) for i in range(200)],
"humidity": [randint(50 + 10 * (i % 2), 65 + 15 * (i % 2)) for i in
range(200)], "location": ["indoor", "outdoor"] * 100, } ) food_rating_data =
pd.DataFrame( { "cuisine": [["Italian", "Mexican", "Chinese"][i % 3] for i in
range(100)], "rating": [random() * 4 + 0.5 * (i % 3) for i in range(100)],
"price": [randint(10, 50) + 4 * (i % 3) for i in range(100)], "wait":
[random() for i in range(100)], } ) with gr.Blocks() as scatter_plots: with
gr.Row(): start = gr.DateTime("2021-01-01 00:00:00", label="Start") end =
gr.DateTime("2021-01-05 00:00:00", label="End") apply_btn = gr.Button("Apply",
scale=0) with gr.Row(): group_by = gr.Radio(["None", "30m", "1h", "4h", "1d"],
value="None", label="Group by") aggregate = gr.Radio(["sum", "mean", "median",
"min", "max"], value="sum", label="Aggregation") temp_by_time =
gr.ScatterPlot( temp_sensor_data, x="time", y="temperature", )
temp_by_time_location = gr.ScatterPlot( temp_sensor_data, x="time",
y="temperature", color="location", ) time_graphs = [temp_by_time,
temp_by_time_location] group_by.change( lambda group:
[gr.ScatterPlot(x_bin=None if group == "None" else group)] * len(time_graphs),
group_by, time_graphs ) aggregate.change( lambda aggregate:
[gr.ScatterPlot(y_aggregate=aggregate)] * len(time_graphs), aggregate,
time_graphs ) price_by_cuisine = gr.ScatterPlot( food_rating_data,
x="cuisine", y="price", ) with gr.Row(): price_by_rating = gr.ScatterPlot(
food_rating_data, x="rating", y="price", color="wait",
show_actions_button=True, ) price_by_rating_color = gr.ScatterPlot(
food_rating_data, x="rating", y="price", color="cuisine", ) if __name__ ==
"__main__": scatter_plots.launch()
import pandas as pd
from random i
|
Demos
|
https://gradio.app/docs/gradio/scatterplot
|
Gradio - Scatterplot Docs
|
ice_by_rating_color = gr.ScatterPlot(
food_rating_data, x="rating", y="price", color="cuisine", ) if __name__ ==
"__main__": scatter_plots.launch()
import pandas as pd
from random import randint, random
import gradio as gr
temp_sensor_data = pd.DataFrame(
{
"time": pd.date_range("2021-01-01", end="2021-01-05", periods=200),
"temperature": [randint(50 + 10 * (i % 2), 65 + 15 * (i % 2)) for i in range(200)],
"humidity": [randint(50 + 10 * (i % 2), 65 + 15 * (i % 2)) for i in range(200)],
"location": ["indoor", "outdoor"] * 100,
}
)
food_rating_data = pd.DataFrame(
{
"cuisine": [["Italian", "Mexican", "Chinese"][i % 3] for i in range(100)],
"rating": [random() * 4 + 0.5 * (i % 3) for i in range(100)],
"price": [randint(10, 50) + 4 * (i % 3) for i in range(100)],
"wait": [random() for i in range(100)],
}
)
with gr.Blocks() as scatter_plots:
with gr.Row():
start = gr.DateTime("2021-01-01 00:00:00", label="Start")
end = gr.DateTime("2021-01-05 00:00:00", label="End")
apply_btn = gr.Button("Apply", scale=0)
with gr.Row():
group_by = gr.Radio(["None", "30m", "1h", "4h", "1d"], value="None", label="Group by")
aggregate = gr.Radio(["sum", "mean", "median", "min", "max"], value="sum", label="Aggregation")
temp_by_time = gr.ScatterPlot(
temp_sensor_data,
x="time",
y="temperature",
)
temp_by_time_location = gr.ScatterPlot(
temp_sensor_data,
x="time",
y="temperature",
color="location",
)
time_graphs = [temp_by_time, temp_by_time_location]
group_by.change(
lambda group: [gr.ScatterPlot(x_bin=None if group == "None" else group)] * len(time_graphs),
group_by
|
Demos
|
https://gradio.app/docs/gradio/scatterplot
|
Gradio - Scatterplot Docs
|
me_graphs = [temp_by_time, temp_by_time_location]
group_by.change(
lambda group: [gr.ScatterPlot(x_bin=None if group == "None" else group)] * len(time_graphs),
group_by,
time_graphs
)
aggregate.change(
lambda aggregate: [gr.ScatterPlot(y_aggregate=aggregate)] * len(time_graphs),
aggregate,
time_graphs
)
price_by_cuisine = gr.ScatterPlot(
food_rating_data,
x="cuisine",
y="price",
)
with gr.Row():
price_by_rating = gr.ScatterPlot(
food_rating_data,
x="rating",
y="price",
color="wait",
show_actions_button=True,
)
price_by_rating_color = gr.ScatterPlot(
food_rating_data,
x="rating",
y="price",
color="cuisine",
)
if __name__ == "__main__":
scatter_plots.launch()
|
Demos
|
https://gradio.app/docs/gradio/scatterplot
|
Gradio - Scatterplot Docs
|
Description
Event listeners allow you to respond to user interactions with the UI
components you've defined in a Gradio Blocks app. When a user interacts with
an element, such as changing a slider value or uploading an image, a function
is called.
Supported Event Listeners
The ScatterPlot component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`ScatterPlot.select(fn, ···)` | Event listener for when the user selects or deselects the NativePlot. Uses event data gradio.SelectData to carry `value` referring to the label of the NativePlot, and `selected` to refer to state of the NativePlot. See EventData documentation on how to use this event data
`ScatterPlot.double_click(fn, ···)` | Triggered when the NativePlot is double clicked.
Event Parameters
Parameters ▼
fn: Callable | None | Literal['decorator']
default `= "decorator"`
the function to call when this event is triggered. 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 | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | 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 | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as outputs. If the function returns no
outputs, this should be an empty list.
api_name: str | None | Literal[False]
default `= None`
defines how the endpoint appears in the API docs. Can be a string, None, or
False. If set to a string, the e
|
Event Listeners
|
https://gradio.app/docs/gradio/scatterplot
|
Gradio - Scatterplot Docs
|
be an empty list.
api_name: str | None | Literal[False]
default `= None`
defines how the endpoint appears in the API docs. Can be a string, None, or
False. If set to a string, the endpoint will be exposed in the API docs with
the given name. If None (default), the name of the function will be used as
the API endpoint. If False, the endpoint will not be exposed in the API docs
and downstream apps (including those that `gr.load` this app) will not be able
to use this event.
api_description: str | None | Literal[False]
default `= None`
Description of the API endpoint. Can be a string, None, or False. If set to a
string, the endpoint will be exposed in the API docs with the given
description. If None, the function's docstring will be used as the API
endpoint description. If False, then no description will be displayed in the
API docs.
scroll_to_output: bool
default `= False`
If True, will scroll to output component on completion
show_progress: Literal['full', 'minimal', 'hidden']
default `= "full"`
how to show the progress animation while event is running: "full" shows a
spinner which covers the output component area as well as a runtime display in
the upper right corner, "minimal" only shows the runtime display, "hidden"
shows no progress animation at all
show_progress_on: Component | list[Component] | None
default `= None`
Component or list of components to show the progress animation on. If None,
will show the progress animation on all of the output components.
queue: bool
default `= True`
If True, will place the request on the queue, if the queue has been enabled.
If False, will not put this event on the queue, even if the queue has been
enabled. If None, will use the queue setting of the gradio app.
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
|
Event Listeners
|
https://gradio.app/docs/gradio/scatterplot
|
Gradio - Scatterplot Docs
|
e the queue setting of the gradio app.
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 listener 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. Functions that have
not yet run (or generators that are iterating) will be cancelled, but
functions that are currently running will be allowed to finish.
trigger_mode: Literal['once', 'multiple', 'always_last'] | None
default `= None`
If "once" (default for all events except `.change()`) would not allow any
submissions while an event is pending. If set to "multiple", unlimited
submissions are allowed while pending, and "always_last" (default for
`.change()` and `.key_up()` events) would allow a second submission after the
pending event is complete.
js: str | Literal[True] | None
default `= None`
Optional frontend js method to run before running 'fn'. Input a
|
Event Listeners
|
https://gradio.app/docs/gradio/scatterplot
|
Gradio - Scatterplot Docs
|
) would allow a second submission after the
pending event is complete.
js: str | Literal[True] | None
default `= None`
Optional frontend js method to run before running 'fn'. Input arguments for js
method are values of 'inputs' and 'outputs', return should be a list of values
for output components.
concurrency_limit: int | None | Literal['default']
default `= "default"`
If set, this is the maximum number of this event that can be running
simultaneously. Can be set to None to mean no concurrency_limit (any number of
this event can be running simultaneously). Set to "default" to use the default
concurrency limit (defined by the `default_concurrency_limit` parameter in
`Blocks.queue()`, which itself is 1 by default).
concurrency_id: str | None
default `= None`
If set, this is the id of the concurrency group. Events with the same
concurrency_id will be limited by the lowest set concurrency_limit.
show_api: bool
default `= True`
whether to show this event in the "view API" page of the Gradio app, or in the
".view_api()" method of the Gradio clients. Unlike setting api_name to False,
setting show_api to False will still allow downstream apps as well as the
Clients to use this event. If fn is None, show_api will automatically be set
to False.
time_limit: int | None
default `= None`
stream_every: float
default `= 0.5`
like_user_message: bool
default `= False`
key: int | str | tuple[int | str, ...] | None
default `= None`
A unique key for this event listener to be used in @gr.render(). If set, this
value identifies an event as identical across re-renders when the key is
identical.
validator: Callable | None
default `= None`
Optional validation function to run before the main function. If provided,
this function will be executed first with queue=False, and only if it
completes successfully will the main function be call
|
Event Listeners
|
https://gradio.app/docs/gradio/scatterplot
|
Gradio - Scatterplot Docs
|
Optional validation function to run before the main function. If provided,
this function will be executed first with queue=False, and only if it
completes successfully will the main function be called. The validator
receives the same inputs as the main function and should return a
`gr.validate()` for each input value.
|
Event Listeners
|
https://gradio.app/docs/gradio/scatterplot
|
Gradio - Scatterplot Docs
|
This class allows you to pass custom error messages to the user. You can do
so by raising a gr.Error("custom message") anywhere in the code, and when that
line is executed the custom message will appear in a modal on the demo.
You can control for how long the error message is displayed with the
`duration` parameter. If it’s `None`, the message will be displayed forever
until the user closes it. If it’s a number, it will be shown for that many
seconds.
You can also hide the error modal from being shown in the UI by setting
`visible=False`.
Below is a demo of how different values of duration control the error,
info, and warning messages. You can see the code
[here](https://huggingface.co/spaces/freddyaboulton/gradio-error-
duration/blob/244331cf53f6b5fa2fd406ece3bf55c6ccb9f5f2/app.pyL17).

|
Description
|
https://gradio.app/docs/gradio/error
|
Gradio - Error Docs
|
import gradio as gr
def divide(numerator, denominator):
if denominator == 0:
raise gr.Error("Cannot divide by zero!")
gr.Interface(divide, ["number", "number"], "number").launch()
|
Example Usage
|
https://gradio.app/docs/gradio/error
|
Gradio - Error Docs
|
Parameters ▼
message: str
default `= "Error raised."`
The error message to be displayed to the user. Can be HTML, which will be
rendered in the modal.
duration: float | None
default `= 10`
The duration in seconds to display the error message. If None or 0, the error
message will be displayed until the user closes it.
visible: bool
default `= True`
Whether the error message should be displayed in the UI.
title: str
default `= "Error"`
The title to be displayed to the user at the top of the error modal.
print_exception: bool
default `= True`
Whether to print traceback of the error to the console when the error is
raised.
|
Initialization
|
https://gradio.app/docs/gradio/error
|
Gradio - Error Docs
|
calculatorblocks_chained_events
Open in 🎢 ↗ import gradio as gr def calculator(num1, operation, num2): if
operation == "add": return num1 + num2 elif operation == "subtract": return
num1 - num2 elif operation == "multiply": return num1 * num2 elif operation ==
"divide": if num2 == 0: raise gr.Error("Cannot divide by zero!") return num1 /
num2 demo = gr.Interface( calculator, [ "number", gr.Radio(["add", "subtract",
"multiply", "divide"]), "number" ], "number", examples=[ [45, "add", 3],
[3.14, "divide", 2], [144, "multiply", 2.5], [0, "subtract", 1.2], ],
title="Toy Calculator", description="Here's a sample toy calculator.", ) if
__name__ == "__main__": demo.launch()
import gradio as gr
def calculator(num1, operation, num2):
if operation == "add":
return num1 + num2
elif operation == "subtract":
return num1 - num2
elif operation == "multiply":
return num1 * num2
elif operation == "divide":
if num2 == 0:
raise gr.Error("Cannot divide by zero!")
return num1 / num2
demo = gr.Interface(
calculator,
[
"number",
gr.Radio(["add", "subtract", "multiply", "divide"]),
"number"
],
"number",
examples=[
[45, "add", 3],
[3.14, "divide", 2],
[144, "multiply", 2.5],
[0, "subtract", 1.2],
],
title="Toy Calculator",
description="Here's a sample toy calculator.",
)
if __name__ == "__main__":
demo.launch()
Open in 🎢 ↗ import gradio as gr def failure(): raise gr.Error("This should
fail!") def exception(): raise ValueError("Something went wrong") def
success(): return True def warning_fn(): gr.Warning("This is a warning!") def
info_fn(): gr.Info("This is some info") with gr.Blocks() as demo:
gr.Markdown("Used in E2E tests of success event trigger. The then event
covered
|
Demos
|
https://gradio.app/docs/gradio/error
|
Gradio - Error Docs
|
def warning_fn(): gr.Warning("This is a warning!") def
info_fn(): gr.Info("This is some info") with gr.Blocks() as demo:
gr.Markdown("Used in E2E tests of success event trigger. The then event
covered in chatbot E2E tests." " Also testing that the status modals show
up.") with gr.Row(): result = gr.Textbox(label="Result") result_2 =
gr.Textbox(label="Consecutive Event") result_failure =
gr.Textbox(label="Failure Event") with gr.Row(): success_btn =
gr.Button(value="Trigger Success") success_btn_2 = gr.Button(value="Trigger
Consecutive Success") failure_btn = gr.Button(value="Trigger Failure")
failure_exception = gr.Button(value="Trigger Failure With ValueError") with
gr.Row(): trigger_warning = gr.Button(value="Trigger Warning") trigger_info =
gr.Button(value="Trigger Info") success_btn_2.click(success, None,
None).success(lambda: "First Event Trigered", None, result).success(lambda:
"Consecutive Event Triggered", None, result_2) success_event =
success_btn.click(success, None, None) success_event.success(lambda: "Success
event triggered", inputs=None, outputs=result) success_event.failure(lambda:
"Should not be triggered", inputs=None, outputs=result_failure) failure_event
= failure_btn.click(failure, None, None) failure_event.success(lambda: "Should
not be triggered", inputs=None, outputs=result) failure_event.failure(lambda:
"Failure event triggered", inputs=None, outputs=result_failure)
failure_exception.click(exception, None, None)
trigger_warning.click(warning_fn, None, None) trigger_info.click(info_fn,
None, None) if __name__ == "__main__": demo.launch(show_error=True)
import gradio as gr
def failure():
raise gr.Error("This should fail!")
def exception():
raise ValueError("Something went wrong")
def success():
return True
def warning_fn():
gr.Warning("This is a warning!")
def info_fn():
gr.Info("This is some info")
with gr.Blocks() as demo:
gr.
|
Demos
|
https://gradio.app/docs/gradio/error
|
Gradio - Error Docs
|
s():
return True
def warning_fn():
gr.Warning("This is a warning!")
def info_fn():
gr.Info("This is some info")
with gr.Blocks() as demo:
gr.Markdown("Used in E2E tests of success event trigger. The then event covered in chatbot E2E tests."
" Also testing that the status modals show up.")
with gr.Row():
result = gr.Textbox(label="Result")
result_2 = gr.Textbox(label="Consecutive Event")
result_failure = gr.Textbox(label="Failure Event")
with gr.Row():
success_btn = gr.Button(value="Trigger Success")
success_btn_2 = gr.Button(value="Trigger Consecutive Success")
failure_btn = gr.Button(value="Trigger Failure")
failure_exception = gr.Button(value="Trigger Failure With ValueError")
with gr.Row():
trigger_warning = gr.Button(value="Trigger Warning")
trigger_info = gr.Button(value="Trigger Info")
success_btn_2.click(success, None, None).success(lambda: "First Event Trigered", None, result).success(lambda: "Consecutive Event Triggered", None, result_2)
success_event = success_btn.click(success, None, None)
success_event.success(lambda: "Success event triggered", inputs=None, outputs=result)
success_event.failure(lambda: "Should not be triggered", inputs=None, outputs=result_failure)
failure_event = failure_btn.click(failure, None, None)
failure_event.success(lambda: "Should not be triggered", inputs=None, outputs=result)
failure_event.failure(lambda: "Failure event triggered", inputs=None, outputs=result_failure)
failure_exception.click(exception, None, None)
trigger_warning.click(warning_fn, None, None)
trigger_info.click(info_fn, None, None)
if __name__ == "__main__":
demo.launch(show_error=True)
|
Demos
|
https://gradio.app/docs/gradio/error
|
Gradio - Error Docs
|
trigger_warning.click(warning_fn, None, None)
trigger_info.click(info_fn, None, None)
if __name__ == "__main__":
demo.launch(show_error=True)
|
Demos
|
https://gradio.app/docs/gradio/error
|
Gradio - Error Docs
|
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.
|
Description
|
https://gradio.app/docs/gradio/examples
|
Gradio - Examples Docs
|
Parameters ▼
examples: list[Any] | list[list[Any]] | str
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: Component | list[Component]
the component or list of components corresponding to the examples
outputs: Component | list[Component] | None
default `= None`
optionally, provide the component or list of components corresponding to the
output of the examples. Required if `cache_examples` is not False.
fn: Callable | None
default `= None`
optionally, provide the function to run to generate the outputs corresponding
to the examples. Required if `cache_examples` is not False. Also required if
`run_on_click` is True.
cache_examples: bool | None
default `= None`
If True, caches examples in the server for fast runtime in examples. If
"lazy", then examples are cached (for all users of the app) after their first
use (by any user of the app). If None, will use the GRADIO_CACHE_EXAMPLES
environment variable, which should be either "true" or "false". In HuggingFace
Spaces, this parameter is True (as long as `fn` and `outputs` are also
provided). The default option otherwise is False. Note that examples are
cached separately from Gradio's queue() so certain features, such as
gr.Progress(), gr.Info(), gr.Warning(), etc. will not be displayed in Gradio's
UI for cached examples.
cache_mode: Literal['eager', 'lazy'] | None
default `= None`
if "lazy", examples are cached after their first use. If "eager", all examples
are
|
Initialization
|
https://gradio.app/docs/gradio/examples
|
Gradio - Examples Docs
|
d in Gradio's
UI for cached examples.
cache_mode: Literal['eager', 'lazy'] | None
default `= None`
if "lazy", examples are cached after their first use. If "eager", all examples
are cached at app launch. If None, will use the GRADIO_CACHE_MODE environment
variable if defined, or default to "eager".
examples_per_page: int
default `= 10`
how many examples to show per page.
label: str | I18nData | 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 not False.
postprocess: bool
default `= True`
if True, postprocesses the example output after running the prediction
function and before caching. Only applies if `cache_examples` is not False.
show_api: bool
default `= False`
Whether to show the event associated with clicking on the examples in the
"view API" page of the Gradio app, or in the ".view_api()" method of the
Gradio clients.
api_name: str | Literal[False]
default `= "load_example"`
Defines how the event associated with clicking on the examples appears in the
API docs. Can be a string or False. If set to a string, the endpoint will be
exposed in the API docs with the given name. If False, the endpoint will not
be exposed in the API docs and downstream apps (including those that `gr.load`
this app) will not be able to use the example
|
Initialization
|
https://gradio.app/docs/gradio/examples
|
Gradio - Examples Docs
|
posed in the API docs with the given name. If False, the endpoint will not
be exposed in the API docs and downstream apps (including those that `gr.load`
this app) will not be able to use the example function.
api_description: str | None | Literal[False]
default `= None`
Description of the event associated with clicking on the examples in the API
docs. Can be a string, None, or False. If set to a string, the endpoint will
be exposed in the API docs with the given description. If None, the function's
docstring will be used as the API endpoint description. If False, then no
description will be displayed in the API docs.
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 not False.
example_labels: list[str] | None
default `= None`
A list of labels for each example. If provided, the length of this list should
be the same as the number of examples, and these labels will be used in the UI
instead of rendering the example values.
visible: bool | Literal['hidden']
default `= True`
If False, the examples component will be hidden in the UI.
preload: int | Literal[False]
default `= False`
If an integer is provided (and examples are being cached), the example at that
index in the examples list will be preloaded when the Gradio app is loaded. If
False, no example will be preloaded.
|
Initialization
|
https://gradio.app/docs/gradio/examples
|
Gradio - Examples Docs
|
Parameters ▼
dataset: gradio.Dataset
The `gr.Dataset` component corresponding to this Examples object.
load_input_event: gradio.events.Dependency
The Gradio event that populates the input values when the examples are
clicked. You can attach a `.then()` or a `.success()` to this event to trigger
subsequent events to fire after this event.
cache_event: gradio.events.Dependency | None
The Gradio event that populates the cached output values when the examples are
clicked. You can attach a `.then()` or a `.success()` to this event to trigger
subsequent events to fire after this event. This event is `None` if
`cache_examples` if False, and is the same as `load_input_event` if
`cache_examples` is `'lazy'`.
|
Attributes
|
https://gradio.app/docs/gradio/examples
|
Gradio - Examples Docs
|
**Updating Examples**
In this demo, we show how to update the examples by updating the samples of
the underlying dataset. Note that this only works if `cache_examples=False` as
updating the underlying dataset does not update the cache.
import gradio as gr
def update_examples(country):
if country == "USA":
return gr.Dataset(samples=[["Chicago"], ["Little Rock"], ["San Francisco"]])
else:
return gr.Dataset(samples=[["Islamabad"], ["Karachi"], ["Lahore"]])
with gr.Blocks() as demo:
dropdown = gr.Dropdown(label="Country", choices=["USA", "Pakistan"], value="USA")
textbox = gr.Textbox()
examples = gr.Examples([["Chicago"], ["Little Rock"], ["San Francisco"]], textbox)
dropdown.change(update_examples, dropdown, examples.dataset)
demo.launch()
|
Examples
|
https://gradio.app/docs/gradio/examples
|
Gradio - Examples Docs
|
calculator_blocks
Open in 🎢 ↗ import gradio as gr def calculator(num1, operation, num2): if
operation == "add": return num1 + num2 elif operation == "subtract": return
num1 - num2 elif operation == "multiply": return num1 * num2 elif operation ==
"divide": return num1 / num2 with gr.Blocks() as demo: with gr.Row(): with
gr.Column(): num_1 = gr.Number(value=4) operation = gr.Radio(["add",
"subtract", "multiply", "divide"]) num_2 = gr.Number(value=0) submit_btn =
gr.Button(value="Calculate") with gr.Column(): result = gr.Number()
submit_btn.click( calculator, inputs=[num_1, operation, num_2],
outputs=[result], api_name=False ) examples = gr.Examples( examples=[ [5,
"add", 3], [4, "divide", 2], [-4, "multiply", 2.5], [0, "subtract", 1.2], ],
inputs=[num_1, operation, num_2], ) if __name__ == "__main__":
demo.launch(show_api=False)
import gradio as gr
def calculator(num1, operation, num2):
if operation == "add":
return num1 + num2
elif operation == "subtract":
return num1 - num2
elif operation == "multiply":
return num1 * num2
elif operation == "divide":
return num1 / num2
with gr.Blocks() as demo:
with gr.Row():
with gr.Column():
num_1 = gr.Number(value=4)
operation = gr.Radio(["add", "subtract", "multiply", "divide"])
num_2 = gr.Number(value=0)
submit_btn = gr.Button(value="Calculate")
with gr.Column():
result = gr.Number()
submit_btn.click(
calculator, inputs=[num_1, operation, num_2], outputs=[result], api_name=False
)
examples = gr.Examples(
examples=[
[5, "add", 3],
[4, "divide", 2],
[-4, "multiply", 2.5],
[0, "subtract", 1.2],
],
inputs=[num_1, operation, num_2],
)
if __name__ == "__mai
|
Demos
|
https://gradio.app/docs/gradio/examples
|
Gradio - Examples Docs
|
[4, "divide", 2],
[-4, "multiply", 2.5],
[0, "subtract", 1.2],
],
inputs=[num_1, operation, num_2],
)
if __name__ == "__main__":
demo.launch(show_api=False)
|
Demos
|
https://gradio.app/docs/gradio/examples
|
Gradio - Examples Docs
|
Creates a component allows users to upload or view 3D Model files (.obj,
.glb, .stl, .gltf, .splat, or .ply).
|
Description
|
https://gradio.app/docs/gradio/model3d
|
Gradio - Model3D Docs
|
**As input component** : Passes the uploaded file as a `str` filepath to
the function.
Your function should accept one of these types:
def predict(
value: str | None
)
...
**As output component** : Expects function to return a `str` or
`pathlib.Path` filepath of type (.obj, .glb, .stl, or .gltf)
Your function should return one of these types:
def predict(···) -> str | Path | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/model3d
|
Gradio - Model3D Docs
|
Parameters ▼
value: str | Callable | None
default `= None`
path to (.obj, .glb, .stl, .gltf, .splat, or .ply) file to show in model3D
viewer. If a function is provided, the function will be called each time the
app loads to set the initial value of this component.
display_mode: Literal['solid', 'point_cloud', 'wireframe'] | None
default `= None`
the display mode of the 3D model in the scene. Can be "solid" (which renders
the model as a solid object), "point_cloud", or "wireframe". For .splat, or
.ply files, this parameter is ignored, as those files can only be rendered as
solid objects.
clear_color: tuple[float, float, float, float] | None
default `= None`
background color of scene, should be a tuple of 4 floats between 0 and 1
representing RGBA values.
camera_position: tuple[int | float | None, int | float | None, int | float | None]
default `= (None, None, None)`
initial camera position of scene, provided as a tuple of `(alpha, beta,
radius)`. Each value is optional. If provided, `alpha` and `beta` should be in
degrees reflecting the angular position along the longitudinal and latitudinal
axes, respectively. Radius corresponds to the distance from the center of the
object to the camera.
zoom_speed: float
default `= 1`
the speed of zooming in and out of the scene when the cursor wheel is rotated
or when screen is pinched on a mobile device. Should be a positive float,
increase this value to make zooming faster, decrease to make it slower.
Affects the wheelPrecision property of the camera.
pan_speed: float
default `= 1`
the speed of panning the scene when the cursor is dragged or when the screen
is dragged on a mobile device. Should be a positive float, increase this value
to make panning faster, decrease to make it slower. Affects the panSensibility
property of the camera.
height: int | str | None
default `= None`
The height of the model3D c
|
Initialization
|
https://gradio.app/docs/gradio/model3d
|
Gradio - Model3D Docs
|
his value
to make panning faster, decrease to make it slower. Affects the panSensibility
property of the camera.
height: int | str | None
default `= None`
The height of the model3D component, specified in pixels if a number is
passed, or in CSS units if a string is passed.
label: str | I18nData | None
default `= None`
the label for this component. Appears above the component and is also used as
the header if there are a table of examples for this component. If None and
used in a `gr.Interface`, the label will be the name of the parameter this
component is assigned to.
show_label: bool | None
default `= None`
if True, will display label.
every: Timer | float | None
default `= None`
Continously calls `value` to recalculate it if `value` is a function (has no
effect otherwise). Can provide a Timer whose tick resets `value`, or a float
that provides the regular interval for the reset Timer.
inputs: Component | list[Component] | set[Component] | None
default `= None`
Components that are used as inputs to calculate `value` if `value` is a
function (has no effect otherwise). `value` is recalculated any time the
inputs change.
container: bool
default `= True`
If True, will place the component in a container - providing some extra
padding around the border.
scale: int | None
default `= None`
relative size compared to adjacent Components. For example if Components A and
B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide
as B. Should be an integer. scale applies in Rows, and to top-level Components
in Blocks where fill_height=True.
min_width: int
default `= 160`
minimum pixel width, will wrap if not sufficient screen space to satisfy this
value. If a certain scale value results in this Component being narrower than
min_width, the min_width parameter will be respected first.
interactive: bool |
|
Initialization
|
https://gradio.app/docs/gradio/model3d
|
Gradio - Model3D Docs
|
reen space to satisfy this
value. If a certain scale value results in this Component being narrower than
min_width, the min_width parameter will be respected first.
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 | Literal['hidden']
default `= True`
If False, component will be hidden. If "hidden", component will be visually
hidden and not take up space in the layout but still exist in the DOM
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.
elem_classes: list[str] | str | None
default `= None`
An optional list of strings that are assigned as the classes of this component
in the HTML DOM. Can be used for targeting CSS styles.
render: bool
default `= True`
If False, component will not render be rendered in the Blocks context. Should
be used if the intention is to assign event listeners now but render the
component later.
key: int | str | tuple[int | str, ...] | None
default `= None`
in a gr.render, Components with the same key across re-renders are treated as
the same component, not a new component. Properties set in 'preserved_by_key'
are not reset across a re-render.
preserved_by_key: list[str] | str | None
default `= "value"`
A list of parameters from this component's constructor. Inside a gr.render()
function, if a component is re-rendered with the same key, these (and only
these) parameters will be preserved in the UI (if they have been changed by
the user or an event listener) instead of re-rendered based on the values
provided during constructor.
|
Initialization
|
https://gradio.app/docs/gradio/model3d
|
Gradio - Model3D Docs
|
he user or an event listener) instead of re-rendered based on the values
provided during constructor.
|
Initialization
|
https://gradio.app/docs/gradio/model3d
|
Gradio - Model3D Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.Model3D` | "model3d" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/model3d
|
Gradio - Model3D Docs
|
Description
Event listeners allow you to respond to user interactions with the UI
components you've defined in a Gradio Blocks app. When a user interacts with
an element, such as changing a slider value or uploading an image, a function
is called.
Supported Event Listeners
The Model3D component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`Model3D.change(fn, ···)` | Triggered when the value of the Model3D changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input.
`Model3D.upload(fn, ···)` | This listener is triggered when the user uploads a file into the Model3D.
`Model3D.edit(fn, ···)` | This listener is triggered when the user edits the Model3D (e.g. image) using the built-in editor.
`Model3D.clear(fn, ···)` | This listener is triggered when the user clears the Model3D using the clear button for the component.
Event Parameters
Parameters ▼
fn: Callable | None | Literal['decorator']
default `= "decorator"`
the function to call when this event is triggered. 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 | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | 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 | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.compo
|
Event Listeners
|
https://gradio.app/docs/gradio/model3d
|
Gradio - Model3D Docs
|
inputs,
this should be an empty list.
outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as outputs. If the function returns no
outputs, this should be an empty list.
api_name: str | None | Literal[False]
default `= None`
defines how the endpoint appears in the API docs. Can be a string, None, or
False. If set to a string, the endpoint will be exposed in the API docs with
the given name. If None (default), the name of the function will be used as
the API endpoint. If False, the endpoint will not be exposed in the API docs
and downstream apps (including those that `gr.load` this app) will not be able
to use this event.
api_description: str | None | Literal[False]
default `= None`
Description of the API endpoint. Can be a string, None, or False. If set to a
string, the endpoint will be exposed in the API docs with the given
description. If None, the function's docstring will be used as the API
endpoint description. If False, then no description will be displayed in the
API docs.
scroll_to_output: bool
default `= False`
If True, will scroll to output component on completion
show_progress: Literal['full', 'minimal', 'hidden']
default `= "full"`
how to show the progress animation while event is running: "full" shows a
spinner which covers the output component area as well as a runtime display in
the upper right corner, "minimal" only shows the runtime display, "hidden"
shows no progress animation at all
show_progress_on: Component | list[Component] | None
default `= None`
Component or list of components to show the progress animation on. If None,
will show the progress animation on all of the output components.
queue: bool
default `= True`
If True, will place the request on the queue, if the queue has been enabled.
If False, will not put this
|
Event Listeners
|
https://gradio.app/docs/gradio/model3d
|
Gradio - Model3D Docs
|
ress animation on all of the output components.
queue: bool
default `= True`
If True, will place the request on the queue, if the queue has been enabled.
If False, will not put this event on the queue, even if the queue has been
enabled. If None, will use the queue setting of the gradio app.
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 listener 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. Functions that have
not yet run (or generators that are iterating) will be cancelled, but
functions that are currently running will be allowed to finish.
trigger_mode: Literal['once', 'multiple', 'always_last'] | None
default `= None`
If "once" (default for all events except `.change()`) would not allow any
submissions while an event is pending. If set to "multiple", unlimited
submissions are allowed while pe
|
Event Listeners
|
https://gradio.app/docs/gradio/model3d
|
Gradio - Model3D Docs
|
one
default `= None`
If "once" (default for all events except `.change()`) would not allow any
submissions while an event is pending. If set to "multiple", unlimited
submissions are allowed while pending, and "always_last" (default for
`.change()` and `.key_up()` events) would allow a second submission after the
pending event is complete.
js: str | Literal[True] | None
default `= None`
Optional frontend js method to run before running 'fn'. Input arguments for js
method are values of 'inputs' and 'outputs', return should be a list of values
for output components.
concurrency_limit: int | None | Literal['default']
default `= "default"`
If set, this is the maximum number of this event that can be running
simultaneously. Can be set to None to mean no concurrency_limit (any number of
this event can be running simultaneously). Set to "default" to use the default
concurrency limit (defined by the `default_concurrency_limit` parameter in
`Blocks.queue()`, which itself is 1 by default).
concurrency_id: str | None
default `= None`
If set, this is the id of the concurrency group. Events with the same
concurrency_id will be limited by the lowest set concurrency_limit.
show_api: bool
default `= True`
whether to show this event in the "view API" page of the Gradio app, or in the
".view_api()" method of the Gradio clients. Unlike setting api_name to False,
setting show_api to False will still allow downstream apps as well as the
Clients to use this event. If fn is None, show_api will automatically be set
to False.
time_limit: int | None
default `= None`
stream_every: float
default `= 0.5`
like_user_message: bool
default `= False`
key: int | str | tuple[int | str, ...] | None
default `= None`
A unique key for this event listener to be used in @gr.render(). If set, this
value identifies an event as identical across re-renders when the key is
|
Event Listeners
|
https://gradio.app/docs/gradio/model3d
|
Gradio - Model3D Docs
|
| tuple[int | str, ...] | None
default `= None`
A unique key for this event listener to be used in @gr.render(). If set, this
value identifies an event as identical across re-renders when the key is
identical.
validator: Callable | None
default `= None`
Optional validation function to run before the main function. If provided,
this function will be executed first with queue=False, and only if it
completes successfully will the main function be called. The validator
receives the same inputs as the main function and should return a
`gr.validate()` for each input value.
|
Event Listeners
|
https://gradio.app/docs/gradio/model3d
|
Gradio - Model3D Docs
|
Creates a code editor for viewing code (as an output component), or for
entering and editing code (as an input component).
|
Description
|
https://gradio.app/docs/gradio/code
|
Gradio - Code Docs
|
**As input component** : Passes the code entered as a `str`.
Your function should accept one of these types:
def predict(
value: str | None
)
...
**As output component** : Expects a `str` of code.
Your function should return one of these types:
def predict(···) -> tuple[str] | str | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/code
|
Gradio - Code Docs
|
Parameters ▼
value: str | Callable | None
default `= None`
Default value to show in the code editor. If a function is provided, the
function will be called each time the app loads to set the initial value of
this component.
language: Literal['python', 'c', 'cpp', 'markdown', 'latex', 'json', 'html', 'css', 'javascript', 'jinja2', 'typescript', 'yaml', 'dockerfile', 'shell', 'r', 'sql', 'sql-msSQL', 'sql-mySQL', 'sql-mariaDB', 'sql-sqlite', 'sql-cassandra', 'sql-plSQL', 'sql-hive', 'sql-pgSQL', 'sql-gql', 'sql-gpSQL', 'sql-sparkSQL', 'sql-esper'] | None
default `= None`
The language to display the code as. Supported languages listed in
`gr.Code.languages`.
every: Timer | float | None
default `= None`
Continously calls `value` to recalculate it if `value` is a function (has no
effect otherwise). Can provide a Timer whose tick resets `value`, or a float
that provides the regular interval for the reset Timer.
inputs: Component | list[Component] | set[Component] | None
default `= None`
Components that are used as inputs to calculate `value` if `value` is a
function (has no effect otherwise). `value` is recalculated any time the
inputs change.
lines: int
default `= 5`
Minimum number of visible lines to show in the code editor.
max_lines: int | None
default `= None`
Maximum number of visible lines to show in the code editor. Defaults to None
and will fill the height of the container.
label: str | I18nData | None
default `= None`
the label for this component. Appears above the component and is also used as
the header if there are a table of examples for this component. If None and
used in a `gr.Interface`, the label will be the name of the parameter this
component is assigned to.
interactive: bool | None
default `= None`
Whether user should be able to enter code or only view it.
show_label: bool | None
default `= No
|
Initialization
|
https://gradio.app/docs/gradio/code
|
Gradio - Code Docs
|
component is assigned to.
interactive: bool | None
default `= None`
Whether user should be able to enter code or only view it.
show_label: bool | None
default `= None`
if True, will display label.
container: bool
default `= True`
If True, will place the component in a container - providing some extra
padding around the border.
scale: int | None
default `= None`
relative size compared to adjacent Components. For example if Components A and
B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide
as B. Should be an integer. scale applies in Rows, and to top-level Components
in Blocks where fill_height=True.
min_width: int
default `= 160`
minimum pixel width, will wrap if not sufficient screen space to satisfy this
value. If a certain scale value results in this Component being narrower than
min_width, the min_width parameter will be respected first.
visible: bool | Literal['hidden']
default `= True`
If False, component will be hidden. If "hidden", component will be visually
hidden and not take up space in the layout but still exist in the DOM
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.
elem_classes: list[str] | str | None
default `= None`
An optional list of strings that are assigned as the classes of this component
in the HTML DOM. Can be used for targeting CSS styles.
render: bool
default `= True`
If False, component will not render be rendered in the Blocks context. Should
be used if the intention is to assign event listeners now but render the
component later.
key: int | str | tuple[int | str, ...] | None
default `= None`
in a gr.render, Components with the same key across re-renders are treated as
the same component, not a new component. Properties set in
|
Initialization
|
https://gradio.app/docs/gradio/code
|
Gradio - Code Docs
|
ey: int | str | tuple[int | str, ...] | None
default `= None`
in a gr.render, Components with the same key across re-renders are treated as
the same component, not a new component. Properties set in 'preserved_by_key'
are not reset across a re-render.
preserved_by_key: list[str] | str | None
default `= "value"`
A list of parameters from this component's constructor. Inside a gr.render()
function, if a component is re-rendered with the same key, these (and only
these) parameters will be preserved in the UI (if they have been changed by
the user or an event listener) instead of re-rendered based on the values
provided during constructor.
wrap_lines: bool
default `= False`
If True, will wrap lines to the width of the container when overflow occurs.
Defaults to False.
show_line_numbers: bool
default `= True`
If True, displays line numbers, and if False, hides line numbers.
autocomplete: bool
default `= False`
If True, will show autocomplete suggestions for supported languages. Defaults
to False.
|
Initialization
|
https://gradio.app/docs/gradio/code
|
Gradio - Code Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.Code` | "code" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/code
|
Gradio - Code Docs
|
Description
Event listeners allow you to respond to user interactions with the UI
components you've defined in a Gradio Blocks app. When a user interacts with
an element, such as changing a slider value or uploading an image, a function
is called.
Supported Event Listeners
The Code component supports the following event listeners. Each event listener
takes the same parameters, which are listed in the Event Parameters table
below.
Listener | Description
---|---
`Code.languages(fn, ···)` | ['python', 'c', 'cpp', 'markdown', 'latex', 'json', 'html', 'css', 'javascript', 'jinja2', 'typescript', 'yaml', 'dockerfile', 'shell', 'r', 'sql', 'sql-msSQL', 'sql-mySQL', 'sql-mariaDB', 'sql-sqlite', 'sql-cassandra', 'sql-plSQL', 'sql-hive', 'sql-pgSQL', 'sql-gql', 'sql-gpSQL', 'sql-sparkSQL', 'sql-esper', None]
`Code.change(fn, ···)` | Triggered when the value of the Code changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input.
`Code.input(fn, ···)` | This listener is triggered when the user changes the value of the Code.
`Code.focus(fn, ···)` | This listener is triggered when the Code is focused.
`Code.blur(fn, ···)` | This listener is triggered when the Code is unfocused/blurred.
Event Parameters
Parameters ▼
|
Event Listeners
|
https://gradio.app/docs/gradio/code
|
Gradio - Code Docs
|
The gr.DeletedFileData class is a subclass of gr.EventData that
specifically carries information about the `.delete()` event. When
gr.DeletedFileData is added as a type hint to an argument of an event listener
method, a gr.DeletedFileData object will automatically be passed as the value
of that argument. The attributes of this object contains information about the
event that triggered the listener.
|
Description
|
https://gradio.app/docs/gradio/deletedfiledata
|
Gradio - Deletedfiledata Docs
|
import gradio as gr
def test(delete_data: gr.DeletedFileData):
return delete_data.file.path
with gr.Blocks() as demo:
files = gr.File(file_count="multiple")
deleted_file = gr.File()
files.delete(test, None, deleted_file)
demo.launch()
|
Example Usage
|
https://gradio.app/docs/gradio/deletedfiledata
|
Gradio - Deletedfiledata Docs
|
Parameters ▼
file: FileData
The file that was deleted, as a FileData object. The str path to the file can
be retrieved with the .path attribute.
|
Attributes
|
https://gradio.app/docs/gradio/deletedfiledata
|
Gradio - Deletedfiledata Docs
|
file_component_events
Open in 🎢 ↗ import gradio as gr def delete_file(n: int, file:
gr.DeletedFileData): return [file.file.path, n + 1] with gr.Blocks() as demo:
with gr.Row(): with gr.Column(): file_component = gr.File(label="Upload Single
File", file_count="single") with gr.Column(): output_file_1 = gr.File(
label="Upload Single File Output", file_count="single" ) num_load_btn_1 =
gr.Number(label="Load Upload Single File", value=0) file_component.upload(
lambda s, n: (s, n + 1), [file_component, num_load_btn_1], [output_file_1,
num_load_btn_1], ) with gr.Row(): with gr.Column(): file_component_multiple =
gr.File( label="Upload Multiple Files", file_count="multiple" ) with
gr.Column(): output_file_2 = gr.File( label="Upload Multiple Files Output",
file_count="multiple" ) num_load_btn_2 = gr.Number(label="Load Upload
Multiple Files", value=0) file_component_multiple.upload( lambda s, n: (s, n +
1), [file_component_multiple, num_load_btn_2], [output_file_2,
num_load_btn_2], ) with gr.Row(): with gr.Column(): file_component_specific =
gr.File( label="Upload Multiple Files Image/Video", file_count="multiple",
file_types=["image", "video"], ) with gr.Column(): output_file_3 = gr.File(
label="Upload Multiple Files Output Image/Video", file_count="multiple" )
num_load_btn_3 = gr.Number( label="Load Upload Multiple Files Image/Video",
value=0 ) file_component_specific.upload( lambda s, n: (s, n + 1),
[file_component_specific, num_load_btn_3], [output_file_3, num_load_btn_3], )
with gr.Row(): with gr.Column(): file_component_pdf = gr.File(label="Upload
PDF File", file_types=[".pdf"]) with gr.Column(): output_file_4 =
gr.File(label="Upload PDF File Output") num_load_btn_4 = gr.Number(label="
Load Upload PDF File", value=0) file_component_pdf.upload( lambda s, n: (s, n
+ 1), [file_component_pdf, num_load_btn_4], [output_file_4, num_load_btn_4], )
with gr.Row(): with gr.Column(): file_component_invalid = gr.File(
label="Upload File with Invalid file_types", file_types=
|
Demos
|
https://gradio.app/docs/gradio/deletedfiledata
|
Gradio - Deletedfiledata Docs
|
1), [file_component_pdf, num_load_btn_4], [output_file_4, num_load_btn_4], )
with gr.Row(): with gr.Column(): file_component_invalid = gr.File(
label="Upload File with Invalid file_types", file_types=["invalid file_type"],
) with gr.Column(): output_file_5 = gr.File(label="Upload File with Invalid
file_types Output") num_load_btn_5 = gr.Number( label="Load Upload File with
Invalid file_types", value=0 ) file_component_invalid.upload( lambda s, n: (s,
n + 1), [file_component_invalid, num_load_btn_5], [output_file_5,
num_load_btn_5], ) with gr.Row(): with gr.Column(): del_file_input =
gr.File(label="Delete File", file_count="multiple") with gr.Column():
del_file_data = gr.Textbox(label="Delete file data") num_load_btn_6 =
gr.Number(label="Deleted File", value=0) del_file_input.delete( delete_file,
[num_load_btn_6], [del_file_data, num_load_btn_6], ) f =
gr.File(label="Upload many File", file_count="multiple")
f.delete(delete_file) f.delete(delete_file, inputs=None, outputs=None) if
__name__ == "__main__": demo.launch()
import gradio as gr
def delete_file(n: int, file: gr.DeletedFileData):
return [file.file.path, n + 1]
with gr.Blocks() as demo:
with gr.Row():
with gr.Column():
file_component = gr.File(label="Upload Single File", file_count="single")
with gr.Column():
output_file_1 = gr.File(
label="Upload Single File Output", file_count="single"
)
num_load_btn_1 = gr.Number(label="Load Upload Single File", value=0)
file_component.upload(
lambda s, n: (s, n + 1),
[file_component, num_load_btn_1],
[output_file_1, num_load_btn_1],
)
with gr.Row():
with gr.Column():
file_component_multiple = gr.File(
label="Upload Multiple Files", file_count="multiple"
|
Demos
|
https://gradio.app/docs/gradio/deletedfiledata
|
Gradio - Deletedfiledata Docs
|
1],
)
with gr.Row():
with gr.Column():
file_component_multiple = gr.File(
label="Upload Multiple Files", file_count="multiple"
)
with gr.Column():
output_file_2 = gr.File(
label="Upload Multiple Files Output", file_count="multiple"
)
num_load_btn_2 = gr.Number(label="Load Upload Multiple Files", value=0)
file_component_multiple.upload(
lambda s, n: (s, n + 1),
[file_component_multiple, num_load_btn_2],
[output_file_2, num_load_btn_2],
)
with gr.Row():
with gr.Column():
file_component_specific = gr.File(
label="Upload Multiple Files Image/Video",
file_count="multiple",
file_types=["image", "video"],
)
with gr.Column():
output_file_3 = gr.File(
label="Upload Multiple Files Output Image/Video", file_count="multiple"
)
num_load_btn_3 = gr.Number(
label="Load Upload Multiple Files Image/Video", value=0
)
file_component_specific.upload(
lambda s, n: (s, n + 1),
[file_component_specific, num_load_btn_3],
[output_file_3, num_load_btn_3],
)
with gr.Row():
with gr.Column():
file_component_pdf = gr.File(label="Upload PDF File", file_types=[".pdf"])
with gr.Column():
output_file_4 = gr.File(label="Upload PDF File Output")
num_load_btn_4 = gr.Number(label="Load Upload PDF File", value=0)
file_component_pdf.upload(
lambda s, n: (s, n + 1),
[file_component_pdf, num_load_bt
|
Demos
|
https://gradio.app/docs/gradio/deletedfiledata
|
Gradio - Deletedfiledata Docs
|
_btn_4 = gr.Number(label="Load Upload PDF File", value=0)
file_component_pdf.upload(
lambda s, n: (s, n + 1),
[file_component_pdf, num_load_btn_4],
[output_file_4, num_load_btn_4],
)
with gr.Row():
with gr.Column():
file_component_invalid = gr.File(
label="Upload File with Invalid file_types",
file_types=["invalid file_type"],
)
with gr.Column():
output_file_5 = gr.File(label="Upload File with Invalid file_types Output")
num_load_btn_5 = gr.Number(
label="Load Upload File with Invalid file_types", value=0
)
file_component_invalid.upload(
lambda s, n: (s, n + 1),
[file_component_invalid, num_load_btn_5],
[output_file_5, num_load_btn_5],
)
with gr.Row():
with gr.Column():
del_file_input = gr.File(label="Delete File", file_count="multiple")
with gr.Column():
del_file_data = gr.Textbox(label="Delete file data")
num_load_btn_6 = gr.Number(label="Deleted File", value=0)
del_file_input.delete(
delete_file,
[num_load_btn_6],
[del_file_data, num_load_btn_6],
)
f = gr.File(label="Upload many File", file_count="multiple")
f.delete(delete_file)
f.delete(delete_file, inputs=None, outputs=None)
if __name__ == "__main__":
demo.launch()
|
Demos
|
https://gradio.app/docs/gradio/deletedfiledata
|
Gradio - Deletedfiledata Docs
|
Creates a gallery or table to display data samples. This component is
primarily designed for internal use to display examples. However, it can also
be used directly to display a dataset and let users select examples.
|
Description
|
https://gradio.app/docs/gradio/dataset
|
Gradio - Dataset Docs
|
**As input component** : Passes the selected sample either as a `list` of
data corresponding to each input component (if `type` is "value") or as an
`int` index (if `type` is "index"), or as a `tuple` of the index and the data
(if `type` is "tuple").
Your function should accept one of these types:
def predict(
value: int | list | None
)
...
**As output component** : Expects an `int` index or `list` of sample data.
Returns the index of the sample in the dataset or `None` if the sample is not
found.
Your function should return one of these types:
def predict(···) -> list[list]
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/dataset
|
Gradio - Dataset Docs
|
Parameters ▼
label: str | I18nData | None
default `= None`
the label for this component, appears above the component.
show_label: bool
default `= True`
If True, the label will be shown above the component.
components: list[Component] | list[str] | None
default `= None`
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
component_props: list[dict[str, Any]] | None
default `= None`
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: Literal['values', 'index', 'tuple']
default `= "values"`
"values" if clicking on a sample should pass the value of the sample, "index"
if it should pass the index of the sample, or "tuple" if it should pass both
the index and the value of the sample.
layout: Literal['gallery', 'table'] | None
default `= None`
"gallery" if the dataset should be displayed as a gallery with each sample in
a clickable card, or "table" if it should be displayed as a table with each
sample in a row. By default, "gallery" is used if there is a single component,
and "table" is used if there are more than one component. If there are more
than one component, the layout can only be "table".
samples_per_page: int
default `= 10`
how many examples to show per page.
visible: bool | Literal['hidden']
|
Initialization
|
https://gradio.app/docs/gradio/dataset
|
Gradio - Dataset Docs
|
re more
than one component, the layout can only be "table".
samples_per_page: int
default `= 10`
how many examples to show per page.
visible: bool | Literal['hidden']
default `= True`
If False, component will be hidden. If "hidden", component will be visually
hidden and not take up space in the layout but still exist in the DOM
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.
elem_classes: list[str] | str | None
default `= None`
An optional list of strings that are assigned as the classes of this component
in the HTML DOM. Can be used for targeting CSS styles.
render: bool
default `= True`
If False, component will not render be rendered in the Blocks context. Should
be used if the intention is to assign event listeners now but render the
component later.
key: int | str | tuple[int | str, ...] | None
default `= None`
in a gr.render, Components with the same key across re-renders are treated as
the same component, not a new component. Properties set in 'preserved_by_key'
are not reset across a re-render.
preserved_by_key: list[str] | str | None
default `= "value"`
A list of parameters from this component's constructor. Inside a gr.render()
function, if a component is re-rendered with the same key, these (and only
these) parameters will be preserved in the UI (if they have been changed by
the user or an event listener) instead of re-rendered based on the values
provided during constructor.
container: bool
default `= True`
If True, will place the component in a container - providing some extra
padding around the border.
scale: int | None
default `= None`
relative size compared to adjacent Components. For example if Components A and
B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wi
|
Initialization
|
https://gradio.app/docs/gradio/dataset
|
Gradio - Dataset Docs
|
scale: int | None
default `= None`
relative size compared to adjacent Components. For example if Components A and
B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide
as B. Should be an integer. scale applies in Rows, and to top-level Components
in Blocks where fill_height=True.
min_width: int
default `= 160`
minimum pixel width, will wrap if not sufficient screen space to satisfy this
value. If a certain scale value results in this Component being narrower than
min_width, the min_width parameter will be respected first.
proxy_url: str | None
default `= None`
The URL of the external Space used to load this component. Set automatically
when using `gr.load()`. This should not be set manually.
sample_labels: list[str] | None
default `= None`
A list of labels for each sample. If provided, the length of this list should
be the same as the number of samples, and these labels will be used in the UI
instead of rendering the sample values.
|
Initialization
|
https://gradio.app/docs/gradio/dataset
|
Gradio - Dataset Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.Dataset` | "dataset" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/dataset
|
Gradio - Dataset Docs
|
**Updating a Dataset**
In this example, we display a text dataset using `gr.Dataset` and then update
it when the user clicks a button:
import gradio as gr
philosophy_quotes = [
["I think therefore I am."],
["The unexamined life is not worth living."]
]
startup_quotes = [
["Ideas are easy. Implementation is hard"],
["Make mistakes faster."]
]
def show_startup_quotes():
return gr.Dataset(samples=startup_quotes)
with gr.Blocks() as demo:
textbox = gr.Textbox()
dataset = gr.Dataset(components=[textbox], samples=philosophy_quotes)
button = gr.Button()
button.click(show_startup_quotes, None, dataset)
demo.launch()
|
Examples
|
https://gradio.app/docs/gradio/dataset
|
Gradio - Dataset Docs
|
Description
Event listeners allow you to respond to user interactions with the UI
components you've defined in a Gradio Blocks app. When a user interacts with
an element, such as changing a slider value or uploading an image, a function
is called.
Supported Event Listeners
The Dataset component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`Dataset.click(fn, ···)` | Triggered when the Dataset is clicked.
`Dataset.select(fn, ···)` | Event listener for when the user selects or deselects the Dataset. Uses event data gradio.SelectData to carry `value` referring to the label of the Dataset, and `selected` to refer to state of the Dataset. See EventData documentation on how to use this event data
Event Parameters
Parameters ▼
fn: Callable | None | Literal['decorator']
default `= "decorator"`
the function to call when this event is triggered. 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 | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | 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 | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as outputs. If the function returns no
outputs, this should be an empty list.
api_name: str | None | Literal[False]
default `= None`
defines how the endpoint appears in the API docs. Can be a string, None, or
False. If set to a string, the endpoint will be exposed in the API doc
|
Event Listeners
|
https://gradio.app/docs/gradio/dataset
|
Gradio - Dataset Docs
|
_name: str | None | Literal[False]
default `= None`
defines how the endpoint appears in the API docs. Can be a string, None, or
False. If set to a string, the endpoint will be exposed in the API docs with
the given name. If None (default), the name of the function will be used as
the API endpoint. If False, the endpoint will not be exposed in the API docs
and downstream apps (including those that `gr.load` this app) will not be able
to use this event.
api_description: str | None | Literal[False]
default `= None`
Description of the API endpoint. Can be a string, None, or False. If set to a
string, the endpoint will be exposed in the API docs with the given
description. If None, the function's docstring will be used as the API
endpoint description. If False, then no description will be displayed in the
API docs.
scroll_to_output: bool
default `= False`
If True, will scroll to output component on completion
show_progress: Literal['full', 'minimal', 'hidden']
default `= "full"`
how to show the progress animation while event is running: "full" shows a
spinner which covers the output component area as well as a runtime display in
the upper right corner, "minimal" only shows the runtime display, "hidden"
shows no progress animation at all
show_progress_on: Component | list[Component] | None
default `= None`
Component or list of components to show the progress animation on. If None,
will show the progress animation on all of the output components.
queue: bool
default `= True`
If True, will place the request on the queue, if the queue has been enabled.
If False, will not put this event on the queue, even if the queue has been
enabled. If None, will use the queue setting of the gradio app.
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
|
Event Listeners
|
https://gradio.app/docs/gradio/dataset
|
Gradio - Dataset Docs
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.