text
stringlengths 0
2k
| heading1
stringlengths 4
79
| source_page_url
stringclasses 178
values | source_page_title
stringclasses 178
values |
---|---|---|---|
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
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 render the
component later.
|
Initialization
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
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.
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/barplot
|
Gradio - Barplot Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.BarPlot` | "barplot" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
bar_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 bar_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.BarPlot(
temp_sensor_data, x="time", y="temperature", ) temp_by_time_location =
gr.BarPlot( temp_sensor_data, x="time", y="temperature", color="location", )
time_graphs = [temp_by_time, temp_by_time_location] group_by.change( lambda
group: [gr.BarPlot(x_bin=None if group == "None" else group)] *
len(time_graphs), group_by, time_graphs ) aggregate.change( lambda aggregate:
[gr.BarPlot(y_aggregate=aggregate)] * len(time_graphs), aggregate, time_graphs
) def rescale(select: gr.SelectData): return select.index rescale_evt =
gr.on([plot.select for plot in time_graphs], rescale, None, [start, end]) for
trigger in [apply_btn.click, rescale_evt.then]: trigger( lambda start, end:
[gr.BarPlot(x_lim=[start, end])] * len(time_graphs), [start, end], time_graphs
) with gr.Row(): price_by_cuisine = gr.BarPlot( food_rating_data, x="cuisine",
y="price", ) with gr.Column(scale=0): gr.Button("Sort $
|
Demos
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
_lim=[start, end])] * len(time_graphs), [start, end], time_graphs
) with gr.Row(): price_by_cuisine = gr.BarPlot( food_rating_data, x="cuisine",
y="price", ) with gr.Column(scale=0): gr.Button("Sort $ > $$$").click(lambda:
gr.BarPlot(sort="y"), None, price_by_cuisine) gr.Button("Sort $$$ >
$").click(lambda: gr.BarPlot(sort="-y"), None, price_by_cuisine)
gr.Button("Sort A > Z").click(lambda: gr.BarPlot(sort=["Chinese", "Italian",
"Mexican"]), None, price_by_cuisine) with gr.Row(): price_by_rating =
gr.BarPlot( food_rating_data, x="rating", y="price", x_bin=1, )
price_by_rating_color = gr.BarPlot( food_rating_data, x="rating", y="price",
color="cuisine", x_bin=1, color_map={"Italian": "red", "Mexican": "green",
"Chinese": "blue"}, ) if __name__ == "__main__": bar_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 bar_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="Gro
|
Demos
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
021-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.BarPlot(
temp_sensor_data,
x="time",
y="temperature",
)
temp_by_time_location = gr.BarPlot(
temp_sensor_data,
x="time",
y="temperature",
color="location",
)
time_graphs = [temp_by_time, temp_by_time_location]
group_by.change(
lambda group: [gr.BarPlot(x_bin=None if group == "None" else group)] * len(time_graphs),
group_by,
time_graphs
)
aggregate.change(
lambda aggregate: [gr.BarPlot(y_aggregate=aggregate)] * len(time_graphs),
aggregate,
time_graphs
)
def rescale(select: gr.SelectData):
return select.index
rescale_evt = gr.on([plot.select for plot in time_graphs], rescale, None, [start, end])
for trigger in [apply_btn.click, rescale_evt.then]:
trigger(
lambda start, end: [gr.BarPlot(x_lim=[start, end])] * len(time_graphs), [start, end], time_graphs
)
with gr.Row():
price_by_cuisine = gr.BarPlot(
food_rating_data,
x="cuisine",
y="price",
)
with gr.Column(scale=0):
gr.Button("Sort $ > $$$").click(lambda: gr.BarPlot(sort="y"), None, price_by_cuisine)
gr.Button("Sort $$$ > $").click(lambda: gr.BarPlot(sort="-y"), None, price_by_cuisine)
gr.Button("Sort A > Z").click(lambda: gr.BarPlot(sort=["Chinese", "Italian", "Mexican"]), None, price_by_cuisine)
with gr.Row():
|
Demos
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
sort="-y"), None, price_by_cuisine)
gr.Button("Sort A > Z").click(lambda: gr.BarPlot(sort=["Chinese", "Italian", "Mexican"]), None, price_by_cuisine)
with gr.Row():
price_by_rating = gr.BarPlot(
food_rating_data,
x="rating",
y="price",
x_bin=1,
)
price_by_rating_color = gr.BarPlot(
food_rating_data,
x="rating",
y="price",
color="cuisine",
x_bin=1,
color_map={"Italian": "red", "Mexican": "green", "Chinese": "blue"},
)
if __name__ == "__main__":
bar_plots.launch()
|
Demos
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot 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 BarPlot component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`BarPlot.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
`BarPlot.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 endpoint will
|
Event Listeners
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
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 for each pa
|
Event Listeners
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
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 arguments for
|
Event Listeners
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
w 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.
|
Event Listeners
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
The gr.UndoData class is a subclass of gr.Event data that specifically
carries information about the `.undo()` event. When gr.UndoData is added as a
type hint to an argument of an event listener method, a gr.UndoData 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/undodata
|
Gradio - Undodata Docs
|
import gradio as gr
def undo(retry_data: gr.UndoData, history: list[gr.MessageDict]):
history_up_to_retry = history[:retry_data.index]
return history_up_to_retry
with gr.Blocks() as demo:
chatbot = gr.Chatbot()
chatbot.undo(undo, chatbot, chatbot)
demo.launch()
|
Example Usage
|
https://gradio.app/docs/gradio/undodata
|
Gradio - Undodata Docs
|
Parameters ▼
index: int | tuple[int, int]
The index of the user message that should be undone.
value: Any
The value of the user message that should be undone.
|
Attributes
|
https://gradio.app/docs/gradio/undodata
|
Gradio - Undodata Docs
|
Displays a classification label, along with confidence scores of top
categories, if provided. As this component does not accept user input, it is
rarely used as an input component.
|
Description
|
https://gradio.app/docs/gradio/label
|
Gradio - Label Docs
|
**As input component** : Depending on the value, passes the label as a `str | int | float`, or the labels and confidences as a `dict[str, float]`.
Your function should accept one of these types:
def predict(
value: dict[str, float] | str | int | float | None
)
...
**As output component** : Expects a `dict[str, float]` of classes and confidences, or `str` with just the class or an `int | float` for regression outputs, or a `str` path to a .json file containing a json dictionary in one of the preceding formats.
Your function should return one of these types:
def predict(···) -> dict[str, float] | str | int | float | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/label
|
Gradio - Label Docs
|
Parameters ▼
value: dict[str, float] | str | float | Callable | None
default `= None`
Default value to show in the component. If a str or number is provided, simply
displays the string or number. If a {Dict[str, float]} of classes and
confidences is provided, displays the top class on top and the
`num_top_classes` below, along with their confidence bars. If a function is
provided, the function will be called each time the app loads to set the
initial value of this component.
num_top_classes: int | None
default `= None`
number of most confident classes to show.
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] | 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 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_he
|
Initialization
|
https://gradio.app/docs/gradio/label
|
Gradio - Label Docs
|
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
default `= True`
If False, component will be hidden.
elem_id: str | None
default `= None`
An optional string that is assigned as the id of this component in the HTML
DOM. Can be used for targeting CSS styles.
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.
color: str | None
default `= None`
The background color of the label (either a valid css color name or
hexadecimal string).
show
|
Initialization
|
https://gradio.app/docs/gradio/label
|
Gradio - Label Docs
|
e values
provided during constructor.
color: str | None
default `= None`
The background color of the label (either a valid css color name or
hexadecimal string).
show_heading: bool
default `= True`
If False, the heading will not be displayed if a dictionary of labels and
confidences is provided. The heading will still be visible if the value is a
string or number.
|
Initialization
|
https://gradio.app/docs/gradio/label
|
Gradio - Label Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.Label` | "label" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/label
|
Gradio - Label 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 Label component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`Label.change(fn, ···)` | Triggered when the value of the Label 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.
`Label.select(fn, ···)` | Event listener for when the user selects or deselects the Label. Uses event data gradio.SelectData to carry `value` referring to the label of the Label, and `selected` to refer to state of the Label. 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 emp
|
Event Listeners
|
https://gradio.app/docs/gradio/label
|
Gradio - Label Docs
|
ontext | 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 on the queue, even if the queue has been
enabled. If None, will use the queu
|
Event Listeners
|
https://gradio.app/docs/gradio/label
|
Gradio - Label Docs
|
lt `= 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 pending, and "always_last" (default for
`.change()` and `.key_up()` events) would al
|
Event Listeners
|
https://gradio.app/docs/gradio/label
|
Gradio - Label Docs
|
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
identical.
|
Event Listeners
|
https://gradio.app/docs/gradio/label
|
Gradio - Label Docs
|
ener to be used in @gr.render(). If set, this
value identifies an event as identical across re-renders when the key is
identical.
|
Event Listeners
|
https://gradio.app/docs/gradio/label
|
Gradio - Label Docs
|
ChatInterface is Gradio's high-level abstraction for creating chatbot UIs,
and allows you to create a web-based demo around a chatbot model in a few
lines of code. Only one parameter is required: fn, which takes a function that
governs the response of the chatbot based on the user input and chat history.
Additional parameters can be used to control the appearance and behavior of
the demo.
|
Description
|
https://gradio.app/docs/gradio/chatinterface
|
Gradio - Chatinterface Docs
|
**Basic Example** : A chatbot that echoes back the users’s message
import gradio as gr
def echo(message, history):
return message
demo = gr.ChatInterface(fn=echo, type="messages", examples=["hello", "hola", "merhaba"], title="Echo Bot")
demo.launch()
**Custom Chatbot** : A `gr.ChatInterface` with a custom `gr.Chatbot` that
includes a placeholder as well as upvote/downvote buttons. The upvote/downvote
buttons are automatically added when a `.like()` event is attached to a
`gr.Chatbot`. In order to attach event listeners to your custom chatbot, wrap
the `gr.Chatbot` as well as the `gr.ChatInterface` inside of a `gr.Blocks`
like this:
import gradio as gr
def yes(message, history):
return "yes"
def vote(data: gr.LikeData):
if data.liked:
print("You upvoted this response: " + data.value["value"])
else:
print("You downvoted this response: " + data.value["value"])
with gr.Blocks() as demo:
chatbot = gr.Chatbot(placeholder="<strong>Your Personal Yes-Man</strong><br>Ask Me Anything")
chatbot.like(vote, None, None)
gr.ChatInterface(fn=yes, type="messages", chatbot=chatbot)
demo.launch()
|
Example Usage
|
https://gradio.app/docs/gradio/chatinterface
|
Gradio - Chatinterface Docs
|
Parameters ▼
fn: Callable
the function to wrap the chat interface around. Normally (assuming `type` is set to "messages"), the function should accept two parameters: a `str` representing the input message and `list` of openai-style dictionaries: {"role": "user" | "assistant", "content": `str` | {"path": `str`} | `gr.Component`} representing the chat history. The function should return/yield a `str` (for a simple message), a supported Gradio component (e.g. gr.Image to return an image), a `dict` (for a complete openai-style message response), or a `list` of such messages.
multimodal: bool
default `= False`
if True, the chat interface will use a `gr.MultimodalTextbox` component for
the input, which allows for the uploading of multimedia files. If False, the
chat interface will use a gr.Textbox component for the input. If this is True,
the first argument of `fn` should accept not a `str` message but a `dict`
message with keys "text" and "files"
type: Literal['messages', 'tuples'] | None
default `= None`
The format of the messages passed into the chat history parameter of `fn`. If "messages", passes the history as a list of dictionaries with openai-style "role" and "content" keys. The "content" key's value should be one of the following - (1) strings in valid Markdown (2) a dictionary with a "path" key and value corresponding to the file to display or (3) an instance of a Gradio component: at the moment gr.Image, gr.Plot, gr.Video, gr.Gallery, gr.Audio, and gr.HTML are supported. The "role" key should be one of 'user' or 'assistant'. Any other roles will not be displayed in the output. If this parameter is 'tuples' (deprecated), passes the chat history as a `list[list[str | None | tuple]]`, i.e. a list of lists. The inner list should have 2 elements: the user message and the response message.
chatbot: Chatbot | None
default `= None`
an instance of the gr.Chatbot component to use for the chat interfac
|
Initialization
|
https://gradio.app/docs/gradio/chatinterface
|
Gradio - Chatinterface Docs
|
list should have 2 elements: the user message and the response message.
chatbot: Chatbot | None
default `= None`
an instance of the gr.Chatbot component to use for the chat interface, if you
would like to customize the chatbot properties. If not provided, a default
gr.Chatbot component will be created.
textbox: Textbox | MultimodalTextbox | None
default `= None`
an instance of the gr.Textbox or gr.MultimodalTextbox component to use for the
chat interface, if you would like to customize the textbox properties. If not
provided, a default gr.Textbox or gr.MultimodalTextbox component will be
created.
additional_inputs: str | Component | list[str | Component] | None
default `= None`
an instance or list of instances of gradio components (or their string
shortcuts) to use as additional inputs to the chatbot. If the components are
not already rendered in a surrounding Blocks, then the components will be
displayed under the chatbot, in an accordion. The values of these components
will be passed into `fn` as arguments in order after the chat history.
additional_inputs_accordion: str | Accordion | None
default `= None`
if a string is provided, this is the label of the `gr.Accordion` to use to
contain additional inputs. A `gr.Accordion` object can be provided as well to
configure other properties of the container holding the additional inputs.
Defaults to a `gr.Accordion(label="Additional Inputs", open=False)`. This
parameter is only used if `additional_inputs` is provided.
additional_outputs: Component | list[Component] | None
default `= None`
an instance or list of instances of gradio components to use as additional
outputs from the chat function. These must be components that are already
defined in the same Blocks scope. If provided, the chat function should return
additional values for these components. See
[demo/chatinterface_artifacts](https://gradio.app/playground?demo=Blank&code=a
|
Initialization
|
https://gradio.app/docs/gradio/chatinterface
|
Gradio - Chatinterface Docs
|
efined in the same Blocks scope. If provided, the chat function should return
additional values for these components. See
[demo/chatinterface_artifacts](https://gradio.app/playground?demo=Blank&code=aW1wb3J0IGdyYWRpbyBhcyBncgoKcHl0aG9uX2NvZGUgPSAiIiIKZGVmIGZpYihuKToKICAgIGlmIG4gPD0gMDoKICAgICAgICByZXR1cm4gMAogICAgZWxpZiBuID09IDE6CiAgICAgICAgcmV0dXJuIDEKICAgIGVsc2U6CiAgICAgICAgcmV0dXJuIGZpYihuLTEpICsgZmliKG4tMikKIiIiCgpqc19jb2RlID0gIiIiCmZ1bmN0aW9uIGZpYihuKSB7CiAgICBpZiAobiA8PSAwKSByZXR1cm4gMDsKICAgIGlmIChuID09PSAxKSByZXR1cm4gMTsKICAgIHJldHVybiBmaWIobiAtIDEpICsgZmliKG4gLSAyKTsKfQoiIiIKCmRlZiBjaGF0KG1lc3NhZ2UsIGhpc3RvcnkpOgogICAgaWYgInB5dGhvbiIgaW4gbWVzc2FnZS5sb3dlcigpOgogICAgICAgIHJldHVybiAiVHlwZSBQeXRob24gb3IgSmF2YVNjcmlwdCB0byBzZWUgdGhlIGNvZGUuIiwgZ3IuQ29kZShsYW5ndWFnZT0icHl0aG9uIiwgdmFsdWU9cHl0aG9uX2NvZGUpCiAgICBlbGlmICJqYXZhc2NyaXB0IiBpbiBtZXNzYWdlLmxvd2VyKCk6CiAgICAgICAgcmV0dXJuICJUeXBlIFB5dGhvbiBvciBKYXZhU2NyaXB0IHRvIHNlZSB0aGUgY29kZS4iLCBnci5Db2RlKGxhbmd1YWdlPSJqYXZhc2NyaXB0IiwgdmFsdWU9anNfY29kZSkKICAgIGVsc2U6CiAgICAgICAgcmV0dXJuICJQbGVhc2UgYXNrIGFib3V0IFB5dGhvbiBvciBKYXZhU2NyaXB0LiIsIE5vbmUKCndpdGggZ3IuQmxvY2tzKCkgYXMgZGVtbzoKICAgIGNvZGUgPSBnci5Db2RlKHJlbmRlcj1GYWxzZSkKICAgIHdpdGggZ3IuUm93KCk6CiAgICAgICAgd2l0aCBnci5Db2x1bW4oKToKICAgICAgICAgICAgZ3IuTWFya2Rvd24oIjxjZW50ZXI%2BPGgxPldyaXRlIFB5dGhvbiBvciBKYXZhU2NyaXB0PC9oMT48L2NlbnRlcj4iKQogICAgICAgICAgICBnci5DaGF0SW50ZXJmYWNlKAogICAgICAgICAgICAgICAgY2hhdCwKICAgICAgICAgICAgICAgIGV4YW1wbGVzPVsiUHl0aG9uIiwgIkphdmFTY3JpcHQiXSwKICAgICAgICAgICAgICAgIGFkZGl0aW9uYWxfb3V0cHV0cz1bY29kZV0sCiAgICAgICAgICAgICAgICB0eXBlPSJtZXNzYWdlcyIKICAgICAgICAgICAgKQogICAgICAgIHdpdGggZ3IuQ29sdW1uKCk6CiAgICAgICAgICAgIGdyLk1hcmtkb3duKCI8Y2VudGVyPjxoMT5Db2RlIEFydGlmYWN0czwvaDE%2BPC9jZW50ZXI%2BIikKICAgICAgICAgICAgY29kZS5yZW5kZXIoKQoKZGVtby5sYXVuY2goKQo%3D).
editable: bool
default `= False`
if True, users can edit past messages to regenerate responses.
examples: list[str] | list[MultimodalValue] | list[list] | N
|
Initialization
|
https://gradio.app/docs/gradio/chatinterface
|
Gradio - Chatinterface Docs
|
oKQo%3D).
editable: bool
default `= False`
if True, users can edit past messages to regenerate responses.
examples: list[str] | list[MultimodalValue] | list[list] | None
default `= None`
sample inputs for the function; if provided, appear within the chatbot and can
be clicked to populate the chatbot input. Should be a list of strings
representing text-only examples, or a list of dictionaries (with keys `text`
and `files`) representing multimodal examples. If `additional_inputs` are
provided, the examples must be a list of lists, where the first element of
each inner list is the string or dictionary example message and the remaining
elements are the example values for the additional inputs -- in this case, the
examples will appear under the chatbot.
example_labels: list[str] | None
default `= None`
labels for the examples, to be displayed instead of the examples themselves.
If provided, should be a list of strings with the same length as the examples
list. Only applies when examples are displayed within the chatbot (i.e. when
`additional_inputs` is not provided).
example_icons: list[str] | None
default `= None`
icons for the examples, to be displayed above the examples. If provided,
should be a list of string URLs or local paths with the same length as the
examples list. Only applies when examples are displayed within the chatbot
(i.e. when `additional_inputs` is not provided).
run_examples_on_click: bool
default `= True`
if True, clicking on an example will run the example through the chatbot fn
and the response will be displayed in the chatbot. If False, clicking on an
example will only populate the chatbot input with the example message. Has no
effect if `cache_examples` is True
cache_examples: bool | None
default `= None`
if True, caches examples in the server for fast runtime in examples. The
default option in HuggingFace Spaces is True. The default option
|
Initialization
|
https://gradio.app/docs/gradio/chatinterface
|
Gradio - Chatinterface Docs
|
cache_examples: bool | None
default `= None`
if True, caches examples in the server for fast runtime in examples. The
default option in HuggingFace Spaces is True. The default option elsewhere is
False. 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 "eager", all examples are cached at app launch. If "lazy", examples are
cached for all users after the first use by any user of the app. If None, will
use the GRADIO_CACHE_MODE environment variable if defined, or default to
"eager".
title: str | I18nData | None
default `= None`
a title for the interface; if provided, appears above chatbot in large font.
Also used as the tab title when opened in a browser window.
description: str | None
default `= None`
a description for the interface; if provided, appears above the chatbot and
beneath the title in regular font. Accepts Markdown and HTML content.
theme: Theme | str | None
default `= None`
a Theme object or a string representing a theme. If a string, will look for a
built-in theme with that name (e.g. "soft" or "default"), or will attempt to
load a theme from the Hugging Face Hub (e.g. "gradio/monochrome"). If None,
will use the Default theme.
flagging_mode: Literal['never', 'manual'] | None
default `= None`
one of "never", "manual". If "never", users will not see a button to flag an
input and output. If "manual", users will see a button to flag.
flagging_options: list[str] | tuple[str, ...] | None
default `= ('Like', 'Dislike')`
a list of strings representing the options that users can choose from when
flagging a message. Defaults to ["Like", "Dislike"]. These two case-sensitive
strings will render as "thumbs up" and "thumbs down" icon resp
|
Initialization
|
https://gradio.app/docs/gradio/chatinterface
|
Gradio - Chatinterface Docs
|
gs representing the options that users can choose from when
flagging a message. Defaults to ["Like", "Dislike"]. These two case-sensitive
strings will render as "thumbs up" and "thumbs down" icon respectively next to
each bot message, but any other strings appear under a separate flag icon.
flagging_dir: str
default `= ".gradio/flagged"`
path to the the directory where flagged data is stored. If the directory does
not exist, it will be created.
css: str | None
default `= None`
Custom css as a code string. This css will be included in the demo webpage.
css_paths: str | Path | list[str | Path] | None
default `= None`
Custom css as a pathlib.Path to a css file or a list of such paths. This css
files will be read, concatenated, and included in the demo webpage. If the
`css` parameter is also set, the css from `css` will be included first.
js: str | Literal[True] | None
default `= None`
Custom js as a code string. The custom js should be in the form of a single js
function. This function will automatically be executed when the page loads.
For more flexibility, use the head parameter to insert js inside <script>
tags.
head: str | None
default `= None`
Custom html code to insert into the head of the demo webpage. This can be used
to add custom meta tags, multiple scripts, stylesheets, etc. to the page.
head_paths: str | Path | list[str | Path] | None
default `= None`
Custom html code as a pathlib.Path to a html file or a list of such paths.
This html files will be read, concatenated, and included in the head of the
demo webpage. If the `head` parameter is also set, the html from `head` will
be included first.
analytics_enabled: bool | None
default `= None`
whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED
environment variable if defined, or default to True.
autofocus: bool
default `= True`
if True, autofo
|
Initialization
|
https://gradio.app/docs/gradio/chatinterface
|
Gradio - Chatinterface Docs
|
e`
whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED
environment variable if defined, or default to True.
autofocus: bool
default `= True`
if True, autofocuses to the textbox when the page loads.
autoscroll: bool
default `= True`
If True, will automatically scroll to the bottom of the chatbot when a new
message appears, unless the user scrolls up. If False, will not scroll to the
bottom of the chatbot automatically.
submit_btn: str | bool | None
default `= True`
If True, will show a submit button with a submit icon within the textbox. If a
string, will use that string as the submit button text in place of the icon.
If False, will not show a submit button.
stop_btn: str | bool | None
default `= True`
If True, will show a button with a stop icon during generator executions, to
stop generating. If a string, will use that string as the submit button text
in place of the stop icon. If False, will not show a stop button.
concurrency_limit: int | None | Literal['default']
default `= "default"`
if set, this is the maximum number of chatbot submissions that can be running
simultaneously. Can be set to None to mean no limit (any number of chatbot
submissions can be running simultaneously). Set to "default" to use the
default concurrency limit (defined by the `default_concurrency_limit`
parameter in `.queue()`, which is 1 by default).
delete_cache: tuple[int, int] | None
default `= None`
a tuple corresponding [frequency, age] both expressed in number of seconds.
Every `frequency` seconds, the temporary files created by this Blocks instance
will be deleted if more than `age` seconds have passed since the file was
created. For example, setting this to (86400, 86400) will delete temporary
files every day. The cache will be deleted entirely when the server restarts.
If None, no cache deletion will occur.
show_progress: Literal['ful
|
Initialization
|
https://gradio.app/docs/gradio/chatinterface
|
Gradio - Chatinterface Docs
|
to (86400, 86400) will delete temporary
files every day. The cache will be deleted entirely when the server restarts.
If None, no cache deletion will occur.
show_progress: Literal['full', 'minimal', 'hidden']
default `= "minimal"`
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
fill_height: bool
default `= True`
if True, the chat interface will expand to the height of window.
fill_width: bool
default `= False`
Whether to horizontally expand to fill container fully. If False, centers and
constrains app to a maximum width.
api_name: str | Literal[False]
default `= "chat"`
defines how the chat endpoint appears in the API docs. Can be a string or
False. If set to a string, the chat endpoint will be exposed in the API docs
with the given name. If False, the chat endpoint will not be exposed in the
API docs and downstream apps (including those that `gr.load` this app) will
not be able to call this chat endpoint.
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.
show_api: bool
default `= True`
whether to show the chat endpoint 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.
save_history: bool
|
Initialization
|
https://gradio.app/docs/gradio/chatinterface
|
Gradio - Chatinterface Docs
|
lse, 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.
save_history: bool
default `= False`
if True, will save the chat history to the browser's local storage and display
previous conversations in a side panel.
|
Initialization
|
https://gradio.app/docs/gradio/chatinterface
|
Gradio - Chatinterface Docs
|
chatinterface_random_responsechatinterface_streaming_echochatinterface_artifacts
Open in 🎢 ↗ import random import gradio as gr def random_response(message,
history): return random.choice(["Yes", "No"]) demo =
gr.ChatInterface(random_response, type="messages", autofocus=False) if
__name__ == "__main__": demo.launch()
import random
import gradio as gr
def random_response(message, history):
return random.choice(["Yes", "No"])
demo = gr.ChatInterface(random_response, type="messages", autofocus=False)
if __name__ == "__main__":
demo.launch()
Open in 🎢 ↗ import time import gradio as gr def slow_echo(message, history):
for i in range(len(message)): time.sleep(0.05) yield "You typed: " + message[:
i + 1] demo = gr.ChatInterface( slow_echo, type="messages",
flagging_mode="manual", flagging_options=["Like", "Spam", "Inappropriate",
"Other"], save_history=True, ) if __name__ == "__main__": demo.launch()
import time
import gradio as gr
def slow_echo(message, history):
for i in range(len(message)):
time.sleep(0.05)
yield "You typed: " + message[: i + 1]
demo = gr.ChatInterface(
slow_echo,
type="messages",
flagging_mode="manual",
flagging_options=["Like", "Spam", "Inappropriate", "Other"],
save_history=True,
)
if __name__ == "__main__":
demo.launch()
Open in 🎢 ↗ import gradio as gr python_code = """ def fib(n): if n <= 0:
return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2) """ js_code =
""" function fib(n) { if (n <= 0) return 0; if (n === 1) return 1; return
fib(n - 1) + fib(n - 2); } """ def chat(message, history): if "python" in
message.lower(): return "Type Python or JavaScript to see the code.",
gr.Code(language="python", value=python_code) elif "javascript" in
message.lower(): return "Type Python or JavaScript to see the code.",
gr.Code(language="
|
Demos
|
https://gradio.app/docs/gradio/chatinterface
|
Gradio - Chatinterface Docs
|
Type Python or JavaScript to see the code.",
gr.Code(language="python", value=python_code) elif "javascript" in
message.lower(): return "Type Python or JavaScript to see the code.",
gr.Code(language="javascript", value=js_code) else: return "Please ask about
Python or JavaScript.", None with gr.Blocks() as demo: code =
gr.Code(render=False) with gr.Row(): with gr.Column():
gr.Markdown("<center><h1>Write Python or JavaScript</h1></center>")
gr.ChatInterface( chat, examples=["Python", "JavaScript"],
additional_outputs=[code], type="messages" ) with gr.Column():
gr.Markdown("<center><h1>Code Artifacts</h1></center>") code.render()
demo.launch()
import gradio as gr
python_code = """
def fib(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
"""
js_code = """
function fib(n) {
if (n <= 0) return 0;
if (n === 1) return 1;
return fib(n - 1) + fib(n - 2);
}
"""
def chat(message, history):
if "python" in message.lower():
return "Type Python or JavaScript to see the code.", gr.Code(language="python", value=python_code)
elif "javascript" in message.lower():
return "Type Python or JavaScript to see the code.", gr.Code(language="javascript", value=js_code)
else:
return "Please ask about Python or JavaScript.", None
with gr.Blocks() as demo:
code = gr.Code(render=False)
with gr.Row():
with gr.Column():
gr.Markdown("
Write Python or JavaScript
")
gr.ChatInterface(
chat,
examples=["Python", "JavaScript"],
additional_outputs=[code],
type="messages"
)
with gr.Column():
gr.Markdown("
Code Artifacts
")
code.rend
|
Demos
|
https://gradio.app/docs/gradio/chatinterface
|
Gradio - Chatinterface Docs
|
tional_outputs=[code],
type="messages"
)
with gr.Column():
gr.Markdown("
Code Artifacts
")
code.render()
demo.launch()
|
Demos
|
https://gradio.app/docs/gradio/chatinterface
|
Gradio - Chatinterface Docs
|
Row is a layout element within Blocks that renders all children
horizontally.
|
Description
|
https://gradio.app/docs/gradio/row
|
Gradio - Row Docs
|
with gr.Blocks() as demo:
with gr.Row():
gr.Image("lion.jpg", scale=2)
gr.Image("tiger.jpg", scale=1)
demo.launch()
|
Example Usage
|
https://gradio.app/docs/gradio/row
|
Gradio - Row Docs
|
Parameters ▼
variant: Literal['default', 'panel', 'compact']
default `= "default"`
row type, 'default' (no background), 'panel' (gray background color and
rounded corners), or 'compact' (rounded corners and no internal gap).
visible: bool
default `= True`
If False, row will be hidden.
elem_id: str | None
default `= None`
An optional string that is assigned as the id of this component in the HTML
DOM. Can be used for targeting CSS styles.
elem_classes: list[str] | str | None
default `= None`
An optional string or list of strings that are assigned as the class of this
component in the HTML DOM. Can be used for targeting CSS styles.
scale: int | None
default `= None`
relative height compared to adjacent elements. 1 or greater indicates the Row
will expand in height, and any child columns will also expand to fill the
height.
render: bool
default `= True`
If False, this layout will not be rendered in the Blocks context. Should be
used if the intention is to assign event listeners now but render the
component later.
height: int | str | None
default `= None`
The height of the row, specified in pixels if a number is passed, or in CSS
units if a string is passed. If content exceeds the height, the row will
scroll vertically. If not set, the row will expand to fit the content.
max_height: int | str | None
default `= None`
The maximum height of the row, specified in pixels if a number is passed, or
in CSS units if a string is passed. If content exceeds the height, the row
will scroll vertically. If content is shorter than the height, the row will
shrink to fit the content. Will not have any effect if `height` is set and is
smaller than `max_height`.
min_height: int | str | None
default `= None`
The minimum height of the row, specified in pixels if a number is passed, or
in CSS units if a string is passed. If content e
|
Initialization
|
https://gradio.app/docs/gradio/row
|
Gradio - Row Docs
|
x_height`.
min_height: int | str | None
default `= None`
The minimum height of the row, specified in pixels if a number is passed, or
in CSS units if a string is passed. If content exceeds the height, the row
will expand to fit the content. Will not have any effect if `height` is set
and is larger than `min_height`.
equal_height: bool
default `= False`
If True, makes every child element have equal height
show_progress: bool
default `= False`
If True, shows progress animation when being updated.
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 `= None`
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/row
|
Gradio - Row Docs
|
Used to create an upload button, when clicked allows a user to upload files
that satisfy the specified file type or generic files (if file_type not set).
|
Description
|
https://gradio.app/docs/gradio/uploadbutton
|
Gradio - Uploadbutton Docs
|
**As input component** : Passes the file as a `str` or `bytes` object, or a
list of `str` or list of `bytes` objects, depending on `type` and
`file_count`.
Your function should accept one of these types:
def predict(
value: bytes | str | list[bytes] | list[str] | None
)
...
**As output component** : Expects a `str` filepath or URL, or a `list[str]`
of filepaths/URLs.
Your function should return one of these types:
def predict(···) -> str | list[str] | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/uploadbutton
|
Gradio - Uploadbutton Docs
|
Parameters ▼
label: str
default `= "Upload a File"`
Text to display on the button. Defaults to "Upload a File".
value: str | I18nData | list[str] | Callable | None
default `= None`
File or list of files to upload by default.
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
default `= True`
If False, component will be hidden.
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 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 UploadButto
|
Initialization
|
https://gradio.app/docs/gradio/uploadbutton
|
Gradio - Uploadbutton Docs
|
ain 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.
type: Literal['filepath', 'binary']
default `= "filepath"`
Type of value to be returned by component. "file" returns a temporary file
object with the same base name as the uploaded file, whose full path can be
retrieved by file_obj.name, "binary" returns an bytes object.
file_count: Literal['single', 'multiple', 'directory']
default `= "single"`
if single, allows user to upload one file. If "multiple", user uploads
multiple files. If "directory", user
|
Initialization
|
https://gradio.app/docs/gradio/uploadbutton
|
Gradio - Uploadbutton Docs
|
file_count: Literal['single', 'multiple', 'directory']
default `= "single"`
if single, allows user to upload one file. If "multiple", user uploads
multiple files. If "directory", user uploads all files in selected directory.
Return type will be list for each file in case of "multiple" or "directory".
file_types: list[str] | None
default `= None`
List of type of files to be uploaded. "file" allows any file to be uploaded,
"image" allows only image files to be uploaded, "audio" allows only audio
files to be uploaded, "video" allows only video files to be uploaded, "text"
allows only text files to be uploaded.
|
Initialization
|
https://gradio.app/docs/gradio/uploadbutton
|
Gradio - Uploadbutton Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.UploadButton` | "uploadbutton" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/uploadbutton
|
Gradio - Uploadbutton Docs
|
upload_and_downloadupload_button
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()
Open in 🎢 ↗ import gradio as gr def upload_file(files): file_paths =
[file.name for file in files] return file_paths with gr.Blocks() as demo:
file_output = gr.File() upload_button = gr.UploadButton("Click to Upload a
File", file_types=["image", "video"], file_count="multiple")
upload_button.upload(upload_file, upload_button, file_output) demo.launch()
import gradio as gr
def upload_file(files):
file_paths = [file.name fo
|
Demos
|
https://gradio.app/docs/gradio/uploadbutton
|
Gradio - Uploadbutton Docs
|
ile_count="multiple")
upload_button.upload(upload_file, upload_button, file_output) demo.launch()
import gradio as gr
def upload_file(files):
file_paths = [file.name for file in files]
return file_paths
with gr.Blocks() as demo:
file_output = gr.File()
upload_button = gr.UploadButton("Click to Upload a File", file_types=["image", "video"], file_count="multiple")
upload_button.upload(upload_file, upload_button, file_output)
demo.launch()
|
Demos
|
https://gradio.app/docs/gradio/uploadbutton
|
Gradio - Uploadbutton 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 UploadButton component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`UploadButton.click(fn, ···)` | Triggered when the UploadButton is clicked.
`UploadButton.upload(fn, ···)` | This listener is triggered when the user uploads a file into the UploadButton.
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 d
|
Event Listeners
|
https://gradio.app/docs/gradio/uploadbutton
|
Gradio - Uploadbutton Docs
|
oint 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 length `max_batch_size`). The function is then
*required* to return a tuple of lists (even if there is only 1 output
component), wit
|
Event Listeners
|
https://gradio.app/docs/gradio/uploadbutton
|
Gradio - Uploadbutton Docs
|
r 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 should be a list of values
for output components.
concurrency_limit: int | None | Literal['default']
default `= "defau
|
Event Listeners
|
https://gradio.app/docs/gradio/uploadbutton
|
Gradio - Uploadbutton Docs
|
ments 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.
|
Event Listeners
|
https://gradio.app/docs/gradio/uploadbutton
|
Gradio - Uploadbutton Docs
|
Creates a button that can be assigned arbitrary .click() events. The value
(label) of the button can be used as an input to the function (rarely used) or
set via the output of a function.
|
Description
|
https://gradio.app/docs/gradio/button
|
Gradio - Button Docs
|
**As input component** : (Rarely used) the `str` corresponding to the
button label when the button is clicked
Your function should accept one of these types:
def predict(
value: str | None
)
...
**As output component** : string corresponding to the button label
Your function should return one of these types:
def predict(···) -> str | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/button
|
Gradio - Button Docs
|
Parameters ▼
value: str | I18nData | Callable
default `= "Run"`
default text for the button to display. If a function is provided, the
function will be called each time the app loads to set the initial value of
this component.
every: Timer | float | None
default `= None`
continuously 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', 'huggingface']
default `= "secondary"`
sets the background and text color of the button. Use 'primary' for main call-
to-action buttons, 'secondary' for a more subdued style, 'stop' for a stop
button, 'huggingface' for a black background with white text, consistent with
Hugging Face's button styles.
size: Literal['sm', 'md', 'lg']
default `= "lg"`
size of the button. Can be "sm", "md", or "lg".
icon: str | Path | None
default `= None`
URL or path to the icon file to display within the button. If None, no icon
will be displayed.
link: str | None
default `= None`
URL to open when the button is clicked. If None, no link will be used.
visible: bool
default `= True`
if False, component will be hidden.
interactive: bool
default `= True`
if False, the Button 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
|
Initialization
|
https://gradio.app/docs/gradio/button
|
Gradio - Button Docs
|
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.
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 value results in this Component being narrower than
min_width, the min_width parameter will be respected first.
|
Initialization
|
https://gradio.app/docs/gradio/button
|
Gradio - Button Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.Button` | "button" | Uses default values
`gradio.ClearButton` | "clearbutton" | Uses default values
`gradio.DeepLinkButton` | "deeplinkbutton" | Uses default values
`gradio.DuplicateButton` | "duplicatebutton" | Uses default values
`gradio.LoginButton` | "loginbutton" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/button
|
Gradio - Button 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 Button component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`Button.click(fn, ···)` | Triggered when the Button 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.
api_description: str |
|
Event Listeners
|
https://gradio.app/docs/gradio/button
|
Gradio - Button Docs
|
nt. 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 `= 4`
Maximum number o
|
Event Listeners
|
https://gradio.app/docs/gradio/button
|
Gradio - Button Docs
|
urn 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 None to mean no concurrency
|
Event Listeners
|
https://gradio.app/docs/gradio/button
|
Gradio - Button Docs
|
oncurrency_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.
|
Event Listeners
|
https://gradio.app/docs/gradio/button
|
Gradio - Button Docs
|
The render decorator allows Gradio Blocks apps to have dynamic layouts, so
that the components and event listeners in your app can change depending on
custom logic. Attaching a @gr.render decorator to a function will cause the
function to be re-run whenever the inputs are changed (or specified triggers
are activated). The function contains the components and event listeners that
will update based on the inputs.
The basic usage of @gr.render is as follows:
1\. Create a function and attach the @gr.render decorator to it.
2\. Add the input components to the `inputs=` argument of @gr.render, and
create a corresponding argument in your function for each component.
3\. Add all components inside the function that you want to update based on
the inputs. Any event listeners that use these components should also be
inside this function.
|
Description
|
https://gradio.app/docs/gradio/render
|
Gradio - Render Docs
|
import gradio as gr
with gr.Blocks() as demo:
input_text = gr.Textbox()
@gr.render(inputs=input_text)
def show_split(text):
if len(text) == 0:
gr.Markdown("No Input Provided")
else:
for letter in text:
with gr.Row():
text = gr.Textbox(letter)
btn = gr.Button("Clear")
btn.click(lambda: gr.Textbox(value=""), None, text)
|
Example Usage
|
https://gradio.app/docs/gradio/render
|
Gradio - Render Docs
|
Parameters ▼
inputs: list[Component] | Component | None
default `= None`
List of gradio.components to use as inputs. If the function takes no inputs,
this should be an empty list.
triggers: list[EventListenerCallable] | EventListenerCallable | None
default `= None`
List of triggers to listen to, e.g. [btn.click, number.change]. If None, will
listen to changes to any inputs.
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.
trigger_mode: Literal['once', 'multiple', 'always_last'] | None
default `= "always_last"`
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.
concurrency_limit: int | None | Literal['default']
default `= None`
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_progress: Literal['full', 'minimal', 'hidden']
default `= "full"`
|
Initialization
|
https://gradio.app/docs/gradio/render
|
Gradio - Render Docs
|
Creates a dropdown of choices from which a single entry or multiple entries
can be selected (as an input component) or displayed (as an output component).
|
Description
|
https://gradio.app/docs/gradio/dropdown
|
Gradio - Dropdown Docs
|
**As input component** : Passes the value of the selected dropdown choice as a `str | int | float` or its index as an `int` into the function, depending on `type`. Or, if `multiselect` is True, passes the values of the selected dropdown choices as a list of corresponding values/indices instead.
Your function should accept one of these types:
def predict(
value: str | int | float | list[str | int | float] | list[int | None] | None
)
...
**As output component** : Expects a `str | int | float` corresponding to the value of the dropdown entry to be selected. Or, if `multiselect` is True, expects a `list` of values corresponding to the selected dropdown entries.
Your function should return one of these types:
def predict(···) -> str | int | float | list[str | int | float] | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/dropdown
|
Gradio - Dropdown Docs
|
Parameters ▼
choices: list[str | int | float | tuple[str, str | int | float]] | None
default `= None`
a list of string or numeric options to choose from. An option can also be a
tuple of the form (name, value), where name is the displayed name of the
dropdown choice and value is the value to be passed to the function, or
returned by the function.
value: str | int | float | list[str | int | float] | Callable | DefaultValue | None
default `= DefaultValue()`
the value selected in dropdown. If `multiselect` is true, this should be list,
otherwise a single string or number from among `choices`. By default, the
first choice in `choices` is initally selected. If set explicitly to None, no
value is initally selected. If a function is provided, the function will be
called each time the app loads to set the initial value of this component.
type: Literal['value', 'index']
default `= "value"`
type of value to be returned by component. "value" returns the string of the
choice selected, "index" returns the index of the choice selected.
multiselect: bool | None
default `= None`
if True, multiple choices can be selected.
allow_custom_value: bool
default `= False`
if True, allows user to enter a custom value that is not in the list of
choices.
max_choices: int | None
default `= None`
maximum number of choices that can be selected. If None, no limit is enforced.
filterable: bool
default `= True`
if True, user will be able to type into the dropdown and filter the choices by
typing. Can only be set to False if `allow_custom_value` is False.
label: str | I18nData | None
default `= None`
the label for this component, displayed above the component if `show_label` is
`True` 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 compon
|
Initialization
|
https://gradio.app/docs/gradio/dropdown
|
Gradio - Dropdown Docs
|
`show_label` is
`True` 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 corresponds to.
info: str | I18nData | None
default `= None`
additional component description, appears below the label in smaller font.
Supports markdown / HTML syntax.
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.
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.
interactive: bool | None
default `= None`
if True, choices in this dropdown will be selectable; if False, selection will
be disabled. If not provided, this is inferred based on whether the component
is used as an input or output.
|
Initialization
|
https://gradio.app/docs/gradio/dropdown
|
Gradio - Dropdown Docs
|
ne`
if True, choices in this dropdown will be selectable; if False, selection will
be disabled. If not provided, this is inferred based on whether the component
is used as an input or output.
visible: bool
default `= True`
if False, component will be hidden.
elem_id: str | None
default `= None`
an optional string that is assigned as the id of this component in the HTML
DOM. Can be used for targeting CSS styles.
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 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`
preserved_by_key: list[str] | str | None
default `= "value"`
|
Initialization
|
https://gradio.app/docs/gradio/dropdown
|
Gradio - Dropdown Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.Dropdown` | "dropdown" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/dropdown
|
Gradio - Dropdown Docs
|
sentence_builder
Open in 🎢 ↗ import gradio as gr def sentence_builder(quantity, animal,
countries, place, activity_list, morning): return f"""The {quantity} {animal}s
from {" and ".join(countries)} went to the {place} where they {" and
".join(activity_list)} until the {"morning" if morning else "night"}""" demo =
gr.Interface( sentence_builder, [ gr.Slider(2, 20, value=4, label="Count",
info="Choose between 2 and 20"), gr.Dropdown( ["cat", "dog", "bird"],
label="Animal", info="Will add more animals later!" ),
gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="Countries", info="Where
are they from?"), gr.Radio(["park", "zoo", "road"], label="Location",
info="Where did they go?"), gr.Dropdown( ["ran", "swam", "ate", "slept"],
value=["swam", "slept"], multiselect=True, label="Activity", info="Lorem ipsum
dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies
aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl." ),
gr.Checkbox(label="Morning", info="Did they do it in the morning?"), ],
"text", examples=[ [2, "cat", ["Japan", "Pakistan"], "park", ["ate", "swam"],
True], [4, "dog", ["Japan"], "zoo", ["ate", "swam"], False], [10, "bird",
["USA", "Pakistan"], "road", ["ran"], False], [8, "cat", ["Pakistan"], "zoo",
["ate"], True], ] ) if __name__ == "__main__": demo.launch()
import gradio as gr
def sentence_builder(quantity, animal, countries, place, activity_list, morning):
return f"""The {quantity} {animal}s from {" and ".join(countries)} went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""
demo = gr.Interface(
sentence_builder,
[
gr.Slider(2, 20, value=4, label="Count", info="Choose between 2 and 20"),
gr.Dropdown(
["cat", "dog", "bird"], label="Animal", info="Will add more animals later!"
),
gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="Countries",
|
Demos
|
https://gradio.app/docs/gradio/dropdown
|
Gradio - Dropdown Docs
|
gr.Dropdown(
["cat", "dog", "bird"], label="Animal", info="Will add more animals later!"
),
gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="Countries", info="Where are they from?"),
gr.Radio(["park", "zoo", "road"], label="Location", info="Where did they go?"),
gr.Dropdown(
["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True, label="Activity", info="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl."
),
gr.Checkbox(label="Morning", info="Did they do it in the morning?"),
],
"text",
examples=[
[2, "cat", ["Japan", "Pakistan"], "park", ["ate", "swam"], True],
[4, "dog", ["Japan"], "zoo", ["ate", "swam"], False],
[10, "bird", ["USA", "Pakistan"], "road", ["ran"], False],
[8, "cat", ["Pakistan"], "zoo", ["ate"], True],
]
)
if __name__ == "__main__":
demo.launch()
|
Demos
|
https://gradio.app/docs/gradio/dropdown
|
Gradio - Dropdown 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 Dropdown component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`Dropdown.change(fn, ···)` | Triggered when the value of the Dropdown 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.
`Dropdown.input(fn, ···)` | This listener is triggered when the user changes the value of the Dropdown.
`Dropdown.select(fn, ···)` | Event listener for when the user selects or deselects the Dropdown. Uses event data gradio.SelectData to carry `value` referring to the label of the Dropdown, and `selected` to refer to state of the Dropdown. See EventData documentation on how to use this event data
`Dropdown.focus(fn, ···)` | This listener is triggered when the Dropdown is focused.
`Dropdown.blur(fn, ···)` | This listener is triggered when the Dropdown is unfocused/blurred.
`Dropdown.key_up(fn, ···)` | This listener is triggered when the user presses a key while the Dropdown is focused.
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[Compone
|
Event Listeners
|
https://gradio.app/docs/gradio/dropdown
|
Gradio - Dropdown Docs
|
nd 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.
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: Com
|
Event Listeners
|
https://gradio.app/docs/gradio/dropdown
|
Gradio - Dropdown Docs
|
utput 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 `= 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,
|
Event Listeners
|
https://gradio.app/docs/gradio/dropdown
|
Gradio - Dropdown Docs
|
ick_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 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
|
Event Listeners
|
https://gradio.app/docs/gradio/dropdown
|
Gradio - Dropdown Docs
|
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.
|
Event Listeners
|
https://gradio.app/docs/gradio/dropdown
|
Gradio - Dropdown Docs
|
Set the static paths to be served by the gradio app.
Static files are are served directly from the file system instead of being
copied. They are served to users with The Content-Disposition HTTP header set
to "inline" when sending these files to users. This indicates that the file
should be displayed directly in the browser window if possible. This function
is useful when you want to serve files that you know will not be modified
during the lifetime of the gradio app (like files used in gr.Examples). By
setting static paths, your app will launch faster and it will consume less
disk space. Calling this function will set the static paths for all gradio
applications defined in the same interpreter session until it is called again
or the session ends.
|
Description
|
https://gradio.app/docs/gradio/set_static_paths
|
Gradio - Set_Static_Paths Docs
|
import gradio as gr
Paths can be a list of strings or pathlib.Path objects
corresponding to filenames or directories.
gr.set_static_paths(paths=["test/test_files/"])
The example files and the default value of the input
will not be copied to the gradio cache and will be served directly.
demo = gr.Interface(
lambda s: s.rotate(45),
gr.Image(value="test/test_files/cheetah1.jpg", type="pil"),
gr.Image(),
examples=["test/test_files/bus.png"],
)
demo.launch()
|
Example Usage
|
https://gradio.app/docs/gradio/set_static_paths
|
Gradio - Set_Static_Paths Docs
|
Parameters ▼
paths: str | Path | list[str | Path]
filepath or list of filepaths or directory names to be served by the gradio
app. If it is a directory name, ALL files located within that directory will
be considered static and not moved to the gradio cache. This also means that
ALL files in that directory will be accessible over the network.
|
Initialization
|
https://gradio.app/docs/gradio/set_static_paths
|
Gradio - Set_Static_Paths Docs
|
The gr.SelectData class is a subclass of gr.EventData that specifically
carries information about the `.select()` event. When gr.SelectData is added
as a type hint to an argument of an event listener method, a gr.SelectData
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/selectdata
|
Gradio - Selectdata Docs
|
import gradio as gr
with gr.Blocks() as demo:
table = gr.Dataframe([[1, 2, 3], [4, 5, 6]])
gallery = gr.Gallery([("cat.jpg", "Cat"), ("dog.jpg", "Dog")])
textbox = gr.Textbox("Hello World!")
statement = gr.Textbox()
def on_select(evt: gr.SelectData):
return f"You selected {evt.value} at {evt.index} from {evt.target}"
table.select(on_select, None, statement)
gallery.select(on_select, None, statement)
textbox.select(on_select, None, statement)
demo.launch()
|
Example Usage
|
https://gradio.app/docs/gradio/selectdata
|
Gradio - Selectdata Docs
|
Parameters ▼
index: int | tuple[int, int]
The index of the selected item. Is a tuple if the component is two dimensional
or selection is a range.
value: Any
The value of the selected item.
row_value: list[float | str]
The value of the entire row that the selected item belongs to, as a 1-D list.
Only implemented for the `Dataframe` component, returns None for other
components.
col_value: list[float | str]
The value of the entire column that the selected item belongs to, as a 1-D
list. Only implemented for the `Dataframe` component, returns None for other
components.
selected: bool
True if the item was selected, False if deselected.
|
Attributes
|
https://gradio.app/docs/gradio/selectdata
|
Gradio - Selectdata Docs
|
gallery_selectionstictactoe
Open in 🎢 ↗ import gradio as gr import numpy as np with gr.Blocks() as demo:
imgs = gr.State() gallery = gr.Gallery(allow_preview=False) def
deselect_images(): return gr.Gallery(selected_index=None) def
generate_images(): images = [] for _ in range(9): image = np.ones((100, 100,
3), dtype=np.uint8) * np.random.randint( 0, 255, 3 ) image is a solid single
color images.append(image) return images, images demo.load(generate_images,
None, [gallery, imgs]) with gr.Row(): selected = gr.Number(show_label=False)
darken_btn = gr.Button("Darken selected") deselect_button =
gr.Button("Deselect") deselect_button.click(deselect_images, None, gallery)
def get_select_index(evt: gr.SelectData): return evt.index
gallery.select(get_select_index, None, selected) def darken_img(imgs, index):
index = int(index) imgs[index] = np.round(imgs[index] * 0.8).astype(np.uint8)
return imgs, imgs darken_btn.click(darken_img, [imgs, selected], [imgs,
gallery]) if __name__ == "__main__": demo.launch()
import gradio as gr
import numpy as np
with gr.Blocks() as demo:
imgs = gr.State()
gallery = gr.Gallery(allow_preview=False)
def deselect_images():
return gr.Gallery(selected_index=None)
def generate_images():
images = []
for _ in range(9):
image = np.ones((100, 100, 3), dtype=np.uint8) * np.random.randint(
0, 255, 3
) image is a solid single color
images.append(image)
return images, images
demo.load(generate_images, None, [gallery, imgs])
with gr.Row():
selected = gr.Number(show_label=False)
darken_btn = gr.Button("Darken selected")
deselect_button = gr.Button("Deselect")
deselect_button.click(deselect_images, None, gallery)
def get_select_index(evt: gr.SelectData):
return evt.index
|
Demos
|
https://gradio.app/docs/gradio/selectdata
|
Gradio - Selectdata Docs
|
deselect_button = gr.Button("Deselect")
deselect_button.click(deselect_images, None, gallery)
def get_select_index(evt: gr.SelectData):
return evt.index
gallery.select(get_select_index, None, selected)
def darken_img(imgs, index):
index = int(index)
imgs[index] = np.round(imgs[index] * 0.8).astype(np.uint8)
return imgs, imgs
darken_btn.click(darken_img, [imgs, selected], [imgs, gallery])
if __name__ == "__main__":
demo.launch()
Open in 🎢 ↗ import gradio as gr with gr.Blocks() as demo: turn =
gr.Textbox("X", interactive=False, label="Turn") board =
gr.Dataframe(value=[["", "", ""]] * 3, interactive=False, type="array") def
place(board: list[list[int]], turn, evt: gr.SelectData): if evt.value: return
board, turn board[evt.index[0]][evt.index[1]] = turn turn = "O" if turn == "X"
else "X" return board, turn board.select(place, [board, turn], [board, turn],
show_progress="hidden") if __name__ == "__main__": demo.launch()
import gradio as gr
with gr.Blocks() as demo:
turn = gr.Textbox("X", interactive=False, label="Turn")
board = gr.Dataframe(value=[["", "", ""]] * 3, interactive=False, type="array")
def place(board: list[list[int]], turn, evt: gr.SelectData):
if evt.value:
return board, turn
board[evt.index[0]][evt.index[1]] = turn
turn = "O" if turn == "X" else "X"
return board, turn
board.select(place, [board, turn], [board, turn], show_progress="hidden")
if __name__ == "__main__":
demo.launch()
|
Demos
|
https://gradio.app/docs/gradio/selectdata
|
Gradio - Selectdata Docs
|
Creates a slider that ranges from `minimum` to `maximum` with a step size
of `step`.
|
Description
|
https://gradio.app/docs/gradio/slider
|
Gradio - Slider Docs
|
**As input component** : Passes slider value as a `float` into the
function.
Your function should accept one of these types:
def predict(
value: float
)
...
**As output component** : Expects an `int` or `float` returned from
function and sets slider value to it as long as it is within range (otherwise,
sets to minimum value).
Your function should return one of these types:
def predict(···) -> float | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/slider
|
Gradio - Slider Docs
|
Parameters ▼
minimum: float
default `= 0`
minimum value for slider. When used as an input, if a user provides a smaller
value, a gr.Error exception is raised by the backend.
maximum: float
default `= 100`
maximum value for slider. When used as an input, if a user provides a larger
value, a gr.Error exception is raised by the backend.
value: float | Callable | None
default `= None`
default value for slider. If a function is provided, the function will be
called each time the app loads to set the initial value of this component.
Ignored if randomized=True.
step: float | None
default `= None`
increment between slider values.
precision: int | None
default `= None`
Precision to round input/output to. If set to 0, will round to nearest integer
and convert type to int. If None, no rounding happens.
label: str | I18nData | None
default `= None`
the label for this component, displayed above the component if `show_label` is
`True` 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 corresponds to.
info: str | I18nData | None
default `= None`
additional component description, appears below the label in smaller font.
Supports markdown / HTML syntax.
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.
show_label: bool | None
default `= None`
if
|
Initialization
|
https://gradio.app/docs/gradio/slider
|
Gradio - Slider Docs
|
sed 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 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 | None
default `= None`
if True, slider will be adjustable; if False, adjusting will be disabled. If
not provided, this is inferred based on whether the component is used as an
input or output.
visible: bool
default `= True`
If False, component will be hidden.
elem_id: str | None
default `= None`
An optional string that is assigned as the id of this component in the HTML
DOM. Can be used for targeting CSS styles.
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 ke
|
Initialization
|
https://gradio.app/docs/gradio/slider
|
Gradio - Slider Docs
|
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.
randomize: bool
default `= False`
If True, the value of the slider when the app loads is taken uniformly at
random from the range given by the minimum and maximum.
show_reset_button: bool
default `= True`
if False, will hide button to reset slider to default value.
|
Initialization
|
https://gradio.app/docs/gradio/slider
|
Gradio - Slider Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.Slider` | "slider" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/slider
|
Gradio - Slider Docs
|
sentence_builderslider_releaseinterface_random_sliderblocks_random_slider
Open in 🎢 ↗ import gradio as gr def sentence_builder(quantity, animal,
countries, place, activity_list, morning): return f"""The {quantity} {animal}s
from {" and ".join(countries)} went to the {place} where they {" and
".join(activity_list)} until the {"morning" if morning else "night"}""" demo =
gr.Interface( sentence_builder, [ gr.Slider(2, 20, value=4, label="Count",
info="Choose between 2 and 20"), gr.Dropdown( ["cat", "dog", "bird"],
label="Animal", info="Will add more animals later!" ),
gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="Countries", info="Where
are they from?"), gr.Radio(["park", "zoo", "road"], label="Location",
info="Where did they go?"), gr.Dropdown( ["ran", "swam", "ate", "slept"],
value=["swam", "slept"], multiselect=True, label="Activity", info="Lorem ipsum
dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies
aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl." ),
gr.Checkbox(label="Morning", info="Did they do it in the morning?"), ],
"text", examples=[ [2, "cat", ["Japan", "Pakistan"], "park", ["ate", "swam"],
True], [4, "dog", ["Japan"], "zoo", ["ate", "swam"], False], [10, "bird",
["USA", "Pakistan"], "road", ["ran"], False], [8, "cat", ["Pakistan"], "zoo",
["ate"], True], ] ) if __name__ == "__main__": demo.launch()
import gradio as gr
def sentence_builder(quantity, animal, countries, place, activity_list, morning):
return f"""The {quantity} {animal}s from {" and ".join(countries)} went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""
demo = gr.Interface(
sentence_builder,
[
gr.Slider(2, 20, value=4, label="Count", info="Choose between 2 and 20"),
gr.Dropdown(
["cat", "dog", "bird"], label="Animal", info="Will add more animals later!"
),
gr.Checkb
|
Demos
|
https://gradio.app/docs/gradio/slider
|
Gradio - Slider Docs
|
abel="Count", info="Choose between 2 and 20"),
gr.Dropdown(
["cat", "dog", "bird"], label="Animal", info="Will add more animals later!"
),
gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="Countries", info="Where are they from?"),
gr.Radio(["park", "zoo", "road"], label="Location", info="Where did they go?"),
gr.Dropdown(
["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True, label="Activity", info="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl."
),
gr.Checkbox(label="Morning", info="Did they do it in the morning?"),
],
"text",
examples=[
[2, "cat", ["Japan", "Pakistan"], "park", ["ate", "swam"], True],
[4, "dog", ["Japan"], "zoo", ["ate", "swam"], False],
[10, "bird", ["USA", "Pakistan"], "road", ["ran"], False],
[8, "cat", ["Pakistan"], "zoo", ["ate"], True],
]
)
if __name__ == "__main__":
demo.launch()
Open in 🎢 ↗ import gradio as gr def identity(x, state): state += 1 return x,
state, state with gr.Blocks() as demo: slider = gr.Slider(0, 100, step=0.1)
state = gr.State(value=0) with gr.Row(): number = gr.Number(label="On
release") number2 = gr.Number(label="Number of events fired")
slider.release(identity, inputs=[slider, state], outputs=[number, state,
number2], api_name="predict") if __name__ == "__main__": print("here")
demo.launch() print(demo.server_port)
import gradio as gr
def identity(x, state):
state += 1
return x, state, state
with gr.Blocks() as demo:
slider = gr.Slider(0, 100, step=0.1)
state = gr.State(value=0)
with gr.Row():
number = gr.Number(label="On release")
number2 = gr.Number(label="Number o
|
Demos
|
https://gradio.app/docs/gradio/slider
|
Gradio - Slider Docs
|
slider = gr.Slider(0, 100, step=0.1)
state = gr.State(value=0)
with gr.Row():
number = gr.Number(label="On release")
number2 = gr.Number(label="Number of events fired")
slider.release(identity, inputs=[slider, state], outputs=[number, state, number2], api_name="predict")
if __name__ == "__main__":
print("here")
demo.launch()
print(demo.server_port)
Open in 🎢 ↗ import gradio as gr def func(slider_1, slider_2, *args): return
slider_1 + slider_2 * 5 demo = gr.Interface( func, [ gr.Slider(minimum=1.5,
maximum=250000.89, randomize=True, label="Random Big Range"),
gr.Slider(minimum=-1, maximum=1, randomize=True, step=0.05, label="Random only
multiple of 0.05 allowed"), gr.Slider(minimum=0, maximum=1, randomize=True,
step=0.25, label="Random only multiples of 0.25 allowed"),
gr.Slider(minimum=-100, maximum=100, randomize=True, step=3, label="Random
between -100 and 100 step 3"), gr.Slider(minimum=-100, maximum=100,
randomize=True, label="Random between -100 and 100"), gr.Slider(value=0.25,
minimum=5, maximum=30, step=-1), ], "number", ) if __name__ == "__main__":
demo.launch()
import gradio as gr
def func(slider_1, slider_2, *args):
return slider_1 + slider_2 * 5
demo = gr.Interface(
func,
[
gr.Slider(minimum=1.5, maximum=250000.89, randomize=True, label="Random Big Range"),
gr.Slider(minimum=-1, maximum=1, randomize=True, step=0.05, label="Random only multiple of 0.05 allowed"),
gr.Slider(minimum=0, maximum=1, randomize=True, step=0.25, label="Random only multiples of 0.25 allowed"),
gr.Slider(minimum=-100, maximum=100, randomize=True, step=3, label="Random between -100 and 100 step 3"),
gr.Slider(minimum=-100, maximum=100, randomize=True, label="Random between -100 and 100"),
gr.Slider(value=0.25, minimum=5, maximum=30, step=-1),
],
|
Demos
|
https://gradio.app/docs/gradio/slider
|
Gradio - Slider Docs
|
d 100 step 3"),
gr.Slider(minimum=-100, maximum=100, randomize=True, label="Random between -100 and 100"),
gr.Slider(value=0.25, minimum=5, maximum=30, step=-1),
],
"number",
)
if __name__ == "__main__":
demo.launch()
Open in 🎢 ↗ import gradio as gr def func(slider_1, slider_2): return slider_1
* 5 + slider_2 with gr.Blocks() as demo: slider = gr.Slider(minimum=-10.2,
maximum=15, label="Random Slider (Static)", randomize=True) slider_1 =
gr.Slider(minimum=100, maximum=200, label="Random Slider (Input 1)",
randomize=True) slider_2 = gr.Slider(minimum=10, maximum=23.2, label="Random
Slider (Input 2)", randomize=True) slider_3 = gr.Slider(value=3, label="Non
random slider") btn = gr.Button("Run") btn.click(func, inputs=[slider_1,
slider_2], outputs=gr.Number()) if __name__ == "__main__": demo.launch()
import gradio as gr
def func(slider_1, slider_2):
return slider_1 * 5 + slider_2
with gr.Blocks() as demo:
slider = gr.Slider(minimum=-10.2, maximum=15, label="Random Slider (Static)", randomize=True)
slider_1 = gr.Slider(minimum=100, maximum=200, label="Random Slider (Input 1)", randomize=True)
slider_2 = gr.Slider(minimum=10, maximum=23.2, label="Random Slider (Input 2)", randomize=True)
slider_3 = gr.Slider(value=3, label="Non random slider")
btn = gr.Button("Run")
btn.click(func, inputs=[slider_1, slider_2], outputs=gr.Number())
if __name__ == "__main__":
demo.launch()
|
Demos
|
https://gradio.app/docs/gradio/slider
|
Gradio - Slider 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 Slider component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`Slider.change(fn, ···)` | Triggered when the value of the Slider 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.
`Slider.input(fn, ···)` | This listener is triggered when the user changes the value of the Slider.
`Slider.release(fn, ···)` | This listener is triggered when the user releases the mouse on this Slider.
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 `=
|
Event Listeners
|
https://gradio.app/docs/gradio/slider
|
Gradio - Slider Docs
|
one
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 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`
|
Event Listeners
|
https://gradio.app/docs/gradio/slider
|
Gradio - Slider Docs
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.