text
stringlengths 0
2k
| heading1
stringlengths 4
79
| source_page_url
stringclasses 178
values | source_page_title
stringclasses 178
values |
---|---|---|---|
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
default `= True`
If False, component will be hidden.
elem_id: str | None
default `= None`
An optional string that is assigned as the id of this component in the HTML
DOM. Can be used for targeting CSS styles.
elem_classes: list[str] | str | None
default `= None`
An optional list of strings that are assigned as the classes of this component
in the HTML DOM. Can be used for targeting CSS styles.
render: bool
default `= True`
If False, component will not render be rendered in the Blocks context. Should
be used if the intention is to assign event listeners now but render the
component later.
key: int | str | tuple[int | str, ...] | None
default `= None`
in a gr.render, Components with the same key across re-renders are treated as
the same component, not a new component. Properties set in 'preserved_by_key'
are not reset across a re-render.
preserved_by_key: list[str] | str | None
default `= "value"`
A list of parameters from this component's constructor. Inside a gr.render()
function, if a component is re-rendered with the same key, these (and only
these) parameters will be preserved in the UI (if they have been changed by
the user or an event listener) instead of re-rendered based on the values
provided during constructor.
|
Initialization
|
https://gradio.app/docs/gradio/colorpicker
|
Gradio - Colorpicker Docs
|
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.
|
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
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
default `= True`
If False, component will be hidden.
elem_id: str | None
default `= None`
An optional string that is assigned as the id of this component in the HTML
DOM. Can be used for targeting CSS styles.
elem_classes: list[str] | str | None
default `= None`
An optional list of strings that are assigned as the classes of this component
in the HTML DOM. Can be used for targeting CSS styles.
render: bool
default `= True`
If False, component will not render be rendered in the Blocks context. Should
be used if the intention is to assign event listeners now but render the
component later.
key: int | str | tuple[int | str, ...] | None
default `= None`
in a gr.render, Components with the same key across re-renders are treated as
the same component, not a new component. Properties set in 'preserved_by_k
|
Initialization
|
https://gradio.app/docs/gradio/radio
|
Gradio - Radio Docs
|
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.
|
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.
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.
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. For example, a newline character or empty
string.
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
|
Initialization
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
`= 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 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:
|
Initialization
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
e, will be rendered as an editable textbox; if False, editing will be
disabled. If not provided, this is inferred based on whether the component is
used as an input or output.
visible: bool
default `= True`
If False, component will be hidden.
elem_id: str | None
default `= None`
An optional string that is assigned as the id of this component in the HTML
DOM. Can be used for targeting CSS styles.
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 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.
|
Initialization
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
ncludes a copy button to copy the text in the textbox. Only applies
if show_label is True.
|
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.
|
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.
|
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'] | 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", "fal-ai", et
|
Initialization
|
https://gradio.app/docs/gradio/load
|
Gradio - Load Docs
|
r 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
|
Variables can also reference each other. For example, look at the example
below:
theme = gr.themes.Default().set(
button_primary_background_fill="FF0000",
button_primary_background_fill_hover="FF0000",
button_primary_border="FF0000",
)
Having to set these values to a common color is a bit tedious. Instead, we
can reference the `button_primary_background_fill` variable in the
`button_primary_background_fill_hover` and `button_primary_border` variables,
using a `*` prefix.
theme = gr.themes.Default().set(
button_primary_background_fill="FF0000",
button_primary_background_fill_hover="*button_primary_background_fill",
button_primary_border="*button_primary_background_fill",
)
Now, if we change the `button_primary_background_fill` variable, the
`button_primary_background_fill_hover` and `button_primary_border` variables
will automatically update as well.
This is particularly useful if you intend to share your theme - it makes it
easy to modify the theme without having to change every variable.
Note that dark mode variables automatically reference each other. For
example:
theme = gr.themes.Default().set(
button_primary_background_fill="FF0000",
button_primary_background_fill_dark="AAAAAA",
button_primary_border="*button_primary_background_fill",
button_primary_border_dark="*button_primary_background_fill_dark",
)
`button_primary_border_dark` will draw its value from
`button_primary_background_fill_dark`, because dark mode always draw from the
dark version of the variable.
|
Referencing Other Variables
|
https://gradio.app/docs/gradio/themes
|
Gradio - Themes Docs
|
Let’s say you want to create a theme from scratch! We’ll go through it step
by step - you can also see the source of prebuilt themes in the gradio source
repo for reference - [here’s the source](https://github.com/gradio-
app/gradio/blob/main/gradio/themes/monochrome.py) for the Monochrome theme.
Our new theme class will inherit from `gradio.themes.Base`, a theme that
sets a lot of convenient defaults. Let’s make a simple demo that creates a
dummy theme called Seafoam, and make a simple app that uses it.
$code_theme_new_step_1
The Base theme is very barebones, and uses `gr.themes.Blue` as it primary
color - you’ll note the primary button and the loading animation are both blue
as a result. Let’s change the defaults core arguments of our app. We’ll
overwrite the constructor and pass new defaults for the core constructor
arguments.
We’ll use `gr.themes.Emerald` as our primary color, and set secondary and
neutral hues to `gr.themes.Blue`. We’ll make our text larger using `text_lg`.
We’ll use `Quicksand` as our default font, loaded from Google Fonts.
$code_theme_new_step_2
See how the primary button and the loading animation are now green? These CSS
variables are tied to the `primary_hue` variable.
Let’s modify the theme a bit more directly. We’ll call the `set()` method to
overwrite CSS variable values explicitly. We can use any CSS logic, and
reference our core constructor arguments using the `*` prefix.
$code_theme_new_step_3
Look how fun our theme looks now! With just a few variable changes, our theme
looks completely different.
You may find it helpful to explore the [source code of the other prebuilt
themes](https://github.com/gradio-app/gradio/blob/main/gradio/themes) to see
how they modified the base theme. You can also find your browser’s Inspector
useful to select elements from the UI and see what CSS variables are being
used in the styles panel.
Sharing Themes
Once you have created a theme, you can upload it to the HuggingFace Hub to
|
Creating a Full Theme
|
https://gradio.app/docs/gradio/themes
|
Gradio - Themes Docs
|
ctor
useful to select elements from the UI and see what CSS variables are being
used in the styles panel.
Sharing Themes
Once you have created a theme, you can upload it to the HuggingFace Hub to let
others view it, use it, and build off of it!
|
Creating a Full Theme
|
https://gradio.app/docs/gradio/themes
|
Gradio - Themes Docs
|
There are two ways to upload a theme, via the theme class instance or the
command line. We will cover both of them with the previously created `seafoam`
theme.
* Via the class instance
Each theme instance has a method called `push_to_hub` we can use to upload a
theme to the HuggingFace hub.
seafoam.push_to_hub(repo_name="seafoam",
version="0.0.1",
hf_token="<token>")
* Via the command line
First save the theme to disk
seafoam.dump(filename="seafoam.json")
Then use the `upload_theme` command:
upload_theme\
"seafoam.json"\
"seafoam"\
--version "0.0.1"\
--hf_token "<token>"
In order to upload a theme, you must have a HuggingFace account and pass your
[Access Token](https://huggingface.co/docs/huggingface_hub/quick-startlogin)
as the `hf_token` argument. However, if you log in via the [HuggingFace
command line](https://huggingface.co/docs/huggingface_hub/quick-startlogin)
(which comes installed with `gradio`), you can omit the `hf_token` argument.
The `version` argument lets you specify a valid [semantic
version](https://www.geeksforgeeks.org/introduction-semantic-versioning/)
string for your theme. That way your users are able to specify which version
of your theme they want to use in their apps. This also lets you publish
updates to your theme without worrying about changing how previously created
apps look. The `version` argument is optional. If omitted, the next patch
version is automatically applied.
|
Uploading a Theme
|
https://gradio.app/docs/gradio/themes
|
Gradio - Themes Docs
|
By calling `push_to_hub` or `upload_theme`, the theme assets will be stored in
a [HuggingFace space](https://huggingface.co/docs/hub/spaces-overview).
The theme preview for our seafoam theme is here: [seafoam
preview](https://huggingface.co/spaces/gradio/seafoam).
|
Theme Previews
|
https://gradio.app/docs/gradio/themes
|
Gradio - Themes Docs
|
The [Theme Gallery](https://huggingface.co/spaces/gradio/theme-gallery) shows
all the public gradio themes. After publishing your theme, it will
automatically show up in the theme gallery after a couple of minutes.
You can sort the themes by the number of likes on the space and from most to
least recently created as well as toggling themes between light and dark mode.
|
Discovering Themes
|
https://gradio.app/docs/gradio/themes
|
Gradio - Themes Docs
|
To use a theme from the hub, use the `from_hub` method on the `ThemeClass` and
pass it to your app:
my_theme = gr.Theme.from_hub("gradio/seafoam")
with gr.Blocks(theme=my_theme) as demo:
....
You can also pass the theme string directly to `Blocks` or `Interface`
(`gr.Blocks(theme="gradio/seafoam")`)
You can pin your app to an upstream theme version by using semantic versioning
expressions.
For example, the following would ensure the theme we load from the `seafoam`
repo was between versions `0.0.1` and `0.1.0`:
with gr.Blocks(theme="gradio/seafoam@>=0.0.1,<0.1.0") as demo:
....
Enjoy creating your own themes! If you make one you’re proud of, please share
it with the world by uploading it to the hub! If you tag us on
[Twitter](https://twitter.com/gradio) we can give your theme a shout out!
|
Downloading
|
https://gradio.app/docs/gradio/themes
|
Gradio - Themes Docs
|
Creates a checkbox that can be set to `True` or `False`. Can be used as an
input to pass a boolean value to a function or as an output to display a
boolean value.
|
Description
|
https://gradio.app/docs/gradio/checkbox
|
Gradio - Checkbox Docs
|
**As input component** : Passes the status of the checkbox as a `bool`.
Your function should accept one of these types:
def predict(
value: bool | None
)
...
**As output component** : Expects a `bool` value that is set as the status
of the checkbox
Your function should return one of these types:
def predict(···) -> bool | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/checkbox
|
Gradio - Checkbox Docs
|
Parameters ▼
value: bool | Callable
default `= False`
if True, checked 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.
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 certain scale value results in
|
Initialization
|
https://gradio.app/docs/gradio/checkbox
|
Gradio - Checkbox Docs
|
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, this checkbox can be checked; if False, checking will be disabled. If
not provided, this is inferred based on whether the component is used as an
input or output.
visible: bool
default `= True`
If False, component will be hidden.
elem_id: str | None
default `= None`
An optional string that is assigned as the id of this component in the HTML
DOM. Can be used for targeting CSS styles.
elem_classes: list[str] | str | None
default `= None`
An optional list of strings that are assigned as the classes of this component
in the HTML DOM. Can be used for targeting CSS styles.
render: bool
default `= True`
If False, component will not render be rendered in the Blocks context. Should
be used if the intention is to assign event listeners now but render the
component later.
key: int | str | tuple[int | str, ...] | None
default `= None`
in a gr.render, Components with the same key across re-renders are treated as
the same component, not a new component. Properties set in 'preserved_by_key'
are not reset across a re-render.
preserved_by_key: list[str] | str | None
default `= "value"`
A list of parameters from this component's constructor. Inside a gr.render()
function, if a component is re-rendered with the same key, these (and only
these) parameters will be preserved in the UI (if they have been changed by
the user or an event listener) instead of re-rendered based on the values
provided during constructor.
|
Initialization
|
https://gradio.app/docs/gradio/checkbox
|
Gradio - Checkbox Docs
|
n event listener) instead of re-rendered based on the values
provided during constructor.
|
Initialization
|
https://gradio.app/docs/gradio/checkbox
|
Gradio - Checkbox Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.Checkbox` | "checkbox" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/checkbox
|
Gradio - Checkbox Docs
|
sentence_builderhello_world_3
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/checkbox
|
Gradio - Checkbox 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 def greet(name, is_morning, temperature):
salutation = "Good morning" if is_morning else "Good evening" greeting =
f"{salutation} {name}. It is {temperature} degrees today" celsius =
(temperature - 32) * 5 / 9 return greeting, round(celsius, 2) demo =
gr.Interface( fn=greet, inputs=["text", "checkbox", gr.Slider(0, 100)],
outputs=["text", "number"], ) if __name__ == "__main__": demo.launch()
import gradio as gr
def greet(name, is_morning, temperature):
salutation = "Good morning" if is_morning else "Good evening"
greeting = f"{salutation} {name}. It is {temperature} degrees today"
celsius = (temperature - 32) * 5 / 9
return greeting, round(celsius, 2)
demo = gr.Interface(
fn=greet,
inputs=["text", "checkbox", gr.Slider(0, 100)],
outp
|
Demos
|
https://gradio.app/docs/gradio/checkbox
|
Gradio - Checkbox Docs
|
celsius = (temperature - 32) * 5 / 9
return greeting, round(celsius, 2)
demo = gr.Interface(
fn=greet,
inputs=["text", "checkbox", gr.Slider(0, 100)],
outputs=["text", "number"],
)
if __name__ == "__main__":
demo.launch()
|
Demos
|
https://gradio.app/docs/gradio/checkbox
|
Gradio - Checkbox 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 Checkbox component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`Checkbox.change(fn, ···)` | Triggered when the value of the Checkbox 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.
`Checkbox.input(fn, ···)` | This listener is triggered when the user changes the value of the Checkbox.
`Checkbox.select(fn, ···)` | Event listener for when the user selects or deselects the Checkbox. Uses event data gradio.SelectData to carry `value` referring to the label of the Checkbox, and `selected` to refer to state of the Checkbox. See EventData documentation on how to use this event data
Event Parameters
Parameters ▼
fn: Callable | None | Literal['decorator']
default `= "decorator"`
the function to call when this event is triggered. Often a machine learning
model's prediction function. Each parameter of the function corresponds to one
input component, and the function should return a single value or a tuple of
values, with each element in the tuple corresponding to one output component.
inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as inputs. If the function takes no inputs,
this should be an empty list.
outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] |
|
Event Listeners
|
https://gradio.app/docs/gradio/checkbox
|
Gradio - Checkbox Docs
|
ts 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 place the request on the queue, if the queue h
|
Event Listeners
|
https://gradio.app/docs/gradio/checkbox
|
Gradio - Checkbox Docs
|
ess 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 while an event is pending. If set to "multiple
|
Event Listeners
|
https://gradio.app/docs/gradio/checkbox
|
Gradio - Checkbox Docs
|
iteral['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(). If set, this
value identifies an event a
|
Event Listeners
|
https://gradio.app/docs/gradio/checkbox
|
Gradio - Checkbox Docs
|
ult `= False`
key: int | str | tuple[int | str, ...] | None
default `= None`
A unique key for this event listener to be used in @gr.render(). If set, this
value identifies an event as identical across re-renders when the key is
identical.
|
Event Listeners
|
https://gradio.app/docs/gradio/checkbox
|
Gradio - Checkbox Docs
|
Displays text that contains spans that are highlighted by category or
numerical value.
|
Description
|
https://gradio.app/docs/gradio/highlightedtext
|
Gradio - Highlightedtext Docs
|
**As input component** : Passes the value as a list of tuples as a `list[tuple]` into the function. Each `tuple` consists of a `str` substring of the text (so the entire text is included) and `str | float | None` label, which is the category or confidence of that substring.
Your function should accept one of these types:
def predict(
value: list[tuple[str, str | float | None]] | None
)
...
**As output component** : Expects a list of (word, category) tuples, or a
dictionary of two keys: "text", and "entities", which itself is a list of
dictionaries, each of which have the keys: "entity" (or "entity_group"),
"start", and "end"
Your function should return one of these types:
def predict(···) -> list[tuple[str, str | float | None]] | dict | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/highlightedtext
|
Gradio - Highlightedtext Docs
|
Parameters ▼
value: list[tuple[str, str | float | None]] | dict | Callable | None
default `= None`
Default value to show. If a function is provided, the function will be called
each time the app loads to set the initial value of this component.
color_map: dict[str, str] | None
default `= None`
A dictionary mapping labels to colors. The colors may be specified as hex
codes or by their names. For example: {"person": "red", "location": "FFEE22"}
show_legend: bool
default `= False`
whether to show span categories in a separate legend or inline.
show_inline_category: bool
default `= True`
If False, will not display span category label. Only applies if
show_legend=False and interactive=False.
combine_adjacent: bool
default `= False`
If True, will merge the labels of adjacent tokens belonging to the same
category.
adjacent_separator: str
default `= ""`
Specifies the separator to be used between tokens if combine_adjacent is True.
label: str | I18nData | None
default `= None`
the label for this component. Appears above the component and is also used as
the header if there are a table of examples for this component. If None and
used in a `gr.Interface`, the label will be the name of the parameter this
component is assigned to.
every: Timer | float | None
default `= None`
Continously calls `value` to recalculate it if `value` is a function (has no
effect otherwise). Can provide a Timer whose tick resets `value`, or a float
that provides the regular interval for the reset Timer.
inputs: Component | list[Component] | set[Component] | None
default `= None`
Components that are used as inputs to calculate `value` if `value` is a
function (has no effect otherwise). `value` is recalculated any time the
inputs change.
show_label: bool | None
default `= None`
if True, will display label.
con
|
Initialization
|
https://gradio.app/docs/gradio/highlightedtext
|
Gradio - Highlightedtext Docs
|
is a
function (has no effect otherwise). `value` is recalculated any time the
inputs change.
show_label: bool | None
default `= None`
if True, will display label.
container: bool
default `= True`
If True, will place the component in a container - providing some extra
padding around the border.
scale: int | None
default `= None`
relative size compared to adjacent Components. For example if Components A and
B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide
as B. Should be an integer. scale applies in Rows, and to top-level Components
in Blocks where fill_height=True.
min_width: int
default `= 160`
minimum pixel width, will wrap if not sufficient screen space to satisfy this
value. If a certain scale value results in this Component being narrower than
min_width, the min_width parameter will be respected first.
visible: bool
default `= True`
If False, component will be hidden.
elem_id: str | None
default `= None`
An optional string that is assigned as the id of this component in the HTML
DOM. Can be used for targeting CSS styles.
elem_classes: list[str] | str | None
default `= None`
An optional list of strings that are assigned as the classes of this component
in the HTML DOM. Can be used for targeting CSS styles.
render: bool
default `= True`
If False, component will not render be rendered in the Blocks context. Should
be used if the intention is to assign event listeners now but render the
component later.
key: int | str | tuple[int | str, ...] | None
default `= None`
in a gr.render, Components with the same key across re-renders are treated as
the same component, not a new component. Properties set in 'preserved_by_key'
are not reset across a re-render.
preserved_by_key: list[str] | str | None
default `= "value"`
A list of parameters from this component's constru
|
Initialization
|
https://gradio.app/docs/gradio/highlightedtext
|
Gradio - Highlightedtext Docs
|
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.
interactive: bool | None
default `= None`
If True, the component will be editable, and allow user to select spans of
text and label them.
rtl: bool
default `= False`
If True, will display the text in right-to-left direction, and the labels in
the legend will also be aligned to the right.
|
Initialization
|
https://gradio.app/docs/gradio/highlightedtext
|
Gradio - Highlightedtext Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.HighlightedText` | "highlightedtext" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/highlightedtext
|
Gradio - Highlightedtext Docs
|
diff_texts
Open in 🎢 ↗ from difflib import Differ import gradio as gr def
diff_texts(text1, text2): d = Differ() return [ (token[2:], token[0] if
token[0] != " " else None) for token in d.compare(text1, text2) ] demo =
gr.Interface( diff_texts, [ gr.Textbox( label="Text 1", info="Initial text",
lines=3, value="The quick brown fox jumped over the lazy dogs.", ),
gr.Textbox( label="Text 2", info="Text to compare", lines=3, value="The fast
brown fox jumps over lazy dogs.", ), ], gr.HighlightedText( label="Diff",
combine_adjacent=True, show_legend=True, color_map={"+": "red", "-":
"green"}), theme=gr.themes.Base() ) if __name__ == "__main__": demo.launch()
from difflib import Differ
import gradio as gr
def diff_texts(text1, text2):
d = Differ()
return [
(token[2:], token[0] if token[0] != " " else None)
for token in d.compare(text1, text2)
]
demo = gr.Interface(
diff_texts,
[
gr.Textbox(
label="Text 1",
info="Initial text",
lines=3,
value="The quick brown fox jumped over the lazy dogs.",
),
gr.Textbox(
label="Text 2",
info="Text to compare",
lines=3,
value="The fast brown fox jumps over lazy dogs.",
),
],
gr.HighlightedText(
label="Diff",
combine_adjacent=True,
show_legend=True,
color_map={"+": "red", "-": "green"}),
theme=gr.themes.Base()
)
if __name__ == "__main__":
demo.launch()
|
Demos
|
https://gradio.app/docs/gradio/highlightedtext
|
Gradio - Highlightedtext 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 HighlightedText component supports the following event listeners. Each
event listener takes the same parameters, which are listed in the Event
Parameters table below.
Listener | Description
---|---
`HighlightedText.change(fn, ···)` | Triggered when the value of the HighlightedText 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.
`HighlightedText.select(fn, ···)` | Event listener for when the user selects or deselects the HighlightedText. Uses event data gradio.SelectData to carry `value` referring to the label of the HighlightedText, and `selected` to refer to state of the HighlightedText. See EventData documentation on how to use this event data
Event Parameters
Parameters ▼
fn: Callable | None | Literal['decorator']
default `= "decorator"`
the function to call when this event is triggered. Often a machine learning
model's prediction function. Each parameter of the function corresponds to one
input component, and the function should return a single value or a tuple of
values, with each element in the tuple corresponding to one output component.
inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as inputs. If the function takes no inputs,
this should be an empty list.
outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use
|
Event Listeners
|
https://gradio.app/docs/gradio/highlightedtext
|
Gradio - Highlightedtext Docs
|
s should be an empty list.
outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as outputs. If the function returns no
outputs, this should be an empty list.
api_name: str | None | Literal[False]
default `= None`
defines how the endpoint appears in the API docs. Can be a string, None, or
False. If set to a string, the endpoint will be exposed in the API docs with
the given name. If None (default), the name of the function will be used as
the API endpoint. If False, the endpoint will not be exposed in the API docs
and downstream apps (including those that `gr.load` this app) will not be able
to use this event.
api_description: str | None | Literal[False]
default `= None`
Description of the API endpoint. Can be a string, None, or False. If set to a
string, the endpoint will be exposed in the API docs with the given
description. If None, the function's docstring will be used as the API
endpoint description. If False, then no description will be displayed in the
API docs.
scroll_to_output: bool
default `= False`
If True, will scroll to output component on completion
show_progress: Literal['full', 'minimal', 'hidden']
default `= "full"`
how to show the progress animation while event is running: "full" shows a
spinner which covers the output component area as well as a runtime display in
the upper right corner, "minimal" only shows the runtime display, "hidden"
shows no progress animation at all
show_progress_on: Component | list[Component] | None
default `= None`
Component or list of components to show the progress animation on. If None,
will show the progress animation on all of the output components.
queue: bool
default `= True`
If True, will place the request on the queue, if the queue has been enabled.
If False, will not put this event on the
|
Event Listeners
|
https://gradio.app/docs/gradio/highlightedtext
|
Gradio - Highlightedtext Docs
|
on on all of the output components.
queue: bool
default `= True`
If True, will place the request on the queue, if the queue has been enabled.
If False, will not put this event on the queue, even if the queue has been
enabled. If None, will use the queue setting of the gradio app.
batch: bool
default `= False`
If True, then the function should process a batch of inputs, meaning that it
should accept a list of input values for each parameter. The lists should be
of equal length (and be up to length `max_batch_size`). The function is then
*required* to return a tuple of lists (even if there is only 1 output
component), with each list in the tuple corresponding to one output component.
max_batch_size: int
default `= 4`
Maximum number of inputs to batch together if this is called from the queue
(only relevant if batch=True)
preprocess: bool
default `= True`
If False, will not run preprocessing of component data before running 'fn'
(e.g. leaving it as a base64 string if this method is called with the `Image`
component).
postprocess: bool
default `= True`
If False, will not run postprocessing of component data before returning 'fn'
output to the browser.
cancels: dict[str, Any] | list[dict[str, Any]] | None
default `= None`
A list of other events to cancel when this listener is triggered. For example,
setting cancels=[click_event] will cancel the click_event, where click_event
is the return value of another components .click method. Functions that have
not yet run (or generators that are iterating) will be cancelled, but
functions that are currently running will be allowed to finish.
trigger_mode: Literal['once', 'multiple', 'always_last'] | None
default `= None`
If "once" (default for all events except `.change()`) would not allow any
submissions while an event is pending. If set to "multiple", unlimited
submissions are allowed while pending, and "
|
Event Listeners
|
https://gradio.app/docs/gradio/highlightedtext
|
Gradio - Highlightedtext Docs
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.