EllieKini/Herta
Audio-to-Audio
•
Updated
text
stringlengths 0
2k
| heading1
stringlengths 4
79
| source_page_url
stringclasses 180
values | source_page_title
stringclasses 180
values |
|---|---|---|---|
`gradio-rs` is a Gradio Client in Rust built by
[@JacobLinCool](https://github.com/JacobLinCool). You can find the repo
[here](https://github.com/JacobLinCool/gradio-rs), and more in depth API
documentation [here](https://docs.rs/gradio/latest/gradio/).
|
Introduction
|
https://gradio.app/docs/third-party-clients/rust-client
|
Third Party Clients - Rust Client Docs
|
Here is an example of using BS-RoFormer model to separate vocals and
background music from an audio file.
use gradio::{PredictionInput, Client, ClientOptions};
[tokio::main]
async fn main() {
if std::env::args().len() < 2 {
println!("Please provide an audio file path as an argument");
std::process::exit(1);
}
let args: Vec<String> = std::env::args().collect();
let file_path = &args[1];
println!("File: {}", file_path);
let client = Client::new("JacobLinCool/vocal-separation", ClientOptions::default())
.await
.unwrap();
let output = client
.predict(
"/separate",
vec![
PredictionInput::from_file(file_path),
PredictionInput::from_value("BS-RoFormer"),
],
)
.await
.unwrap();
println!(
"Vocals: {}",
output[0].clone().as_file().unwrap().url.unwrap()
);
println!(
"Background: {}",
output[1].clone().as_file().unwrap().url.unwrap()
);
}
You can find more examples [here](https://github.com/JacobLinCool/gradio-
rs/tree/main/examples).
|
Usage
|
https://gradio.app/docs/third-party-clients/rust-client
|
Third Party Clients - Rust Client Docs
|
cargo install gradio
gr --help
Take [stabilityai/stable-
diffusion-3-medium](https://huggingface.co/spaces/stabilityai/stable-
diffusion-3-medium) HF Space as an example:
> gr list stabilityai/stable-diffusion-3-medium
API Spec for stabilityai/stable-diffusion-3-medium:
/infer
Parameters:
prompt ( str )
negative_prompt ( str )
seed ( float ) numeric value between 0 and 2147483647
randomize_seed ( bool )
width ( float ) numeric value between 256 and 1344
height ( float ) numeric value between 256 and 1344
guidance_scale ( float ) numeric value between 0.0 and 10.0
num_inference_steps ( float ) numeric value between 1 and 50
Returns:
Result ( filepath )
Seed ( float ) numeric value between 0 and 2147483647
> gr run stabilityai/stable-diffusion-3-medium infer 'Rusty text "AI & CLI" on the snow.' '' 0 true 1024 1024 5 28
Result: https://stabilityai-stable-diffusion-3-medium.hf.space/file=/tmp/gradio/5735ca7775e05f8d56d929d8f57b099a675c0a01/image.webp
Seed: 486085626
For file input, simply use the file path as the argument:
gr run hf-audio/whisper-large-v3 predict 'test-audio.wav' 'transcribe'
output: " Did you know you can try the coolest model on your command line?"
|
Command Line Interface
|
https://gradio.app/docs/third-party-clients/rust-client
|
Third Party Clients - Rust Client Docs
|
Gradio applications support programmatic requests from many environments:
* The [Python Client](/docs/python-client): `gradio-client` allows you to make requests from Python environments.
* The [JavaScript Client](/docs/js-client): `@gradio/client` allows you to make requests in TypeScript from the browser or server-side.
* You can also query gradio apps [directly from cURL](/guides/querying-gradio-apps-with-curl).
|
Gradio Clients
|
https://gradio.app/docs/third-party-clients/introduction
|
Third Party Clients - Introduction Docs
|
We also encourage the development and use of third party clients built by
the community:
* [Rust Client](/docs/third-party-clients/rust-client): `gradio-rs` built by [@JacobLinCool](https://github.com/JacobLinCool) allows you to make requests in Rust.
* [Powershell Client](https://github.com/rrg92/powershai): `powershai` built by [@rrg92](https://github.com/rrg92) allows you to make requests to Gradio apps directly from Powershell. See [here for documentation](https://github.com/rrg92/powershai/blob/main/docs/en-US/providers/HUGGING-FACE.md)
|
Community Clients
|
https://gradio.app/docs/third-party-clients/introduction
|
Third Party Clients - Introduction Docs
|
Creates a bar plot component to display data from a pandas DataFrame.
|
Description
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
**As input component** : The data to display in a line plot.
Your function should accept one of these types:
def predict(
value: AltairPlotData
)
...
**As output component** : Expects a pandas DataFrame containing the data to
display in the line plot. The DataFrame should contain at least two columns,
one for the x-axis (corresponding to this component's `x` argument) and one
for the y-axis (corresponding to `y`).
Your function should return one of these types:
def predict(···) -> pd.DataFrame | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
Parameters ▼
value: pd.DataFrame | Callable | None
default `= None`
The pandas dataframe containing the data to display in the plot.
x: str | None
default `= None`
Column corresponding to the x axis. Column can be numeric, datetime, or
string/category.
y: str | None
default `= None`
Column corresponding to the y axis. Column must be numeric.
color: str | None
default `= None`
Column corresponding to series, visualized by color. Column must be
string/category.
title: str | None
default `= None`
The title to display on top of the chart.
x_title: str | None
default `= None`
The title given to the x axis. By default, uses the value of the x parameter.
y_title: str | None
default `= None`
The title given to the y axis. By default, uses the value of the y parameter.
color_title: str | None
default `= None`
The title given to the color legend. By default, uses the value of color
parameter.
x_bin: str | float | None
default `= None`
Grouping used to cluster x values. If x column is numeric, should be number to
bin the x values. If x column is datetime, should be string such as "1h",
"15m", "10s", using "s", "m", "h", "d" suffixes.
y_aggregate: Literal['sum', 'mean', 'median', 'min', 'max', 'count'] | None
default `= None`
Aggregation function used to aggregate y values, used if x_bin is provided or
x is a string/category. Must be one of "sum", "mean", "median", "min", "max".
color_map: dict[str, str] | None
default `= None`
Mapping of series to color names or codes. For example, {"success": "green",
"fail": "FF8888"}.
x_lim: list[float] | None
default `= None`
A tuple or list containing the limits for the x-axis, specified as [x_min,
x_max]. If x column is datetime type, x_lim should be timestamps.
y_lim: list[float | None]
default `= None`
A
|
Initialization
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
ple or list containing the limits for the x-axis, specified as [x_min,
x_max]. If x column is datetime type, x_lim should be timestamps.
y_lim: list[float | None]
default `= None`
A tuple of list containing the limits for the y-axis, specified as [y_min,
y_max]. To fix only one of these values, set the other to None, e.g. [0, None]
to scale from 0 to the maximum to value.
x_label_angle: float
default `= 0`
The angle of the x-axis labels in degrees offset clockwise.
y_label_angle: float
default `= 0`
The angle of the y-axis labels in degrees offset clockwise.
x_axis_labels_visible: bool | Literal['hidden']
default `= True`
Whether the x-axis labels should be visible. Can be hidden when many x-axis
labels are present.
caption: str | I18nData | None
default `= None`
The (optional) caption to display below the plot.
sort: Literal['x', 'y', '-x', '-y'] | list[str] | None
default `= None`
The sorting order of the x values, if x column is type string/category. Can be
"x", "y", "-x", "-y", or list of strings that represent the order of the
categories.
tooltip: Literal['axis', 'none', 'all'] | list[str]
default `= "axis"`
The tooltip to display when hovering on a point. "axis" shows the values for
the axis columns, "all" shows all column values, and "none" shows no tooltips.
Can also provide a list of strings representing columns to show in the
tooltip, which will be displayed along with axis values.
height: int | None
default `= None`
The height of the plot in pixels.
label: str | I18nData | None
default `= None`
The (optional) label to display on the top left corner of the plot.
show_label: bool | None
default `= None`
Whether the label should be displayed.
container: bool
default `= True`
If True, will place the component in a container - providing some extra
padding around the
|
Initialization
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
default `= None`
Whether the label should be displayed.
container: bool
default `= True`
If True, will place the component in a container - providing some extra
padding around the border.
scale: int | None
default `= None`
relative size compared to adjacent Components. For example if Components A and
B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide
as B. Should be an integer. scale applies in Rows, and to top-level Components
in Blocks where fill_height=True.
min_width: int
default `= 160`
minimum pixel width, will wrap if not sufficient screen space to satisfy this
value. If a certain scale value results in this Component being narrower than
min_width, the min_width parameter will be respected first.
every: Timer | float | None
default `= None`
Continously calls `value` to recalculate it if `value` is a function (has no
effect otherwise). Can provide a Timer whose tick resets `value`, or a float
that provides the regular interval for the reset Timer.
inputs: Component | list[Component] | Set[Component] | None
default `= None`
Components that are used as inputs to calculate `value` if `value` is a
function (has no effect otherwise). `value` is recalculated any time the
inputs change.
visible: bool | Literal['hidden']
default `= True`
Whether the plot should be visible.
elem_id: str | None
default `= None`
An optional string that is assigned as the id of this component in the HTML
DOM. Can be used for targeting CSS styles.
elem_classes: list[str] | str | None
default `= None`
An optional list of strings that are assigned as the classes of this component
in the HTML DOM. Can be used for targeting CSS styles.
render: bool
default `= True`
If False, component will not render be rendered in the Blocks context. Should
be used if the intention is to assign event listeners now but re
|
Initialization
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
S styles.
render: bool
default `= True`
If False, component will not render be rendered in the Blocks context. Should
be used if the intention is to assign event listeners now but render the
component later.
show_fullscreen_button: bool
default `= False`
If True, will show a button to make plot visible in fullscreen mode.
show_export_button: bool
default `= False`
If True, will show a button to export and download the current view of the
plot as a PNG image.
key: int | str | tuple[int | str, ...] | None
default `= None`
in a gr.render, Components with the same key across re-renders are treated as
the same component, not a new component. Properties set in 'preserved_by_key'
are not reset across a re-render.
preserved_by_key: list[str] | str | None
default `= "value"`
A list of parameters from this component's constructor. Inside a gr.render()
function, if a component is re-rendered with the same key, these (and only
these) parameters will be preserved in the UI (if they have been changed by
the user or an event listener) instead of re-rendered based on the values
provided during constructor.
|
Initialization
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.BarPlot` | "barplot" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
bar_plot_demo
Open in 🎢 ↗ import pandas as pd from random import randint, random import
gradio as gr temp_sensor_data = pd.DataFrame( { "time":
pd.date_range("2021-01-01", end="2021-01-05", periods=200), "temperature":
[randint(50 + 10 * (i % 2), 65 + 15 * (i % 2)) for i in range(200)],
"humidity": [randint(50 + 10 * (i % 2), 65 + 15 * (i % 2)) for i in
range(200)], "location": ["indoor", "outdoor"] * 100, } ) food_rating_data =
pd.DataFrame( { "cuisine": [["Italian", "Mexican", "Chinese"][i % 3] for i in
range(100)], "rating": [random() * 4 + 0.5 * (i % 3) for i in range(100)],
"price": [randint(10, 50) + 4 * (i % 3) for i in range(100)], "wait":
[random() for i in range(100)], } ) with gr.Blocks() as bar_plots: with
gr.Row(): start = gr.DateTime("2021-01-01 00:00:00", label="Start") end =
gr.DateTime("2021-01-05 00:00:00", label="End") apply_btn = gr.Button("Apply",
scale=0) with gr.Row(): group_by = gr.Radio(["None", "30m", "1h", "4h", "1d"],
value="None", label="Group by") aggregate = gr.Radio(["sum", "mean", "median",
"min", "max"], value="sum", label="Aggregation") temp_by_time = gr.BarPlot(
temp_sensor_data, x="time", y="temperature", ) temp_by_time_location =
gr.BarPlot( temp_sensor_data, x="time", y="temperature", color="location", )
time_graphs = [temp_by_time, temp_by_time_location] group_by.change( lambda
group: [gr.BarPlot(x_bin=None if group == "None" else group)] *
len(time_graphs), group_by, time_graphs ) aggregate.change( lambda aggregate:
[gr.BarPlot(y_aggregate=aggregate)] * len(time_graphs), aggregate, time_graphs
) def rescale(select: gr.SelectData): return select.index rescale_evt =
gr.on([plot.select for plot in time_graphs], rescale, None, [start, end]) for
trigger in [apply_btn.click, rescale_evt.then]: trigger( lambda start, end:
[gr.BarPlot(x_lim=[start, end])] * len(time_graphs), [start, end], time_graphs
) with gr.Row(): price_by_cuisine = gr.BarPlot( food_rating_data, x="cuisine",
y="price", ) with gr.Column(scale=0): gr.Button("Sort $
|
Demos
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
_lim=[start, end])] * len(time_graphs), [start, end], time_graphs
) with gr.Row(): price_by_cuisine = gr.BarPlot( food_rating_data, x="cuisine",
y="price", ) with gr.Column(scale=0): gr.Button("Sort $ > $$$").click(lambda:
gr.BarPlot(sort="y"), None, price_by_cuisine) gr.Button("Sort $$$ >
$").click(lambda: gr.BarPlot(sort="-y"), None, price_by_cuisine)
gr.Button("Sort A > Z").click(lambda: gr.BarPlot(sort=["Chinese", "Italian",
"Mexican"]), None, price_by_cuisine) with gr.Row(): price_by_rating =
gr.BarPlot( food_rating_data, x="rating", y="price", x_bin=1, )
price_by_rating_color = gr.BarPlot( food_rating_data, x="rating", y="price",
color="cuisine", x_bin=1, color_map={"Italian": "red", "Mexican": "green",
"Chinese": "blue"}, ) if __name__ == "__main__": bar_plots.launch()
import pandas as pd
from random import randint, random
import gradio as gr
temp_sensor_data = pd.DataFrame(
{
"time": pd.date_range("2021-01-01", end="2021-01-05", periods=200),
"temperature": [randint(50 + 10 * (i % 2), 65 + 15 * (i % 2)) for i in range(200)],
"humidity": [randint(50 + 10 * (i % 2), 65 + 15 * (i % 2)) for i in range(200)],
"location": ["indoor", "outdoor"] * 100,
}
)
food_rating_data = pd.DataFrame(
{
"cuisine": [["Italian", "Mexican", "Chinese"][i % 3] for i in range(100)],
"rating": [random() * 4 + 0.5 * (i % 3) for i in range(100)],
"price": [randint(10, 50) + 4 * (i % 3) for i in range(100)],
"wait": [random() for i in range(100)],
}
)
with gr.Blocks() as bar_plots:
with gr.Row():
start = gr.DateTime("2021-01-01 00:00:00", label="Start")
end = gr.DateTime("2021-01-05 00:00:00", label="End")
apply_btn = gr.Button("Apply", scale=0)
with gr.Row():
group_by = gr.Radio(["None", "30m", "1h", "4h", "1d"], value="None", label="Gro
|
Demos
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
021-01-05 00:00:00", label="End")
apply_btn = gr.Button("Apply", scale=0)
with gr.Row():
group_by = gr.Radio(["None", "30m", "1h", "4h", "1d"], value="None", label="Group by")
aggregate = gr.Radio(["sum", "mean", "median", "min", "max"], value="sum", label="Aggregation")
temp_by_time = gr.BarPlot(
temp_sensor_data,
x="time",
y="temperature",
)
temp_by_time_location = gr.BarPlot(
temp_sensor_data,
x="time",
y="temperature",
color="location",
)
time_graphs = [temp_by_time, temp_by_time_location]
group_by.change(
lambda group: [gr.BarPlot(x_bin=None if group == "None" else group)] * len(time_graphs),
group_by,
time_graphs
)
aggregate.change(
lambda aggregate: [gr.BarPlot(y_aggregate=aggregate)] * len(time_graphs),
aggregate,
time_graphs
)
def rescale(select: gr.SelectData):
return select.index
rescale_evt = gr.on([plot.select for plot in time_graphs], rescale, None, [start, end])
for trigger in [apply_btn.click, rescale_evt.then]:
trigger(
lambda start, end: [gr.BarPlot(x_lim=[start, end])] * len(time_graphs), [start, end], time_graphs
)
with gr.Row():
price_by_cuisine = gr.BarPlot(
food_rating_data,
x="cuisine",
y="price",
)
with gr.Column(scale=0):
gr.Button("Sort $ > $$$").click(lambda: gr.BarPlot(sort="y"), None, price_by_cuisine)
gr.Button("Sort $$$ > $").click(lambda: gr.BarPlot(sort="-y"), None, price_by_cuisine)
gr.Button("Sort A > Z").click(lambda: gr.BarPlot(sort=["Chinese", "Italian", "Mexican"]), None, price_by_cuisine)
with gr.Row():
|
Demos
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
sort="-y"), None, price_by_cuisine)
gr.Button("Sort A > Z").click(lambda: gr.BarPlot(sort=["Chinese", "Italian", "Mexican"]), None, price_by_cuisine)
with gr.Row():
price_by_rating = gr.BarPlot(
food_rating_data,
x="rating",
y="price",
x_bin=1,
)
price_by_rating_color = gr.BarPlot(
food_rating_data,
x="rating",
y="price",
color="cuisine",
x_bin=1,
color_map={"Italian": "red", "Mexican": "green", "Chinese": "blue"},
)
if __name__ == "__main__":
bar_plots.launch()
|
Demos
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
Description
Event listeners allow you to respond to user interactions with the UI
components you've defined in a Gradio Blocks app. When a user interacts with
an element, such as changing a slider value or uploading an image, a function
is called.
Supported Event Listeners
The BarPlot component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`BarPlot.select(fn, ···)` | Event listener for when the user selects or deselects the NativePlot. Uses event data gradio.SelectData to carry `value` referring to the label of the NativePlot, and `selected` to refer to state of the NativePlot. See EventData documentation on how to use this event data
`BarPlot.double_click(fn, ···)` | Triggered when the NativePlot is double clicked.
Event Parameters
Parameters ▼
fn: Callable | None | Literal['decorator']
default `= "decorator"`
the function to call when this event is triggered. Often a machine learning
model's prediction function. Each parameter of the function corresponds to one
input component, and the function should return a single value or a tuple of
values, with each element in the tuple corresponding to one output component.
inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as inputs. If the function takes no inputs,
this should be an empty list.
outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as outputs. If the function returns no
outputs, this should be an empty list.
api_name: str | None | Literal[False]
default `= None`
defines how the endpoint appears in the API docs. Can be a string, None, or
False. If set to a string, the endpoint will
|
Event Listeners
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
list.
api_name: str | None | Literal[False]
default `= None`
defines how the endpoint appears in the API docs. Can be a string, None, or
False. If set to a string, the endpoint will be exposed in the API docs with
the given name. If None (default), the name of the function will be used as
the API endpoint. If False, the endpoint will not be exposed in the API docs
and downstream apps (including those that `gr.load` this app) will not be able
to use this event.
api_description: str | None | Literal[False]
default `= None`
Description of the API endpoint. Can be a string, None, or False. If set to a
string, the endpoint will be exposed in the API docs with the given
description. If None, the function's docstring will be used as the API
endpoint description. If False, then no description will be displayed in the
API docs.
scroll_to_output: bool
default `= False`
If True, will scroll to output component on completion
show_progress: Literal['full', 'minimal', 'hidden']
default `= "full"`
how to show the progress animation while event is running: "full" shows a
spinner which covers the output component area as well as a runtime display in
the upper right corner, "minimal" only shows the runtime display, "hidden"
shows no progress animation at all
show_progress_on: Component | list[Component] | None
default `= None`
Component or list of components to show the progress animation on. If None,
will show the progress animation on all of the output components.
queue: bool
default `= True`
If True, will place the request on the queue, if the queue has been enabled.
If False, will not put this event on the queue, even if the queue has been
enabled. If None, will use the queue setting of the gradio app.
batch: bool
default `= False`
If True, then the function should process a batch of inputs, meaning that it
should accept a list of input values for each pa
|
Event Listeners
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
setting of the gradio app.
batch: bool
default `= False`
If True, then the function should process a batch of inputs, meaning that it
should accept a list of input values for each parameter. The lists should be
of equal length (and be up to length `max_batch_size`). The function is then
*required* to return a tuple of lists (even if there is only 1 output
component), with each list in the tuple corresponding to one output component.
max_batch_size: int
default `= 4`
Maximum number of inputs to batch together if this is called from the queue
(only relevant if batch=True)
preprocess: bool
default `= True`
If False, will not run preprocessing of component data before running 'fn'
(e.g. leaving it as a base64 string if this method is called with the `Image`
component).
postprocess: bool
default `= True`
If False, will not run postprocessing of component data before returning 'fn'
output to the browser.
cancels: dict[str, Any] | list[dict[str, Any]] | None
default `= None`
A list of other events to cancel when this listener is triggered. For example,
setting cancels=[click_event] will cancel the click_event, where click_event
is the return value of another components .click method. Functions that have
not yet run (or generators that are iterating) will be cancelled, but
functions that are currently running will be allowed to finish.
trigger_mode: Literal['once', 'multiple', 'always_last'] | None
default `= None`
If "once" (default for all events except `.change()`) would not allow any
submissions while an event is pending. If set to "multiple", unlimited
submissions are allowed while pending, and "always_last" (default for
`.change()` and `.key_up()` events) would allow a second submission after the
pending event is complete.
js: str | Literal[True] | None
default `= None`
Optional frontend js method to run before running 'fn'. Input arguments for
|
Event Listeners
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
w a second submission after the
pending event is complete.
js: str | Literal[True] | None
default `= None`
Optional frontend js method to run before running 'fn'. Input arguments for js
method are values of 'inputs' and 'outputs', return should be a list of values
for output components.
concurrency_limit: int | None | Literal['default']
default `= "default"`
If set, this is the maximum number of this event that can be running
simultaneously. Can be set to None to mean no concurrency_limit (any number of
this event can be running simultaneously). Set to "default" to use the default
concurrency limit (defined by the `default_concurrency_limit` parameter in
`Blocks.queue()`, which itself is 1 by default).
concurrency_id: str | None
default `= None`
If set, this is the id of the concurrency group. Events with the same
concurrency_id will be limited by the lowest set concurrency_limit.
show_api: bool
default `= True`
whether to show this event in the "view API" page of the Gradio app, or in the
".view_api()" method of the Gradio clients. Unlike setting api_name to False,
setting show_api to False will still allow downstream apps as well as the
Clients to use this event. If fn is None, show_api will automatically be set
to False.
time_limit: int | None
default `= None`
stream_every: float
default `= 0.5`
like_user_message: bool
default `= False`
key: int | str | tuple[int | str, ...] | None
default `= None`
A unique key for this event listener to be used in @gr.render(). If set, this
value identifies an event as identical across re-renders when the key is
identical.
validator: Callable | None
default `= None`
Optional validation function to run before the main function. If provided,
this function will be executed first with queue=False, and only if it
completes successfully will the main function be called. The vali
|
Event Listeners
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot Docs
|
alidation function to run before the main function. If provided,
this function will be executed first with queue=False, and only if it
completes successfully will the main function be called. The validator
receives the same inputs as the main function and should return a
`gr.validate()` for each input value.
|
Event Listeners
|
https://gradio.app/docs/gradio/barplot
|
Gradio - Barplot 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
|
The gr.LikeData class is a subclass of gr.EventData that specifically
carries information about the `.like()` event. When gr.LikeData is added as a
type hint to an argument of an event listener method, a gr.LikeData object
will automatically be passed as the value of that argument. The attributes of
this object contains information about the event that triggered the listener.
|
Description
|
https://gradio.app/docs/gradio/likedata
|
Gradio - Likedata Docs
|
import gradio as gr
def test(value, like_data: gr.LikeData):
return {
"chatbot_value": value,
"liked_message": like_data.value,
"liked_index": like_data.index,
"liked_or_disliked_as_bool": like_data.liked
}
with gr.Blocks() as demo:
c = gr.Chatbot([("abc", "def")])
t = gr.JSON()
c.like(test, c, t)
demo.launch()
|
Example Usage
|
https://gradio.app/docs/gradio/likedata
|
Gradio - Likedata Docs
|
Parameters ▼
index: int | tuple[int, int]
The index of the liked/disliked item. Is a tuple if the component is two
dimensional.
value: Any
The value of the liked/disliked item.
liked: bool
True if the item was liked, False if disliked, or string value if any other
feedback.
|
Attributes
|
https://gradio.app/docs/gradio/likedata
|
Gradio - Likedata Docs
|
chatbot_core_components_simple
Open in 🎢 ↗ import gradio as gr import random Chatbot demo with multimodal
input (text, markdown, LaTeX, code blocks, image, audio, video, & model3d).
Plus shows support for streaming text. color_map = { "harmful": "crimson",
"neutral": "gray", "beneficial": "green", } def html_src(harm_level): return
f""" <div style="display: flex; gap: 5px;"> <div style="background-color:
{color_map[harm_level]}; padding: 2px; border-radius: 5px;"> {harm_level}
</div> </div> """ def print_like_dislike(x: gr.LikeData): print(x.index,
x.value, x.liked) def add_message(history, message): for x in
message["files"]: history.append(((x,), None)) if message["text"] is not None:
history.append((message["text"], None)) return history,
gr.MultimodalTextbox(value=None, interactive=False) def bot(history,
response_type): if response_type == "gallery": history[-1][1] = gr.Gallery( [
"https://raw.githubusercontent.com/gradio-
app/gradio/main/test/test_files/bus.png",
"https://raw.githubusercontent.com/gradio-
app/gradio/main/test/test_files/bus.png", ] ) elif response_type == "image":
history[-1][1] = gr.Image( "https://raw.githubusercontent.com/gradio-
app/gradio/main/test/test_files/bus.png" ) elif response_type == "video":
history[-1][1] = gr.Video( "https://github.com/gradio-
app/gradio/raw/main/gradio/media_assets/videos/world.mp4", label="test" ) elif
response_type == "audio": history[-1][1] = gr.Audio(
"https://github.com/gradio-
app/gradio/raw/main/gradio/media_assets/audio/audio_sample.wav" ) elif
response_type == "html": history[-1][1] = gr.HTML(
html_src(random.choice(["harmful", "neutral", "beneficial"])) ) elif
response_type == "model3d": history[-1][1] = gr.Model3D(
"https://github.com/gradio-
app/gradio/raw/main/gradio/media_assets/models3d/Fox.gltf" ) else:
history[-1][1] = "Cool!" return history with gr.Blocks(fill_height=True) as
demo: chatbot = gr.Chatbot( elem_id="chatbot", bubble_full_width=False,
scale=1, ) response_type = gr.Radio( [ "ima
|
Demos
|
https://gradio.app/docs/gradio/likedata
|
Gradio - Likedata Docs
|
) else:
history[-1][1] = "Cool!" return history with gr.Blocks(fill_height=True) as
demo: chatbot = gr.Chatbot( elem_id="chatbot", bubble_full_width=False,
scale=1, ) response_type = gr.Radio( [ "image", "text", "gallery", "video",
"audio", "html", "model3d", ], value="text", label="Response Type", )
chat_input = gr.MultimodalTextbox( interactive=True, placeholder="Enter
message or upload file...", show_label=False, ) chat_msg = chat_input.submit(
add_message, [chatbot, chat_input], [chatbot, chat_input] ) bot_msg =
chat_msg.then( bot, [chatbot, response_type], chatbot, api_name="bot_response"
) bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None,
[chat_input]) chatbot.like(print_like_dislike, None, None) if __name__ ==
"__main__": demo.launch()
import gradio as gr
import random
Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, video, & model3d). Plus shows support for streaming text.
color_map = {
"harmful": "crimson",
"neutral": "gray",
"beneficial": "green",
}
def html_src(harm_level):
return f"""
{harm_level}
"""
def print_like_dislike(x: gr.LikeData):
print(x.index, x.value, x.liked)
def add_message(history, message):
for x in message["files"]:
history.append(((x,), None))
if message["text"] is not None:
history.append((message["text"], None))
return history, gr.MultimodalTextbox(value=None, interactive=False)
def bot(history, response_type):
if response_type == "gallery":
history[-1][1] = gr.Gallery(
[
"https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png",
"https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png",
]
)
|
Demos
|
https://gradio.app/docs/gradio/likedata
|
Gradio - Likedata Docs
|
sercontent.com/gradio-app/gradio/main/test/test_files/bus.png",
"https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png",
]
)
elif response_type == "image":
history[-1][1] = gr.Image(
"https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png"
)
elif response_type == "video":
history[-1][1] = gr.Video(
"https://github.com/gradio-app/gradio/raw/main/gradio/media_assets/videos/world.mp4",
label="test"
)
elif response_type == "audio":
history[-1][1] = gr.Audio(
"https://github.com/gradio-app/gradio/raw/main/gradio/media_assets/audio/audio_sample.wav"
)
elif response_type == "html":
history[-1][1] = gr.HTML(
html_src(random.choice(["harmful", "neutral", "beneficial"]))
)
elif response_type == "model3d":
history[-1][1] = gr.Model3D(
"https://github.com/gradio-app/gradio/raw/main/gradio/media_assets/models3d/Fox.gltf"
)
else:
history[-1][1] = "Cool!"
return history
with gr.Blocks(fill_height=True) as demo:
chatbot = gr.Chatbot(
elem_id="chatbot",
bubble_full_width=False,
scale=1,
)
response_type = gr.Radio(
[
"image",
"text",
"gallery",
"video",
"audio",
"html",
"model3d",
],
value="text",
label="Response Type",
)
chat_input = gr.MultimodalTextbox(
interactive=True,
placeholder="Enter message or upload file...",
show_label=False,
)
chat_msg = chat_input.submit(
add_message, [chatbot, ch
|
Demos
|
https://gradio.app/docs/gradio/likedata
|
Gradio - Likedata Docs
|
interactive=True,
placeholder="Enter message or upload file...",
show_label=False,
)
chat_msg = chat_input.submit(
add_message, [chatbot, chat_input], [chatbot, chat_input]
)
bot_msg = chat_msg.then(
bot, [chatbot, response_type], chatbot, api_name="bot_response"
)
bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input])
chatbot.like(print_like_dislike, None, None)
if __name__ == "__main__":
demo.launch()
|
Demos
|
https://gradio.app/docs/gradio/likedata
|
Gradio - Likedata Docs
|
A Gradio request object that can be used to access the request headers,
cookies, query parameters and other information about the request from within
the prediction function. The class is a thin wrapper around the
fastapi.Request class. Attributes of this class include: `headers`, `client`,
`query_params`, `session_hash`, and `path_params`. If auth is enabled, the
`username` attribute can be used to get the logged in user. In some
environments, the dict-like attributes (e.g. `requests.headers`,
`requests.query_params`) of this class are automatically converted to
dictionaries, so we recommend converting them to dictionaries before accessing
attributes for consistent behavior in different environments.
|
Description
|
https://gradio.app/docs/gradio/request
|
Gradio - Request Docs
|
import gradio as gr
def echo(text, request: gr.Request):
if request:
print("Request headers dictionary:", request.headers)
print("IP address:", request.client.host)
print("Query parameters:", dict(request.query_params))
print("Session hash:", request.session_hash)
return text
io = gr.Interface(echo, "textbox", "textbox").launch()
|
Example Usage
|
https://gradio.app/docs/gradio/request
|
Gradio - Request Docs
|
Parameters ▼
request: fastapi.Request | None
default `= None`
A fastapi.Request
username: str | None
default `= None`
The username of the logged in user (if auth is enabled)
session_hash: str | None
default `= None`
The session hash of the current session. It is unique for each page load.
|
Initialization
|
https://gradio.app/docs/gradio/request
|
Gradio - Request Docs
|
request_ip_headers
Open in 🎢 ↗ import gradio as gr def predict(text, request: gr.Request):
headers = request.headers host = request.client.host user_agent =
request.headers["user-agent"] return { "ip": host, "user_agent": user_agent,
"headers": headers, } gr.Interface(predict, "text", "json").launch()
import gradio as gr
def predict(text, request: gr.Request):
headers = request.headers
host = request.client.host
user_agent = request.headers["user-agent"]
return {
"ip": host,
"user_agent": user_agent,
"headers": headers,
}
gr.Interface(predict, "text", "json").launch()
|
Demos
|
https://gradio.app/docs/gradio/request
|
Gradio - Request Docs
|
Displays a classification label, along with confidence scores of top
categories, if provided. As this component does not accept user input, it is
rarely used as an input component.
|
Description
|
https://gradio.app/docs/gradio/label
|
Gradio - Label Docs
|
**As input component** : Depending on the value, passes the label as a `str | int | float`, or the labels and confidences as a `dict[str, float]`.
Your function should accept one of these types:
def predict(
value: dict[str, float] | str | int | float | None
)
...
**As output component** : Expects a `dict[str, float]` of classes and confidences, or `str` with just the class or an `int | float` for regression outputs, or a `str` path to a .json file containing a json dictionary in one of the preceding formats.
Your function should return one of these types:
def predict(···) -> dict[str, float] | str | int | float | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/label
|
Gradio - Label Docs
|
Parameters ▼
value: dict[str, float] | str | float | Callable | None
default `= None`
Default value to show in the component. If a str or number is provided, simply
displays the string or number. If a {Dict[str, float]} of classes and
confidences is provided, displays the top class on top and the
`num_top_classes` below, along with their confidence bars. If a function is
provided, the function will be called each time the app loads to set the
initial value of this component.
num_top_classes: int | None
default `= None`
number of most confident classes to show.
label: str | I18nData | None
default `= None`
the label for this component. Appears above the component and is also used as
the header if there are a table of examples for this component. If None and
used in a `gr.Interface`, the label will be the name of the parameter this
component is assigned to.
every: Timer | float | None
default `= None`
Continously calls `value` to recalculate it if `value` is a function (has no
effect otherwise). Can provide a Timer whose tick resets `value`, or a float
that provides the regular interval for the reset Timer.
inputs: Component | list[Component] | set[Component] | None
default `= None`
Components that are used as inputs to calculate `value` if `value` is a
function (has no effect otherwise). `value` is recalculated any time the
inputs change.
show_label: bool | None
default `= None`
if True, will display label.
container: bool
default `= True`
If True, will place the component in a container - providing some extra
padding around the border.
scale: int | None
default `= None`
relative size compared to adjacent Components. For example if Components A and
B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide
as B. Should be an integer. scale applies in Rows, and to top-level Components
in Blocks where fill_he
|
Initialization
|
https://gradio.app/docs/gradio/label
|
Gradio - Label Docs
|
if Components A and
B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide
as B. Should be an integer. scale applies in Rows, and to top-level Components
in Blocks where fill_height=True.
min_width: int
default `= 160`
minimum pixel width, will wrap if not sufficient screen space to satisfy this
value. If a certain scale value results in this Component being narrower than
min_width, the min_width parameter will be respected first.
visible: bool | Literal['hidden']
default `= True`
If False, component will be hidden. If "hidden", component will be visually
hidden and not take up space in the layout but still exist in the DOM
elem_id: str | None
default `= None`
An optional string that is assigned as the id of this component in the HTML
DOM. Can be used for targeting CSS styles.
elem_classes: list[str] | str | None
default `= None`
An optional list of strings that are assigned as the classes of this component
in the HTML DOM. Can be used for targeting CSS styles.
render: bool
default `= True`
If False, component will not render be rendered in the Blocks context. Should
be used if the intention is to assign event listeners now but render the
component later.
key: int | str | tuple[int | str, ...] | None
default `= None`
in a gr.render, Components with the same key across re-renders are treated as
the same component, not a new component. Properties set in 'preserved_by_key'
are not reset across a re-render.
preserved_by_key: list[str] | str | None
default `= "value"`
A list of parameters from this component's constructor. Inside a gr.render()
function, if a component is re-rendered with the same key, these (and only
these) parameters will be preserved in the UI (if they have been changed by
the user or an event listener) instead of re-rendered based on the values
provided during constructor.
color: str | Non
|
Initialization
|
https://gradio.app/docs/gradio/label
|
Gradio - Label Docs
|
meters will be preserved in the UI (if they have been changed by
the user or an event listener) instead of re-rendered based on the values
provided during constructor.
color: str | None
default `= None`
The background color of the label (either a valid css color name or
hexadecimal string).
show_heading: bool
default `= True`
If False, the heading will not be displayed if a dictionary of labels and
confidences is provided. The heading will still be visible if the value is a
string or number.
|
Initialization
|
https://gradio.app/docs/gradio/label
|
Gradio - Label Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.Label` | "label" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/label
|
Gradio - Label Docs
|
Description
Event listeners allow you to respond to user interactions with the UI
components you've defined in a Gradio Blocks app. When a user interacts with
an element, such as changing a slider value or uploading an image, a function
is called.
Supported Event Listeners
The Label component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`Label.change(fn, ···)` | Triggered when the value of the Label changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input.
`Label.select(fn, ···)` | Event listener for when the user selects or deselects the Label. Uses event data gradio.SelectData to carry `value` referring to the label of the Label, and `selected` to refer to state of the Label. See EventData documentation on how to use this event data
Event Parameters
Parameters ▼
fn: Callable | None | Literal['decorator']
default `= "decorator"`
the function to call when this event is triggered. Often a machine learning
model's prediction function. Each parameter of the function corresponds to one
input component, and the function should return a single value or a tuple of
values, with each element in the tuple corresponding to one output component.
inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as inputs. If the function takes no inputs,
this should be an empty list.
outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as outputs. If the function returns no
outputs, this should be an emp
|
Event Listeners
|
https://gradio.app/docs/gradio/label
|
Gradio - Label Docs
|
ontext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as outputs. If the function returns no
outputs, this should be an empty list.
api_name: str | None | Literal[False]
default `= None`
defines how the endpoint appears in the API docs. Can be a string, None, or
False. If set to a string, the endpoint will be exposed in the API docs with
the given name. If None (default), the name of the function will be used as
the API endpoint. If False, the endpoint will not be exposed in the API docs
and downstream apps (including those that `gr.load` this app) will not be able
to use this event.
api_description: str | None | Literal[False]
default `= None`
Description of the API endpoint. Can be a string, None, or False. If set to a
string, the endpoint will be exposed in the API docs with the given
description. If None, the function's docstring will be used as the API
endpoint description. If False, then no description will be displayed in the
API docs.
scroll_to_output: bool
default `= False`
If True, will scroll to output component on completion
show_progress: Literal['full', 'minimal', 'hidden']
default `= "full"`
how to show the progress animation while event is running: "full" shows a
spinner which covers the output component area as well as a runtime display in
the upper right corner, "minimal" only shows the runtime display, "hidden"
shows no progress animation at all
show_progress_on: Component | list[Component] | None
default `= None`
Component or list of components to show the progress animation on. If None,
will show the progress animation on all of the output components.
queue: bool
default `= True`
If True, will place the request on the queue, if the queue has been enabled.
If False, will not put this event on the queue, even if the queue has been
enabled. If None, will use the queu
|
Event Listeners
|
https://gradio.app/docs/gradio/label
|
Gradio - Label Docs
|
lt `= True`
If True, will place the request on the queue, if the queue has been enabled.
If False, will not put this event on the queue, even if the queue has been
enabled. If None, will use the queue setting of the gradio app.
batch: bool
default `= False`
If True, then the function should process a batch of inputs, meaning that it
should accept a list of input values for each parameter. The lists should be
of equal length (and be up to length `max_batch_size`). The function is then
*required* to return a tuple of lists (even if there is only 1 output
component), with each list in the tuple corresponding to one output component.
max_batch_size: int
default `= 4`
Maximum number of inputs to batch together if this is called from the queue
(only relevant if batch=True)
preprocess: bool
default `= True`
If False, will not run preprocessing of component data before running 'fn'
(e.g. leaving it as a base64 string if this method is called with the `Image`
component).
postprocess: bool
default `= True`
If False, will not run postprocessing of component data before returning 'fn'
output to the browser.
cancels: dict[str, Any] | list[dict[str, Any]] | None
default `= None`
A list of other events to cancel when this listener is triggered. For example,
setting cancels=[click_event] will cancel the click_event, where click_event
is the return value of another components .click method. Functions that have
not yet run (or generators that are iterating) will be cancelled, but
functions that are currently running will be allowed to finish.
trigger_mode: Literal['once', 'multiple', 'always_last'] | None
default `= None`
If "once" (default for all events except `.change()`) would not allow any
submissions while an event is pending. If set to "multiple", unlimited
submissions are allowed while pending, and "always_last" (default for
`.change()` and `.key_up()` events) would al
|
Event Listeners
|
https://gradio.app/docs/gradio/label
|
Gradio - Label Docs
|
not allow any
submissions while an event is pending. If set to "multiple", unlimited
submissions are allowed while pending, and "always_last" (default for
`.change()` and `.key_up()` events) would allow a second submission after the
pending event is complete.
js: str | Literal[True] | None
default `= None`
Optional frontend js method to run before running 'fn'. Input arguments for js
method are values of 'inputs' and 'outputs', return should be a list of values
for output components.
concurrency_limit: int | None | Literal['default']
default `= "default"`
If set, this is the maximum number of this event that can be running
simultaneously. Can be set to None to mean no concurrency_limit (any number of
this event can be running simultaneously). Set to "default" to use the default
concurrency limit (defined by the `default_concurrency_limit` parameter in
`Blocks.queue()`, which itself is 1 by default).
concurrency_id: str | None
default `= None`
If set, this is the id of the concurrency group. Events with the same
concurrency_id will be limited by the lowest set concurrency_limit.
show_api: bool
default `= True`
whether to show this event in the "view API" page of the Gradio app, or in the
".view_api()" method of the Gradio clients. Unlike setting api_name to False,
setting show_api to False will still allow downstream apps as well as the
Clients to use this event. If fn is None, show_api will automatically be set
to False.
time_limit: int | None
default `= None`
stream_every: float
default `= 0.5`
like_user_message: bool
default `= False`
key: int | str | tuple[int | str, ...] | None
default `= None`
A unique key for this event listener to be used in @gr.render(). If set, this
value identifies an event as identical across re-renders when the key is
identical.
validator: Callable | None
default `= None`
Optional
|
Event Listeners
|
https://gradio.app/docs/gradio/label
|
Gradio - Label Docs
|
ener to be used in @gr.render(). If set, this
value identifies an event as identical across re-renders when the key is
identical.
validator: Callable | None
default `= None`
Optional validation function to run before the main function. If provided,
this function will be executed first with queue=False, and only if it
completes successfully will the main function be called. The validator
receives the same inputs as the main function and should return a
`gr.validate()` for each input value.
|
Event Listeners
|
https://gradio.app/docs/gradio/label
|
Gradio - Label Docs
|
Creates a navigation bar component for multipage Gradio apps. The navbar
component allows customizing the appearance of the navbar for that page. Only
one Navbar component can exist per page in a Blocks app, and it can be placed
anywhere within the page.
The Navbar component is designed to control the appearance of the navigation
bar in multipage applications. When present in a Blocks app, its properties
override the default navbar behavior.
|
Description
|
https://gradio.app/docs/gradio/navbar
|
Gradio - Navbar Docs
|
**As input component** : The preprocessed input data sent to the user's
function in the backend.
Your function should accept one of these types:
def predict(
value: list[tuple[str, str]] | None
)
...
**As output component** : The output data received by the component from
the user's function in the backend.
Your function should return one of these types:
def predict(···) -> list[tuple[str, str]] | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/navbar
|
Gradio - Navbar Docs
|
Parameters ▼
value: list[tuple[str, str]] | None
default `= None`
If a list of tuples of (page_name, page_path) are provided, these additional
pages will be added to the navbar alongside the existing pages defined in the
Blocks app. The page_path can be either a relative path for internal Gradio
app pages (e.g., "analytics") or an absolute URL for external links (e.g.,
"https://twitter.com/username"). Otherwise, only the pages defined using the
`Blocks.route` method will be displayed. Example: [("Dashboard", "dashboard"),
("About", "https://twitter.com/abidlabs")]
visible: bool
default `= True`
If True, the navbar will be visible. If False, the navbar will be hidden.
main_page_name: str | Literal[False]
default `= "Home"`
The title to display in the navbar for the main page of the Gradio. If False,
the main page will not be displayed in the navbar.
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.
|
Initialization
|
https://gradio.app/docs/gradio/navbar
|
Gradio - Navbar Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.Navbar` | "navbar" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/navbar
|
Gradio - Navbar 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 Navbar component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`Navbar.change(fn, ···)` | Triggered when the value of the Navbar 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.
Event Parameters
Parameters ▼
fn: Callable | None | Literal['decorator']
default `= "decorator"`
the function to call when this event is triggered. Often a machine learning
model's prediction function. Each parameter of the function corresponds to one
input component, and the function should return a single value or a tuple of
values, with each element in the tuple corresponding to one output component.
inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as inputs. If the function takes no inputs,
this should be an empty list.
outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as outputs. If the function returns no
outputs, this should be an empty list.
api_name: str | None | Literal[False]
default `= None`
defines how the endpoint appears in the API docs. Can be a string, None, or
False. If set to a string, the endpoint will be exposed in the API docs with
the given name. If None (default), the name of t
|
Event Listeners
|
https://gradio.app/docs/gradio/navbar
|
Gradio - Navbar Docs
|
efines how the endpoint appears in the API docs. Can be a string, None, or
False. If set to a string, the endpoint will be exposed in the API docs with
the given name. If None (default), the name of the function will be used as
the API endpoint. If False, the endpoint will not be exposed in the API docs
and downstream apps (including those that `gr.load` this app) will not be able
to use this event.
api_description: str | None | Literal[False]
default `= None`
Description of the API endpoint. Can be a string, None, or False. If set to a
string, the endpoint will be exposed in the API docs with the given
description. If None, the function's docstring will be used as the API
endpoint description. If False, then no description will be displayed in the
API docs.
scroll_to_output: bool
default `= False`
If True, will scroll to output component on completion
show_progress: Literal['full', 'minimal', 'hidden']
default `= "full"`
how to show the progress animation while event is running: "full" shows a
spinner which covers the output component area as well as a runtime display in
the upper right corner, "minimal" only shows the runtime display, "hidden"
shows no progress animation at all
show_progress_on: Component | list[Component] | None
default `= None`
Component or list of components to show the progress animation on. If None,
will show the progress animation on all of the output components.
queue: bool
default `= True`
If True, will place the request on the queue, if the queue has been enabled.
If False, will not put this event on the queue, even if the queue has been
enabled. If None, will use the queue setting of the gradio app.
batch: bool
default `= False`
If True, then the function should process a batch of inputs, meaning that it
should accept a list of input values for each parameter. The lists should be
of equal length (and be up to length `max_batch_size
|
Event Listeners
|
https://gradio.app/docs/gradio/navbar
|
Gradio - Navbar Docs
|
e, then the function should process a batch of inputs, meaning that it
should accept a list of input values for each parameter. The lists should be
of equal length (and be up to length `max_batch_size`). The function is then
*required* to return a tuple of lists (even if there is only 1 output
component), with each list in the tuple corresponding to one output component.
max_batch_size: int
default `= 4`
Maximum number of inputs to batch together if this is called from the queue
(only relevant if batch=True)
preprocess: bool
default `= True`
If False, will not run preprocessing of component data before running 'fn'
(e.g. leaving it as a base64 string if this method is called with the `Image`
component).
postprocess: bool
default `= True`
If False, will not run postprocessing of component data before returning 'fn'
output to the browser.
cancels: dict[str, Any] | list[dict[str, Any]] | None
default `= None`
A list of other events to cancel when this listener is triggered. For example,
setting cancels=[click_event] will cancel the click_event, where click_event
is the return value of another components .click method. Functions that have
not yet run (or generators that are iterating) will be cancelled, but
functions that are currently running will be allowed to finish.
trigger_mode: Literal['once', 'multiple', 'always_last'] | None
default `= None`
If "once" (default for all events except `.change()`) would not allow any
submissions while an event is pending. If set to "multiple", unlimited
submissions are allowed while pending, and "always_last" (default for
`.change()` and `.key_up()` events) would allow a second submission after the
pending event is complete.
js: str | Literal[True] | None
default `= None`
Optional frontend js method to run before running 'fn'. Input arguments for js
method are values of 'inputs' and 'outputs', return should be a list of value
|
Event Listeners
|
https://gradio.app/docs/gradio/navbar
|
Gradio - Navbar Docs
|
r | Literal[True] | None
default `= None`
Optional frontend js method to run before running 'fn'. Input arguments for js
method are values of 'inputs' and 'outputs', return should be a list of values
for output components.
concurrency_limit: int | None | Literal['default']
default `= "default"`
If set, this is the maximum number of this event that can be running
simultaneously. Can be set to None to mean no concurrency_limit (any number of
this event can be running simultaneously). Set to "default" to use the default
concurrency limit (defined by the `default_concurrency_limit` parameter in
`Blocks.queue()`, which itself is 1 by default).
concurrency_id: str | None
default `= None`
If set, this is the id of the concurrency group. Events with the same
concurrency_id will be limited by the lowest set concurrency_limit.
show_api: bool
default `= True`
whether to show this event in the "view API" page of the Gradio app, or in the
".view_api()" method of the Gradio clients. Unlike setting api_name to False,
setting show_api to False will still allow downstream apps as well as the
Clients to use this event. If fn is None, show_api will automatically be set
to False.
time_limit: int | None
default `= None`
stream_every: float
default `= 0.5`
like_user_message: bool
default `= False`
key: int | str | tuple[int | str, ...] | None
default `= None`
A unique key for this event listener to be used in @gr.render(). If set, this
value identifies an event as identical across re-renders when the key is
identical.
validator: Callable | None
default `= None`
Optional validation function to run before the main function. If provided,
this function will be executed first with queue=False, and only if it
completes successfully will the main function be called. The validator
receives the same inputs as the main function and should return a
`gr.valid
|
Event Listeners
|
https://gradio.app/docs/gradio/navbar
|
Gradio - Navbar Docs
|
ll be executed first with queue=False, and only if it
completes successfully will the main function be called. The validator
receives the same inputs as the main function and should return a
`gr.validate()` for each input value.
|
Event Listeners
|
https://gradio.app/docs/gradio/navbar
|
Gradio - Navbar Docs
|
This class is a wrapper over the Dataset component and can be used to
create Examples for Blocks / Interfaces. Populates the Dataset component with
examples and assigns event listener so that clicking on an example populates
the input/output components. Optionally handles example caching for fast
inference.
|
Description
|
https://gradio.app/docs/gradio/examples
|
Gradio - Examples Docs
|
Parameters ▼
examples: list[Any] | list[list[Any]] | str
example inputs that can be clicked to populate specific components. Should be
nested list, in which the outer list consists of samples and each inner list
consists of an input corresponding to each input component. A string path to a
directory of examples can also be provided but it should be within the
directory with the python file running the gradio app. If there are multiple
input components and a directory is provided, a log.csv file must be present
in the directory to link corresponding inputs.
inputs: Component | list[Component]
the component or list of components corresponding to the examples
outputs: Component | list[Component] | None
default `= None`
optionally, provide the component or list of components corresponding to the
output of the examples. Required if `cache_examples` is not False.
fn: Callable | None
default `= None`
optionally, provide the function to run to generate the outputs corresponding
to the examples. Required if `cache_examples` is not False. Also required if
`run_on_click` is True.
cache_examples: bool | None
default `= None`
If True, caches examples in the server for fast runtime in examples. If
"lazy", then examples are cached (for all users of the app) after their first
use (by any user of the app). If None, will use the GRADIO_CACHE_EXAMPLES
environment variable, which should be either "true" or "false". In HuggingFace
Spaces, this parameter is True (as long as `fn` and `outputs` are also
provided). The default option otherwise is False. Note that examples are
cached separately from Gradio's queue() so certain features, such as
gr.Progress(), gr.Info(), gr.Warning(), etc. will not be displayed in Gradio's
UI for cached examples.
cache_mode: Literal['eager', 'lazy'] | None
default `= None`
if "lazy", examples are cached after their first use. If "eager", all examples
are
|
Initialization
|
https://gradio.app/docs/gradio/examples
|
Gradio - Examples Docs
|
d in Gradio's
UI for cached examples.
cache_mode: Literal['eager', 'lazy'] | None
default `= None`
if "lazy", examples are cached after their first use. If "eager", all examples
are cached at app launch. If None, will use the GRADIO_CACHE_MODE environment
variable if defined, or default to "eager".
examples_per_page: int
default `= 10`
how many examples to show per page.
label: str | I18nData | None
default `= "Examples"`
the label to use for the examples component (by default, "Examples")
elem_id: str | None
default `= None`
an optional string that is assigned as the id of this component in the HTML
DOM.
run_on_click: bool
default `= False`
if cache_examples is False, clicking on an example does not run the function
when an example is clicked. Set this to True to run the function when an
example is clicked. Has no effect if cache_examples is True.
preprocess: bool
default `= True`
if True, preprocesses the example input before running the prediction function
and caching the output. Only applies if `cache_examples` is not False.
postprocess: bool
default `= True`
if True, postprocesses the example output after running the prediction
function and before caching. Only applies if `cache_examples` is not False.
show_api: bool
default `= False`
Whether to show the event associated with clicking on the examples in the
"view API" page of the Gradio app, or in the ".view_api()" method of the
Gradio clients.
api_name: str | Literal[False]
default `= "load_example"`
Defines how the event associated with clicking on the examples appears in the
API docs. Can be a string or False. If set to a string, the endpoint will be
exposed in the API docs with the given name. If False, the endpoint will not
be exposed in the API docs and downstream apps (including those that `gr.load`
this app) will not be able to use the example
|
Initialization
|
https://gradio.app/docs/gradio/examples
|
Gradio - Examples Docs
|
posed in the API docs with the given name. If False, the endpoint will not
be exposed in the API docs and downstream apps (including those that `gr.load`
this app) will not be able to use the example function.
api_description: str | None | Literal[False]
default `= None`
Description of the event associated with clicking on the examples in the API
docs. Can be a string, None, or False. If set to a string, the endpoint will
be exposed in the API docs with the given description. If None, the function's
docstring will be used as the API endpoint description. If False, then no
description will be displayed in the API docs.
batch: bool
default `= False`
If True, then the function should process a batch of inputs, meaning that it
should accept a list of input values for each parameter. Used only if
cache_examples is not False.
example_labels: list[str] | None
default `= None`
A list of labels for each example. If provided, the length of this list should
be the same as the number of examples, and these labels will be used in the UI
instead of rendering the example values.
visible: bool | Literal['hidden']
default `= True`
If False, the examples component will be hidden in the UI.
preload: int | Literal[False]
default `= False`
If an integer is provided (and examples are being cached), the example at that
index in the examples list will be preloaded when the Gradio app is loaded. If
False, no example will be preloaded.
|
Initialization
|
https://gradio.app/docs/gradio/examples
|
Gradio - Examples Docs
|
Parameters ▼
dataset: gradio.Dataset
The `gr.Dataset` component corresponding to this Examples object.
load_input_event: gradio.events.Dependency
The Gradio event that populates the input values when the examples are
clicked. You can attach a `.then()` or a `.success()` to this event to trigger
subsequent events to fire after this event.
cache_event: gradio.events.Dependency | None
The Gradio event that populates the cached output values when the examples are
clicked. You can attach a `.then()` or a `.success()` to this event to trigger
subsequent events to fire after this event. This event is `None` if
`cache_examples` if False, and is the same as `load_input_event` if
`cache_examples` is `'lazy'`.
|
Attributes
|
https://gradio.app/docs/gradio/examples
|
Gradio - Examples Docs
|
**Updating Examples**
In this demo, we show how to update the examples by updating the samples of
the underlying dataset. Note that this only works if `cache_examples=False` as
updating the underlying dataset does not update the cache.
import gradio as gr
def update_examples(country):
if country == "USA":
return gr.Dataset(samples=[["Chicago"], ["Little Rock"], ["San Francisco"]])
else:
return gr.Dataset(samples=[["Islamabad"], ["Karachi"], ["Lahore"]])
with gr.Blocks() as demo:
dropdown = gr.Dropdown(label="Country", choices=["USA", "Pakistan"], value="USA")
textbox = gr.Textbox()
examples = gr.Examples([["Chicago"], ["Little Rock"], ["San Francisco"]], textbox)
dropdown.change(update_examples, dropdown, examples.dataset)
demo.launch()
|
Examples
|
https://gradio.app/docs/gradio/examples
|
Gradio - Examples Docs
|
calculator_blocks
Open in 🎢 ↗ import gradio as gr def calculator(num1, operation, num2): if
operation == "add": return num1 + num2 elif operation == "subtract": return
num1 - num2 elif operation == "multiply": return num1 * num2 elif operation ==
"divide": return num1 / num2 with gr.Blocks() as demo: with gr.Row(): with
gr.Column(): num_1 = gr.Number(value=4) operation = gr.Radio(["add",
"subtract", "multiply", "divide"]) num_2 = gr.Number(value=0) submit_btn =
gr.Button(value="Calculate") with gr.Column(): result = gr.Number()
submit_btn.click( calculator, inputs=[num_1, operation, num_2],
outputs=[result], api_name=False ) examples = gr.Examples( examples=[ [5,
"add", 3], [4, "divide", 2], [-4, "multiply", 2.5], [0, "subtract", 1.2], ],
inputs=[num_1, operation, num_2], ) if __name__ == "__main__":
demo.launch(show_api=False)
import gradio as gr
def calculator(num1, operation, num2):
if operation == "add":
return num1 + num2
elif operation == "subtract":
return num1 - num2
elif operation == "multiply":
return num1 * num2
elif operation == "divide":
return num1 / num2
with gr.Blocks() as demo:
with gr.Row():
with gr.Column():
num_1 = gr.Number(value=4)
operation = gr.Radio(["add", "subtract", "multiply", "divide"])
num_2 = gr.Number(value=0)
submit_btn = gr.Button(value="Calculate")
with gr.Column():
result = gr.Number()
submit_btn.click(
calculator, inputs=[num_1, operation, num_2], outputs=[result], api_name=False
)
examples = gr.Examples(
examples=[
[5, "add", 3],
[4, "divide", 2],
[-4, "multiply", 2.5],
[0, "subtract", 1.2],
],
inputs=[num_1, operation, num_2],
)
if __name__ == "__mai
|
Demos
|
https://gradio.app/docs/gradio/examples
|
Gradio - Examples Docs
|
[4, "divide", 2],
[-4, "multiply", 2.5],
[0, "subtract", 1.2],
],
inputs=[num_1, operation, num_2],
)
if __name__ == "__main__":
demo.launch(show_api=False)
|
Demos
|
https://gradio.app/docs/gradio/examples
|
Gradio - Examples Docs
|
Creates a "Sign In" button that redirects the user to sign in with Hugging
Face OAuth. Once the user is signed in, the button will act as a logout
button, and you can retrieve a signed-in user's profile by adding a parameter
of type `gr.OAuthProfile` to any Gradio function. This will only work if this
Gradio app is running in a Hugging Face Space. Permissions for the OAuth app
can be configured in the Spaces README file, as described here:
<https://huggingface.co/docs/hub/en/spaces-oauth.> For local development,
instead of OAuth, the local Hugging Face account that is logged in (via `hf
auth login`) will be available through the `gr.OAuthProfile` object.
|
Description
|
https://gradio.app/docs/gradio/loginbutton
|
Gradio - Loginbutton Docs
|
**As input component** : (Rarely used) the `str` corresponding to the
button label when the button is clicked
Your function should accept one of these types:
def predict(
value: str | None
)
...
**As output component** : string corresponding to the button label
Your function should return one of these types:
def predict(···) -> str | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/loginbutton
|
Gradio - Loginbutton Docs
|
Parameters ▼
value: str
default `= "Sign in with Hugging Face"`
logout_value: str
default `= "Logout ({})"`
The text to display when the user is signed in. The string should contain a
placeholder for the username with a call-to-action to logout, e.g. "Logout
({})".
every: Timer | float | None
default `= None`
inputs: Component | list[Component] | set[Component] | None
default `= None`
variant: Literal['primary', 'secondary', 'stop', 'huggingface']
default `= "huggingface"`
size: Literal['sm', 'md', 'lg']
default `= "lg"`
icon: str | Path | None
default `= "/home/runner/work/gradio/gradio/gradio/icons/huggingface-
logo.svg"`
link: str | None
default `= None`
visible: bool | Literal['hidden']
default `= True`
interactive: bool
default `= True`
elem_id: str | None
default `= None`
elem_classes: list[str] | str | None
default `= None`
render: bool
default `= True`
key: int | str | tuple[int | str, ...] | None
default `= None`
preserved_by_key: list[str] | str | None
default `= "value"`
scale: int | None
default `= None`
min_width: int | None
default `= None`
|
Initialization
|
https://gradio.app/docs/gradio/loginbutton
|
Gradio - Loginbutton Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.LoginButton` | "loginbutton" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/loginbutton
|
Gradio - Loginbutton Docs
|
login_with_huggingface
Open in 🎢 ↗ from __future__ import annotations import gradio as gr from huggingface_hub import whoami def hello(profile: gr.OAuthProfile | None) -> str: if profile is None: return "I don't know you." return f"Hello {profile.name}" def list_organizations(oauth_token: gr.OAuthToken | None) -> str: if oauth_token is None: return "Please deploy this on Spaces and log in to list organizations." org_names = [org["name"] for org in whoami(oauth_token.token)["orgs"]] return f"You belong to {', '.join(org_names)}." with gr.Blocks() as demo: gr.LoginButton() m1 = gr.Markdown() m2 = gr.Markdown() demo.load(hello, inputs=None, outputs=m1) demo.load(list_organizations, inputs=None, outputs=m2) if __name__ == "__main__": demo.launch()
from __future__ import annotations
import gradio as gr
from huggingface_hub import whoami
def hello(profile: gr.OAuthProfile | None) -> str:
if profile is None:
return "I don't know you."
return f"Hello {profile.name}"
def list_organizations(oauth_token: gr.OAuthToken | None) -> str:
if oauth_token is None:
return "Please deploy this on Spaces and log in to list organizations."
org_names = [org["name"] for org in whoami(oauth_token.token)["orgs"]]
return f"You belong to {', '.join(org_names)}."
with gr.Blocks() as demo:
gr.LoginButton()
m1 = gr.Markdown()
m2 = gr.Markdown()
demo.load(hello, inputs=None, outputs=m1)
demo.load(list_organizations, inputs=None, outputs=m2)
if __name__ == "__main__":
demo.launch()
|
Demos
|
https://gradio.app/docs/gradio/loginbutton
|
Gradio - Loginbutton Docs
|
Description
Event listeners allow you to respond to user interactions with the UI
components you've defined in a Gradio Blocks app. When a user interacts with
an element, such as changing a slider value or uploading an image, a function
is called.
Supported Event Listeners
The LoginButton component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`LoginButton.click(fn, ···)` | Triggered when the Button is clicked.
Event Parameters
Parameters ▼
fn: Callable | None | Literal['decorator']
default `= "decorator"`
the function to call when this event is triggered. Often a machine learning
model's prediction function. Each parameter of the function corresponds to one
input component, and the function should return a single value or a tuple of
values, with each element in the tuple corresponding to one output component.
inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as inputs. If the function takes no inputs,
this should be an empty list.
outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as outputs. If the function returns no
outputs, this should be an empty list.
api_name: str | None | Literal[False]
default `= None`
defines how the endpoint appears in the API docs. Can be a string, None, or
False. If set to a string, the endpoint will be exposed in the API docs with
the given name. If None (default), the name of the function will be used as
the API endpoint. If False, the endpoint will not be exposed in the API docs
and downstream apps (including those that `gr.load` this app) will not be able
to use this event.
api_descripti
|
Event Listeners
|
https://gradio.app/docs/gradio/loginbutton
|
Gradio - Loginbutton Docs
|
API endpoint. If False, the endpoint will not be exposed in the API docs
and downstream apps (including those that `gr.load` this app) will not be able
to use this event.
api_description: str | None | Literal[False]
default `= None`
Description of the API endpoint. Can be a string, None, or False. If set to a
string, the endpoint will be exposed in the API docs with the given
description. If None, the function's docstring will be used as the API
endpoint description. If False, then no description will be displayed in the
API docs.
scroll_to_output: bool
default `= False`
If True, will scroll to output component on completion
show_progress: Literal['full', 'minimal', 'hidden']
default `= "full"`
how to show the progress animation while event is running: "full" shows a
spinner which covers the output component area as well as a runtime display in
the upper right corner, "minimal" only shows the runtime display, "hidden"
shows no progress animation at all
show_progress_on: Component | list[Component] | None
default `= None`
Component or list of components to show the progress animation on. If None,
will show the progress animation on all of the output components.
queue: bool
default `= True`
If True, will place the request on the queue, if the queue has been enabled.
If False, will not put this event on the queue, even if the queue has been
enabled. If None, will use the queue setting of the gradio app.
batch: bool
default `= False`
If True, then the function should process a batch of inputs, meaning that it
should accept a list of input values for each parameter. The lists should be
of equal length (and be up to length `max_batch_size`). The function is then
*required* to return a tuple of lists (even if there is only 1 output
component), with each list in the tuple corresponding to one output component.
max_batch_size: int
default `= 4`
Maximu
|
Event Listeners
|
https://gradio.app/docs/gradio/loginbutton
|
Gradio - Loginbutton Docs
|
ed* to return a tuple of lists (even if there is only 1 output
component), with each list in the tuple corresponding to one output component.
max_batch_size: int
default `= 4`
Maximum number of inputs to batch together if this is called from the queue
(only relevant if batch=True)
preprocess: bool
default `= True`
If False, will not run preprocessing of component data before running 'fn'
(e.g. leaving it as a base64 string if this method is called with the `Image`
component).
postprocess: bool
default `= True`
If False, will not run postprocessing of component data before returning 'fn'
output to the browser.
cancels: dict[str, Any] | list[dict[str, Any]] | None
default `= None`
A list of other events to cancel when this listener is triggered. For example,
setting cancels=[click_event] will cancel the click_event, where click_event
is the return value of another components .click method. Functions that have
not yet run (or generators that are iterating) will be cancelled, but
functions that are currently running will be allowed to finish.
trigger_mode: Literal['once', 'multiple', 'always_last'] | None
default `= None`
If "once" (default for all events except `.change()`) would not allow any
submissions while an event is pending. If set to "multiple", unlimited
submissions are allowed while pending, and "always_last" (default for
`.change()` and `.key_up()` events) would allow a second submission after the
pending event is complete.
js: str | Literal[True] | None
default `= None`
Optional frontend js method to run before running 'fn'. Input arguments for js
method are values of 'inputs' and 'outputs', return should be a list of values
for output components.
concurrency_limit: int | None | Literal['default']
default `= "default"`
If set, this is the maximum number of this event that can be running
simultaneously. Can be set to None to mean no c
|
Event Listeners
|
https://gradio.app/docs/gradio/loginbutton
|
Gradio - Loginbutton Docs
|
concurrency_limit: int | None | Literal['default']
default `= "default"`
If set, this is the maximum number of this event that can be running
simultaneously. Can be set to None to mean no concurrency_limit (any number of
this event can be running simultaneously). Set to "default" to use the default
concurrency limit (defined by the `default_concurrency_limit` parameter in
`Blocks.queue()`, which itself is 1 by default).
concurrency_id: str | None
default `= None`
If set, this is the id of the concurrency group. Events with the same
concurrency_id will be limited by the lowest set concurrency_limit.
show_api: bool
default `= True`
whether to show this event in the "view API" page of the Gradio app, or in the
".view_api()" method of the Gradio clients. Unlike setting api_name to False,
setting show_api to False will still allow downstream apps as well as the
Clients to use this event. If fn is None, show_api will automatically be set
to False.
time_limit: int | None
default `= None`
stream_every: float
default `= 0.5`
like_user_message: bool
default `= False`
key: int | str | tuple[int | str, ...] | None
default `= None`
A unique key for this event listener to be used in @gr.render(). If set, this
value identifies an event as identical across re-renders when the key is
identical.
validator: Callable | None
default `= None`
Optional validation function to run before the main function. If provided,
this function will be executed first with queue=False, and only if it
completes successfully will the main function be called. The validator
receives the same inputs as the main function and should return a
`gr.validate()` for each input value.
|
Event Listeners
|
https://gradio.app/docs/gradio/loginbutton
|
Gradio - Loginbutton Docs
|
A Gradio Interface includes a ‘Flag’ button that appears underneath the
output. By default, clicking on the Flag button sends the input and output
data back to the machine where the gradio demo is running, and saves it to a
CSV log file. But this default behavior can be changed. To set what happens
when the Flag button is clicked, you pass an instance of a subclass of
_FlaggingCallback_ to the _flagging_callback_ parameter in the _Interface_
constructor. You can use one of the _FlaggingCallback_ subclasses that are
listed below, or you can create your own, which lets you do whatever you want
with the data that is being flagged.
SimpleCSVLogger
gradio.SimpleCSVLogger(···)
|
Description
|
https://gradio.app/docs/gradio/flagging
|
Gradio - Flagging Docs
|
A simplified implementation of the FlaggingCallback abstract class provided
for illustrative purposes. Each flagged sample (both the input and output
data) is logged to a CSV file on the machine running the gradio app.
|
Description
|
https://gradio.app/docs/gradio/flagging
|
Gradio - Flagging Docs
|
import gradio as gr
def image_classifier(inp):
return {'cat': 0.3, 'dog': 0.7}
demo = gr.Interface(fn=image_classifier, inputs="image", outputs="label",
flagging_callback=SimpleCSVLogger())
CSVLogger
gradio.CSVLogger(···)
|
Example Usage
|
https://gradio.app/docs/gradio/flagging
|
Gradio - Flagging Docs
|
The default implementation of the FlaggingCallback abstract class in
gradio>=5.0. Each flagged sample (both the input and output data) is logged to
a CSV file with headers on the machine running the gradio app. Unlike
ClassicCSVLogger, this implementation is concurrent-safe and it creates a new
dataset file every time the headers of the CSV (derived from the labels of the
components) change. It also only creates columns for "username" and "flag" if
the flag_option and username are provided, respectively.
|
Description
|
https://gradio.app/docs/gradio/flagging
|
Gradio - Flagging Docs
|
import gradio as gr
def image_classifier(inp):
return {'cat': 0.3, 'dog': 0.7}
demo = gr.Interface(fn=image_classifier, inputs="image", outputs="label",
flagging_callback=CSVLogger())
|
Example Usage
|
https://gradio.app/docs/gradio/flagging
|
Gradio - Flagging Docs
|
Parameters ▼
simplify_file_data: bool
default `= True`
If True, the file data will be simplified before being written to the CSV
file. If CSVLogger is being used to cache examples, this is set to False to
preserve the original FileData class
verbose: bool
default `= True`
If True, prints messages to the console about the dataset file creation
dataset_file_name: str | None
default `= None`
The name of the dataset file to be created (should end in ".csv"). If None,
the dataset file will be named "dataset1.csv" or the next available number.
|
Initialization
|
https://gradio.app/docs/gradio/flagging
|
Gradio - Flagging Docs
|
Creates a Dialogue component for displaying or collecting multi-speaker
conversations. This component can be used as input to allow users to enter
dialogue involving multiple speakers, or as output to display diarized speech,
such as the result of a transcription or speaker identification model. Each
message can be associated with a specific speaker, making it suitable for use
cases like conversations, interviews, or meetings.
|
Description
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
**As input component** : Returns the dialogue as a string or list of
dictionaries.
Your function should accept one of these types:
def predict(
value: tuple[str, list[tuple[str, str]]] | None
)
...
**As output component** : Expects a string or a list of dictionaries of
dialogue lines, where each dictionary contains 'speaker' and 'text' keys, or a
string.
Your function should return one of these types:
def predict(···) -> tuple[np.ndarray | PIL.Image.Image | str, list[tuple[np.ndarray | tuple[int, int, int, int], str]]] | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
Parameters ▼
value: list[dict[str, str]] | Callable | None
default `= None`
Value of the dialogue. It is a list of dictionaries, each containing a
'speaker' key and a 'text' key. If a function is provided, the function will
be called each time the app loads to set the initial value of this component.
type: Literal['list', 'text']
default `= "text"`
The type of the component, either "list" for a multi-speaker dialogue
consisting of dictionaries with 'speaker' and 'text' keys or "text" for a
single text input. Defaults to "text".
speakers: list[str] | None
default `= None`
The different speakers allowed in the dialogue. If `None` or an empty list, no
speakers will be displayed. Instead, the component will be a standard textarea
that optionally supports `tags` autocompletion.
formatter: Callable | None
default `= None`
A function that formats the dialogue line dictionary, e.g. {"speaker":
"Speaker 1", "text": "Hello, how are you?"} into a string, e.g. "Speaker 1:
Hello, how are you?". This function is run on user input and the resulting
string is passed into the prediction function.
unformatter: Callable | None
default `= None`
A function that parses a formatted dialogue string back into a dialogue line
dictionary. Should take a single string line and return a dictionary with
'speaker' and 'text' keys. If not provided, the default unformatter will
attempt to parse the default formatter pattern.
tags: list[str] | None
default `= None`
The different tags allowed in the dialogue. Tags are displayed in an
autocomplete menu below the input textbox when the user starts typing `:`. Use
the exact tag name expected by the AI model or inference function.
separator: str
default `= " "`
The separator between the different dialogue lines used to join the formatted
dialogue lines into a single string. It should be unambiguous. For example, a
newline character
|
Initialization
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
tor: str
default `= " "`
The separator between the different dialogue lines used to join the formatted
dialogue lines into a single string. It should be unambiguous. For example, a
newline character or tab character.
color_map: dict[str, str] | None
default `= None`
A dictionary mapping speaker names to colors. The colors may be specified as
hex codes or by their names. For example: {"Speaker 1": "red", "Speaker 2":
"FFEE22"}. If not provided, default colors will be assigned to speakers. This
is only used if `interactive` is False.
label: str | None
default `= "Dialogue"`
the label for this component, displayed above the component if `show_label` is
`True` and is also used as the header if there are a table of examples for
this component. If None and used in a `gr.Interface`, the label will be the
name of the parameter this component corresponds to.
info: str | None
default `= "Type colon (:) in the dialogue line to see the available tags"`
placeholder: str | None
default `= None`
placeholder hint to provide behind textarea.
show_label: bool | None
default `= None`
if True, will display the label. If False, the copy button is hidden as well
as well as the label.
container: bool
default `= True`
if True, will place the component in a container - providing some extra
padding around the border.
scale: int | None
default `= None`
relative size compared to adjacent Components. For example if Components A and
B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide
as B. Should be an integer. scale applies in Rows, and to top-level Components
in Blocks where fill_height=True.
min_width: int
default `= 160`
minimum pixel width, will wrap if not sufficient screen space to satisfy this
value. If a certain scale value results in this Component being narrower than
min_width, the min_width parameter will be respec
|
Initialization
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
um pixel width, will wrap if not sufficient screen space to satisfy this
value. If a certain scale value results in this Component being narrower than
min_width, the min_width parameter will be respected first.
interactive: bool | None
default `= None`
if True, will be rendered as an editable textbox; if False, editing will be
disabled. If not provided, this is inferred based on whether the component is
used as an input or output.
visible: bool | Literal['hidden']
default `= True`
If False, component will be hidden. If "hidden", component will be visually
hidden and not take up space in the layout but still exist in the DOM
elem_id: str | None
default `= None`
An optional string that is assigned as the id of this component in the HTML
DOM. Can be used for targeting CSS styles.
autofocus: bool
default `= False`
If True, will focus on the textbox when the page loads. Use this carefully, as
it can cause usability issues for sighted and non-sighted users.
autoscroll: bool
default `= True`
If True, will automatically scroll to the bottom of the textbox when the value
changes, unless the user scrolls up. If False, will not scroll to the bottom
of the textbox when the value changes.
elem_classes: list[str] | str | None
default `= None`
An optional list of strings that are assigned as the classes of this component
in the HTML DOM. Can be used for targeting CSS styles.
render: bool
default `= True`
If False, component will not render be rendered in the Blocks context. Should
be used if the intention is to assign event listeners now but render the
component later.
key: int | str | None
default `= None`
if assigned, will be used to assume identity across a re-render. Components
that have the same key across a re-render will have their value preserved.
max_lines: int | None
default `= None`
maximum number of lines allo
|
Initialization
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
identity across a re-render. Components
that have the same key across a re-render will have their value preserved.
max_lines: int | None
default `= None`
maximum number of lines allowed in the dialogue.
show_submit_button: bool
default `= True`
If True, includes a submit button to submit the dialogue.
show_copy_button: bool
default `= True`
If True, includes a copy button to copy the text in the textbox. Only applies
if show_label is True.
ui_mode: Literal['dialogue', 'text', 'both']
default `= "both"`
Determines the user interface mode of the component. Can be "dialogue"
(displays dialogue lines), "text" (displays a single text input), or "both"
(displays both dialogue lines and a text input). Defaults to "both".
|
Initialization
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.Dialogue` | "dialogue" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
dia_dialogue_demo
Open in 🎢 ↗ import gradio as gr import httpx tags = [ "(laughs)", "(clears throat)", "(sighs)", "(gasps)", "(coughs)", "(singing)", "(sings)", "(mumbles)", "(beep)", "(groans)", "(sniffs)", "(claps)", "(screams)", "(inhales)", "(exhales)", "(applause)", "(burps)", "(humming)", "(sneezes)", "(chuckle)", "(whistles)", ] speakers = ["Speaker 1", "Speaker 2"] client = httpx.AsyncClient(timeout=180) API_URL = "https://router.huggingface.co/fal-ai/fal-ai/dia-tts" async def query(dialogue: str, token: gr.OAuthToken | None): if token is None: raise gr.Error( "No token provided. Use Sign in with Hugging Face to get a token." ) headers = { "Authorization": f"Bearer {token.token}", } response = await client.post(API_URL, headers=headers, json={"text": dialogue}) url = response.json()["audio"]["url"] print("URL: ", url) return url def formatter(speaker, text): speaker = speaker.split(" ")[1] return f"[S{speaker}] {text}" with gr.Blocks() as demo: with gr.Sidebar(): login_button = gr.LoginButton() gr.HTML( """ <h1 style='text-align: center; display: flex; align-items: center; justify-content: center;'> <img src="https://huggingface.co/datasets/freddyaboulton/bucket/resolve/main/dancing_huggy.gif" alt="Dancing Huggy" style="height: 100px; margin-right: 10px"> Dia Dialogue Generation Model </h1> <h2 style='text-align: center; display: flex; align-items: center; justify-content: center;'>Model by <a href="https://huggingface.co/nari-labs/Dia-1.6B"> Nari Labs</a>. Powered by HF and <a href="https://fal.ai/">Fal AI</a> API.</h2> <h4>Dia is a dialogue generation model that can generate realistic dialogue between two speakers. Use the dialogue component to create a conversation and then hit the submit button in the bottom right corner to see it come to life .</h4> """ ) with gr.Row(): with gr.Column(): dialogue = gr.Dialogue( speakers=speakers, tags=tags, formatter=formatter ) with gr.Column(): with gr.Row(): audio = gr.Audio(label="Audio") with gr
|
Demos
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
life .</h4> """ ) with gr.Row(): with gr.Column(): dialogue = gr.Dialogue( speakers=speakers, tags=tags, formatter=formatter ) with gr.Column(): with gr.Row(): audio = gr.Audio(label="Audio") with gr.Row(): gr.DeepLinkButton(value="Share Audio via Link") with gr.Row(): gr.Examples( examples=[ [ [ { "speaker": "Speaker 1", "text": "Why did the chicken cross the road?", }, {"speaker": "Speaker 2", "text": "I don't know!"}, { "speaker": "Speaker 1", "text": "to get to the other side! (laughs)", }, ] ], [ [ { "speaker": "Speaker 1", "text": "I am a little tired today (sighs).", }, {"speaker": "Speaker 2", "text": "Hang in there!"}, ] ], ], inputs=[dialogue], cache_examples=False, ) dialogue.submit(query, [dialogue], audio) if __name__ == "__main__": demo.launch()
import gradio as gr
import httpx
tags = [
"(laughs)",
"(clears throat)",
"(sighs)",
"(gasps)",
"(coughs)",
"(singing)",
"(sings)",
"(mumbles)",
"(beep)",
"(groans)",
"(sniffs)",
"(claps)",
"(screams)",
"(inhales)",
"(exhales)",
"(applause)",
"(burps)",
"(humming)",
"(sneezes)",
"(chuckle)",
"(whistles)",
]
speakers = ["Speaker 1", "Speaker 2"]
client = httpx.AsyncClient(timeout=180)
API_URL = "https://router.huggingface.co/fal-ai/fal-ai/dia-tts"
async def query(dialogue: str, token: gr.OAuthToken | None):
if token is None:
raise gr.Error(
"No token provided. Use Sign in with Hugging Face to get a token."
)
headers = {
"Authorization": f"Bearer {token.token}",
}
response = await client.post(API_URL, headers=headers, json={"text": dialogue})
url = response.json()["audio"]["url"]
print("URL: ", url)
return url
def formatter(speaker, text):
speaker = spea
|
Demos
|
https://gradio.app/docs/gradio/dialogue
|
Gradio - Dialogue Docs
|
No dataset card yet