text
stringlengths 0
2k
| heading1
stringlengths 4
79
| source_page_url
stringclasses 180
values | source_page_title
stringclasses 180
values |
|---|---|---|---|
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/simpleimage
|
Gradio - Simpleimage Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.SimpleImage` | "simpleimage" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/simpleimage
|
Gradio - Simpleimage 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 SimpleImage component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`SimpleImage.clear(fn, ···)` | This listener is triggered when the user clears the SimpleImage using the clear button for the component.
`SimpleImage.change(fn, ···)` | Triggered when the value of the SimpleImage 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.
`SimpleImage.upload(fn, ···)` | This listener is triggered when the user uploads a file into the SimpleImage.
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.
|
Event Listeners
|
https://gradio.app/docs/gradio/simpleimage
|
Gradio - Simpleimage Docs
|
ponent | 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 queue setting of the
|
Event Listeners
|
https://gradio.app/docs/gradio/simpleimage
|
Gradio - Simpleimage Docs
|
rue, 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 allow a second subm
|
Event Listeners
|
https://gradio.app/docs/gradio/simpleimage
|
Gradio - Simpleimage Docs
|
bmissions 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.
validator: Callable | None
default `= None`
Optional validation funct
|
Event Listeners
|
https://gradio.app/docs/gradio/simpleimage
|
Gradio - Simpleimage Docs
|
n @gr.render(). If set, this
value identifies an event as identical across re-renders when the key is
identical.
validator: Callable | None
default `= None`
Optional validation function to run before the main function. If provided,
this function will be executed first with queue=False, and only if it
completes successfully will the main function be called. The validator
receives the same inputs as the main function and should return a
`gr.validate()` for each input value.
|
Event Listeners
|
https://gradio.app/docs/gradio/simpleimage
|
Gradio - Simpleimage Docs
|
A Gradio Interface includes a ‘Flag’ button that appears underneath the
output. By default, clicking on the Flag button sends the input and output
data back to the machine where the gradio demo is running, and saves it to a
CSV log file. But this default behavior can be changed. To set what happens
when the Flag button is clicked, you pass an instance of a subclass of
_FlaggingCallback_ to the _flagging_callback_ parameter in the _Interface_
constructor. You can use one of the _FlaggingCallback_ subclasses that are
listed below, or you can create your own, which lets you do whatever you want
with the data that is being flagged.
SimpleCSVLogger
gradio.SimpleCSVLogger(···)
|
Description
|
https://gradio.app/docs/gradio/flagging
|
Gradio - Flagging Docs
|
A simplified implementation of the FlaggingCallback abstract class provided
for illustrative purposes. Each flagged sample (both the input and output
data) is logged to a CSV file on the machine running the gradio app.
|
Description
|
https://gradio.app/docs/gradio/flagging
|
Gradio - Flagging Docs
|
import gradio as gr
def image_classifier(inp):
return {'cat': 0.3, 'dog': 0.7}
demo = gr.Interface(fn=image_classifier, inputs="image", outputs="label",
flagging_callback=SimpleCSVLogger())
CSVLogger
gradio.CSVLogger(···)
|
Example Usage
|
https://gradio.app/docs/gradio/flagging
|
Gradio - Flagging Docs
|
The default implementation of the FlaggingCallback abstract class in
gradio>=5.0. Each flagged sample (both the input and output data) is logged to
a CSV file with headers on the machine running the gradio app. Unlike
ClassicCSVLogger, this implementation is concurrent-safe and it creates a new
dataset file every time the headers of the CSV (derived from the labels of the
components) change. It also only creates columns for "username" and "flag" if
the flag_option and username are provided, respectively.
|
Description
|
https://gradio.app/docs/gradio/flagging
|
Gradio - Flagging Docs
|
import gradio as gr
def image_classifier(inp):
return {'cat': 0.3, 'dog': 0.7}
demo = gr.Interface(fn=image_classifier, inputs="image", outputs="label",
flagging_callback=CSVLogger())
|
Example Usage
|
https://gradio.app/docs/gradio/flagging
|
Gradio - Flagging Docs
|
Parameters ▼
simplify_file_data: bool
default `= True`
If True, the file data will be simplified before being written to the CSV
file. If CSVLogger is being used to cache examples, this is set to False to
preserve the original FileData class
verbose: bool
default `= True`
If True, prints messages to the console about the dataset file creation
dataset_file_name: str | None
default `= None`
The name of the dataset file to be created (should end in ".csv"). If None,
the dataset file will be named "dataset1.csv" or the next available number.
|
Initialization
|
https://gradio.app/docs/gradio/flagging
|
Gradio - Flagging Docs
|
Used to render arbitrary Markdown output. Can also render latex enclosed by
dollar signs as well as code blocks with syntax highlighting. Supported
languages are bash, c, cpp, go, java, javascript, json, php, python, rust,
sql, and yaml. As this component does not accept user input, it is rarely used
as an input component.
|
Description
|
https://gradio.app/docs/gradio/markdown
|
Gradio - Markdown Docs
|
**As input component** : Passes the `str` of Markdown corresponding to the
displayed value.
Your function should accept one of these types:
def predict(
value: str | None
)
...
**As output component** : Expects a valid `str` that can be rendered as
Markdown.
Your function should return one of these types:
def predict(···) -> str | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/markdown
|
Gradio - Markdown Docs
|
Parameters ▼
value: str | I18nData | Callable | None
default `= None`
Value to show in Markdown component. If a function is provided, the function
will be called each time the app loads to set the initial value of this
component.
label: str | I18nData | None
default `= None`
This parameter has no effect
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`
This parameter has no effect.
rtl: bool
default `= False`
If True, sets the direction of the rendered text to right-to-left. Default is
False, which renders text left-to-right.
latex_delimiters: list[dict[str, str | bool]] | None
default `= None`
A list of dicts of the form {"left": open delimiter (str), "right": close
delimiter (str), "display": whether to display in newline (bool)} that will be
used to render LaTeX expressions. If not provided, `latex_delimiters` is set
to `[{ "left": "$$", "right": "$$", "display": True }]`, so only expressions
enclosed in $$ delimiters will be rendered as LaTeX, and in a new line. Pass
in an empty list to disable LaTeX rendering. For more information, see the
[KaTeX documentation](https://katex.org/docs/autorender.html).
visible: bool | Literal['hidden']
default `= True`
If False, component will be hidden. If "hidden", component will be visually
hidden and not take up space in the layout but still exist in the DOM
elem_id: str | None
default `= None
|
Initialization
|
https://gradio.app/docs/gradio/markdown
|
Gradio - Markdown Docs
|
If False, component will be hidden. If "hidden", component will be visually
hidden and not take up space in the layout but still exist in the DOM
elem_id: str | None
default `= None`
An optional string that is assigned as the id of this component in the HTML
DOM. Can be used for targeting CSS styles.
elem_classes: list[str] | str | None
default `= None`
An optional list of strings that are assigned as the classes of this component
in the HTML DOM. Can be used for targeting CSS styles.
render: bool
default `= True`
If False, component will not render be rendered in the Blocks context. Should
be used if the intention is to assign event listeners now but render the
component later.
key: int | str | tuple[int | str, ...] | None
default `= None`
in a gr.render, Components with the same key across re-renders are treated as
the same component, not a new component. Properties set in 'preserved_by_key'
are not reset across a re-render.
preserved_by_key: list[str] | str | None
default `= "value"`
A list of parameters from this component's constructor. Inside a gr.render()
function, if a component is re-rendered with the same key, these (and only
these) parameters will be preserved in the UI (if they have been changed by
the user or an event listener) instead of re-rendered based on the values
provided during constructor.
sanitize_html: bool
default `= True`
If False, will disable HTML sanitization when converted from markdown. This is
not recommended, as it can lead to security vulnerabilities.
line_breaks: bool
default `= False`
If True, will enable Github-flavored Markdown line breaks in chatbot messages.
If False (default), single new lines will be ignored.
header_links: bool
default `= False`
If True, will automatically create anchors for headings, displaying a link
icon on hover.
height: int | str | None
defaul
|
Initialization
|
https://gradio.app/docs/gradio/markdown
|
Gradio - Markdown Docs
|
nored.
header_links: bool
default `= False`
If True, will automatically create anchors for headings, displaying a link
icon on hover.
height: int | str | None
default `= None`
The height of the component, specified in pixels if a number is passed, or in
CSS units if a string is passed. If markdown content exceeds the height, the
component will scroll.
max_height: int | str | None
default `= None`
The maximum height of the component, specified in pixels if a number is
passed, or in CSS units if a string is passed. If markdown content exceeds the
height, the component will scroll. If markdown content is shorter than the
height, the component 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 component, specified in pixels if a number is
passed, or in CSS units if a string is passed. If markdown content exceeds the
height, the component will expand to fit the content. Will not have any effect
if `height` is set and is larger than `min_height`.
show_copy_button: bool
default `= False`
If True, includes a copy button to copy the text in the Markdown component.
Default is False.
container: bool
default `= False`
If True, the Markdown component will be displayed in a container. Default is
False.
padding: bool
default `= False`
If True, the Markdown component will have a certain padding (set by the
`--block-padding` CSS variable) in all directions. Default is False.
|
Initialization
|
https://gradio.app/docs/gradio/markdown
|
Gradio - Markdown Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.Markdown` | "markdown" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/markdown
|
Gradio - Markdown Docs
|
blocks_helloblocks_kinematics
Open in 🎢 ↗ import gradio as gr def welcome(name): return f"Welcome to Gradio,
{name}!" with gr.Blocks() as demo: gr.Markdown( """ Hello World! Start
typing below to see the output. """) inp = gr.Textbox(placeholder="What is
your name?") out = gr.Textbox() inp.change(welcome, inp, out) if __name__ ==
"__main__": demo.launch()
import gradio as gr
def welcome(name):
return f"Welcome to Gradio, {name}!"
with gr.Blocks() as demo:
gr.Markdown(
"""
Hello World!
Start typing below to see the output.
""")
inp = gr.Textbox(placeholder="What is your name?")
out = gr.Textbox()
inp.change(welcome, inp, out)
if __name__ == "__main__":
demo.launch()
Open in 🎢 ↗ import pandas as pd import numpy as np import gradio as gr def
plot(v, a): g = 9.81 theta = a / 180 * 3.14 tmax = ((2 * v) * np.sin(theta)) /
g timemat = tmax * np.linspace(0, 1, 40) x = (v * timemat) * np.cos(theta) y =
((v * timemat) * np.sin(theta)) - ((0.5 * g) * (timemat**2)) df =
pd.DataFrame({"x": x, "y": y}) return df demo = gr.Blocks() with demo:
gr.Markdown( r"Let's do some kinematics! Choose the speed and angle to see the
trajectory. Remember that the range $R = v_0^2 \cdot \frac{\sin(2\theta)}{g}$"
) with gr.Row(): speed = gr.Slider(1, 30, 25, label="Speed") angle =
gr.Slider(0, 90, 45, label="Angle") output = gr.LinePlot( x="x", y="y",
overlay_point=True, tooltip=["x", "y"], x_lim=[0, 100], y_lim=[0, 60],
width=350, height=300, ) btn = gr.Button(value="Run") btn.click(plot, [speed,
angle], output) if __name__ == "__main__": demo.launch()
import pandas as pd
import numpy as np
import gradio as gr
def plot(v, a):
g = 9.81
theta = a / 180 * 3.14
tmax = ((2 * v) * np.sin(theta)) / g
timemat = tmax * np.linspace(0, 1, 40)
x = (v * timemat) * np.cos(theta)
y =
|
Demos
|
https://gradio.app/docs/gradio/markdown
|
Gradio - Markdown Docs
|
g = 9.81
theta = a / 180 * 3.14
tmax = ((2 * v) * np.sin(theta)) / g
timemat = tmax * np.linspace(0, 1, 40)
x = (v * timemat) * np.cos(theta)
y = ((v * timemat) * np.sin(theta)) - ((0.5 * g) * (timemat**2))
df = pd.DataFrame({"x": x, "y": y})
return df
demo = gr.Blocks()
with demo:
gr.Markdown(
r"Let's do some kinematics! Choose the speed and angle to see the trajectory. Remember that the range $R = v_0^2 \cdot \frac{\sin(2\theta)}{g}$"
)
with gr.Row():
speed = gr.Slider(1, 30, 25, label="Speed")
angle = gr.Slider(0, 90, 45, label="Angle")
output = gr.LinePlot(
x="x",
y="y",
overlay_point=True,
tooltip=["x", "y"],
x_lim=[0, 100],
y_lim=[0, 60],
width=350,
height=300,
)
btn = gr.Button(value="Run")
btn.click(plot, [speed, angle], output)
if __name__ == "__main__":
demo.launch()
|
Demos
|
https://gradio.app/docs/gradio/markdown
|
Gradio - Markdown 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 Markdown component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`Markdown.change(fn, ···)` | Triggered when the value of the Markdown 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.
`Markdown.copy(fn, ···)` | This listener is triggered when the user copies content from the Markdown. Uses event data gradio.CopyData to carry information about the copied content. See EventData documentation on how to use this event data
Event Parameters
Parameters ▼
fn: Callable | None | Literal['decorator']
default `= "decorator"`
the function to call when this event is triggered. Often a machine learning
model's prediction function. Each parameter of the function corresponds to one
input component, and the function should return a single value or a tuple of
values, with each element in the tuple corresponding to one output component.
inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as inputs. If the function takes no inputs,
this should be an empty list.
outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as outputs. If the function returns no
outputs, this should be an empty list.
api_name: s
|
Event Listeners
|
https://gradio.app/docs/gradio/markdown
|
Gradio - Markdown Docs
|
xt] | 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 queue setting of the gradio app.
|
Event Listeners
|
https://gradio.app/docs/gradio/markdown
|
Gradio - Markdown Docs
|
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 allow a second submission after the
pe
|
Event Listeners
|
https://gradio.app/docs/gradio/markdown
|
Gradio - Markdown Docs
|
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.
validator: Callable | None
default `= None`
Optional validation function to run before t
|
Event Listeners
|
https://gradio.app/docs/gradio/markdown
|
Gradio - Markdown Docs
|
set, this
value identifies an event as identical across re-renders when the key is
identical.
validator: Callable | None
default `= None`
Optional validation function to run before the main function. If provided,
this function will be executed first with queue=False, and only if it
completes successfully will the main function be called. The validator
receives the same inputs as the main function and should return a
`gr.validate()` for each input value.
|
Event Listeners
|
https://gradio.app/docs/gradio/markdown
|
Gradio - Markdown Docs
|
Creates a textarea for user to enter string input or display string output.
|
Description
|
https://gradio.app/docs/gradio/textbox
|
Gradio - Textbox Docs
|
**As input component** : Passes text value as a `str` into the function.
Your function should accept one of these types:
def predict(
value: str | None
)
...
**As output component** : Expects a `str` returned from function and sets
textarea value to it.
Your function should return one of these types:
def predict(···) -> str | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/textbox
|
Gradio - Textbox Docs
|
Parameters ▼
value: str | I18nData | Callable | None
default `= None`
text to show in textbox. 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['text', 'password', 'email']
default `= "text"`
The type of textbox. One of: 'text' (which allows users to enter any text),
'password' (which masks text entered by the user), 'email' (which suggests
email input to the browser). For "password" and "email" types, `lines` must be
1 and `max_lines` must be None or 1.
lines: int
default `= 1`
minimum number of line rows to provide in textarea.
max_lines: int | None
default `= None`
maximum number of line rows to provide in textarea. Must be at least `lines`.
If not provided, the maximum number of lines is max(lines, 20) for "text"
type, and 1 for "password" and "email" types.
placeholder: str | I18nData | None
default `= None`
placeholder hint to provide behind textarea.
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`
|
Initialization
|
https://gradio.app/docs/gradio/textbox
|
Gradio - Textbox Docs
|
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 the label. If False, the copy button is hidden as well
as well as the 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, will be rendered as an editable textbox; if False, editing will be
disabled. If not provided, this is inferred based on whether the component is
used as an input or output.
visible: bool | Literal['hidden']
default `= True`
If False, component will be hidden. If "hidden", component will be visually
hidden and not take up space in the layout but still exist in the DOM
elem_id: str | None
default `= None`
An optional string that is assigned as the id of this component in the HTML
DOM. Can be used for targeting CSS styles.
autofocus: bool
default `= False`
If True, will focus on the textbox when the page loads. Use this carefully, as
it can cause usability issues for sighted and no
|
Initialization
|
https://gradio.app/docs/gradio/textbox
|
Gradio - Textbox Docs
|
argeting CSS styles.
autofocus: bool
default `= False`
If True, will focus on the textbox when the page loads. Use this carefully, as
it can cause usability issues for sighted and non-sighted users.
autoscroll: bool
default `= True`
If True, will automatically scroll to the bottom of the textbox when the value
changes, unless the user scrolls up. If False, will not scroll to the bottom
of the textbox when the value changes.
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.
text_align: Literal['left', 'right'] | None
default `= None`
How to align the text in the textbox, can be: "left", "right", or None
(default). If None, the alignment is left if `rtl` is False, or right if `rtl`
is True. Can only be changed if `type` is "text".
rtl: bool
default `= False`
If True and `type` is "text", sets the direction of the text to right-to-left
(cursor appears on the left of
|
Initialization
|
https://gradio.app/docs/gradio/textbox
|
Gradio - Textbox Docs
|
rue. Can only be changed if `type` is "text".
rtl: bool
default `= False`
If True and `type` is "text", sets the direction of the text to right-to-left
(cursor appears on the left of the text). Default is False, which renders
cursor on the right.
show_copy_button: bool
default `= False`
If True, includes a copy button to copy the text in the textbox. Only applies
if show_label is True.
max_length: int | None
default `= None`
maximum number of characters (including newlines) allowed in the textbox. If
None, there is no maximum length.
submit_btn: str | bool | None
default `= False`
If False, will not show a submit button. If True, will show a submit button
with an icon. If a string, will use that string as the submit button text.
When the submit button is shown, the border of the textbox will be removed,
which is useful for creating a chat interface.
stop_btn: str | bool | None
default `= False`
If False, will not show a stop button. If True, will show a stop button with
an icon. If a string, will use that string as the stop button text. When the
stop button is shown, the border of the textbox will be removed, which is
useful for creating a chat interface.
html_attributes: InputHTMLAttributes | None
default `= None`
An instance of gr.InputHTMLAttributes, which can be used to set HTML
attributes for the input/textarea elements. Example:
InputHTMLAttributes(autocorrect="off", spellcheck=False) to disable
autocorrect and spellcheck.
|
Initialization
|
https://gradio.app/docs/gradio/textbox
|
Gradio - Textbox Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.Textbox` | "textbox" | Uses default values
`gradio.TextArea` | "textarea" | Uses lines=7
|
Shortcuts
|
https://gradio.app/docs/gradio/textbox
|
Gradio - Textbox Docs
|
hello_worlddiff_textssentence_builder
Open in 🎢 ↗ import gradio as gr def greet(name): return "Hello " + name + "!"
demo = gr.Interface(fn=greet, inputs="textbox", outputs="textbox") if __name__
== "__main__": demo.launch()
import gradio as gr
def greet(name):
return "Hello " + name + "!"
demo = gr.Interface(fn=greet, inputs="textbox", outputs="textbox")
if __name__ == "__main__":
demo.launch()
Open in 🎢 ↗ from difflib import Differ import gradio as gr def
diff_texts(text1, text2): d = Differ() return [ (token[2:], token[0] if
token[0] != " " else None) for token in d.compare(text1, text2) ] demo =
gr.Interface( diff_texts, [ gr.Textbox( label="Text 1", info="Initial text",
lines=3, value="The quick brown fox jumped over the lazy dogs.", ),
gr.Textbox( label="Text 2", info="Text to compare", lines=3, value="The fast
brown fox jumps over lazy dogs.", ), ], gr.HighlightedText( label="Diff",
combine_adjacent=True, show_legend=True, color_map={"+": "red", "-":
"green"}), theme=gr.themes.Base() ) if __name__ == "__main__": demo.launch()
from difflib import Differ
import gradio as gr
def diff_texts(text1, text2):
d = Differ()
return [
(token[2:], token[0] if token[0] != " " else None)
for token in d.compare(text1, text2)
]
demo = gr.Interface(
diff_texts,
[
gr.Textbox(
label="Text 1",
info="Initial text",
lines=3,
value="The quick brown fox jumped over the lazy dogs.",
),
gr.Textbox(
label="Text 2",
info="Text to compare",
lines=3,
value="The fast brown fox jumps over lazy dogs.",
),
],
gr.HighlightedText(
label="Diff",
combine_adjacent=True,
show_legend=True,
|
Demos
|
https://gradio.app/docs/gradio/textbox
|
Gradio - Textbox Docs
|
value="The fast brown fox jumps over lazy dogs.",
),
],
gr.HighlightedText(
label="Diff",
combine_adjacent=True,
show_legend=True,
color_map={"+": "red", "-": "green"}),
theme=gr.themes.Base()
)
if __name__ == "__main__":
demo.launch()
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(
|
Demos
|
https://gradio.app/docs/gradio/textbox
|
Gradio - Textbox Docs
|
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()
|
Demos
|
https://gradio.app/docs/gradio/textbox
|
Gradio - Textbox 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 Textbox component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`Textbox.change(fn, ···)` | Triggered when the value of the Textbox 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.
`Textbox.input(fn, ···)` | This listener is triggered when the user changes the value of the Textbox.
`Textbox.select(fn, ···)` | Event listener for when the user selects or deselects the Textbox. Uses event data gradio.SelectData to carry `value` referring to the label of the Textbox, and `selected` to refer to state of the Textbox. See EventData documentation on how to use this event data
`Textbox.submit(fn, ···)` | This listener is triggered when the user presses the Enter key while the Textbox is focused.
`Textbox.focus(fn, ···)` | This listener is triggered when the Textbox is focused.
`Textbox.blur(fn, ···)` | This listener is triggered when the Textbox is unfocused/blurred.
`Textbox.stop(fn, ···)` | This listener is triggered when the user reaches the end of the media playing in the Textbox.
`Textbox.copy(fn, ···)` | This listener is triggered when the user copies content from the Textbox. Uses event data gradio.CopyData to carry information about the copied content. See EventData documentation on how to use this event data
Event Parameters
Parameters ▼
fn: Callable | None | Literal['decorator']
default `= "decorator"`
the function to cal
|
Event Listeners
|
https://gradio.app/docs/gradio/textbox
|
Gradio - Textbox Docs
|
EventData documentation on how to use this event data
Event Parameters
Parameters ▼
fn: Callable | None | Literal['decorator']
default `= "decorator"`
the function to call when this event is triggered. Often a machine learning
model's prediction function. Each parameter of the function corresponds to one
input component, and the function should return a single value or a tuple of
values, with each element in the tuple corresponding to one output component.
inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as inputs. If the function takes no inputs,
this should be an empty list.
outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as outputs. If the function returns no
outputs, this should be an empty list.
api_name: str | None | Literal[False]
default `= None`
defines how the endpoint appears in the API docs. Can be a string, None, or
False. If set to a string, the endpoint will be exposed in the API docs with
the given name. If None (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: Lite
|
Event Listeners
|
https://gradio.app/docs/gradio/textbox
|
Gradio - Textbox Docs
|
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 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
|
Event Listeners
|
https://gradio.app/docs/gradio/textbox
|
Gradio - Textbox Docs
|
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_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 thi
|
Event Listeners
|
https://gradio.app/docs/gradio/textbox
|
Gradio - Textbox Docs
|
this is the id of the concurrency group. Events with the same
concurrency_id will be limited by the lowest set concurrency_limit.
show_api: bool
default `= True`
whether to show this event in the "view API" page of the Gradio app, or in the
".view_api()" method of the Gradio clients. Unlike setting api_name to False,
setting show_api to False will still allow downstream apps as well as the
Clients to use this event. If fn is None, show_api will automatically be set
to False.
time_limit: int | None
default `= None`
stream_every: float
default `= 0.5`
like_user_message: bool
default `= False`
key: int | str | tuple[int | str, ...] | None
default `= None`
A unique key for this event listener to be used in @gr.render(). If set, this
value identifies an event as identical across re-renders when the key is
identical.
validator: Callable | None
default `= None`
Optional validation function to run before the main function. If provided,
this function will be executed first with queue=False, and only if it
completes successfully will the main function be called. The validator
receives the same inputs as the main function and should return a
`gr.validate()` for each input value.
|
Event Listeners
|
https://gradio.app/docs/gradio/textbox
|
Gradio - Textbox Docs
|
Creates a video component that can be used to upload/record videos (as an
input) or display videos (as an output). For the video to be playable in the
browser it must have a compatible container and codec combination. Allowed
combinations are .mp4 with h264 codec, .ogg with theora codec, and .webm with
vp9 codec. If the component detects that the output video would not be
playable in the browser it will attempt to convert it to a playable mp4 video.
If the conversion fails, the original video is returned.
|
Description
|
https://gradio.app/docs/gradio/video
|
Gradio - Video Docs
|
**As input component** : Passes the uploaded video as a `str` filepath or
URL whose extension can be modified by `format`.
Your function should accept one of these types:
def predict(
value: str | None
)
...
**As output component** : Expects a `str` or `pathlib.Path` filepath to a video which is displayed, or a `Tuple[str | pathlib.Path, str | pathlib.Path | None]` where the first element is a filepath to a video and the second element is an optional filepath to a subtitle file.
Your function should return one of these types:
def predict(···) -> str | Path | tuple[str | Path, str | Path | None] | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/video
|
Gradio - Video Docs
|
Parameters ▼
value: str | Path | tuple[str | Path, str | Path | None] | Callable | None
default `= None`
path or URL for the default value that Video component is going to take. Can
also be a tuple consisting of (video filepath, subtitle filepath). If a
subtitle file is provided, it should be of type .srt or .vtt. Or can be
callable, in which case the function will be called whenever the app loads to
set the initial value of the component.
format: str | None
default `= None`
the file extension with which to save video, such as 'avi' or 'mp4'. This
parameter applies both when this component is used as an input to determine
which file format to convert user-provided video to, and when this component
is used as an output to determine the format of video returned to the user. If
None, no file format conversion is done and the video is kept as is. Use 'mp4'
to ensure browser playability.
sources: list[Literal['upload', 'webcam']] | Literal['upload', 'webcam'] | None
default `= None`
list of sources permitted for video. "upload" creates a box where user can
drop a video file, "webcam" allows user to record a video from their webcam.
If None, defaults to both ["upload, "webcam"].
height: int | str | None
default `= None`
The height of the component, specified in pixels if a number is passed, or in
CSS units if a string is passed. This has no effect on the preprocessed video
file, but will affect the displayed video.
width: int | str | None
default `= None`
The width of the component, specified in pixels if a number is passed, or in
CSS units if a string is passed. This has no effect on the preprocessed video
file, but will affect the displayed video.
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.Interf
|
Initialization
|
https://gradio.app/docs/gradio/video
|
Gradio - Video Docs
|
| 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_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, will allow users to upload a video; if False, can only be used to
display videos. If not provided, this is inferred based on whether the
component is used as an input or output.
visible: bool | Literal['hidden']
default `= True`
If False, component will be hidden. If "hidden",
|
Initialization
|
https://gradio.app/docs/gradio/video
|
Gradio - Video Docs
|
d, this is inferred based on whether the
component is used as an input or output.
visible: bool | Literal['hidden']
default `= True`
If False, component will be hidden. If "hidden", component will be visually
hidden and not take up space in the layout but still exist in the DOM
elem_id: str | None
default `= None`
an optional string that is assigned as the id of this component in the HTML
DOM. Can be used for targeting CSS styles.
elem_classes: list[str] | str | None
default `= None`
an optional list of strings that are assigned as the classes of this component
in the HTML DOM. Can be used for targeting CSS styles.
render: bool
default `= True`
if False, component will not render be rendered in the Blocks context. Should
be used if the intention is to assign event listeners now but render the
component later.
key: int | str | tuple[int | str, ...] | None
default `= None`
in a gr.render, Components with the same key across re-renders are treated as
the same component, not a new component. Properties set in 'preserved_by_key'
are not reset across a re-render.
preserved_by_key: list[str] | str | None
default `= "value"`
A list of parameters from this component's constructor. Inside a gr.render()
function, if a component is re-rendered with the same key, these (and only
these) parameters will be preserved in the UI (if they have been changed by
the user or an event listener) instead of re-rendered based on the values
provided during constructor.
mirror_webcam: bool | None
default `= None`
webcam_options: WebcamOptions | None
default `= None`
A `gr.WebcamOptions` instance that allows developers to specify custom media
constraints for the webcam stream. This parameter provides flexibility to
control the video stream's properties, such as resolution and front or rear
camera on mobile devices. See
[demo/webcam_constraints](https://gr
|
Initialization
|
https://gradio.app/docs/gradio/video
|
Gradio - Video Docs
|
the webcam stream. This parameter provides flexibility to
control the video stream's properties, such as resolution and front or rear
camera on mobile devices. See
[demo/webcam_constraints](https://gradio.app/playground?demo=Blank&code=aW1wb3J0IGdyYWRpbyBhcyBncgppbXBvcnQgY3YyICAjIHR5cGU6IGlnbm9yZQoKZGVmIGdldF92aWRlb19zaGFwZSh2aWRlbyk6CiAgICBjYXAgPSBjdjIuVmlkZW9DYXB0dXJlKHZpZGVvKQogICAgd2lkdGggPSBpbnQoY2FwLmdldChjdjIuQ0FQX1BST1BfRlJBTUVfV0lEVEgpKQogICAgaGVpZ2h0ID0gaW50KGNhcC5nZXQoY3YyLkNBUF9QUk9QX0ZSQU1FX0hFSUdIVCkpCiAgICBjYXAucmVsZWFzZSgpCiAgICByZXR1cm4geyJ3aWR0aCI6IHdpZHRoLCAiaGVpZ2h0IjogaGVpZ2h0fQoKZGVmIGltYWdlX21vZChpbWFnZSk6CiAgICB3aWR0aCwgaGVpZ2h0ID0gaW1hZ2Uuc2l6ZQogICAgcmV0dXJuIHsid2lkdGgiOiB3aWR0aCwgImhlaWdodCI6IGhlaWdodH0KCgp2aWRlbyA9IGdyLkludGVyZmFjZSgKICAgIGZuPWdldF92aWRlb19zaGFwZSwKICAgIGlucHV0cz1nci5WaWRlbyh3ZWJjYW1fY29uc3RyYWludHM9eyJ2aWRlbyI6IHsid2lkdGgiOiA4MDAsICJoZWlnaHQiOiA2MDB9fSwgc291cmNlcz0id2ViY2FtIiksCiAgICBvdXRwdXRzPWdyLkpTT04oKQopCgppbWFnZSA9IGdyLkludGVyZmFjZSgKICAgICAgICBpbWFnZV9tb2QsCiAgICAgICAgZ3IuSW1hZ2UodHlwZT0icGlsIiwgd2ViY2FtX2NvbnN0cmFpbnRzPXsidmlkZW8iOiB7IndpZHRoIjogODAwLCAiaGVpZ2h0IjogNjAwfX0sIHNvdXJjZXM9IndlYmNhbSIpLAogICAgICAgIGdyLkpzb24oKSkKCndpdGggZ3IuQmxvY2tzKCkgYXMgZGVtbzoKICAgIGdyLk1hcmtkb3duKCIiIiMgV2ViY2FtIENvbnN0cmFpbnRzCiAgICAgICAgICAgICAgICBUaGUgd2ViY2FtIGNvbnN0cmFpbnRzIGFyZSBzZXQgdG8gODAweDYwMCB3aXRoIHRoZSBmb2xsb3dpbmcgc3ludGF4OgogICAgICAgICAgICAgICAgYGBgcHl0aG9uCiAgICAgICAgICAgICAgICBnci5WaWRlbyh3ZWJjYW1fY29uc3RyYWludHM9eyJ2aWRlbyI6IHsid2lkdGgiOiA4MDAsICJoZWlnaHQiOiA2MDB9fSwgc291cmNlcz0id2ViY2FtIikKICAgICAgICAgICAgICAgIGBgYAogICAgICAgICAgICAgICAgIiIiKQogICAgd2l0aCBnci5UYWJzKCk6CiAgICAgICAgd2l0aCBnci5UYWIoIlZpZGVvIik6CiAgICAgICAgICAgIHZpZGVvLnJlbmRlcigpCiAgICAgICAgd2l0aCBnci5UYWIoIkltYWdlIik6CiAgICAgICAgICAgIGltYWdlLnJlbmRlcigpCgppZiBfX25hbWVfXyA9PSAiX19tYWluX18iOgogICAgZGVtby5sYXVuY2goKQ%3D%3D&reqs=b3BlbmN2LXB5dGhvbg%3D%3D)
include_audio: bool | None
default `= None`
whether the component should recor
|
Initialization
|
https://gradio.app/docs/gradio/video
|
Gradio - Video Docs
|
cigpCgppZiBfX25hbWVfXyA9PSAiX19tYWluX18iOgogICAgZGVtby5sYXVuY2goKQ%3D%3D&reqs=b3BlbmN2LXB5dGhvbg%3D%3D)
include_audio: bool | None
default `= None`
whether the component should record/retain the audio track for a video. By
default, audio is excluded for webcam videos and included for uploaded videos.
autoplay: bool
default `= False`
whether to automatically play the video when the component is used as an
output. Note: browsers will not autoplay video files if the user has not
interacted with the page yet.
show_share_button: bool | None
default `= None`
if True, will show a share icon in the corner of the component that allows
user to share outputs to Hugging Face Spaces Discussions. If False, icon does
not appear. If set to None (default behavior), then the icon appears if this
Gradio app is launched on Spaces, but not otherwise.
show_download_button: bool | None
default `= None`
if True, will show a download icon in the corner of the component that allows
user to download the output. If False, icon does not appear. By default, it
will be True for output components and False for input components.
min_length: int | None
default `= None`
the minimum length of video (in seconds) that the user can pass into the
prediction function. If None, there is no minimum length.
max_length: int | None
default `= None`
the maximum length of video (in seconds) that the user can pass into the
prediction function. If None, there is no maximum length.
loop: bool
default `= False`
if True, the video will loop when it reaches the end and continue playing from
the beginning.
streaming: bool
default `= False`
when used set as an output, takes video chunks yielded from the backend and
combines them into one streaming video output. Each chunk should be a video
file with a .ts extension using an h.264 encoding. Mp4 files are also accepted
but they wil
|
Initialization
|
https://gradio.app/docs/gradio/video
|
Gradio - Video Docs
|
nks yielded from the backend and
combines them into one streaming video output. Each chunk should be a video
file with a .ts extension using an h.264 encoding. Mp4 files are also accepted
but they will be converted to h.264 encoding.
watermark: WatermarkOptions | None
default `= None`
A `gr.WatermarkOptions` instance that includes an image file and position to
be used as a watermark on the video. The image is not scaled and is displayed
on the provided position on the video. Valid formats for the image are: jpeg,
png.
webcam_constraints: dict[str, Any] | None
default `= None`
|
Initialization
|
https://gradio.app/docs/gradio/video
|
Gradio - Video Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.Video` | "video" | Uses default values
`gradio.PlayableVideo` | "playablevideo" | Uses format="mp4"
|
Shortcuts
|
https://gradio.app/docs/gradio/video
|
Gradio - Video Docs
|
video_identity_2
Open in 🎢 ↗ import gradio as gr def video_identity(video): return video demo =
gr.Interface(video_identity, gr.Video(), "playable_video", ) if __name__ ==
"__main__": demo.launch()
import gradio as gr
def video_identity(video):
return video
demo = gr.Interface(video_identity,
gr.Video(),
"playable_video",
)
if __name__ == "__main__":
demo.launch()
|
Demos
|
https://gradio.app/docs/gradio/video
|
Gradio - Video 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 Video component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`Video.change(fn, ···)` | Triggered when the value of the Video 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.
`Video.clear(fn, ···)` | This listener is triggered when the user clears the Video using the clear button for the component.
`Video.start_recording(fn, ···)` | This listener is triggered when the user starts recording with the Video.
`Video.stop_recording(fn, ···)` | This listener is triggered when the user stops recording with the Video.
`Video.stop(fn, ···)` | This listener is triggered when the user reaches the end of the media playing in the Video.
`Video.play(fn, ···)` | This listener is triggered when the user plays the media in the Video.
`Video.pause(fn, ···)` | This listener is triggered when the media in the Video stops for any reason.
`Video.end(fn, ···)` | This listener is triggered when the user reaches the end of the media playing in the Video.
`Video.upload(fn, ···)` | This listener is triggered when the user uploads a file into the Video.
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
|
Event Listeners
|
https://gradio.app/docs/gradio/video
|
Gradio - Video Docs
|
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 | 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 a
|
Event Listeners
|
https://gradio.app/docs/gradio/video
|
Gradio - Video Docs
|
w_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 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 cli
|
Event Listeners
|
https://gradio.app/docs/gradio/video
|
Gradio - Video Docs
|
ancels: 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_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 dow
|
Event Listeners
|
https://gradio.app/docs/gradio/video
|
Gradio - Video Docs
|
ther to show this event in the "view API" page of the Gradio app, or in the
".view_api()" method of the Gradio clients. Unlike setting api_name to False,
setting show_api to False will still allow downstream apps as well as the
Clients to use this event. If fn is None, show_api will automatically be set
to False.
time_limit: int | None
default `= None`
stream_every: float
default `= 0.5`
like_user_message: bool
default `= False`
key: int | str | tuple[int | str, ...] | None
default `= None`
A unique key for this event listener to be used in @gr.render(). If set, this
value identifies an event as identical across re-renders when the key is
identical.
validator: Callable | None
default `= None`
Optional validation function to run before the main function. If provided,
this function will be executed first with queue=False, and only if it
completes successfully will the main function be called. The validator
receives the same inputs as the main function and should return a
`gr.validate()` for each input value.
|
Event Listeners
|
https://gradio.app/docs/gradio/video
|
Gradio - Video Docs
|
Helper Classes
|
https://gradio.app/docs/gradio/video
|
Gradio - Video Docs
|
|
gradio.WebcamOptions(···)
Description
A dataclass for specifying options for the webcam tool in the ImageEditor
component. An instance of this class can be passed to the `webcam_options`
parameter of `gr.ImageEditor`.
Initialization
Parameters ▼
mirror: bool
default `= True`
If True, the webcam will be mirrored.
constraints: dict[str, Any] | None
default `= None`
A dictionary of constraints for the webcam.
|
Webcam Options
|
https://gradio.app/docs/gradio/video
|
Gradio - Video Docs
|
This function allows you to pass custom warning messages to the user. You
can do so simply by writing `gr.Warning('message here')` in your function, and
when that line is executed the custom message will appear in a modal on the
demo. The modal is yellow by default and has the heading: "Warning." Queue
must be enabled for this behavior; otherwise, the warning will be printed to
the console using the `warnings` library.
|
Description
|
https://gradio.app/docs/gradio/warning
|
Gradio - Warning Docs
|
import gradio as gr
def hello_world():
gr.Warning('This is a warning message.')
return "hello world"
with gr.Blocks() as demo:
md = gr.Markdown()
demo.load(hello_world, inputs=None, outputs=[md])
demo.queue().launch()
|
Example Usage
|
https://gradio.app/docs/gradio/warning
|
Gradio - Warning Docs
|
Parameters ▼
message: str
default `= "Warning issued."`
The warning message to be displayed to the user. Can be HTML, which will be
rendered in the modal.
duration: float | None
default `= 10`
The duration in seconds that the warning message should be displayed for. If
None or 0, the message will be displayed indefinitely until the user closes
it.
visible: bool
default `= True`
Whether the error message should be displayed in the UI.
title: str
default `= "Warning"`
The title to be displayed to the user at the top of the modal.
|
Initialization
|
https://gradio.app/docs/gradio/warning
|
Gradio - Warning Docs
|
blocks_chained_events
Open in 🎢 ↗ import gradio as gr def failure(): raise gr.Error("This should
fail!") def exception(): raise ValueError("Something went wrong") def
success(): return True def warning_fn(): gr.Warning("This is a warning!") def
info_fn(): gr.Info("This is some info") with gr.Blocks() as demo:
gr.Markdown("Used in E2E tests of success event trigger. The then event
covered in chatbot E2E tests." " Also testing that the status modals show
up.") with gr.Row(): result = gr.Textbox(label="Result") result_2 =
gr.Textbox(label="Consecutive Event") result_failure =
gr.Textbox(label="Failure Event") with gr.Row(): success_btn =
gr.Button(value="Trigger Success") success_btn_2 = gr.Button(value="Trigger
Consecutive Success") failure_btn = gr.Button(value="Trigger Failure")
failure_exception = gr.Button(value="Trigger Failure With ValueError") with
gr.Row(): trigger_warning = gr.Button(value="Trigger Warning") trigger_info =
gr.Button(value="Trigger Info") success_btn_2.click(success, None,
None).success(lambda: "First Event Trigered", None, result).success(lambda:
"Consecutive Event Triggered", None, result_2) success_event =
success_btn.click(success, None, None) success_event.success(lambda: "Success
event triggered", inputs=None, outputs=result) success_event.failure(lambda:
"Should not be triggered", inputs=None, outputs=result_failure) failure_event
= failure_btn.click(failure, None, None) failure_event.success(lambda: "Should
not be triggered", inputs=None, outputs=result) failure_event.failure(lambda:
"Failure event triggered", inputs=None, outputs=result_failure)
failure_exception.click(exception, None, None)
trigger_warning.click(warning_fn, None, None) trigger_info.click(info_fn,
None, None) if __name__ == "__main__": demo.launch(show_error=True)
import gradio as gr
def failure():
raise gr.Error("This should fail!")
def exception():
raise ValueError("Something went wrong")
def success():
|
Demos
|
https://gradio.app/docs/gradio/warning
|
Gradio - Warning Docs
|
import gradio as gr
def failure():
raise gr.Error("This should fail!")
def exception():
raise ValueError("Something went wrong")
def success():
return True
def warning_fn():
gr.Warning("This is a warning!")
def info_fn():
gr.Info("This is some info")
with gr.Blocks() as demo:
gr.Markdown("Used in E2E tests of success event trigger. The then event covered in chatbot E2E tests."
" Also testing that the status modals show up.")
with gr.Row():
result = gr.Textbox(label="Result")
result_2 = gr.Textbox(label="Consecutive Event")
result_failure = gr.Textbox(label="Failure Event")
with gr.Row():
success_btn = gr.Button(value="Trigger Success")
success_btn_2 = gr.Button(value="Trigger Consecutive Success")
failure_btn = gr.Button(value="Trigger Failure")
failure_exception = gr.Button(value="Trigger Failure With ValueError")
with gr.Row():
trigger_warning = gr.Button(value="Trigger Warning")
trigger_info = gr.Button(value="Trigger Info")
success_btn_2.click(success, None, None).success(lambda: "First Event Trigered", None, result).success(lambda: "Consecutive Event Triggered", None, result_2)
success_event = success_btn.click(success, None, None)
success_event.success(lambda: "Success event triggered", inputs=None, outputs=result)
success_event.failure(lambda: "Should not be triggered", inputs=None, outputs=result_failure)
failure_event = failure_btn.click(failure, None, None)
failure_event.success(lambda: "Should not be triggered", inputs=None, outputs=result)
failure_event.failure(lambda: "Failure event triggered", inputs=None, outputs=result_failure)
failure_exception.click(exception, None, None)
trigger
|
Demos
|
https://gradio.app/docs/gradio/warning
|
Gradio - Warning Docs
|
outputs=result)
failure_event.failure(lambda: "Failure event triggered", inputs=None, outputs=result_failure)
failure_exception.click(exception, None, None)
trigger_warning.click(warning_fn, None, None)
trigger_info.click(info_fn, None, None)
if __name__ == "__main__":
demo.launch(show_error=True)
|
Demos
|
https://gradio.app/docs/gradio/warning
|
Gradio - Warning Docs
|
Creates a chatbot that displays user-submitted messages and responses.
Supports a subset of Markdown including bold, italics, code, tables. Also
supports audio/video/image files, which are displayed in the Chatbot, and
other kinds of files which are displayed as links. This component is usually
used as an output component.
|
Description
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
The data format accepted by the Chatbot is dictated by the `type` parameter.
This parameter can take two values, `'tuples'` and `'messages'`. The
`'tuples'` type is deprecated and will be removed in a future version of
Gradio.
|
Behavior
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
If the `type` is `'messages'`, then the data sent to/from the chatbot will be
a list of dictionaries with `role` and `content` keys. This format is
compliant with the format expected by most LLM APIs (HuggingChat, OpenAI,
Claude). The `role` key is either `'user'` or `'assistant'` and the `content`
key can be one of the following should be a string (rendered as markdown/html)
or a Gradio component (useful for displaying files).
As an example:
import gradio as gr
history = [
{"role": "assistant", "content": "I am happy to provide you that report and plot."},
{"role": "assistant", "content": gr.Plot(value=make_plot_from_file('quaterly_sales.txt'))}
]
with gr.Blocks() as demo:
gr.Chatbot(history, type="messages")
demo.launch()
For convenience, you can use the `ChatMessage` dataclass so that your text
editor can give you autocomplete hints and typechecks.
import gradio as gr
history = [
gr.ChatMessage(role="assistant", content="How can I help you?"),
gr.ChatMessage(role="user", content="Can you make me a plot of quarterly sales?"),
gr.ChatMessage(role="assistant", content="I am happy to provide you that report and plot.")
]
with gr.Blocks() as demo:
gr.Chatbot(history, type="messages")
demo.launch()
|
Message format
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
Parameters ▼
value: list[MessageDict | Message] | TupleFormat | Callable | None
default `= None`
Default list of messages to show in chatbot, where each message is of the
format {"role": "user", "content": "Help me."}. Role can be one of "user",
"assistant", or "system". Content should be either text, or media passed as a
Gradio component, e.g. {"content": gr.Image("lion.jpg")}. 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['messages', 'tuples'] | None
default `= None`
The format of the messages passed into the chat history parameter of `fn`. If "messages", passes the value 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 Image, Plot, Video, Gallery, Audio, HTML, and Model3D 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', expects 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, but this format is deprecated.
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.
|
Initialization
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
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.
visible: bool | Literal['hidden']
default `= True`
If False, component will be hidden. If "hidden", component will be visually
hidden and not take up space in the layout but still exist in the DOM
elem_id: str | None
default `= None`
An optional string that is assigned as the id of this component in the HTML
DOM. Can be used for targeting CSS styles.
elem_classes: list[str] | str | None
default `= None`
An optional list of strings that are assigned as the classes of this component
in the HTML DOM. Can be used for targeting CSS styles.
autoscroll: bool
default `= True`
If True, will automatically scroll to the bottom of the textbox when the value
changes,
|
Initialization
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
onent
in the HTML DOM. Can be used for targeting CSS styles.
autoscroll: bool
default `= True`
If True, will automatically scroll to the bottom of the textbox when the value
changes, unless the user scrolls up. If False, will not scroll to the bottom
of the textbox when the value changes.
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.
height: int | str | None
default `= 400`
The height of the component, specified in pixels if a number is passed, or in
CSS units if a string is passed. If messages exceed the height, the component
will scroll.
resizable: bool
default `= False`
If True, the user of the Gradio app can resize the chatbot by dragging the
bottom right corner.
resizeable: bool
default `= False`
max_height: int | str | None
default `= None`
The maximum height of the component, specified in pixels if a number is
passed, or in CSS units if a string is passed. If messages exceed the height,
the component will scroll. If messages are shorter than the height, the
component will shrink to fit the content. Will not have any effect if `height`
is
|
Initialization
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
ring is passed. If messages exceed the height,
the component will scroll. If messages are shorter than the height, the
component 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 component, specified in pixels if a number is
passed, or in CSS units if a string is passed. If messages exceed the height,
the component will expand to fit the content. Will not have any effect if
`height` is set and is larger than `min_height`.
editable: Literal['user', 'all'] | None
default `= None`
Allows user to edit messages in the chatbot. If set to "user", allows editing
of user messages. If set to "all", allows editing of assistant messages as
well.
latex_delimiters: list[dict[str, str | bool]] | None
default `= None`
A list of dicts of the form {"left": open delimiter (str), "right": close
delimiter (str), "display": whether to display in newline (bool)} that will be
used to render LaTeX expressions. If not provided, `latex_delimiters` is set
to `[{ "left": "$$", "right": "$$", "display": True }]`, so only expressions
enclosed in $$ delimiters will be rendered as LaTeX, and in a new line. Pass
in an empty list to disable LaTeX rendering. For more information, see the
[KaTeX documentation](https://katex.org/docs/autorender.html).
rtl: bool
default `= False`
If True, sets the direction of the rendered text to right-to-left. Default is
False, which renders text left-to-right.
show_share_button: bool | None
default `= None`
If True, will show a share icon in the corner of the component that allows
user to share outputs to Hugging Face Spaces Discussions. If False, icon does
not appear. If set to None (default behavior), then the icon appears if this
Gradio app is launched on Spaces, but not otherwise.
show_copy_button: bool
default `= False`
If True
|
Initialization
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
oes
not appear. If set to None (default behavior), then the icon appears if this
Gradio app is launched on Spaces, but not otherwise.
show_copy_button: bool
default `= False`
If True, will show a copy button for each chatbot message.
watermark: str | None
default `= None`
If provided, this text will be appended to the end of messages copied from the
chatbot, after a blank line. Useful for indicating that the message is
generated by an AI model.
avatar_images: tuple[str | Path | None, str | Path | None] | None
default `= None`
Tuple of two avatar image paths or URLs for user and bot (in that order). Pass
None for either the user or bot image to skip. Must be within the working
directory of the Gradio app or an external URL.
sanitize_html: bool
default `= True`
If False, will disable HTML sanitization for chatbot messages. This is not
recommended, as it can lead to security vulnerabilities.
render_markdown: bool
default `= True`
If False, will disable Markdown rendering for chatbot messages.
feedback_options: list[str] | tuple[str, ...] | None
default `= ('Like', 'Dislike')`
A list of strings representing the feedback options that will be displayed to
the user. The exact case-sensitive strings "Like" and "Dislike" will render as
thumb icons, but any other choices will appear under a separate flag icon.
feedback_value: list[str | None] | None
default `= None`
A list of strings representing the feedback state for entire chat. Only works
when type="messages". Each entry in the list corresponds to that assistant
message, in order, and the value is the feedback given (e.g. "Like",
"Dislike", or any custom feedback option) or None if no feedback was given for
that message.
bubble_full_width: <class 'inspect._empty'>
default `= None`
Deprecated.
line_breaks: bool
default `= True`
If True (default), will enable Githu
|
Initialization
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
n for
that message.
bubble_full_width: <class 'inspect._empty'>
default `= None`
Deprecated.
line_breaks: bool
default `= True`
If True (default), will enable Github-flavored Markdown line breaks in chatbot
messages. If False, single new lines will be ignored. Only applies if
`render_markdown` is True.
layout: Literal['panel', 'bubble'] | None
default `= None`
If "panel", will display the chatbot in a llm style layout. If "bubble", will
display the chatbot with message bubbles, with the user and bot messages on
alterating sides. Will default to "bubble".
placeholder: str | None
default `= None`
a placeholder message to display in the chatbot when it is empty. Centered
vertically and horizontally in the Chatbot. Supports Markdown and HTML. If
None, no placeholder is displayed.
examples: list[ExampleMessage] | None
default `= None`
A list of example messages to display in the chatbot before any user/assistant
messages are shown. Each example should be a dictionary with an optional
"text" key representing the message that should be populated in the Chatbot
when clicked, an optional "files" key, whose value should be a list of files
to populate in the Chatbot, an optional "icon" key, whose value should be a
filepath or URL to an image to display in the example box, and an optional
"display_text" key, whose value should be the text to display in the example
box. If "display_text" is not provided, the value of "text" will be displayed.
show_copy_all_button: <class 'inspect._empty'>
default `= False`
If True, will show a copy all button that copies all chatbot messages to the
clipboard.
allow_file_downloads: <class 'inspect._empty'>
default `= True`
If True, will show a download button for chatbot messages that contain media.
Defaults to True.
group_consecutive_messages: bool
default `= True`
If True, will display consecutive messa
|
Initialization
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
True, will show a download button for chatbot messages that contain media.
Defaults to True.
group_consecutive_messages: bool
default `= True`
If True, will display consecutive messages from the same role in the same
bubble. If False, will display each message in a separate bubble. Defaults to
True.
allow_tags: list[str] | bool
default `= False`
If a list of tags is provided, these tags will be preserved in the output
chatbot messages, even if `sanitize_html` is `True`. For example, if this list
is ["thinking"], the tags `<thinking>` and `</thinking>` will not be removed.
If True, all custom tags (non-standard HTML tags) will be preserved. If False,
no tags will be preserved (default behavior).
|
Initialization
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.Chatbot` | "chatbot" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
**Displaying Thoughts/Tool Usage**
When `type` is `messages`, you can provide additional metadata regarding any
tools used to generate the response. This is useful for displaying the thought
process of LLM agents. For example,
def generate_response(history):
history.append(
ChatMessage(role="assistant",
content="The weather API says it is 20 degrees Celcius in New York.",
metadata={"title": "🛠️ Used tool Weather API"})
)
return history
Would be displayed as following:

You can also specify metadata with a plain python dictionary,
def generate_response(history):
history.append(
dict(role="assistant",
content="The weather API says it is 20 degrees Celcius in New York.",
metadata={"title": "🛠️ Used tool Weather API"})
)
return history
**Using Gradio Components Inside`gr.Chatbot`**
The `Chatbot` component supports using many of the core Gradio components
(such as `gr.Image`, `gr.Plot`, `gr.Audio`, and `gr.HTML`) inside of the
chatbot. Simply include one of these components in your list of tuples. Here’s
an example:
import gradio as gr
def load():
return [
("Here's an audio", gr.Audio("https://github.com/gradio-app/gradio/raw/main/gradio/media_assets/audio/audio_sample.wav")),
("Here's an video", gr.Video("https://github.com/gradio-app/gradio/raw/main/gradio/media_assets/videos/world.mp4"))
]
with gr.Blocks() as demo:
chatbot = gr.Chatbot()
button = gr.Button("Load audio and video")
button.click(load, None, chatbot)
demo.launch()
|
Examples
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
chatbot_simplechatbot_streamingchatbot_with_toolschatbot_core_components
Open in 🎢 ↗ import gradio as gr import random import time with gr.Blocks() as
demo: chatbot = gr.Chatbot(type="messages") msg = gr.Textbox() clear =
gr.ClearButton([msg, chatbot]) def respond(message, chat_history): bot_message
= random.choice(["How are you?", "Today is a great day", "I'm very hungry"])
chat_history.append({"role": "user", "content": message})
chat_history.append({"role": "assistant", "content": bot_message})
time.sleep(2) return "", chat_history msg.submit(respond, [msg, chatbot],
[msg, chatbot]) if __name__ == "__main__": demo.launch()
import gradio as gr
import random
import time
with gr.Blocks() as demo:
chatbot = gr.Chatbot(type="messages")
msg = gr.Textbox()
clear = gr.ClearButton([msg, chatbot])
def respond(message, chat_history):
bot_message = random.choice(["How are you?", "Today is a great day", "I'm very hungry"])
chat_history.append({"role": "user", "content": message})
chat_history.append({"role": "assistant", "content": bot_message})
time.sleep(2)
return "", chat_history
msg.submit(respond, [msg, chatbot], [msg, chatbot])
if __name__ == "__main__":
demo.launch()
Open in 🎢 ↗ import gradio as gr import random import time with gr.Blocks() as
demo: chatbot = gr.Chatbot(type="messages") msg = gr.Textbox() clear =
gr.Button("Clear") def user(user_message, history: list): return "", history +
[{"role": "user", "content": user_message}] def bot(history: list):
bot_message = random.choice(["How are you?", "I love you", "I'm very hungry"])
history.append({"role": "assistant", "content": ""}) for character in
bot_message: history[-1]['content'] += character time.sleep(0.05) yield
history msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
bot, chatbot, chatbot ) clear.click(lambda: None, N
|
Demos
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
bot_message: history[-1]['content'] += character time.sleep(0.05) yield
history msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
bot, chatbot, chatbot ) clear.click(lambda: None, None, chatbot, queue=False)
if __name__ == "__main__": demo.launch()
import gradio as gr
import random
import time
with gr.Blocks() as demo:
chatbot = gr.Chatbot(type="messages")
msg = gr.Textbox()
clear = gr.Button("Clear")
def user(user_message, history: list):
return "", history + [{"role": "user", "content": user_message}]
def bot(history: list):
bot_message = random.choice(["How are you?", "I love you", "I'm very hungry"])
history.append({"role": "assistant", "content": ""})
for character in bot_message:
history[-1]['content'] += character
time.sleep(0.05)
yield history
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
bot, chatbot, chatbot
)
clear.click(lambda: None, None, chatbot, queue=False)
if __name__ == "__main__":
demo.launch()
Open in 🎢 ↗ import gradio as gr from gradio import ChatMessage import time def
generate_response(history): history.append( ChatMessage( role="user",
content="What is the weather in San Francisco right now?" ) ) yield history
time.sleep(0.25) history.append( ChatMessage( role="assistant", content="In
order to find the current weather in San Francisco, I will need to use my
weather tool.", ) ) yield history time.sleep(0.25) history.append(
ChatMessage( role="assistant", content="API Error when connecting to weather
service.", metadata={"title": "💥 Error using tool 'Weather'"}, ) ) yield
history time.sleep(0.25) history.append( ChatMessage( role="assistant",
content="I will try again", ) ) yield history time.sleep(0.25) history.append(
ChatMessage( role="assistant", content="
|
Demos
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
) yield
history time.sleep(0.25) history.append( ChatMessage( role="assistant",
content="I will try again", ) ) yield history time.sleep(0.25) history.append(
ChatMessage( role="assistant", content="Weather 72 degrees Fahrenheit with 20%
chance of rain.", metadata={"title": "🛠️ Used tool 'Weather'"}, ) ) yield
history time.sleep(0.25) history.append( ChatMessage( role="assistant",
content="Now that the API succeeded I can complete my task.", ) ) yield
history time.sleep(0.25) history.append( ChatMessage( role="assistant",
content="It's a sunny day in San Francisco with a current temperature of 72
degrees Fahrenheit and a 20% chance of rain. Enjoy the weather!", ) ) yield
history def like(evt: gr.LikeData): print("User liked the response")
print(evt.index, evt.liked, evt.value) with gr.Blocks() as demo: chatbot =
gr.Chatbot(type="messages", height=500, show_copy_button=True) button =
gr.Button("Get San Francisco Weather") button.click(generate_response,
chatbot, chatbot) chatbot.like(like) if __name__ == "__main__": demo.launch()
import gradio as gr
from gradio import ChatMessage
import time
def generate_response(history):
history.append(
ChatMessage(
role="user", content="What is the weather in San Francisco right now?"
)
)
yield history
time.sleep(0.25)
history.append(
ChatMessage(
role="assistant",
content="In order to find the current weather in San Francisco, I will need to use my weather tool.",
)
)
yield history
time.sleep(0.25)
history.append(
ChatMessage(
role="assistant",
content="API Error when connecting to weather service.",
metadata={"title": "💥 Error using tool 'Weather'"},
)
)
yield history
time.sleep(0.25)
history.append(
ChatMes
|
Demos
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
r service.",
metadata={"title": "💥 Error using tool 'Weather'"},
)
)
yield history
time.sleep(0.25)
history.append(
ChatMessage(
role="assistant",
content="I will try again",
)
)
yield history
time.sleep(0.25)
history.append(
ChatMessage(
role="assistant",
content="Weather 72 degrees Fahrenheit with 20% chance of rain.",
metadata={"title": "🛠️ Used tool 'Weather'"},
)
)
yield history
time.sleep(0.25)
history.append(
ChatMessage(
role="assistant",
content="Now that the API succeeded I can complete my task.",
)
)
yield history
time.sleep(0.25)
history.append(
ChatMessage(
role="assistant",
content="It's a sunny day in San Francisco with a current temperature of 72 degrees Fahrenheit and a 20% chance of rain. Enjoy the weather!",
)
)
yield history
def like(evt: gr.LikeData):
print("User liked the response")
print(evt.index, evt.liked, evt.value)
with gr.Blocks() as demo:
chatbot = gr.Chatbot(type="messages", height=500, show_copy_button=True)
button = gr.Button("Get San Francisco Weather")
button.click(generate_response, chatbot, chatbot)
chatbot.like(like)
if __name__ == "__main__":
demo.launch()
Open in 🎢 ↗ import gradio as gr import os import plotly.express as px import
random Chatbot demo with multimodal input (text, markdown, LaTeX, code
blocks, image, audio, video, & model3d). Plus shows support for streaming
text. txt = """ Absolutely! The mycorrhizal network, often referred to as the
"Wood Wide Web," is a symbiotic association between fungi
|
Demos
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
age, audio, video, & model3d). Plus shows support for streaming
text. txt = """ Absolutely! The mycorrhizal network, often referred to as the
"Wood Wide Web," is a symbiotic association between fungi and the roots of
most plant species. Here’s a deeper dive into how it works and its
implications: How It Works 1\. **Symbiosis**: Mycorrhizal fungi attach to
plant roots, extending far into the soil. The plant provides the fungi with
carbohydrates produced via photosynthesis. In return, the fungi help the plant
absorb water and essential nutrients like phosphorus and nitrogen from the
soil. 2\. **Network Formation**: The fungal hyphae (thread-like structures)
connect individual plants, creating an extensive underground network. This
network can link many plants together, sometimes spanning entire forests. 3\.
**Communication**: Trees and plants use this network to communicate and share
resources. For example, a tree under attack by pests can send chemical signals
through the mycorrhizal network to warn neighboring trees. These trees can
then produce defensive chemicals to prepare for the impending threat.
Benefits and Functions 1\. **Resource Sharing**: The network allows for the
redistribution of resources among plants. For instance, a large, established
tree might share excess nutrients and water with smaller, younger trees,
promoting overall forest health. 2\. **Defense Mechanism**: The ability to
share information about pests and diseases enhances the resilience of plant
communities. This early warning system helps plants activate their defenses
before they are directly affected. 3\. **Support for Seedlings**: Young
seedlings, which have limited root systems, benefit immensely from the
mycorrhizal network. They receive nutrients and water from larger plants,
increasing their chances of survival and growth. Ecological Impact 1\.
**Biodiversity**: The mycorrhizal network supports biodiversity by fostering a
cooperative environment. Plants of different spec
|
Demos
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
reasing their chances of survival and growth. Ecological Impact 1\.
**Biodiversity**: The mycorrhizal network supports biodiversity by fostering a
cooperative environment. Plants of different species can coexist and thrive
because of the shared resources and information. 2\. **Forest Health**: The
network enhances the overall health of forests. By enabling efficient nutrient
cycling and supporting plant defenses, it contributes to the stability and
longevity of forest ecosystems. 3\. **Climate Change Mitigation**: Healthy
forests act as significant carbon sinks, absorbing carbon dioxide from the
atmosphere. The mycorrhizal network plays a critical role in maintaining
forest health and, consequently, in mitigating climate change. Research
and Discoveries 1\. **Suzanne Simard's Work**: Ecologist Suzanne Simard’s
research has been pivotal in uncovering the complexities of the mycorrhizal
network. She demonstrated that trees of different species can share resources
and that "mother trees" (large, older trees) play a crucial role in nurturing
younger plants. 2\. **Implications for Conservation**: Understanding the
mycorrhizal network has significant implications for conservation efforts. It
highlights the importance of preserving not just individual trees but entire
ecosystems, including the fungal networks that sustain them. Practical
Applications 1\. **Agriculture**: Farmers and horticulturists are exploring
the use of mycorrhizal fungi to improve crop yields and soil health. By
incorporating these fungi into agricultural practices, they can reduce the
need for chemical fertilizers and enhance plant resilience. 2\.
**Reforestation**: In reforestation projects, introducing mycorrhizal fungi
can accelerate the recovery of degraded lands. The fungi help establish
healthy plant communities, ensuring the success of newly planted trees. The
"Wood Wide Web" exemplifies the intricate and often hidden connections that
sustain life on Earth. It’s a reminder of the pr
|
Demos
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
healthy plant communities, ensuring the success of newly planted trees. The
"Wood Wide Web" exemplifies the intricate and often hidden connections that
sustain life on Earth. It’s a reminder of the profound interdependence within
natural systems and the importance of preserving these delicate relationships.
""" def random_plot(): df = px.data.iris() fig = px.scatter( df,
x="sepal_width", y="sepal_length", color="species", size="petal_length",
hover_data=["petal_width"], ) return fig color_map = { "harmful": "crimson",
"neutral": "gray", "beneficial": "green", } def html_src(harm_level): return
f""" <div style="display: flex; gap: 5px;"> <div style="background-color:
{color_map[harm_level]}; padding: 2px; border-radius: 5px;"> {harm_level}
</div> </div> """ def print_like_dislike(x: gr.LikeData): print(x.index,
x.value, x.liked) def random_bokeh_plot(): from bokeh.models import
ColumnDataSource, Whisker from bokeh.plotting import figure from
bokeh.sampledata.autompg2 import autompg2 as df from bokeh.transform import
factor_cmap, jitter classes = sorted(df["class"].unique()) p = figure(
height=400, x_range=classes, background_fill_color="efefef", title="Car class
vs HWY mpg with quintile ranges", ) p.xgrid.grid_line_color = None g =
df.groupby("class") upper = g.hwy.quantile(0.80) lower = g.hwy.quantile(0.20)
source = ColumnDataSource(data=dict(base=classes, upper=upper, lower=lower))
error = Whisker( base="base", upper="upper", lower="lower", source=source,
level="annotation", line_width=2, ) error.upper_head.size = 20
error.lower_head.size = 20 p.add_layout(error) p.circle( jitter("class", 0.3,
range=p.x_range), "hwy", source=df, alpha=0.5, size=13, line_color="white",
color=factor_cmap("class", "Light6", classes), ) return p get_file(),
get_image(), get_model3d(), get_video() return file paths to sample media
included with Gradio from gradio.media import get_file, get_image,
get_model3d, get_video def random_matplotlib_plot(): import numpy as np import
pandas as
|
Demos
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
et_video() return file paths to sample media
included with Gradio from gradio.media import get_file, get_image,
get_model3d, get_video def random_matplotlib_plot(): import numpy as np import
pandas as pd import matplotlib.pyplot as plt countries = ["USA", "Canada",
"Mexico", "UK"] months = ["January", "February", "March", "April", "May"] m =
months.index("January") r = 3.2 start_day = 30 * m final_day = 30 * (m + 1) x
= np.arange(start_day, final_day + 1) pop_count = {"USA": 350, "Canada": 40,
"Mexico": 300, "UK": 120} df = pd.DataFrame({"day": x}) for country in
countries: df[country] = x ** (r) * (pop_count[country] + 1) fig =
plt.figure() plt.plot(df["day"], df[countries].to_numpy()) plt.title("Outbreak
in " + "January") plt.ylabel("Cases") plt.xlabel("Days since Day 0")
plt.legend(countries) return fig def add_message(history, message): for x in
message["files"]: history.append({"role": "user", "content": {"path": x}}) if
message["text"] is not None: history.append({"role": "user", "content":
message["text"]}) return history, gr.MultimodalTextbox(value=None,
interactive=False) def bot(history, response_type): msg = {"role":
"assistant", "content": ""} if response_type == "plot": content =
gr.Plot(random_plot()) elif response_type == "bokeh_plot": content =
gr.Plot(random_bokeh_plot()) elif response_type == "matplotlib_plot": content
= gr.Plot(random_matplotlib_plot()) elif response_type == "gallery": content =
gr.Gallery( [get_image("avatar.png"), get_image("avatar.png")] ) elif
response_type == "dataframe": content = gr.Dataframe( interactive=True,
headers=["One", "Two", "Three"], col_count=(3, "fixed"), row_count=(3,
"fixed"), value=[[1, 2, 3], [4, 5, 6], [7, 8, 9]], label="Dataframe", ) elif
response_type == "image": content = gr.Image(get_image("avatar.png")) elif
response_type == "video": content = gr.Video(get_video("world.mp4")) elif
response_type == "audio": content = gr.Audio(os.path.join("files",
"audio.wav")) elif response_type == "audio_file": conten
|
Demos
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
if
response_type == "video": content = gr.Video(get_video("world.mp4")) elif
response_type == "audio": content = gr.Audio(os.path.join("files",
"audio.wav")) elif response_type == "audio_file": content = {"path":
os.path.join("files", "audio.wav"), "alt_text": "description"} elif
response_type == "image_file": content = {"path": get_image("avatar.png"),
"alt_text": "description"} elif response_type == "video_file": content =
{"path": get_video("world.mp4"), "alt_text": "description"} elif response_type
== "txt_file": content = {"path": get_file("sample.txt"), "alt_text":
"description"} elif response_type == "model3d_file": content = {"path":
get_model3d("Duck.glb"), "alt_text": "description"} elif response_type ==
"html": content = gr.HTML( html_src(random.choice(["harmful", "neutral",
"beneficial"])) ) elif response_type == "model3d": content =
gr.Model3D(get_model3d("Duck.glb")) else: content = txt msg["content"] =
content history.append(msg) return history fig = random_plot() with
gr.Blocks(fill_height=True) as demo: chatbot = gr.Chatbot( elem_id="chatbot",
type="messages", bubble_full_width=False, scale=1, show_copy_button=True,
avatar_images=( None, get_image("avatar.png"), ), ) response_type = gr.Radio(
[ "audio_file", "image_file", "video_file", "txt_file", "model3d_file",
"plot", "matplotlib_plot", "bokeh_plot", "image", "text", "gallery",
"dataframe", "video", "audio", "html", "model3d", ], value="text",
label="Response Type", ) chat_input = gr.MultimodalTextbox( interactive=True,
placeholder="Enter message or upload file...", show_label=False, ) chat_msg =
chat_input.submit( add_message, [chatbot, chat_input], [chatbot, chat_input] )
bot_msg = chat_msg.then( bot, [chatbot, response_type], chatbot,
api_name="bot_response" ) bot_msg.then(lambda:
gr.MultimodalTextbox(interactive=True), None, [chat_input])
chatbot.like(print_like_dislike, None, None) if __name__ == "__main__":
demo.launch()
import gradio as gr
import os
import plotly.exp
|
Demos
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
tbox(interactive=True), None, [chat_input])
chatbot.like(print_like_dislike, None, None) if __name__ == "__main__":
demo.launch()
import gradio as gr
import os
import plotly.express as px
import random
Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, video, & model3d). Plus shows support for streaming text.
txt = """
Absolutely! The mycorrhizal network, often referred to as the "Wood Wide Web," is a symbiotic association between fungi and the roots of most plant species. Here’s a deeper dive into how it works and its implications:
How It Works
1. **Symbiosis**: Mycorrhizal fungi attach to plant roots, extending far into the soil. The plant provides the fungi with carbohydrates produced via photosynthesis. In return, the fungi help the plant absorb water and essential nutrients like phosphorus and nitrogen from the soil.
2. **Network Formation**: The fungal hyphae (thread-like structures) connect individual plants, creating an extensive underground network. This network can link many plants together, sometimes spanning entire forests.
3. **Communication**: Trees and plants use this network to communicate and share resources. For example, a tree under attack by pests can send chemical signals through the mycorrhizal network to warn neighboring trees. These trees can then produce defensive chemicals to prepare for the impending threat.
Benefits and Functions
1. **Resource Sharing**: The network allows for the redistribution of resources among plants. For instance, a large, established tree might share excess nutrients and water with smaller, younger trees, promoting overall forest health.
2. **Defense Mechanism**: The ability to share information about pests and diseases enhances the resilience of plant communities. This early warning system helps plants activate their defenses before they are directly affected
|
Demos
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
The ability to share information about pests and diseases enhances the resilience of plant communities. This early warning system helps plants activate their defenses before they are directly affected.
3. **Support for Seedlings**: Young seedlings, which have limited root systems, benefit immensely from the mycorrhizal network. They receive nutrients and water from larger plants, increasing their chances of survival and growth.
Ecological Impact
1. **Biodiversity**: The mycorrhizal network supports biodiversity by fostering a cooperative environment. Plants of different species can coexist and thrive because of the shared resources and information.
2. **Forest Health**: The network enhances the overall health of forests. By enabling efficient nutrient cycling and supporting plant defenses, it contributes to the stability and longevity of forest ecosystems.
3. **Climate Change Mitigation**: Healthy forests act as significant carbon sinks, absorbing carbon dioxide from the atmosphere. The mycorrhizal network plays a critical role in maintaining forest health and, consequently, in mitigating climate change.
Research and Discoveries
1. **Suzanne Simard's Work**: Ecologist Suzanne Simard’s research has been pivotal in uncovering the complexities of the mycorrhizal network. She demonstrated that trees of different species can share resources and that "mother trees" (large, older trees) play a crucial role in nurturing younger plants.
2. **Implications for Conservation**: Understanding the mycorrhizal network has significant implications for conservation efforts. It highlights the importance of preserving not just individual trees but entire ecosystems, including the fungal networks that sustain them.
Practical Applications
1. **Agriculture**: Farmers and horticulturists are exploring the use of mycorrhizal fungi to improve crop yields and soil health. By incorporating the
|
Demos
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
em.
Practical Applications
1. **Agriculture**: Farmers and horticulturists are exploring the use of mycorrhizal fungi to improve crop yields and soil health. By incorporating these fungi into agricultural practices, they can reduce the need for chemical fertilizers and enhance plant resilience.
2. **Reforestation**: In reforestation projects, introducing mycorrhizal fungi can accelerate the recovery of degraded lands. The fungi help establish healthy plant communities, ensuring the success of newly planted trees.
The "Wood Wide Web" exemplifies the intricate and often hidden connections that sustain life on Earth. It’s a reminder of the profound interdependence within natural systems and the importance of preserving these delicate relationships.
"""
def random_plot():
df = px.data.iris()
fig = px.scatter(
df,
x="sepal_width",
y="sepal_length",
color="species",
size="petal_length",
hover_data=["petal_width"],
)
return fig
color_map = {
"harmful": "crimson",
"neutral": "gray",
"beneficial": "green",
}
def html_src(harm_level):
return f"""
{harm_level}
"""
def print_like_dislike(x: gr.LikeData):
print(x.index, x.value, x.liked)
def random_bokeh_plot():
from bokeh.models import ColumnDataSource, Whisker
from bokeh.plotting import figure
from bokeh.sampledata.autompg2 import autompg2 as df
from bokeh.transform import factor_cmap, jitter
classes = sorted(df["class"].unique())
p = figure(
height=400,
x_range=classes,
background_fill_color="efefef",
title="Car class vs HWY mpg with quintile ranges",
)
p.xgrid.grid_line_color = None
g =
|
Demos
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
x_range=classes,
background_fill_color="efefef",
title="Car class vs HWY mpg with quintile ranges",
)
p.xgrid.grid_line_color = None
g = df.groupby("class")
upper = g.hwy.quantile(0.80)
lower = g.hwy.quantile(0.20)
source = ColumnDataSource(data=dict(base=classes, upper=upper, lower=lower))
error = Whisker(
base="base",
upper="upper",
lower="lower",
source=source,
level="annotation",
line_width=2,
)
error.upper_head.size = 20
error.lower_head.size = 20
p.add_layout(error)
p.circle(
jitter("class", 0.3, range=p.x_range),
"hwy",
source=df,
alpha=0.5,
size=13,
line_color="white",
color=factor_cmap("class", "Light6", classes),
)
return p
get_file(), get_image(), get_model3d(), get_video() return file paths to sample media included with Gradio
from gradio.media import get_file, get_image, get_model3d, get_video
def random_matplotlib_plot():
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
countries = ["USA", "Canada", "Mexico", "UK"]
months = ["January", "February", "March", "April", "May"]
m = months.index("January")
r = 3.2
start_day = 30 * m
final_day = 30 * (m + 1)
x = np.arange(start_day, final_day + 1)
pop_count = {"USA": 350, "Canada": 40, "Mexico": 300, "UK": 120}
df = pd.DataFrame({"day": x})
for country in countries:
df[country] = x ** (r) * (pop_count[country] + 1)
fig = plt.figure()
plt.plot(df["day"], df[countries].to_numpy())
plt.title("Outbreak in " + "January")
plt.ylabel("Cases")
plt.xlabel("Days since Day 0")
plt.legend(count
|
Demos
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
figure()
plt.plot(df["day"], df[countries].to_numpy())
plt.title("Outbreak in " + "January")
plt.ylabel("Cases")
plt.xlabel("Days since Day 0")
plt.legend(countries)
return fig
def add_message(history, message):
for x in message["files"]:
history.append({"role": "user", "content": {"path": x}})
if message["text"] is not None:
history.append({"role": "user", "content": message["text"]})
return history, gr.MultimodalTextbox(value=None, interactive=False)
def bot(history, response_type):
msg = {"role": "assistant", "content": ""}
if response_type == "plot":
content = gr.Plot(random_plot())
elif response_type == "bokeh_plot":
content = gr.Plot(random_bokeh_plot())
elif response_type == "matplotlib_plot":
content = gr.Plot(random_matplotlib_plot())
elif response_type == "gallery":
content = gr.Gallery(
[get_image("avatar.png"), get_image("avatar.png")]
)
elif response_type == "dataframe":
content = gr.Dataframe(
interactive=True,
headers=["One", "Two", "Three"],
col_count=(3, "fixed"),
row_count=(3, "fixed"),
value=[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
label="Dataframe",
)
elif response_type == "image":
content = gr.Image(get_image("avatar.png"))
elif response_type == "video":
content = gr.Video(get_video("world.mp4"))
elif response_type == "audio":
content = gr.Audio(os.path.join("files", "audio.wav"))
elif response_type == "audio_file":
content = {"path": os.path.join("files", "audio.wav"), "alt_text": "description"}
elif response_type == "image_file":
content = {"path": get_image("avatar.png"), "alt_text": "description"}
|
Demos
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
{"path": os.path.join("files", "audio.wav"), "alt_text": "description"}
elif response_type == "image_file":
content = {"path": get_image("avatar.png"), "alt_text": "description"}
elif response_type == "video_file":
content = {"path": get_video("world.mp4"), "alt_text": "description"}
elif response_type == "txt_file":
content = {"path": get_file("sample.txt"), "alt_text": "description"}
elif response_type == "model3d_file":
content = {"path": get_model3d("Duck.glb"), "alt_text": "description"}
elif response_type == "html":
content = gr.HTML(
html_src(random.choice(["harmful", "neutral", "beneficial"]))
)
elif response_type == "model3d":
content = gr.Model3D(get_model3d("Duck.glb"))
else:
content = txt
msg["content"] = content
history.append(msg)
return history
fig = random_plot()
with gr.Blocks(fill_height=True) as demo:
chatbot = gr.Chatbot(
elem_id="chatbot",
type="messages",
bubble_full_width=False,
scale=1,
show_copy_button=True,
avatar_images=(
None,
get_image("avatar.png"),
),
)
response_type = gr.Radio(
[
"audio_file",
"image_file",
"video_file",
"txt_file",
"model3d_file",
"plot",
"matplotlib_plot",
"bokeh_plot",
"image",
"text",
"gallery",
"dataframe",
"video",
"audio",
"html",
"model3d",
],
value="text",
label="Response Type",
)
chat_input = gr.MultimodalTextbox(
interactive=True,
|
Demos
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
"html",
"model3d",
],
value="text",
label="Response Type",
)
chat_input = gr.MultimodalTextbox(
interactive=True,
placeholder="Enter message or upload file...",
show_label=False,
)
chat_msg = chat_input.submit(
add_message, [chatbot, chat_input], [chatbot, chat_input]
)
bot_msg = chat_msg.then(
bot, [chatbot, response_type], chatbot, api_name="bot_response"
)
bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input])
chatbot.like(print_like_dislike, None, None)
if __name__ == "__main__":
demo.launch()
|
Demos
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot 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 Chatbot component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`Chatbot.change(fn, ···)` | Triggered when the value of the Chatbot 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.
`Chatbot.select(fn, ···)` | Event listener for when the user selects or deselects the Chatbot. Uses event data gradio.SelectData to carry `value` referring to the label of the Chatbot, and `selected` to refer to state of the Chatbot. See EventData documentation on how to use this event data
`Chatbot.like(fn, ···)` | This listener is triggered when the user likes/dislikes from within the Chatbot. This event has EventData of type gradio.LikeData that carries information, accessible through LikeData.index and LikeData.value. See EventData documentation on how to use this event data.
`Chatbot.retry(fn, ···)` | This listener is triggered when the user clicks the retry button in the chatbot message.
`Chatbot.undo(fn, ···)` | This listener is triggered when the user clicks the undo button in the chatbot message.
`Chatbot.example_select(fn, ···)` | This listener is triggered when the user clicks on an example from within the Chatbot. This event has SelectData of type gradio.SelectData that carries information, accessible through SelectData.index and SelectData.value. See SelectData documentation on how to use this event data.
`Chatbot.option_select(fn, ···)` | This listener is trigge
|
Event Listeners
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
carries information, accessible through SelectData.index and SelectData.value. See SelectData documentation on how to use this event data.
`Chatbot.option_select(fn, ···)` | This listener is triggered when the user clicks on an option from within the Chatbot. This event has SelectData of type gradio.SelectData that carries information, accessible through SelectData.index and SelectData.value. See SelectData documentation on how to use this event data.
`Chatbot.clear(fn, ···)` | This listener is triggered when the user clears the Chatbot using the clear button for the component.
`Chatbot.copy(fn, ···)` | This listener is triggered when the user copies content from the Chatbot. Uses event data gradio.CopyData to carry information about the copied content. See EventData documentation on how to use this event data
`Chatbot.edit(fn, ···)` | This listener is triggered when the user edits the Chatbot (e.g. image) using the built-in editor.
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
|
Event Listeners
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
nents 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`
If True, then the function should process
|
Event Listeners
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
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 allow a second submission after the
pending event is complete.
js: str | Literal[True] | None
default `
|
Event Listeners
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
nding, 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.
validator: Callable | None
default `= None`
Optional validation function to run before the main function. If provided,
this function will be executed first with queue=Fal
|
Event Listeners
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
identical.
validator: Callable | None
default `= None`
Optional validation function to run before the main function. If provided,
this function will be executed first with queue=False, and only if it
completes successfully will the main function be called. The validator
receives the same inputs as the main function and should return a
`gr.validate()` for each input value.
|
Event Listeners
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
Helper Classes
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
|
gradio.ChatMessage(···)
Description
A dataclass that represents a message in the Chatbot component (with
type="messages"). The only required field is `content`. The value of
`gr.Chatbot` is a list of these dataclasses.
Parameters ▼
content: str | FileData | Component | FileDataDict | tuple | list
The content of the message. Can be a string or a Gradio component.
role: Literal['user', 'assistant', 'system']
default `= "assistant"`
The role of the message, which determines the alignment of the message in the
chatbot. Can be "user", "assistant", or "system". Defaults to "assistant".
metadata: MetadataDict
default `= _HAS_DEFAULT_FACTORY_CLASS()`
The metadata of the message, which is used to display intermediate thoughts /
tool usage. Should be a dictionary with the following keys: "title" (required
to display the thought), and optionally: "id" and "parent_id" (to nest
thoughts), "duration" (to display the duration of the thought), "status" (to
display the status of the thought).
options: list[OptionDict]
default `= _HAS_DEFAULT_FACTORY_CLASS()`
The options of the message. A list of Option objects, which are dictionaries
with the following keys: "label" (the text to display in the option), and
optionally "value" (the value to return when the option is selected if
different from the label).
|
ChatMessage
|
https://gradio.app/docs/gradio/chatbot
|
Gradio - Chatbot Docs
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.