text
stringlengths 0
2k
| heading1
stringlengths 4
79
| source_page_url
stringclasses 179
values | source_page_title
stringclasses 179
values |
---|---|---|---|
ue`
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 and edit an image; if False, can only be
used to display images. If not provided, this is inferred based on whether the
component is used as an input or output.
visible: bool | 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
|
Initialization
|
https://gradio.app/docs/gradio/imageeditor
|
Gradio - Imageeditor Docs
|
nt | 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.
placeholder: str | None
default `= None`
Custom text for the upload area. Overrides default upload messages when
provided. Accepts new lines and `` to designate a heading.
mirror_webcam: bool | None
default `= None`
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.
crop_size: tuple[int | float, int | float] | str | None
default `= None`
Deprecated. Used to set the `canvas_size` parameter.
transforms: Iterable[Literal['crop', 'resize']] | None
default `= ('crop', 'resize')`
The transforms tools to make available to users. "crop" allows the user to
crop the image.
eraser: Eraser | None | Literal[False]
default `= None`
The options for the eraser tool in the image editor. Should be an instance of
the `gr.Eraser` class, or None to use the default settings. Can also be False
to hide the eraser tool. See `gr.Eraser` docs.
brush: Brush | None | Literal[False]
default `= None`
The options for the brush tool in the image editor. Should be an insta
|
Initialization
|
https://gradio.app/docs/gradio/imageeditor
|
Gradio - Imageeditor Docs
|
o be False
to hide the eraser tool. See `gr.Eraser` docs.
brush: Brush | None | Literal[False]
default `= None`
The options for the brush tool in the image editor. Should be an instance of
the `gr.Brush` class, or None to use the default settings. Can also be False
to hide the brush tool, which will also hide the eraser tool. See `gr.Brush`
docs.
format: str
default `= "webp"`
Format to save image if it does not already have a valid format (e.g. if the
image is being returned to the frontend as a numpy array or PIL Image). The
format should be supported by the PIL library. This parameter has no effect on
SVG files.
layers: bool | LayerOptions
default `= True`
The options for the layer tool in the image editor. Can be a boolean or an
instance of the `gr.LayerOptions` class. If True, will allow users to add
layers to the image. If False, the layers option will be hidden. If an
instance of `gr.LayerOptions`, it will be used to configure the layer tool.
See `gr.LayerOptions` docs.
canvas_size: tuple[int, int]
default `= (800, 800)`
The initial size of the canvas in pixels. The first value is the width and the
second value is the height. If `fixed_canvas` is `True`, uploaded images will
be rescaled to fit the canvas size while preserving the aspect ratio.
Otherwise, the canvas size will change to match the size of an uploaded image.
fixed_canvas: bool
default `= False`
If True, the canvas size will not change based on the size of the background
image and the image will be rescaled to fit (while preserving the aspect
ratio) and placed in the center of the canvas.
show_fullscreen_button: bool
default `= True`
If True, will display button to view image in fullscreen mode.
webcam_options: WebcamOptions | None
default `= None`
The options for the webcam tool in the image editor. Can be an instance of the
`gr.WebcamOptions` class, or None to use the def
|
Initialization
|
https://gradio.app/docs/gradio/imageeditor
|
Gradio - Imageeditor Docs
|
webcam_options: WebcamOptions | None
default `= None`
The options for the webcam tool in the image editor. Can be an instance of the
`gr.WebcamOptions` class, or None to use the default settings. See
`gr.WebcamOptions` docs.
|
Initialization
|
https://gradio.app/docs/gradio/imageeditor
|
Gradio - Imageeditor Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.ImageEditor` | "imageeditor" | Uses default values
`gradio.Sketchpad` | "sketchpad" | Uses sources=(), brush=Brush(colors=["000000"], color_mode="fixed")
`gradio.Paint` | "paint" | Uses sources=()
`gradio.ImageMask` | "imagemask" | Uses brush=Brush(colors=["000000"], color_mode="fixed")
|
Shortcuts
|
https://gradio.app/docs/gradio/imageeditor
|
Gradio - Imageeditor Docs
|
image_editor
Open in 🎢 ↗ import gradio as gr import time def sleep(im): time.sleep(5)
return [im["background"], im["layers"][0], im["layers"][1], im["composite"]]
def predict(im): return im["composite"] with gr.Blocks() as demo: with
gr.Row(): im = gr.ImageEditor( type="numpy", crop_size="1:1", ) im_preview =
gr.Image() n_upload = gr.Number(0, label="Number of upload events", step=1)
n_change = gr.Number(0, label="Number of change events", step=1) n_input =
gr.Number(0, label="Number of input events", step=1) im.upload(lambda x: x +
1, outputs=n_upload, inputs=n_upload) im.change(lambda x: x + 1,
outputs=n_change, inputs=n_change) im.input(lambda x: x + 1, outputs=n_input,
inputs=n_input) im.change(predict, outputs=im_preview, inputs=im,
show_progress="hidden") if __name__ == "__main__": demo.launch()
import gradio as gr
import time
def sleep(im):
time.sleep(5)
return [im["background"], im["layers"][0], im["layers"][1], im["composite"]]
def predict(im):
return im["composite"]
with gr.Blocks() as demo:
with gr.Row():
im = gr.ImageEditor(
type="numpy",
crop_size="1:1",
)
im_preview = gr.Image()
n_upload = gr.Number(0, label="Number of upload events", step=1)
n_change = gr.Number(0, label="Number of change events", step=1)
n_input = gr.Number(0, label="Number of input events", step=1)
im.upload(lambda x: x + 1, outputs=n_upload, inputs=n_upload)
im.change(lambda x: x + 1, outputs=n_change, inputs=n_change)
im.input(lambda x: x + 1, outputs=n_input, inputs=n_input)
im.change(predict, outputs=im_preview, inputs=im, show_progress="hidden")
if __name__ == "__main__":
demo.launch()
|
Demos
|
https://gradio.app/docs/gradio/imageeditor
|
Gradio - Imageeditor 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 ImageEditor component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`ImageEditor.clear(fn, ···)` | This listener is triggered when the user clears the ImageEditor using the clear button for the component.
`ImageEditor.change(fn, ···)` | Triggered when the value of the ImageEditor 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.
`ImageEditor.input(fn, ···)` | This listener is triggered when the user changes the value of the ImageEditor.
`ImageEditor.select(fn, ···)` | Event listener for when the user selects or deselects the ImageEditor. Uses event data gradio.SelectData to carry `value` referring to the label of the ImageEditor, and `selected` to refer to state of the ImageEditor. See EventData documentation on how to use this event data
`ImageEditor.upload(fn, ···)` | This listener is triggered when the user uploads a file into the ImageEditor.
`ImageEditor.apply(fn, ···)` | This listener is triggered when the user applies changes to the ImageEditor through an integrated UI action.
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 ele
|
Event Listeners
|
https://gradio.app/docs/gradio/imageeditor
|
Gradio - Imageeditor Docs
|
ten 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 as a runtime display in
the upper right corner, "mi
|
Event Listeners
|
https://gradio.app/docs/gradio/imageeditor
|
Gradio - Imageeditor Docs
|
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 click_event, where click_event
is the return value of
|
Event Listeners
|
https://gradio.app/docs/gradio/imageeditor
|
Gradio - Imageeditor Docs
|
ne
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 downstream apps as well as the
Clients to use this ev
|
Event Listeners
|
https://gradio.app/docs/gradio/imageeditor
|
Gradio - Imageeditor Docs
|
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/imageeditor
|
Gradio - Imageeditor Docs
|
Helper Classes
|
https://gradio.app/docs/gradio/imageeditor
|
Gradio - Imageeditor Docs
|
|
gradio.Brush(···)
Description
A dataclass for specifying options for the brush tool in the ImageEditor
component. An instance of this class can be passed to the `brush` parameter of
`gr.ImageEditor`.
Initialization
Parameters ▼
default_size: int | Literal['auto']
default `= "auto"`
The default radius, in pixels, of the brush tool. Defaults to "auto" in which
case the radius is automatically determined based on the size of the image
(generally 1/50th of smaller dimension).
colors: list[str | tuple[str, float]] | str | tuple[str, float] | None
default `= None`
A list of colors to make available to the user when using the brush. Defaults
to a list of 5 colors.
default_color: str | tuple[str, float] | None
default `= None`
The default color of the brush. Defaults to the first color in the `colors`
list.
color_mode: Literal['fixed', 'defaults']
default `= "defaults"`
If set to "fixed", user can only select from among the colors in `colors`. If
"defaults", the colors in `colors` are provided as a default palette, but the
user can also select any color using a color picker.
|
Brush
|
https://gradio.app/docs/gradio/imageeditor
|
Gradio - Imageeditor Docs
|
gradio.Eraser(···)
Description
A dataclass for specifying options for the eraser tool in the ImageEditor
component. An instance of this class can be passed to the `eraser` parameter
of `gr.ImageEditor`.
Initialization
Parameters ▼
default_size: int | Literal['auto']
default `= "auto"`
The default radius, in pixels, of the eraser tool. Defaults to "auto" in which
case the radius is automatically determined based on the size of the image
(generally 1/50th of smaller dimension).
|
Eraser
|
https://gradio.app/docs/gradio/imageeditor
|
Gradio - Imageeditor Docs
|
gradio.LayerOptions(···)
Description
A dataclass for specifying options for the layer tool in the ImageEditor
component. An instance of this class can be passed to the `layers` parameter
of `gr.ImageEditor`.
Initialization
Parameters ▼
allow_additional_layers: bool
default `= True`
If True, users can add additional layers to the image. If False, the add layer
button will not be shown.
layers: list[str] | None
default `= None`
A list of layers to make available to the user when using the layer tool. One
layer must be provided, if the length of the list is 0 then a layer will be
generated automatically.
disabled: bool
default `= False`
|
Layer Options
|
https://gradio.app/docs/gradio/imageeditor
|
Gradio - Imageeditor 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/imageeditor
|
Gradio - Imageeditor Docs
|
Creates a "Sign In" button that redirects the user to sign in with Hugging
Face OAuth. Once the user is signed in, the button will act as a logout
button, and you can retrieve a signed-in user's profile by adding a parameter
of type `gr.OAuthProfile` to any Gradio function. This will only work if this
Gradio app is running in a Hugging Face Space. Permissions for the OAuth app
can be configured in the Spaces README file, as described here:
<https://huggingface.co/docs/hub/en/spaces-oauth.> For local development,
instead of OAuth, the local Hugging Face account that is logged in (via `hf
auth login`) will be available through the `gr.OAuthProfile` object.
|
Description
|
https://gradio.app/docs/gradio/loginbutton
|
Gradio - Loginbutton Docs
|
**As input component** : (Rarely used) the `str` corresponding to the
button label when the button is clicked
Your function should accept one of these types:
def predict(
value: str | None
)
...
**As output component** : string corresponding to the button label
Your function should return one of these types:
def predict(···) -> str | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/loginbutton
|
Gradio - Loginbutton Docs
|
Parameters ▼
value: str
default `= "Sign in with Hugging Face"`
logout_value: str
default `= "Logout ({})"`
The text to display when the user is signed in. The string should contain a
placeholder for the username with a call-to-action to logout, e.g. "Logout
({})".
every: Timer | float | None
default `= None`
inputs: Component | list[Component] | set[Component] | None
default `= None`
variant: Literal['primary', 'secondary', 'stop', 'huggingface']
default `= "huggingface"`
size: Literal['sm', 'md', 'lg']
default `= "lg"`
icon: str | Path | None
default `= "/home/runner/work/gradio/gradio/gradio/icons/huggingface-
logo.svg"`
link: str | None
default `= None`
visible: bool | Literal['hidden']
default `= True`
interactive: bool
default `= True`
elem_id: str | None
default `= None`
elem_classes: list[str] | str | None
default `= None`
render: bool
default `= True`
key: int | str | tuple[int | str, ...] | None
default `= None`
preserved_by_key: list[str] | str | None
default `= "value"`
scale: int | None
default `= None`
min_width: int | None
default `= None`
|
Initialization
|
https://gradio.app/docs/gradio/loginbutton
|
Gradio - Loginbutton Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.LoginButton` | "loginbutton" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/loginbutton
|
Gradio - Loginbutton Docs
|
login_with_huggingface
Open in 🎢 ↗ from __future__ import annotations import gradio as gr from huggingface_hub import whoami def hello(profile: gr.OAuthProfile | None) -> str: if profile is None: return "I don't know you." return f"Hello {profile.name}" def list_organizations(oauth_token: gr.OAuthToken | None) -> str: if oauth_token is None: return "Please deploy this on Spaces and log in to list organizations." org_names = [org["name"] for org in whoami(oauth_token.token)["orgs"]] return f"You belong to {', '.join(org_names)}." with gr.Blocks() as demo: gr.LoginButton() m1 = gr.Markdown() m2 = gr.Markdown() demo.load(hello, inputs=None, outputs=m1) demo.load(list_organizations, inputs=None, outputs=m2) if __name__ == "__main__": demo.launch()
from __future__ import annotations
import gradio as gr
from huggingface_hub import whoami
def hello(profile: gr.OAuthProfile | None) -> str:
if profile is None:
return "I don't know you."
return f"Hello {profile.name}"
def list_organizations(oauth_token: gr.OAuthToken | None) -> str:
if oauth_token is None:
return "Please deploy this on Spaces and log in to list organizations."
org_names = [org["name"] for org in whoami(oauth_token.token)["orgs"]]
return f"You belong to {', '.join(org_names)}."
with gr.Blocks() as demo:
gr.LoginButton()
m1 = gr.Markdown()
m2 = gr.Markdown()
demo.load(hello, inputs=None, outputs=m1)
demo.load(list_organizations, inputs=None, outputs=m2)
if __name__ == "__main__":
demo.launch()
|
Demos
|
https://gradio.app/docs/gradio/loginbutton
|
Gradio - Loginbutton 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 LoginButton component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`LoginButton.click(fn, ···)` | Triggered when the Button is clicked.
Event Parameters
Parameters ▼
fn: Callable | None | Literal['decorator']
default `= "decorator"`
the function to call when this event is triggered. Often a machine learning
model's prediction function. Each parameter of the function corresponds to one
input component, and the function should return a single value or a tuple of
values, with each element in the tuple corresponding to one output component.
inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as inputs. If the function takes no inputs,
this should be an empty list.
outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as outputs. If the function returns no
outputs, this should be an empty list.
api_name: str | None | Literal[False]
default `= None`
defines how the endpoint appears in the API docs. Can be a string, None, or
False. If set to a string, the endpoint will be exposed in the API docs with
the given name. If None (default), the name of the function will be used as
the API endpoint. If False, the endpoint will not be exposed in the API docs
and downstream apps (including those that `gr.load` this app) will not be able
to use this event.
api_descripti
|
Event Listeners
|
https://gradio.app/docs/gradio/loginbutton
|
Gradio - Loginbutton Docs
|
API endpoint. If False, the endpoint will not be exposed in the API docs
and downstream apps (including those that `gr.load` this app) will not be able
to use this event.
api_description: str | None | Literal[False]
default `= None`
Description of the API endpoint. Can be a string, None, or False. If set to a
string, the endpoint will be exposed in the API docs with the given
description. If None, the function's docstring will be used as the API
endpoint description. If False, then no description will be displayed in the
API docs.
scroll_to_output: bool
default `= False`
If True, will scroll to output component on completion
show_progress: Literal['full', 'minimal', 'hidden']
default `= "full"`
how to show the progress animation while event is running: "full" shows a
spinner which covers the output component area as well as a runtime display in
the upper right corner, "minimal" only shows the runtime display, "hidden"
shows no progress animation at all
show_progress_on: Component | list[Component] | None
default `= None`
Component or list of components to show the progress animation on. If None,
will show the progress animation on all of the output components.
queue: bool
default `= True`
If True, will place the request on the queue, if the queue has been enabled.
If False, will not put this event on the queue, even if the queue has been
enabled. If None, will use the queue setting of the gradio app.
batch: bool
default `= False`
If True, then the function should process a batch of inputs, meaning that it
should accept a list of input values for each parameter. The lists should be
of equal length (and be up to length `max_batch_size`). The function is then
*required* to return a tuple of lists (even if there is only 1 output
component), with each list in the tuple corresponding to one output component.
max_batch_size: int
default `= 4`
Maximu
|
Event Listeners
|
https://gradio.app/docs/gradio/loginbutton
|
Gradio - Loginbutton Docs
|
ed* to return a tuple of lists (even if there is only 1 output
component), with each list in the tuple corresponding to one output component.
max_batch_size: int
default `= 4`
Maximum number of inputs to batch together if this is called from the queue
(only relevant if batch=True)
preprocess: bool
default `= True`
If False, will not run preprocessing of component data before running 'fn'
(e.g. leaving it as a base64 string if this method is called with the `Image`
component).
postprocess: bool
default `= True`
If False, will not run postprocessing of component data before returning 'fn'
output to the browser.
cancels: dict[str, Any] | list[dict[str, Any]] | None
default `= None`
A list of other events to cancel when this listener is triggered. For example,
setting cancels=[click_event] will cancel the click_event, where click_event
is the return value of another components .click method. Functions that have
not yet run (or generators that are iterating) will be cancelled, but
functions that are currently running will be allowed to finish.
trigger_mode: Literal['once', 'multiple', 'always_last'] | None
default `= None`
If "once" (default for all events except `.change()`) would not allow any
submissions while an event is pending. If set to "multiple", unlimited
submissions are allowed while pending, and "always_last" (default for
`.change()` and `.key_up()` events) would allow a second submission after the
pending event is complete.
js: str | Literal[True] | None
default `= None`
Optional frontend js method to run before running 'fn'. Input arguments for js
method are values of 'inputs' and 'outputs', return should be a list of values
for output components.
concurrency_limit: int | None | Literal['default']
default `= "default"`
If set, this is the maximum number of this event that can be running
simultaneously. Can be set to None to mean no c
|
Event Listeners
|
https://gradio.app/docs/gradio/loginbutton
|
Gradio - Loginbutton Docs
|
concurrency_limit: int | None | Literal['default']
default `= "default"`
If set, this is the maximum number of this event that can be running
simultaneously. Can be set to None to mean no concurrency_limit (any number of
this event can be running simultaneously). Set to "default" to use the default
concurrency limit (defined by the `default_concurrency_limit` parameter in
`Blocks.queue()`, which itself is 1 by default).
concurrency_id: str | None
default `= None`
If set, this is the id of the concurrency group. Events with the same
concurrency_id will be limited by the lowest set concurrency_limit.
show_api: bool
default `= True`
whether to show this event in the "view API" page of the Gradio app, or in the
".view_api()" method of the Gradio clients. Unlike setting api_name to False,
setting show_api to False will still allow downstream apps as well as the
Clients to use this event. If fn is None, show_api will automatically be set
to False.
time_limit: int | None
default `= None`
stream_every: float
default `= 0.5`
like_user_message: bool
default `= False`
key: int | str | tuple[int | str, ...] | None
default `= None`
A unique key for this event listener to be used in @gr.render(). If set, this
value identifies an event as identical across re-renders when the key is
identical.
validator: Callable | None
default `= None`
Optional validation function to run before the main function. If provided,
this function will be executed first with queue=False, and only if it
completes successfully will the main function be called. The validator
receives the same inputs as the main function and should return a
`gr.validate()` for each input value.
|
Event Listeners
|
https://gradio.app/docs/gradio/loginbutton
|
Gradio - Loginbutton Docs
|
The Progress class provides a custom progress tracker that is used in a
function signature. To attach a Progress tracker to a function, simply add a
parameter right after the input parameters that has a default value set to a
`gradio.Progress()` instance. The Progress tracker can then be updated in the
function by calling the Progress object or using the `tqdm` method on an
Iterable.
|
Description
|
https://gradio.app/docs/gradio/progress
|
Gradio - Progress Docs
|
import gradio as gr
import time
def my_function(x, progress=gr.Progress()):
progress(0, desc="Starting...")
time.sleep(1)
for i in progress.tqdm(range(100)):
time.sleep(0.1)
return x
gr.Interface(my_function, gr.Textbox(), gr.Textbox()).queue().launch()
|
Example Usage
|
https://gradio.app/docs/gradio/progress
|
Gradio - Progress Docs
|
Parameters ▼
track_tqdm: bool
default `= False`
If True, the Progress object will track any tqdm.tqdm iterations with the tqdm
library in the function.
|
Initialization
|
https://gradio.app/docs/gradio/progress
|
Gradio - Progress Docs
|
Methods
|
https://gradio.app/docs/gradio/progress
|
Gradio - Progress Docs
|
|
%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)
gradio.Progress.__call__(progress, ···)
Description
%20Copyright%202022%20Fontic
|
__call__
|
https://gradio.app/docs/gradio/progress
|
Gradio - Progress Docs
|
20512'%3e%3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\(Commercial%20License\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)
Updates progress tracker with progress and message text.
Parameters ▼
progress: float | tuple[int, int | None] | None
If float, should be between 0 and 1 representing completion. If Tuple, first
number represents steps completed, and second value represents total steps or
None if unknown. If None, hides progress bar.
desc: str | None
default `= None`
description to display.
total: int | float | None
default `= None`
estimated total
|
__call__
|
https://gradio.app/docs/gradio/progress
|
Gradio - Progress Docs
|
None if unknown. If None, hides progress bar.
desc: str | None
default `= None`
description to display.
total: int | float | None
default `= None`
estimated total number of steps.
unit: str
default `= "steps"`
unit of iterations.
|
__call__
|
https://gradio.app/docs/gradio/progress
|
Gradio - Progress Docs
|
%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)
gradio.Progress.tqdm(iterable, ···)
Description
%20Copyright%202022%20Fonticons,
|
tqdm
|
https://gradio.app/docs/gradio/progress
|
Gradio - Progress Docs
|
2'%3e%3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\(Commercial%20License\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)
Attaches progress tracker to iterable, like tqdm.
Parameters ▼
iterable: Iterable | None
iterable to attach progress tracker to.
desc: str | None
default `= None`
description to display.
total: int | float | None
default `= None`
estimated total number of steps.
unit: str
default `= "steps"`
unit of iterations.
|
tqdm
|
https://gradio.app/docs/gradio/progress
|
Gradio - Progress Docs
|
total number of steps.
unit: str
default `= "steps"`
unit of iterations.
|
tqdm
|
https://gradio.app/docs/gradio/progress
|
Gradio - Progress Docs
|
%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)
gradio.Progress.__call__(progress, ···)
Description
%20Copyright%202022%20Fontic
|
__call__
|
https://gradio.app/docs/gradio/progress
|
Gradio - Progress Docs
|
20512'%3e%3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\(Commercial%20License\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)
Updates progress tracker with progress and message text.
Parameters ▼
progress: float | tuple[int, int | None] | None
If float, should be between 0 and 1 representing completion. If Tuple, first
number represents steps completed, and second value represents total steps or
None if unknown. If None, hides progress bar.
desc: str | None
default `= None`
description to display.
total: int | float | None
default `= None`
estimated total
|
__call__
|
https://gradio.app/docs/gradio/progress
|
Gradio - Progress Docs
|
None if unknown. If None, hides progress bar.
desc: str | None
default `= None`
description to display.
total: int | float | None
default `= None`
estimated total number of steps.
unit: str
default `= "steps"`
unit of iterations.
|
__call__
|
https://gradio.app/docs/gradio/progress
|
Gradio - Progress Docs
|
%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)
gradio.Progress.tqdm(iterable, ···)
Description
%20Copyright%202022%20Fonticons,
|
tqdm
|
https://gradio.app/docs/gradio/progress
|
Gradio - Progress Docs
|
2'%3e%3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\(Commercial%20License\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)
Attaches progress tracker to iterable, like tqdm.
Parameters ▼
iterable: Iterable | None
iterable to attach progress tracker to.
desc: str | None
default `= None`
description to display.
total: int | float | None
default `= None`
estimated total number of steps.
unit: str
default `= "steps"`
unit of iterations.
|
tqdm
|
https://gradio.app/docs/gradio/progress
|
Gradio - Progress Docs
|
total number of steps.
unit: str
default `= "steps"`
unit of iterations.
|
tqdm
|
https://gradio.app/docs/gradio/progress
|
Gradio - Progress Docs
|
Creates a color picker for user to select a color as string input. Can be
used as an input to pass a color value to a function or as an output to
display a color value.
|
Description
|
https://gradio.app/docs/gradio/colorpicker
|
Gradio - Colorpicker Docs
|
**As input component** : Passes selected color value as a hex `str` into
the function.
Your function should accept one of these types:
def predict(
value: str | None
)
...
**As output component** : Expects a hex `str` returned from function and
sets color picker value to it.
Your function should return one of these types:
def predict(···) -> str | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/colorpicker
|
Gradio - Colorpicker Docs
|
Parameters ▼
value: str | Callable | None
default `= None`
default color hex code to provide in color picker. 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`
the label for this component, displayed above the component if `show_label` is
`True` and is also used as the header if there are a table of examples for
this component. If None and used in a `gr.Interface`, the label will be the
name of the parameter this component corresponds to.
info: str | I18nData | None
default `= None`
additional component description, appears below the label in smaller font.
Supports markdown / HTML syntax.
every: Timer | float | None
default `= None`
Continously calls `value` to recalculate it if `value` is a function (has no
effect otherwise). Can provide a Timer whose tick resets `value`, or a float
that provides the regular interval for the reset Timer.
inputs: Component | list[Component] | set[Component] | None
default `= None`
Components that are used as inputs to calculate `value` if `value` is a
function (has no effect otherwise). `value` is recalculated any time the
inputs change.
show_label: bool | None
default `= None`
if 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 cer
|
Initialization
|
https://gradio.app/docs/gradio/colorpicker
|
Gradio - Colorpicker Docs
|
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 color picker; if False, editing will
be disabled. If not provided, this is inferred based on whether the component
is used as an input or output.
visible: bool | 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
|
Initialization
|
https://gradio.app/docs/gradio/colorpicker
|
Gradio - Colorpicker Docs
|
ender()
function, if a component is re-rendered with the same key, these (and only
these) parameters will be preserved in the UI (if they have been changed by
the user or an event listener) instead of re-rendered based on the values
provided during constructor.
|
Initialization
|
https://gradio.app/docs/gradio/colorpicker
|
Gradio - Colorpicker Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.ColorPicker` | "colorpicker" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/colorpicker
|
Gradio - Colorpicker Docs
|
color_picker
Open in 🎢 ↗ import gradio as gr import numpy as np from PIL import Image,
ImageColor def change_color(icon, color): """ Function that given an icon in
.png format changes its color Args: icon: Icon whose color needs to be
changed. color: Chosen color with which to edit the input icon. Returns:
edited_image: Edited icon. """ img = icon.convert("LA") img =
img.convert("RGBA") image_np = np.array(icon) _, _, _, alpha = image_np.T mask
= alpha > 0 image_np[..., :-1][mask.T] = ImageColor.getcolor(color, "RGB")
edited_image = Image.fromarray(image_np) return edited_image inputs = [
gr.Image(label="icon", type="pil", image_mode="RGBA"),
gr.ColorPicker(label="color"), ] outputs = gr.Image(label="colored icon") demo
= gr.Interface( fn=change_color, inputs=inputs, outputs=outputs ) if __name__
== "__main__": demo.launch()
import gradio as gr
import numpy as np
from PIL import Image, ImageColor
def change_color(icon, color):
"""
Function that given an icon in .png format changes its color
Args:
icon: Icon whose color needs to be changed.
color: Chosen color with which to edit the input icon.
Returns:
edited_image: Edited icon.
"""
img = icon.convert("LA")
img = img.convert("RGBA")
image_np = np.array(icon)
_, _, _, alpha = image_np.T
mask = alpha > 0
image_np[..., :-1][mask.T] = ImageColor.getcolor(color, "RGB")
edited_image = Image.fromarray(image_np)
return edited_image
inputs = [
gr.Image(label="icon", type="pil", image_mode="RGBA"),
gr.ColorPicker(label="color"),
]
outputs = gr.Image(label="colored icon")
demo = gr.Interface(
fn=change_color,
inputs=inputs,
outputs=outputs
)
if __name__ == "__main__":
demo.launch()
|
Demos
|
https://gradio.app/docs/gradio/colorpicker
|
Gradio - Colorpicker 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 ColorPicker component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`ColorPicker.change(fn, ···)` | Triggered when the value of the ColorPicker 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.
`ColorPicker.input(fn, ···)` | This listener is triggered when the user changes the value of the ColorPicker.
`ColorPicker.submit(fn, ···)` | This listener is triggered when the user presses the Enter key while the ColorPicker is focused.
`ColorPicker.focus(fn, ···)` | This listener is triggered when the ColorPicker is focused.
`ColorPicker.blur(fn, ···)` | This listener is triggered when the ColorPicker is unfocused/blurred.
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 | Bloc
|
Event Listeners
|
https://gradio.app/docs/gradio/colorpicker
|
Gradio - Colorpicker Docs
|
default `= None`
List of gradio.components to use as inputs. If the function takes no inputs,
this should be an empty list.
outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as outputs. If the function returns no
outputs, this should be an empty list.
api_name: str | None | Literal[False]
default `= None`
defines how the endpoint appears in the API docs. Can be a string, None, or
False. If set to a string, the endpoint will be exposed in the API docs with
the given name. If None (default), the name of the function will be used as
the API endpoint. If False, the endpoint will not be exposed in the API docs
and downstream apps (including those that `gr.load` this app) will not be able
to use this event.
api_description: str | None | Literal[False]
default `= None`
Description of the API endpoint. Can be a string, None, or False. If set to a
string, the endpoint will be exposed in the API docs with the given
description. If None, the function's docstring will be used as the API
endpoint description. If False, then no description will be displayed in the
API docs.
scroll_to_output: bool
default `= False`
If True, will scroll to output component on completion
show_progress: Literal['full', 'minimal', 'hidden']
default `= "full"`
how to show the progress animation while event is running: "full" shows a
spinner which covers the output component area as well as a runtime display in
the upper right corner, "minimal" only shows the runtime display, "hidden"
shows no progress animation at all
show_progress_on: 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 pla
|
Event Listeners
|
https://gradio.app/docs/gradio/colorpicker
|
Gradio - Colorpicker Docs
|
ent or list of components to show the progress animation on. If None,
will show the progress animation on all of the output components.
queue: bool
default `= True`
If True, will place the request on the queue, if the queue has been enabled.
If False, will not put this event on the queue, even if the queue has been
enabled. If None, will use the queue setting of the gradio app.
batch: bool
default `= False`
If True, then the function should process a batch of inputs, meaning that it
should accept a list of input values for each parameter. The lists should be
of equal length (and be up to length `max_batch_size`). The function is then
*required* to return a tuple of lists (even if there is only 1 output
component), with each list in the tuple corresponding to one output component.
max_batch_size: int
default `= 4`
Maximum number of inputs to batch together if this is called from the queue
(only relevant if batch=True)
preprocess: bool
default `= True`
If False, will not run preprocessing of component data before running 'fn'
(e.g. leaving it as a base64 string if this method is called with the `Image`
component).
postprocess: bool
default `= True`
If False, will not run postprocessing of component data before returning 'fn'
output to the browser.
cancels: dict[str, Any] | list[dict[str, Any]] | None
default `= None`
A list of other events to cancel when this listener is triggered. For example,
setting cancels=[click_event] will cancel the click_event, where click_event
is the return value of another components .click method. Functions that have
not yet run (or generators that are iterating) will be cancelled, 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 whi
|
Event Listeners
|
https://gradio.app/docs/gradio/colorpicker
|
Gradio - Colorpicker Docs
|
to finish.
trigger_mode: Literal['once', 'multiple', 'always_last'] | None
default `= None`
If "once" (default for all events except `.change()`) would not allow any
submissions while an event is pending. If set to "multiple", unlimited
submissions are allowed while pending, and "always_last" (default for
`.change()` and `.key_up()` events) would allow a second submission after the
pending event is complete.
js: str | Literal[True] | None
default `= None`
Optional frontend js method to run before running 'fn'. Input arguments for js
method are values of 'inputs' and 'outputs', return should be a list of values
for output components.
concurrency_limit: int | None | Literal['default']
default `= "default"`
If set, this is the maximum number of this event that can be running
simultaneously. Can be set to None to mean no concurrency_limit (any number of
this event can be running simultaneously). Set to "default" to use the default
concurrency limit (defined by the `default_concurrency_limit` parameter in
`Blocks.queue()`, which itself is 1 by default).
concurrency_id: str | None
default `= None`
If set, this is the id of the concurrency group. Events with the same
concurrency_id will be limited by the lowest set concurrency_limit.
show_api: bool
default `= True`
whether to show this event in the "view API" page of the Gradio app, or in the
".view_api()" method of the Gradio clients. Unlike setting api_name to False,
setting show_api to False will still allow downstream apps as well as the
Clients to use this event. If fn is None, show_api will automatically be set
to False.
time_limit: int | None
default `= None`
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(
|
Event Listeners
|
https://gradio.app/docs/gradio/colorpicker
|
Gradio - Colorpicker Docs
|
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/colorpicker
|
Gradio - Colorpicker Docs
|
Group is a layout element within Blocks which groups together children so
that they do not have any padding or margin between them.
|
Description
|
https://gradio.app/docs/gradio/group
|
Gradio - Group Docs
|
with gr.Group():
gr.Textbox(label="First")
gr.Textbox(label="Last")
|
Example Usage
|
https://gradio.app/docs/gradio/group
|
Gradio - Group Docs
|
Parameters ▼
visible: bool | Literal['hidden']
default `= True`
If False, group will be hidden.
elem_id: str | None
default `= None`
An optional string that is assigned as the id of this component in the HTML
DOM. Can be used for targeting CSS styles.
elem_classes: list[str] | str | None
default `= None`
An optional string or list of strings that are assigned as the class of this
component in the HTML DOM. Can be used for targeting CSS styles.
render: bool
default `= True`
If False, this layout will not be rendered in the Blocks context. Should be
used if the intention is to assign event listeners now but render the
component later.
key: int | str | tuple[int | str, ...] | None
default `= None`
in a gr.render, Components with the same key across re-renders are treated as
the same component, not a new component. Properties set in 'preserved_by_key'
are not reset across a re-render.
preserved_by_key: list[str] | str | None
default `= None`
A list of parameters from this component's constructor. Inside a gr.render()
function, if a component is re-rendered with the same key, these (and only
these) parameters will be preserved in the UI (if they have been changed by
the user or an event listener) instead of re-rendered based on the values
provided during constructor.
|
Initialization
|
https://gradio.app/docs/gradio/group
|
Gradio - Group Docs
|
Creates a set of (string or numeric type) radio buttons of which only one
can be selected.
|
Description
|
https://gradio.app/docs/gradio/radio
|
Gradio - Radio Docs
|
**As input component** : Passes the value of the selected radio button as a `str | int | float`, or its index as an `int` into the function, depending on `type`.
Your function should accept one of these types:
def predict(
value: str | int | float | None
)
...
**As output component** : Expects a `str | int | float` corresponding to the value of the radio button to be selected
Your function should return one of these types:
def predict(···) -> str | int | float | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/radio
|
Gradio - Radio Docs
|
Parameters ▼
choices: list[str | int | float | tuple[str, str | int | float]] | None
default `= None`
A list of string or numeric options to select from. An option can also be a
tuple of the form (name, value), where name is the displayed name of the radio
button and value is the value to be passed to the function, or returned by the
function.
value: str | int | float | Callable | None
default `= None`
The option selected by default. If None, no option is selected by default. If
a function is provided, the function will be called each time the app loads to
set the initial value of this component.
type: Literal['value', 'index']
default `= "value"`
Type of value to be returned by component. "value" returns the string of the
choice selected, "index" returns the index of the choice selected.
label: str | I18nData | None
default `= None`
the label for this component, displayed above the component if `show_label` is
`True` and is also used as the header if there are a table of examples for
this component. If None and used in a `gr.Interface`, the label will be the
name of the parameter this component corresponds to.
info: str | I18nData | None
default `= None`
additional component description, appears below the label in smaller font.
Supports markdown / HTML syntax.
every: Timer | float | None
default `= None`
Continously calls `value` to recalculate it if `value` is a function (has no
effect otherwise). Can provide a Timer whose tick resets `value`, or a float
that provides the regular interval for the reset Timer.
inputs: Component | list[Component] | set[Component] | None
default `= None`
Components that are used as inputs to calculate `value` if `value` is a
function (has no effect otherwise). `value` is recalculated any time the
inputs change.
show_label: bool | None
default `= None`
if True, will display label.
|
Initialization
|
https://gradio.app/docs/gradio/radio
|
Gradio - Radio Docs
|
value` is a
function (has no effect otherwise). `value` is recalculated any time the
inputs change.
show_label: bool | None
default `= None`
if True, will display label.
container: bool
default `= True`
If True, will place the component in a container - providing some extra
padding around the border.
scale: int | None
default `= None`
Relative width compared to adjacent Components in a Row. For example, if
Component A has scale=2, and Component B has scale=1, A will be twice as wide
as B. Should be an integer.
min_width: int
default `= 160`
Minimum pixel width, will wrap if not sufficient screen space to satisfy this
value. If a certain scale value results in this Component being narrower than
min_width, the min_width parameter will be respected first.
interactive: bool | None
default `= None`
If True, choices in this radio group will be selectable; if False, selection
will be disabled. If not provided, this is inferred based on whether the
component is used as an input or output.
visible: bool | 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, Compon
|
Initialization
|
https://gradio.app/docs/gradio/radio
|
Gradio - Radio Docs
|
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.
rtl: bool
default `= False`
If True, the radio buttons will be displayed in right-to-left order. Default
is False.
|
Initialization
|
https://gradio.app/docs/gradio/radio
|
Gradio - Radio Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.Radio` | "radio" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/radio
|
Gradio - Radio Docs
|
sentence_builderblocks_essay
Open in 🎢 ↗ import gradio as gr def sentence_builder(quantity, animal,
countries, place, activity_list, morning): return f"""The {quantity} {animal}s
from {" and ".join(countries)} went to the {place} where they {" and
".join(activity_list)} until the {"morning" if morning else "night"}""" demo =
gr.Interface( sentence_builder, [ gr.Slider(2, 20, value=4, label="Count",
info="Choose between 2 and 20"), gr.Dropdown( ["cat", "dog", "bird"],
label="Animal", info="Will add more animals later!" ),
gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="Countries", info="Where
are they from?"), gr.Radio(["park", "zoo", "road"], label="Location",
info="Where did they go?"), gr.Dropdown( ["ran", "swam", "ate", "slept"],
value=["swam", "slept"], multiselect=True, label="Activity", info="Lorem ipsum
dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies
aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl." ),
gr.Checkbox(label="Morning", info="Did they do it in the morning?"), ],
"text", examples=[ [2, "cat", ["Japan", "Pakistan"], "park", ["ate", "swam"],
True], [4, "dog", ["Japan"], "zoo", ["ate", "swam"], False], [10, "bird",
["USA", "Pakistan"], "road", ["ran"], False], [8, "cat", ["Pakistan"], "zoo",
["ate"], True], ] ) if __name__ == "__main__": demo.launch()
import gradio as gr
def sentence_builder(quantity, animal, countries, place, activity_list, morning):
return f"""The {quantity} {animal}s from {" and ".join(countries)} went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""
demo = gr.Interface(
sentence_builder,
[
gr.Slider(2, 20, value=4, label="Count", info="Choose between 2 and 20"),
gr.Dropdown(
["cat", "dog", "bird"], label="Animal", info="Will add more animals later!"
),
gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="
|
Demos
|
https://gradio.app/docs/gradio/radio
|
Gradio - Radio Docs
|
,
gr.Dropdown(
["cat", "dog", "bird"], label="Animal", info="Will add more animals later!"
),
gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="Countries", info="Where are they from?"),
gr.Radio(["park", "zoo", "road"], label="Location", info="Where did they go?"),
gr.Dropdown(
["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True, label="Activity", info="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl."
),
gr.Checkbox(label="Morning", info="Did they do it in the morning?"),
],
"text",
examples=[
[2, "cat", ["Japan", "Pakistan"], "park", ["ate", "swam"], True],
[4, "dog", ["Japan"], "zoo", ["ate", "swam"], False],
[10, "bird", ["USA", "Pakistan"], "road", ["ran"], False],
[8, "cat", ["Pakistan"], "zoo", ["ate"], True],
]
)
if __name__ == "__main__":
demo.launch()
Open in 🎢 ↗ import gradio as gr countries_cities_dict = { "USA": ["New York",
"Los Angeles", "Chicago"], "Canada": ["Toronto", "Montreal", "Vancouver"],
"Pakistan": ["Karachi", "Lahore", "Islamabad"], } def change_textbox(choice):
if choice == "short": return gr.Textbox(lines=2, visible=True),
gr.Button(interactive=True) elif choice == "long": return gr.Textbox(lines=8,
visible=True, value="Lorem ipsum dolor sit amet"), gr.Button(interactive=True)
else: return gr.Textbox(visible=False), gr.Button(interactive=False) with
gr.Blocks() as demo: radio = gr.Radio( ["short", "long", "none"], label="What
kind of essay would you like to write?" ) text = gr.Textbox(lines=2,
interactive=True, show_copy_button=True) with gr.Row(): num =
gr.Number(minimum=0, maximum=100, label="input") out =
gr.Number(label="output") minimum_slider = gr.Slider(0, 100, 0, label="min"
|
Demos
|
https://gradio.app/docs/gradio/radio
|
Gradio - Radio Docs
|
ines=2,
interactive=True, show_copy_button=True) with gr.Row(): num =
gr.Number(minimum=0, maximum=100, label="input") out =
gr.Number(label="output") minimum_slider = gr.Slider(0, 100, 0, label="min")
maximum_slider = gr.Slider(0, 100, 100, label="max") submit_btn =
gr.Button("Submit", variant="primary") with gr.Row(): country =
gr.Dropdown(list(countries_cities_dict.keys()), label="Country") cities =
gr.Dropdown([], label="Cities") @country.change(inputs=country,
outputs=cities) def update_cities(country): cities =
list(countries_cities_dict[country]) return gr.Dropdown(choices=cities,
value=cities[0], interactive=True) def reset_bounds(minimum, maximum): return
gr.Number(minimum=minimum, maximum=maximum) radio.change(fn=change_textbox,
inputs=radio, outputs=[text, submit_btn]) gr.on( [minimum_slider.change,
maximum_slider.change], reset_bounds, [minimum_slider, maximum_slider],
outputs=num, ) num.submit(lambda x: x, num, out) if __name__ == "__main__":
demo.launch()
import gradio as gr
countries_cities_dict = {
"USA": ["New York", "Los Angeles", "Chicago"],
"Canada": ["Toronto", "Montreal", "Vancouver"],
"Pakistan": ["Karachi", "Lahore", "Islamabad"],
}
def change_textbox(choice):
if choice == "short":
return gr.Textbox(lines=2, visible=True), gr.Button(interactive=True)
elif choice == "long":
return gr.Textbox(lines=8, visible=True, value="Lorem ipsum dolor sit amet"), gr.Button(interactive=True)
else:
return gr.Textbox(visible=False), gr.Button(interactive=False)
with gr.Blocks() as demo:
radio = gr.Radio(
["short", "long", "none"], label="What kind of essay would you like to write?"
)
text = gr.Textbox(lines=2, interactive=True, show_copy_button=True)
with gr.Row():
num = gr.Number(minimum=0, maximum=100, label="input")
out = gr.Number(label="output")
m
|
Demos
|
https://gradio.app/docs/gradio/radio
|
Gradio - Radio Docs
|
x(lines=2, interactive=True, show_copy_button=True)
with gr.Row():
num = gr.Number(minimum=0, maximum=100, label="input")
out = gr.Number(label="output")
minimum_slider = gr.Slider(0, 100, 0, label="min")
maximum_slider = gr.Slider(0, 100, 100, label="max")
submit_btn = gr.Button("Submit", variant="primary")
with gr.Row():
country = gr.Dropdown(list(countries_cities_dict.keys()), label="Country")
cities = gr.Dropdown([], label="Cities")
@country.change(inputs=country, outputs=cities)
def update_cities(country):
cities = list(countries_cities_dict[country])
return gr.Dropdown(choices=cities, value=cities[0], interactive=True)
def reset_bounds(minimum, maximum):
return gr.Number(minimum=minimum, maximum=maximum)
radio.change(fn=change_textbox, inputs=radio, outputs=[text, submit_btn])
gr.on(
[minimum_slider.change, maximum_slider.change],
reset_bounds,
[minimum_slider, maximum_slider],
outputs=num,
)
num.submit(lambda x: x, num, out)
if __name__ == "__main__":
demo.launch()
|
Demos
|
https://gradio.app/docs/gradio/radio
|
Gradio - Radio 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 Radio component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`Radio.select(fn, ···)` | Event listener for when the user selects or deselects the Radio. Uses event data gradio.SelectData to carry `value` referring to the label of the Radio, and `selected` to refer to state of the Radio. See EventData documentation on how to use this event data
`Radio.change(fn, ···)` | Triggered when the value of the Radio 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.
`Radio.input(fn, ···)` | This listener is triggered when the user changes the value of the Radio.
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`
Li
|
Event Listeners
|
https://gradio.app/docs/gradio/radio
|
Gradio - Radio Docs
|
function takes no inputs,
this should be an empty list.
outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as outputs. If the function returns no
outputs, this should be an empty list.
api_name: str | None | Literal[False]
default `= None`
defines how the endpoint appears in the API docs. Can be a string, None, or
False. If set to a string, the endpoint will be exposed in the API docs with
the given name. If None (default), the name of the function will be used as
the API endpoint. If False, the endpoint will not be exposed in the API docs
and downstream apps (including those that `gr.load` this app) will not be able
to use this event.
api_description: str | None | Literal[False]
default `= None`
Description of the API endpoint. Can be a string, None, or False. If set to a
string, the endpoint will be exposed in the API docs with the given
description. If None, the function's docstring will be used as the API
endpoint description. If False, then no description will be displayed in the
API docs.
scroll_to_output: bool
default `= False`
If True, will scroll to output component on completion
show_progress: Literal['full', 'minimal', 'hidden']
default `= "full"`
how to show the progress animation while event is running: "full" shows a
spinner which covers the output component area as well as a runtime display in
the upper right corner, "minimal" only shows the runtime display, "hidden"
shows no progress animation at all
show_progress_on: 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,
|
Event Listeners
|
https://gradio.app/docs/gradio/radio
|
Gradio - Radio Docs
|
will show the progress animation on all of the output components.
queue: bool
default `= True`
If True, will place the request on the queue, if the queue has been enabled.
If False, will not put this event on the queue, even if the queue has been
enabled. If None, will use the queue setting of the gradio app.
batch: bool
default `= False`
If True, then the function should process a batch of inputs, meaning that it
should accept a list of input values for each parameter. The lists should be
of equal length (and be up to length `max_batch_size`). The function is then
*required* to return a tuple of lists (even if there is only 1 output
component), with each list in the tuple corresponding to one output component.
max_batch_size: int
default `= 4`
Maximum number of inputs to batch together if this is called from the queue
(only relevant if batch=True)
preprocess: bool
default `= True`
If False, will not run preprocessing of component data before running 'fn'
(e.g. leaving it as a base64 string if this method is called with the `Image`
component).
postprocess: bool
default `= True`
If False, will not run postprocessing of component data before returning 'fn'
output to the browser.
cancels: dict[str, Any] | list[dict[str, Any]] | None
default `= None`
A list of other events to cancel when this listener is triggered. For example,
setting cancels=[click_event] will cancel the click_event, where click_event
is the return value of another components .click method. Functions that have
not yet run (or generators that are iterating) will be cancelled, 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 ar
|
Event Listeners
|
https://gradio.app/docs/gradio/radio
|
Gradio - Radio Docs
|
'always_last'] | None
default `= None`
If "once" (default for all events except `.change()`) would not allow any
submissions while an event is pending. If set to "multiple", unlimited
submissions are allowed while pending, and "always_last" (default for
`.change()` and `.key_up()` events) would allow a second submission after the
pending event is complete.
js: str | Literal[True] | None
default `= None`
Optional frontend js method to run before running 'fn'. Input arguments for js
method are values of 'inputs' and 'outputs', return should be a list of values
for output components.
concurrency_limit: int | None | Literal['default']
default `= "default"`
If set, this is the maximum number of this event that can be running
simultaneously. Can be set to None to mean no concurrency_limit (any number of
this event can be running simultaneously). Set to "default" to use the default
concurrency limit (defined by the `default_concurrency_limit` parameter in
`Blocks.queue()`, which itself is 1 by default).
concurrency_id: str | None
default `= None`
If set, this is the id of the concurrency group. Events with the same
concurrency_id will be limited by the lowest set concurrency_limit.
show_api: bool
default `= True`
whether to show this event in the "view API" page of the Gradio app, or in the
".view_api()" method of the Gradio clients. Unlike setting api_name to False,
setting show_api to False will still allow downstream apps as well as the
Clients to use this event. If fn is None, show_api will automatically be set
to False.
time_limit: int | None
default `= None`
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-rende
|
Event Listeners
|
https://gradio.app/docs/gradio/radio
|
Gradio - Radio Docs
|
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/radio
|
Gradio - Radio Docs
|
Creates a Dialogue component for displaying or collecting multi-speaker
conversations. This component can be used as input to allow users to enter
dialogue involving multiple speakers, or as output to display diarized speech,
such as the result of a transcription or speaker identification model. Each
message can be associated with a specific speaker, making it suitable for use
cases like conversations, interviews, or meetings.
|
Description
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
**As input component** : Returns the dialogue as a string or list of
dictionaries.
Your function should accept one of these types:
def predict(
value: tuple[str, list[tuple[str, str]]] | None
)
...
**As output component** : Expects a string or a list of dictionaries of
dialogue lines, where each dictionary contains 'speaker' and 'text' keys, or a
string.
Your function should return one of these types:
def predict(···) -> tuple[np.ndarray | PIL.Image.Image | str, list[tuple[np.ndarray | tuple[int, int, int, int], str]]] | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
Parameters ▼
value: list[dict[str, str]] | Callable | None
default `= None`
Value of the dialogue. It is a list of dictionaries, each containing a
'speaker' key and a 'text' key. 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['list', 'text']
default `= "text"`
The type of the component, either "list" for a multi-speaker dialogue
consisting of dictionaries with 'speaker' and 'text' keys or "text" for a
single text input. Defaults to "text".
speakers: list[str] | None
default `= None`
The different speakers allowed in the dialogue. If `None` or an empty list, no
speakers will be displayed. Instead, the component will be a standard textarea
that optionally supports `tags` autocompletion.
formatter: Callable | None
default `= None`
A function that formats the dialogue line dictionary, e.g. {"speaker":
"Speaker 1", "text": "Hello, how are you?"} into a string, e.g. "Speaker 1:
Hello, how are you?". This function is run on user input and the resulting
string is passed into the prediction function.
unformatter: Callable | None
default `= None`
A function that parses a formatted dialogue string back into a dialogue line
dictionary. Should take a single string line and return a dictionary with
'speaker' and 'text' keys. If not provided, the default unformatter will
attempt to parse the default formatter pattern.
tags: list[str] | None
default `= None`
The different tags allowed in the dialogue. Tags are displayed in an
autocomplete menu below the input textbox when the user starts typing `:`. Use
the exact tag name expected by the AI model or inference function.
separator: str
default `= " "`
The separator between the different dialogue lines used to join the formatted
dialogue lines into a single string. It should be unambiguous. For example, a
newline character
|
Initialization
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
tor: str
default `= " "`
The separator between the different dialogue lines used to join the formatted
dialogue lines into a single string. It should be unambiguous. For example, a
newline character or tab character.
color_map: dict[str, str] | None
default `= None`
A dictionary mapping speaker names to colors. The colors may be specified as
hex codes or by their names. For example: {"Speaker 1": "red", "Speaker 2":
"FFEE22"}. If not provided, default colors will be assigned to speakers. This
is only used if `interactive` is False.
label: str | None
default `= "Dialogue"`
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 | None
default `= "Type colon (:) in the dialogue line to see the available tags"`
placeholder: str | None
default `= None`
placeholder hint to provide behind textarea.
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 respec
|
Initialization
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
um 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 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 | None
default `= None`
if assigned, will be used to assume identity across a re-render. Components
that have the same key across a re-render will have their value preserved.
max_lines: int | None
default `= None`
maximum number of lines allo
|
Initialization
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
identity across a re-render. Components
that have the same key across a re-render will have their value preserved.
max_lines: int | None
default `= None`
maximum number of lines allowed in the dialogue.
show_submit_button: bool
default `= True`
If True, includes a submit button to submit the dialogue.
show_copy_button: bool
default `= True`
If True, includes a copy button to copy the text in the textbox. Only applies
if show_label is True.
ui_mode: Literal['dialogue', 'text', 'both']
default `= "both"`
Determines the user interface mode of the component. Can be "dialogue"
(displays dialogue lines), "text" (displays a single text input), or "both"
(displays both dialogue lines and a text input). Defaults to "both".
|
Initialization
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.Dialogue` | "dialogue" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
dia_dialogue_demo
Open in 🎢 ↗ import gradio as gr import httpx tags = [ "(laughs)", "(clears throat)", "(sighs)", "(gasps)", "(coughs)", "(singing)", "(sings)", "(mumbles)", "(beep)", "(groans)", "(sniffs)", "(claps)", "(screams)", "(inhales)", "(exhales)", "(applause)", "(burps)", "(humming)", "(sneezes)", "(chuckle)", "(whistles)", ] speakers = ["Speaker 1", "Speaker 2"] client = httpx.AsyncClient(timeout=180) API_URL = "https://router.huggingface.co/fal-ai/fal-ai/dia-tts" async def query(dialogue: str, token: gr.OAuthToken | None): if token is None: raise gr.Error( "No token provided. Use Sign in with Hugging Face to get a token." ) headers = { "Authorization": f"Bearer {token.token}", } response = await client.post(API_URL, headers=headers, json={"text": dialogue}) url = response.json()["audio"]["url"] print("URL: ", url) return url def formatter(speaker, text): speaker = speaker.split(" ")[1] return f"[S{speaker}] {text}" with gr.Blocks() as demo: with gr.Sidebar(): login_button = gr.LoginButton() gr.HTML( """ <h1 style='text-align: center; display: flex; align-items: center; justify-content: center;'> <img src="https://huggingface.co/datasets/freddyaboulton/bucket/resolve/main/dancing_huggy.gif" alt="Dancing Huggy" style="height: 100px; margin-right: 10px"> Dia Dialogue Generation Model </h1> <h2 style='text-align: center; display: flex; align-items: center; justify-content: center;'>Model by <a href="https://huggingface.co/nari-labs/Dia-1.6B"> Nari Labs</a>. Powered by HF and <a href="https://fal.ai/">Fal AI</a> API.</h2> <h4>Dia is a dialogue generation model that can generate realistic dialogue between two speakers. Use the dialogue component to create a conversation and then hit the submit button in the bottom right corner to see it come to life .</h4> """ ) with gr.Row(): with gr.Column(): dialogue = gr.Dialogue( speakers=speakers, tags=tags, formatter=formatter ) with gr.Column(): with gr.Row(): audio = gr.Audio(label="Audio") with gr
|
Demos
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
life .</h4> """ ) with gr.Row(): with gr.Column(): dialogue = gr.Dialogue( speakers=speakers, tags=tags, formatter=formatter ) with gr.Column(): with gr.Row(): audio = gr.Audio(label="Audio") with gr.Row(): gr.DeepLinkButton(value="Share Audio via Link") with gr.Row(): gr.Examples( examples=[ [ [ { "speaker": "Speaker 1", "text": "Why did the chicken cross the road?", }, {"speaker": "Speaker 2", "text": "I don't know!"}, { "speaker": "Speaker 1", "text": "to get to the other side! (laughs)", }, ] ], [ [ { "speaker": "Speaker 1", "text": "I am a little tired today (sighs).", }, {"speaker": "Speaker 2", "text": "Hang in there!"}, ] ], ], inputs=[dialogue], cache_examples=False, ) dialogue.submit(query, [dialogue], audio) if __name__ == "__main__": demo.launch()
import gradio as gr
import httpx
tags = [
"(laughs)",
"(clears throat)",
"(sighs)",
"(gasps)",
"(coughs)",
"(singing)",
"(sings)",
"(mumbles)",
"(beep)",
"(groans)",
"(sniffs)",
"(claps)",
"(screams)",
"(inhales)",
"(exhales)",
"(applause)",
"(burps)",
"(humming)",
"(sneezes)",
"(chuckle)",
"(whistles)",
]
speakers = ["Speaker 1", "Speaker 2"]
client = httpx.AsyncClient(timeout=180)
API_URL = "https://router.huggingface.co/fal-ai/fal-ai/dia-tts"
async def query(dialogue: str, token: gr.OAuthToken | None):
if token is None:
raise gr.Error(
"No token provided. Use Sign in with Hugging Face to get a token."
)
headers = {
"Authorization": f"Bearer {token.token}",
}
response = await client.post(API_URL, headers=headers, json={"text": dialogue})
url = response.json()["audio"]["url"]
print("URL: ", url)
return url
def formatter(speaker, text):
speaker = spea
|
Demos
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
eaders=headers, json={"text": dialogue})
url = response.json()["audio"]["url"]
print("URL: ", url)
return url
def formatter(speaker, text):
speaker = speaker.split(" ")[1]
return f"[S{speaker}] {text}"
with gr.Blocks() as demo:
with gr.Sidebar():
login_button = gr.LoginButton()
gr.HTML(
"""
 Dia Dialogue Generation Model
Model by [ Nari Labs](https://huggingface.co/nari-labs/Dia-1.6B). Powered by HF and [Fal AI](https://fal.ai/) API.
Dia is a dialogue generation model that can generate realistic dialogue between two speakers. Use the dialogue component to create a conversation and then hit the submit button in the bottom right corner to see it come to life .
"""
)
with gr.Row():
with gr.Column():
dialogue = gr.Dialogue(
speakers=speakers, tags=tags, formatter=formatter
)
with gr.Column():
with gr.Row():
audio = gr.Audio(label="Audio")
with gr.Row():
gr.DeepLinkButton(value="Share Audio via Link")
with gr.Row():
gr.Examples(
examples=[
[
[
{
"speaker": "Speaker 1",
"text": "Why did the chicken cross the road?",
},
{"speaker": "Speaker 2", "text": "I don't know!"},
{
"speaker": "Speaker 1",
"text": "to get to the other side! (laughs)",
|
Demos
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
2", "text": "I don't know!"},
{
"speaker": "Speaker 1",
"text": "to get to the other side! (laughs)",
},
]
],
[
[
{
"speaker": "Speaker 1",
"text": "I am a little tired today (sighs).",
},
{"speaker": "Speaker 2", "text": "Hang in there!"},
]
],
],
inputs=[dialogue],
cache_examples=False,
)
dialogue.submit(query, [dialogue], audio)
if __name__ == "__main__":
demo.launch()
|
Demos
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue 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 Dialogue component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`Dialogue.change(fn, ···)` | Triggered when the value of the Dialogue 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.
`Dialogue.input(fn, ···)` | This listener is triggered when the user changes the value of the Dialogue.
`Dialogue.submit(fn, ···)` | This listener is triggered when the user presses the Enter key while the Dialogue is focused.
Event Parameters
Parameters ▼
fn: Callable | None | Literal['decorator']
default `= "decorator"`
the function to call when this event is triggered. Often a machine learning
model's prediction function. Each parameter of the function corresponds to one
input component, and the function should return a single value or a tuple of
values, with each element in the tuple corresponding to one output component.
inputs: Component | BlockContext | list[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
|
Event Listeners
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
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.
b
|
Event Listeners
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
n 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
pending even
|
Event Listeners
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
ending. 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 the main fu
|
Event Listeners
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
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/dialogue
|
Gradio - Dialogue Docs
|
Constructs a Gradio app automatically from a Hugging Face model/Space repo
name or a 3rd-party API provider. Note that if a Space repo is loaded, certain
high-level attributes of the Blocks (e.g. custom `css`, `js`, and `head`
attributes) will not be loaded.
|
Description
|
https://gradio.app/docs/gradio/load
|
Gradio - Load Docs
|
import gradio as gr
demo = gr.load("gradio/question-answering", src="spaces")
demo.launch()
|
Example Usage
|
https://gradio.app/docs/gradio/load
|
Gradio - Load Docs
|
Parameters ▼
name: str
the name of the model (e.g. "google/vit-base-patch16-224") or Space (e.g.
"flax-community/spanish-gpt2"). This is the first parameter passed into the
`src` function. Can also be formatted as {src}/{repo name} (e.g.
"models/google/vit-base-patch16-224") if `src` is not provided.
src: Callable[[str, str | None], Blocks] | Literal['models', 'spaces', 'huggingface'] | None
default `= None`
function that accepts a string model `name` and a string or None `token` and
returns a Gradio app. Alternatively, this parameter takes one of two strings
for convenience: "models" (for loading a Hugging Face model through the
Inference API) or "spaces" (for loading a Hugging Face Space). If None, uses
the prefix of the `name` parameter to determine `src`.
token: str | None
default `= None`
optional token that is passed as the second parameter to the `src` function.
If not explicitly provided, will use the HF_TOKEN environment variable or
fallback to the locally-saved HF token when loading models but not Spaces
(when loading Spaces, only provide a token if you are loading a trusted
private Space as the token can be read by the Space you are loading). Find
your HF tokens here: https://huggingface.co/settings/tokens.
hf_token: str | None
default `= None`
accept_token: bool | LoginButton
default `= False`
if True, a Textbox component is first rendered to allow the user to provide a
token, which will be used instead of the `token` parameter when calling the
loaded model or Space. Can also provide an instance of a gr.LoginButton in the
same Blocks scope, which allows the user to login with a Hugging Face account
whose token will be used instead of the `token` parameter when calling the
loaded model or Space.
provider: PROVIDER_T | None
default `= None`
the name of the third-party (non-Hugging Face) providers to use for model
inference (e.g. "replicate", "sambanova
|
Initialization
|
https://gradio.app/docs/gradio/load
|
Gradio - Load Docs
|
loaded model or Space.
provider: PROVIDER_T | None
default `= None`
the name of the third-party (non-Hugging Face) providers to use for model
inference (e.g. "replicate", "sambanova", "fal-ai", etc). Should be one of the
providers supported by `huggingface_hub.InferenceClient`. This parameter is
only used when `src` is "models"
kwargs: <class 'inspect._empty'>
additional keyword parameters to pass into the `src` function. If `src` is
"models" or "Spaces", these parameters are passed into the `gr.Interface` or
`gr.ChatInterface` constructor.
|
Initialization
|
https://gradio.app/docs/gradio/load
|
Gradio - Load Docs
|
Gradio features a built-in theming engine that lets you customize the look
and feel of your app. You can choose from a variety of themes, or create your
own. To do so, pass the `theme=` kwarg to the `Blocks` or `Interface`
constructor. For example:
with gr.Blocks(theme=gr.themes.Soft()) as demo:
...
Gradio comes with a set of prebuilt themes which you can load from
`gr.themes.*`. These are:
* — `gr.themes.Base()`
* — `gr.themes.Default()`
* — `gr.themes.Glass()`
* — `gr.themes.Monochrome()`
* — `gr.themes.Soft()`
Each of these themes set values for hundreds of CSS variables. You can use
prebuilt themes as a starting point for your own custom themes, or you can
create your own themes from scratch. Let’s take a look at each approach.
|
Introduction
|
https://gradio.app/docs/gradio/themes
|
Gradio - Themes Docs
|
The easiest way to build a theme is using the Theme Builder. To launch the
Theme Builder locally, run the following code:
import gradio as gr
gr.themes.builder()
You can use the Theme Builder running on Spaces above, though it runs much
faster when you launch it locally via `gr.themes.builder()`.
As you edit the values in the Theme Builder, the app will preview updates
in real time. You can download the code to generate the theme you’ve created
so you can use it in any Gradio app.
In the rest of the guide, we will cover building themes programmatically.
|
Using the Theme Builder
|
https://gradio.app/docs/gradio/themes
|
Gradio - Themes Docs
|
Constructor
Although each theme has hundreds of CSS variables, the values for most
these variables are drawn from 8 core variables which can be set through the
constructor of each prebuilt theme. Modifying these 8 arguments allows you to
quickly change the look and feel of your app.
|
Extending Themes via the
|
https://gradio.app/docs/gradio/themes
|
Gradio - Themes Docs
|
The first 3 constructor arguments set the colors of the theme and are
`gradio.themes.Color` objects. Internally, these Color objects hold brightness
values for the palette of a single hue, ranging from 50, 100, 200…, 800, 900,
950. Other CSS variables are derived from these 3 colors.
The 3 color constructor arguments are:
* — `primary_hue`: This is the color draws attention in your theme. In the default theme, this is set to `gradio.themes.colors.orange`.
* — `secondary_hue`: This is the color that is used for secondary elements in your theme. In the default theme, this is set to `gradio.themes.colors.blue`.
* — `neutral_hue`: This is the color that is used for text and other neutral elements in your theme. In the default theme, this is set to `gradio.themes.colors.gray`.
You could modify these values using their string shortcuts, such as
with gr.Blocks(theme=gr.themes.Default(primary_hue="red", secondary_hue="pink")) as demo:
...
or you could use the `Color` objects directly, like this:
with gr.Blocks(theme=gr.themes.Default(primary_hue=gr.themes.colors.red, secondary_hue=gr.themes.colors.pink)) as demo:
...
Predefined colors are:
* — `slate`
* — `gray`
* — `zinc`
* — `neutral`
* — `stone`
* — `red`
* — `orange`
* — `amber`
* — `yellow`
* — `lime`
* — `green`
* — `emerald`
* — `teal`
* — `cyan`
* — `sky`
* — `blue`
* — `indigo`
* — `violet`
* — `purple`
* — `fuchsia`
* — `pink`
* — `rose`
You could also create your own custom `Color` objects and pass them in.
|
Core Colors
|
https://gradio.app/docs/gradio/themes
|
Gradio - Themes Docs
|
The next 3 constructor arguments set the sizing of the theme and are
`gradio.themes.Size` objects. Internally, these Size objects hold pixel size
values that range from `xxs` to `xxl`. Other CSS variables are derived from
these 3 sizes.
* — `spacing_size`: This sets the padding within and spacing between elements. In the default theme, this is set to `gradio.themes.sizes.spacing_md`.
* — `radius_size`: This sets the roundedness of corners of elements. In the default theme, this is set to `gradio.themes.sizes.radius_md`.
* — `text_size`: This sets the font size of text. In the default theme, this is set to `gradio.themes.sizes.text_md`.
You could modify these values using their string shortcuts, such as
with gr.Blocks(theme=gr.themes.Default(spacing_size="sm", radius_size="none")) as demo:
...
or you could use the `Size` objects directly, like this:
with gr.Blocks(theme=gr.themes.Default(spacing_size=gr.themes.sizes.spacing_sm, radius_size=gr.themes.sizes.radius_none)) as demo:
...
The predefined size objects are:
* — `radius_none`
* — `radius_sm`
* — `radius_md`
* — `radius_lg`
* — `spacing_sm`
* — `spacing_md`
* — `spacing_lg`
* — `text_sm`
* — `text_md`
* — `text_lg`
You could also create your own custom `Size` objects and pass them in.
|
Core Sizing
|
https://gradio.app/docs/gradio/themes
|
Gradio - Themes Docs
|
The final 2 constructor arguments set the fonts of the theme. You can pass
a list of fonts to each of these arguments to specify fallbacks. If you
provide a string, it will be loaded as a system font. If you provide a
`gradio.themes.GoogleFont`, the font will be loaded from Google Fonts.
* — `font`: This sets the primary font of the theme. In the default theme, this is set to `gradio.themes.GoogleFont("Source Sans Pro")`.
* — `font_mono`: This sets the monospace font of the theme. In the default theme, this is set to `gradio.themes.GoogleFont("IBM Plex Mono")`.
You could modify these values such as the following:
with gr.Blocks(theme=gr.themes.Default(font=[gr.themes.GoogleFont("Inconsolata"), "Arial", "sans-serif"])) as demo:
...
|
Core Fonts
|
https://gradio.app/docs/gradio/themes
|
Gradio - Themes Docs
|
You can also modify the values of CSS variables after the theme has been
loaded. To do so, use the `.set()` method of the theme object to get access to
the CSS variables. For example:
theme = gr.themes.Default(primary_hue="blue").set(
loader_color="FF0000",
slider_color="FF0000",
)
with gr.Blocks(theme=theme) as demo:
...
In the example above, we’ve set the `loader_color` and `slider_color`
variables to `FF0000`, despite the overall `primary_color` using the blue
color palette. You can set any CSS variable that is defined in the theme in
this manner.
Your IDE type hinting should help you navigate these variables. Since there
are so many CSS variables, let’s take a look at how these variables are named
and organized.
|
Extending Themes via `.set()`
|
https://gradio.app/docs/gradio/themes
|
Gradio - Themes Docs
|
Conventions
CSS variable names can get quite long, like
`button_primary_background_fill_hover_dark`! However they follow a common
naming convention that makes it easy to understand what they do and to find
the variable you’re looking for. Separated by underscores, the variable name
is made up of:
* — 1. The target element, such as `button`, `slider`, or `block`.
* — 2. The target element type or sub-element, such as `button_primary`, or `block_label`.
* — 3. The property, such as `button_primary_background_fill`, or `block_label_border_width`.
* — 4. Any relevant state, such as `button_primary_background_fill_hover`.
* — 5. If the value is different in dark mode, the suffix `_dark`. For example, `input_border_color_focus_dark`.
Of course, many CSS variable names are shorter than this, such as
`table_border_color`, or `input_shadow`.
|
CSS Variable Naming
|
https://gradio.app/docs/gradio/themes
|
Gradio - Themes Docs
|
Though there are hundreds of CSS variables, they do not all have to have
individual values. They draw their values by referencing a set of core
variables and referencing each other. This allows us to only have to modify a
few variables to change the look and feel of the entire theme, while also
getting finer control of individual elements that we may want to modify.
Referencing Core Variables
To reference one of the core constructor variables, precede the variable
name with an asterisk. To reference a core color, use the `*primary_`,
`*secondary_`, or `*neutral_` prefix, followed by the brightness value. For
example:
theme = gr.themes.Default(primary_hue="blue").set(
button_primary_background_fill="*primary_200",
button_primary_background_fill_hover="*primary_300",
)
In the example above, we’ve set the `button_primary_background_fill` and
`button_primary_background_fill_hover` variables to `*primary_200` and
`*primary_300`. These variables will be set to the 200 and 300 brightness
values of the blue primary color palette, respectively.
Similarly, to reference a core size, use the `*spacing_`, `*radius_`, or
`*text_` prefix, followed by the size value. For example:
theme = gr.themes.Default(radius_size="md").set(
button_primary_border_radius="*radius_xl",
)
In the example above, we’ve set the `button_primary_border_radius` variable
to `*radius_xl`. This variable will be set to the `xl` setting of the medium
radius size range.
|
CSS Variable Organization
|
https://gradio.app/docs/gradio/themes
|
Gradio - Themes Docs
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.