New to Gradio? Start here: Getting Started
See the Release History
Building Demos
Interface
gradio.Interface(fn, inputs, outputs, ···)
Interface is Gradio's main high-level class, and allows you to create a web-based GUI / demo around a machine learning model (or any Python function) in a few lines of code. You must specify three parameters: (1) the function to create a GUI for (2) the desired input components and (3) the desired output components. Additional parameters can be used to control the appearance and behavior of the demo.
Example Usage
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")
demo.launch()
Parameter | Description |
---|---|
fn
Callable required |
the function to wrap an interface around. 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
str | IOComponent | list[str | IOComponent] | None required |
a single Gradio component, or list of Gradio components. Components can either be passed as instantiated objects, or referred to by their string shortcuts. The number of input components should match the number of parameters in fn. If set to None, then only the output components will be displayed. |
outputs
str | IOComponent | list[str | IOComponent] | None required |
a single Gradio component, or list of Gradio components. Components can either be passed as instantiated objects, or referred to by their string shortcuts. The number of output components should match the number of values returned by fn. If set to None, then only the input components will be displayed. |
examples
list[Any] | list[list[Any]] | str | None default: None |
sample inputs for the function; if provided, appear below the UI components and can be clicked to populate the interface. 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. |
cache_examples
bool | None default: None |
If True, caches examples in the server for fast runtime in examples. The default option in HuggingFace Spaces is True. The default option elsewhere is False. |
examples_per_page
int default: 10 |
If examples are provided, how many to display per page. |
live
bool default: False |
whether the interface should automatically rerun if any of the inputs change. |
interpretation
Callable | str | None default: None |
function that provides interpretation explaining prediction output. Pass "default" to use simple built-in interpreter, "shap" to use a built-in shapley-based interpreter, or your own custom interpretation function. For more information on the different interpretation methods, see the Advanced Interface Features guide. |
num_shap
float default: 2.0 |
a multiplier that determines how many examples are computed for shap-based interpretation. Increasing this value will increase shap runtime, but improve results. Only applies if interpretation is "shap". |
title
str | None default: None |
a title for the interface; if provided, appears above the input and output components in large font. Also used as the tab title when opened in a browser window. |
description
str | None default: None |
a description for the interface; if provided, appears above the input and output components and beneath the title in regular font. Accepts Markdown and HTML content. |
article
str | None default: None |
an expanded article explaining the interface; if provided, appears below the input and output components in regular font. Accepts Markdown and HTML content. |
thumbnail
str | None default: None |
path or url to image to use as display image when the web demo is shared on social media. |
theme
Theme | str | None default: None |
Theme to use, loaded from gradio.themes. |
css
str | None default: None |
custom css or path to custom css file to use with interface. |
allow_flagging
str | None default: None |
one of "never", "auto", or "manual". If "never" or "auto", users will not see a button to flag an input and output. If "manual", users will see a button to flag. If "auto", every input the user submits will be automatically flagged (outputs are not flagged). If "manual", both the input and outputs are flagged when the user clicks flag button. This parameter can be set with environmental variable GRADIO_ALLOW_FLAGGING; otherwise defaults to "manual". |
flagging_options
list[str] | list[tuple[str, str]] | None default: None |
if provided, allows user to select from the list of options when flagging. Only applies if allow_flagging is "manual". Can either be a list of tuples of the form (label, value), where label is the string that will be displayed on the button and value is the string that will be stored in the flagging CSV; or it can be a list of strings ["X", "Y"], in which case the values will be the list of strings and the labels will ["Flag as X", "Flag as Y"], etc. |
flagging_dir
str default: "flagged" |
what to name the directory where flagged data is stored. |
flagging_callback
FlaggingCallback default: CSVLogger() |
An instance of a subclass of FlaggingCallback which will be called when a sample is flagged. By default logs to a local CSV file. |
analytics_enabled
bool | None default: None |
Whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable if defined, or default to True. |
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) |
Methods
launch
gradio.Interface.launch(···)
Launches a simple web server that serves the demo. Can also be used to create a public link used by anyone to access the demo from their browser by setting share=True.
Example Usage
import gradio as gr
def reverse(text):
return text[::-1]
demo = gr.Interface(reverse, "text", "text")
demo.launch(share=True, auth=("username", "password"))
Parameter | Description |
---|---|
inline
bool | None default: None |
whether to display in the interface inline in an iframe. Defaults to True in python notebooks; False otherwise. |
inbrowser
bool default: False |
whether to automatically launch the interface in a new tab on the default browser. |
share
bool | None default: None |
whether to create a publicly shareable link for the interface. Creates an SSH tunnel to make your UI accessible from anywhere. If not provided, it is set to False by default every time, except when running in Google Colab. When localhost is not accessible (e.g. Google Colab), setting share=False is not supported. |
debug
bool default: False |
if True, blocks the main thread from running. If running in Google Colab, this is needed to print the errors in the cell output. |
enable_queue
bool | None default: None |
DEPRECATED (use .queue() method instead.) if True, inference requests will be served through a queue instead of with parallel threads. Required for longer inference times (> 1min) to prevent timeout. The default option in HuggingFace Spaces is True. The default option elsewhere is False. |
max_threads
int default: 40 |
the maximum number of total threads that the Gradio app can generate in parallel. The default is inherited from the starlette library (currently 40). Applies whether the queue is enabled or not. But if queuing is enabled, this parameter is increaseed to be at least the concurrency_count of the queue. |
auth
Callable | tuple[str, str] | list[tuple[str, str]] | None default: None |
If provided, username and password (or list of username-password tuples) required to access interface. Can also provide function that takes username and password and returns True if valid login. |
auth_message
str | None default: None |
If provided, HTML message provided on login page. |
prevent_thread_lock
bool default: False |
If True, the interface will block the main thread while the server is running. |
show_error
bool default: False |
If True, any errors in the interface will be displayed in an alert modal and printed in the browser console log |
server_name
str | None default: None |
to make app accessible on local network, set this to "0.0.0.0". Can be set by environment variable GRADIO_SERVER_NAME. If None, will use "127.0.0.1". |
server_port
int | None default: None |
will start gradio app on this port (if available). Can be set by environment variable GRADIO_SERVER_PORT. If None, will search for an available port starting at 7860. |
show_tips
bool default: False |
if True, will occasionally show tips about new Gradio features |
height
int default: 500 |
The height in pixels of the iframe element containing the interface (used if inline=True) |
width
int | str default: "100%" |
The width in pixels of the iframe element containing the interface (used if inline=True) |
encrypt
bool | None default: None |
DEPRECATED. Has no effect. |
favicon_path
str | None default: None |
If a path to a file (.png, .gif, or .ico) is provided, it will be used as the favicon for the web page. |
ssl_keyfile
str | None default: None |
If a path to a file is provided, will use this as the private key file to create a local server running on https. |
ssl_certfile
str | None default: None |
If a path to a file is provided, will use this as the signed certificate for https. Needs to be provided if ssl_keyfile is provided. |
ssl_keyfile_password
str | None default: None |
If a password is provided, will use this with the ssl certificate for https. |
ssl_verify
bool default: True |
If False, skips certificate validation which allows self-signed certificates to be used. |
quiet
bool default: False |
If True, suppresses most print statements. |
show_api
bool default: True |
If True, shows the api docs in the footer of the app. Default True. If the queue is enabled, then api_open parameter of .queue() will determine if the api docs are shown, independent of the value of show_api. |
file_directories
list[str] | None default: None |
This parameter has been renamed to `allowed_paths`. It will be removed in a future version. |
allowed_paths
list[str] | None default: None |
List of complete filepaths or parent directories that gradio is allowed to serve (in addition to the directory containing the gradio python file). Must be absolute paths. Warning: if you provide directories, any files in these directories or their subdirectories are accessible to all users of your app. |
blocked_paths
list[str] | None default: None |
List of complete filepaths or parent directories that gradio is not allowed to serve (i.e. users of your app are not allowed to access). Must be absolute paths. Warning: takes precedence over `allowed_paths` and all other directories exposed by Gradio by default. |
root_path
str default: "" |
The root path (or "mount point") of the application, if it's not served from the root ("/") of the domain. Often used when the application is behind a reverse proxy that forwards requests to the application. For example, if the application is served at "https://example.com/myapp", the `root_path` should be set to "/myapp". |
load
gradio.Interface.load(name, ···)
Warning: this method will be deprecated. Use the equivalent `gradio.load()` instead. This is a class method that constructs a Blocks from a Hugging Face repo. Can accept model repos (if src is "models") or Space repos (if src is "spaces"). The input and output components are automatically loaded from the repo.
Parameter | Description |
---|---|
name
str required |
the name of the model (e.g. "gpt2" or "facebook/bart-base") or space (e.g. "flax-community/spanish-gpt2"), can include the `src` as prefix (e.g. "models/facebook/bart-base") |
src
str | None default: None |
the source of the model: `models` or `spaces` (or leave empty if source is provided as a prefix in `name`) |
api_key
str | None default: None |
optional access token for loading private Hugging Face Hub models or spaces. Find your token here: https://huggingface.co/settings/tokens |
alias
str | None default: None |
optional string used as the name of the loaded model instead of the default name (only applies if loading a Space running Gradio 2.x) |
from_pipeline
gradio.Interface.from_pipeline(pipeline, ···)
Class method that constructs an Interface from a Hugging Face transformers.Pipeline object. The input and output components are automatically determined from the pipeline.
Example Usage
import gradio as gr
from transformers import pipeline
pipe = pipeline("image-classification")
gr.Interface.from_pipeline(pipe).launch()
Parameter | Description |
---|---|
pipeline
Pipeline required |
the pipeline object to use. |
integrate
gradio.Interface.integrate(···)
A catch-all method for integrating with other libraries. This method should be run after launch()
Parameter | Description |
---|---|
comet_ml
default: None |
If a comet_ml Experiment object is provided, will integrate with the experiment and appear on Comet dashboard |
wandb
ModuleType | None default: None |
If the wandb module is provided, will integrate with it and appear on WandB dashboard |
mlflow
ModuleType | None default: None |
If the mlflow module is provided, will integrate with the experiment and appear on ML Flow dashboard |
queue
gradio.Interface.queue(···)
You can control the rate of processed requests by creating a queue. This will allow you to set the number of requests to be processed at one time, and will let users know their position in the queue.
Example Usage
demo = gr.Interface(image_generator, gr.Textbox(), gr.Image())
demo.queue(concurrency_count=3)
demo.launch()
Parameter | Description |
---|---|
concurrency_count
int default: 1 |
Number of worker threads that will be processing requests from the queue concurrently. Increasing this number will increase the rate at which requests are processed, but will also increase the memory usage of the queue. |
status_update_rate
float | Literal['auto'] default: "auto" |
If "auto", Queue will send status estimations to all clients whenever a job is finished. Otherwise Queue will send status at regular intervals set by this parameter as the number of seconds. |
client_position_to_load_data
int | None default: None |
DEPRECATED. This parameter is deprecated and has no effect. |
default_enabled
bool | None default: None |
Deprecated and has no effect. |
api_open
bool default: True |
If True, the REST routes of the backend will be open, allowing requests made directly to those endpoints to skip the queue. |
max_size
int | None default: None |
The maximum number of events the queue will store at any given moment. If the queue is full, new events will not be added and a user will receive a message saying that the queue is full. If None, the queue size will be unlimited. |
Step-by-step Guides
Flagging
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(···)
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.
Example Usage
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())
Step-by-step Guides
No guides yet, contribute a guide about SimpleCSVLogger
CSVLogger
gradio.CSVLogger(···)
The default implementation of the FlaggingCallback abstract class. Each flagged sample (both the input and output data) is logged to a CSV file with headers on the machine running the gradio app.
Example Usage
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())
Step-by-step Guides
HuggingFaceDatasetSaver
gradio.HuggingFaceDatasetSaver(hf_token, dataset_name, ···)
A callback that saves each flagged sample (both the input and output data) to a HuggingFace dataset.
Example Usage
import gradio as gr
hf_writer = gr.HuggingFaceDatasetSaver(HF_API_TOKEN, "image-classification-mistakes")
def image_classifier(inp):
return {'cat': 0.3, 'dog': 0.7}
demo = gr.Interface(fn=image_classifier, inputs="image", outputs="label",
allow_flagging="manual", flagging_callback=hf_writer)
Parameter | Description |
---|---|
hf_token
str required |
The HuggingFace token to use to create (and write the flagged sample to) the HuggingFace dataset (defaults to the registered one). |
dataset_name
str required |
The repo_id of the dataset to save the data to, e.g. "image-classifier-1" or "username/image-classifier-1". |
organization
str | None default: None |
Deprecated argument. Please pass a full dataset id (e.g. 'username/dataset_name') to `dataset_name` instead. |
private
bool default: False |
Whether the dataset should be private (defaults to False). |
info_filename
str default: "dataset_info.json" |
The name of the file to save the dataset info (defaults to "dataset_infos.json"). |
separate_dirs
bool default: False |
If True, each flagged item will be saved in a separate directory. This makes the flagging more robust to concurrent editing, but may be less convenient to use. |
verbose
bool default: True |
Step-by-step Guides
Combining Interfaces
Once you have created several Interfaces, we provide several classes that let you start combining them together. For example, you can chain them in Series or compare their outputs in Parallel if the inputs and outputs match accordingly. You can also display arbitrary Interfaces together in a tabbed layout using TabbedInterface.
TabbedInterface
gradio.TabbedInterface(interface_list, ···)
A TabbedInterface is created by providing a list of Interfaces, each of which gets rendered in a separate tab.
import gradio as gr
title = "GPT-J-6B"
tts_examples = [
"I love learning machine learning",
"How do you do?",
]
tts_demo = gr.load(
"huggingface/facebook/fastspeech2-en-ljspeech",
title=None,
examples=tts_examples,
description="Give me something to say!",
)
stt_demo = gr.load(
"huggingface/facebook/wav2vec2-base-960h",
title=None,
inputs="mic",
description="Let me try to guess what you're saying!",
)
demo = gr.TabbedInterface([tts_demo, stt_demo], ["Text-to-speech", "Speech-to-text"])
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
interface_list
list[Interface] required |
a list of interfaces to be rendered in tabs. |
tab_names
list[str] | None default: None |
a list of tab names. If None, the tab names will be "Tab 1", "Tab 2", etc. |
title
str | None default: None |
a title for the interface; if provided, appears above the input and output components in large font. Also used as the tab title when opened in a browser window. |
theme
Theme | None default: None |
|
analytics_enabled
bool | None default: None |
whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable or default to True. |
css
str | None default: None |
custom css or path to custom css file to apply to entire Blocks |
Parallel
gradio.Parallel(interfaces, ···)
Creates a new Interface consisting of multiple Interfaces in parallel (comparing their outputs). The Interfaces to put in Parallel must share the same input components (but can have different output components).
import gradio as gr
greeter_1 = gr.Interface(lambda name: f"Hello {name}!", inputs="textbox", outputs=gr.Textbox(label="Greeter 1"))
greeter_2 = gr.Interface(lambda name: f"Greetings {name}!", inputs="textbox", outputs=gr.Textbox(label="Greeter 2"))
demo = gr.Parallel(greeter_1, greeter_2)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
interfaces
required |
any number of Interface objects that are to be compared in parallel |
options
|
additional kwargs that are passed into the new Interface object to customize it |
Step-by-step Guides
Series
gradio.Series(interfaces, ···)
Creates a new Interface from multiple Interfaces in series (the output of one is fed as the input to the next, and so the input and output components must agree between the interfaces).
import gradio as gr
get_name = gr.Interface(lambda name: name, inputs="textbox", outputs="textbox")
prepend_hello = gr.Interface(lambda name: f"Hello {name}!", inputs="textbox", outputs="textbox")
append_nice = gr.Interface(lambda greeting: f"{greeting} Nice to meet you!",
inputs="textbox", outputs=gr.Textbox(label="Greeting"))
demo = gr.Series(get_name, prepend_hello, append_nice)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
interfaces
required |
any number of Interface objects that are to be connected in series |
options
|
additional kwargs that are passed into the new Interface object to customize it |
Step-by-step Guides
Blocks
with gr.Blocks():
Blocks is Gradio's low-level API that allows you to create more custom web applications and demos than Interfaces (yet still entirely in Python).
Compared to the Interface class, Blocks offers more flexibility and control over: (1) the layout of components (2) the events that trigger the execution of functions (3) data flows (e.g. inputs can trigger outputs, which can trigger the next level of outputs). Blocks also offers ways to group together related demos such as with tabs.
The basic usage of Blocks is as follows: create a Blocks object, then use it as a context (with the "with" statement), and then define layouts, components, or events within the Blocks context. Finally, call the launch() method to launch the demo.
Example Usage
import gradio as gr
def update(name):
return f"Welcome to Gradio, {name}!"
with gr.Blocks() as demo:
gr.Markdown("Start typing below and then click **Run** to see the output.")
with gr.Row():
inp = gr.Textbox(placeholder="What is your name?")
out = gr.Textbox()
btn = gr.Button("Run")
btn.click(fn=update, inputs=inp, outputs=out)
demo.launch()
Parameter | Description |
---|---|
theme
Theme | str | None default: None |
a Theme object or a string representing a theme. If a string, will look for a built-in theme with that name (e.g. "soft" or "default"), or will attempt to load a theme from the HF Hub (e.g. "gradio/monochrome"). If None, will use the Default theme. |
analytics_enabled
bool | None default: None |
whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable or default to True. |
mode
str default: "blocks" |
a human-friendly name for the kind of Blocks or Interface being created. |
title
str default: "Gradio" |
The tab title to display when this is opened in a browser window. |
css
str | None default: None |
custom css or path to custom css file to apply to entire Blocks |
Methods
launch
gradio.Blocks.launch(···)
Launches a simple web server that serves the demo. Can also be used to create a public link used by anyone to access the demo from their browser by setting share=True.
Example Usage
import gradio as gr
def reverse(text):
return text[::-1]
with gr.Blocks() as demo:
button = gr.Button(value="Reverse")
button.click(reverse, gr.Textbox(), gr.Textbox())
demo.launch(share=True, auth=("username", "password"))
Parameter | Description |
---|---|
inline
bool | None default: None |
whether to display in the interface inline in an iframe. Defaults to True in python notebooks; False otherwise. |
inbrowser
bool default: False |
whether to automatically launch the interface in a new tab on the default browser. |
share
bool | None default: None |
whether to create a publicly shareable link for the interface. Creates an SSH tunnel to make your UI accessible from anywhere. If not provided, it is set to False by default every time, except when running in Google Colab. When localhost is not accessible (e.g. Google Colab), setting share=False is not supported. |
debug
bool default: False |
if True, blocks the main thread from running. If running in Google Colab, this is needed to print the errors in the cell output. |
enable_queue
bool | None default: None |
DEPRECATED (use .queue() method instead.) if True, inference requests will be served through a queue instead of with parallel threads. Required for longer inference times (> 1min) to prevent timeout. The default option in HuggingFace Spaces is True. The default option elsewhere is False. |
max_threads
int default: 40 |
the maximum number of total threads that the Gradio app can generate in parallel. The default is inherited from the starlette library (currently 40). Applies whether the queue is enabled or not. But if queuing is enabled, this parameter is increaseed to be at least the concurrency_count of the queue. |
auth
Callable | tuple[str, str] | list[tuple[str, str]] | None default: None |
If provided, username and password (or list of username-password tuples) required to access interface. Can also provide function that takes username and password and returns True if valid login. |
auth_message
str | None default: None |
If provided, HTML message provided on login page. |
prevent_thread_lock
bool default: False |
If True, the interface will block the main thread while the server is running. |
show_error
bool default: False |
If True, any errors in the interface will be displayed in an alert modal and printed in the browser console log |
server_name
str | None default: None |
to make app accessible on local network, set this to "0.0.0.0". Can be set by environment variable GRADIO_SERVER_NAME. If None, will use "127.0.0.1". |
server_port
int | None default: None |
will start gradio app on this port (if available). Can be set by environment variable GRADIO_SERVER_PORT. If None, will search for an available port starting at 7860. |
show_tips
bool default: False |
if True, will occasionally show tips about new Gradio features |
height
int default: 500 |
The height in pixels of the iframe element containing the interface (used if inline=True) |
width
int | str default: "100%" |
The width in pixels of the iframe element containing the interface (used if inline=True) |
encrypt
bool | None default: None |
DEPRECATED. Has no effect. |
favicon_path
str | None default: None |
If a path to a file (.png, .gif, or .ico) is provided, it will be used as the favicon for the web page. |
ssl_keyfile
str | None default: None |
If a path to a file is provided, will use this as the private key file to create a local server running on https. |
ssl_certfile
str | None default: None |
If a path to a file is provided, will use this as the signed certificate for https. Needs to be provided if ssl_keyfile is provided. |
ssl_keyfile_password
str | None default: None |
If a password is provided, will use this with the ssl certificate for https. |
ssl_verify
bool default: True |
If False, skips certificate validation which allows self-signed certificates to be used. |
quiet
bool default: False |
If True, suppresses most print statements. |
show_api
bool default: True |
If True, shows the api docs in the footer of the app. Default True. If the queue is enabled, then api_open parameter of .queue() will determine if the api docs are shown, independent of the value of show_api. |
file_directories
list[str] | None default: None |
This parameter has been renamed to `allowed_paths`. It will be removed in a future version. |
allowed_paths
list[str] | None default: None |
List of complete filepaths or parent directories that gradio is allowed to serve (in addition to the directory containing the gradio python file). Must be absolute paths. Warning: if you provide directories, any files in these directories or their subdirectories are accessible to all users of your app. |
blocked_paths
list[str] | None default: None |
List of complete filepaths or parent directories that gradio is not allowed to serve (i.e. users of your app are not allowed to access). Must be absolute paths. Warning: takes precedence over `allowed_paths` and all other directories exposed by Gradio by default. |
root_path
str default: "" |
The root path (or "mount point") of the application, if it's not served from the root ("/") of the domain. Often used when the application is behind a reverse proxy that forwards requests to the application. For example, if the application is served at "https://example.com/myapp", the `root_path` should be set to "/myapp". |
queue
gradio.Blocks.queue(···)
You can control the rate of processed requests by creating a queue. This will allow you to set the number of requests to be processed at one time, and will let users know their position in the queue.
Example Usage
with gr.Blocks() as demo:
button = gr.Button(label="Generate Image")
button.click(fn=image_generator, inputs=gr.Textbox(), outputs=gr.Image())
demo.queue(concurrency_count=3)
demo.launch()
Parameter | Description |
---|---|
concurrency_count
int default: 1 |
Number of worker threads that will be processing requests from the queue concurrently. Increasing this number will increase the rate at which requests are processed, but will also increase the memory usage of the queue. |
status_update_rate
float | Literal['auto'] default: "auto" |
If "auto", Queue will send status estimations to all clients whenever a job is finished. Otherwise Queue will send status at regular intervals set by this parameter as the number of seconds. |
client_position_to_load_data
int | None default: None |
DEPRECATED. This parameter is deprecated and has no effect. |
default_enabled
bool | None default: None |
Deprecated and has no effect. |
api_open
bool default: True |
If True, the REST routes of the backend will be open, allowing requests made directly to those endpoints to skip the queue. |
max_size
int | None default: None |
The maximum number of events the queue will store at any given moment. If the queue is full, new events will not be added and a user will receive a message saying that the queue is full. If None, the queue size will be unlimited. |
integrate
gradio.Blocks.integrate(···)
A catch-all method for integrating with other libraries. This method should be run after launch()
Parameter | Description |
---|---|
comet_ml
default: None |
If a comet_ml Experiment object is provided, will integrate with the experiment and appear on Comet dashboard |
wandb
ModuleType | None default: None |
If the wandb module is provided, will integrate with it and appear on WandB dashboard |
mlflow
ModuleType | None default: None |
If the mlflow module is provided, will integrate with the experiment and appear on ML Flow dashboard |
load
gradio.Blocks.load(···)
For reverse compatibility reasons, this is both a class method and an instance method, the two of which, confusingly, do two completely different things.
Class method: loads a demo from a Hugging Face Spaces repo and creates it locally and returns a block instance. Warning: this method will be deprecated. Use the equivalent `gradio.load()` instead.
Instance method: adds event that runs as soon as the demo loads in the browser. Example usage below.
Example Usage
import gradio as gr
import datetime
with gr.Blocks() as demo:
def get_time():
return datetime.datetime.now().time()
dt = gr.Textbox(label="Current time")
demo.load(get_time, inputs=None, outputs=dt)
demo.launch()
Parameter | Description |
---|---|
fn
Callable | None default: None |
Instance Method - the function to wrap an interface around. 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
list[Component] | None default: None |
Instance Method - List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list. |
outputs
list[Component] | None default: None |
Instance Method - List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list. |
api_name
str | None default: None |
Instance Method - Defining this parameter exposes the endpoint in the api docs |
scroll_to_output
bool default: False |
Instance Method - If True, will scroll to output component on completion |
show_progress
bool default: True |
Instance Method - If True, will show progress animation while pending |
queue
default: None |
Instance Method - If True, will place the request on the queue, if the queue exists |
batch
bool default: False |
Instance Method - 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 |
Instance Method - Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True) |
preprocess
bool default: True |
Instance Method - 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 |
Instance Method - If False, will not run postprocessing of component data before returning 'fn' output to the browser. |
every
float | None default: None |
Instance Method - Run this event 'every' number of seconds. Interpreted in seconds. Queue must be enabled. |
name
str | None default: None |
Class Method - the name of the model (e.g. "gpt2" or "facebook/bart-base") or space (e.g. "flax-community/spanish-gpt2"), can include the `src` as prefix (e.g. "models/facebook/bart-base") |
src
str | None default: None |
Class Method - the source of the model: `models` or `spaces` (or leave empty if source is provided as a prefix in `name`) |
api_key
str | None default: None |
Class Method - optional access token for loading private Hugging Face Hub models or spaces. Find your token here: https://huggingface.co/settings/tokens |
alias
str | None default: None |
Class Method - optional string used as the name of the loaded model instead of the default name (only applies if loading a Space running Gradio 2.x) |
Step-by-step Guides
Block Layouts
Customize the layout of your Blocks UI with the layout classes below.
Row
with gr.Row():
Row is a layout element within Blocks that renders all children horizontally.
Example Usage
with gr.Blocks() as demo:
with gr.Row():
gr.Image("lion.jpg")
gr.Image("tiger.jpg")
demo.launch()
Parameter | Description |
---|---|
variant
str default: "default" |
row type, 'default' (no background), 'panel' (gray background color and rounded corners), or 'compact' (rounded corners and no internal gap). |
visible
bool default: True |
If False, row will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
Step-by-step Guides
Column
with gr.Column():
Column is a layout element within Blocks that renders all children vertically. The widths of columns can be set through the `scale` and `min_width` parameters. If a certain scale results in a column narrower than min_width, the min_width parameter will win.
Example Usage
with gr.Blocks() as demo:
with gr.Row():
with gr.Column(scale=1):
text1 = gr.Textbox()
text2 = gr.Textbox()
with gr.Column(scale=4):
btn1 = gr.Button("Button 1")
btn2 = gr.Button("Button 2")
Parameter | Description |
---|---|
scale
int default: 1 |
relative width compared to adjacent Columns. For example, if Column A has scale=2, and Column B has scale=1, A will be twice as wide as B. |
min_width
int default: 320 |
minimum pixel width of Column, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in a column narrower than min_width, the min_width parameter will be respected first. |
variant
str default: "default" |
column type, 'default' (no background), 'panel' (gray background color and rounded corners), or 'compact' (rounded corners and no internal gap). |
visible
bool default: True |
If False, column will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
Step-by-step Guides
Tab
with gr.Tab():
Tab (or its alias TabItem) is a layout element. Components defined within the Tab will be visible when this tab is selected tab.
Example Usage
with gr.Blocks() as demo:
with gr.Tab("Lion"):
gr.Image("lion.jpg")
gr.Button("New Lion")
with gr.Tab("Tiger"):
gr.Image("tiger.jpg")
gr.Button("New Tiger")
Parameter | Description |
---|---|
label
str required |
The visual label for the tab |
id
int | str | None default: None |
An optional identifier for the tab, required if you wish to control the selected tab from a predict function. |
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. |
Methods
select
gradio.Tab.select(fn, ···)
This event is triggered when the user selects from within the Component. This event has EventData of type gradio.SelectData that carries information, accessible through SelectData.index and SelectData.value. See EventData documentation on how to use this event data.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
Box
with gr.Box():
Box is a a layout element which places children in a box with rounded corners and some padding around them.
Example Usage
with gr.Box():
gr.Textbox(label="First")
gr.Textbox(label="Last")
Parameter | Description |
---|---|
visible
bool default: True |
If False, box will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
Step-by-step Guides
No guides yet, contribute a guide about Box
Accordion
gradio.Accordion(label, ···)
Accordion is a layout element which can be toggled to show/hide the contained content.
Example Usage
with gr.Accordion("See Details"):
gr.Markdown("lorem ipsum")
Parameter | Description |
---|---|
label
required |
name of accordion section. |
open
bool default: True |
if True, accordion is open by default. |
visible
bool default: True |
|
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. |
Step-by-step Guides
No guides yet, contribute a guide about Accordion
Themes
Customize the look of your app by writing your own custom theme
Base
gradio.Base(···)
Parameter | Description |
---|---|
primary_hue
colors.Color | str default: Color() |
The primary hue of the theme. Load a preset, like gradio.themes.colors.green (or just the string "green"), or pass your own gradio.themes.utils.Color object. |
secondary_hue
colors.Color | str default: Color() |
The secondary hue of the theme. Load a preset, like gradio.themes.colors.green (or just the string "green"), or pass your own gradio.themes.utils.Color object. |
neutral_hue
colors.Color | str default: Color() |
The neutral hue of the theme, used . Load a preset, like gradio.themes.colors.green (or just the string "green"), or pass your own gradio.themes.utils.Color object. |
text_size
sizes.Size | str default: Size() |
The size of the text. Load a preset, like gradio.themes.sizes.text_sm (or just the string "sm"), or pass your own gradio.themes.utils.Size object. |
spacing_size
sizes.Size | str default: Size() |
The size of the spacing. Load a preset, like gradio.themes.sizes.spacing_sm (or just the string "sm"), or pass your own gradio.themes.utils.Size object. |
radius_size
sizes.Size | str default: Size() |
The radius size of corners. Load a preset, like gradio.themes.sizes.radius_sm (or just the string "sm"), or pass your own gradio.themes.utils.Size object. |
font
fonts.Font | str | Iterable[fonts.Font | str] default: ( |
The primary font to use for the theme. Pass a string for a system font, or a gradio.themes.font.GoogleFont object to load a font from Google Fonts. Pass a list of fonts for fallbacks. |
font_mono
fonts.Font | str | Iterable[fonts.Font | str] default: ( |
The monospace font to use for the theme, applies to code. Pass a string for a system font, or a gradio.themes.font.GoogleFont object to load a font from Google Fonts. Pass a list of fonts for fallbacks. |
Methods
push_to_hub
gradio.Base.push_to_hub(repo_name, ···)
Upload a theme to the HuggingFace hub.
This requires a HuggingFace account.
Parameter | Description |
---|---|
repo_name
str required |
The name of the repository to store the theme assets, e.g. 'my_theme' or 'sunset'. |
org_name
str | None default: None |
The name of the org to save the space in. If None (the default), the username corresponding to the logged in user, or hƒ_token is used. |
version
str | None default: None |
A semantic version tag for theme. Bumping the version tag lets you publish updates to a theme without changing the look of applications that already loaded your theme. |
hf_token
str | None default: None |
API token for your HuggingFace account |
theme_name
str | None default: None |
Name for the name. If None, defaults to repo_name |
description
str | None default: None |
A long form description to your theme. |
private
bool default: False |
from_hub
gradio.Base.from_hub(repo_name, ···)
Load a theme from the hub.
This DOES NOT require a HuggingFace account for downloading publicly available themes.
Parameter | Description |
---|---|
repo_name
str required |
string of the form |
hf_token
str | None default: None |
HuggingFace Token. Only needed to download private themes. |
load
gradio.Base.load(path, ···)
Load a theme from a json file.
Parameter | Description |
---|---|
path
str required |
The filepath to read. |
dump
gradio.Base.dump(filename, ···)
Write the theme to a json file.
Parameter | Description |
---|---|
filename
str required |
The path to write the theme too |
from_dict
gradio.Base.from_dict(theme, ···)
Create a theme instance from a dictionary representation.
Parameter | Description |
---|---|
theme
dict[str, dict[str, str]] required |
The dictionary representation of the theme. |
to_dict
gradio.Base.to_dict(···)
Convert the theme into a python dictionary.
Step-by-step Guides
No guides yet, contribute a guide about Base
Components
Gradio includes pre-built components that can be used as inputs or outputs in your Interface or Blocks with a single line of code. Components include preprocessing steps that convert user data submitted through browser to something that be can used by a Python function, and postprocessing steps to convert values returned by a Python function into something that can be displayed in a browser.
Consider an example with three inputs (Textbox, Number, and Image) and two outputs (Number and Gallery), below is a diagram of what our preprocessing will send to the function and what our postprocessing will require from it.
Components also come with certain events that they support. These are methods that are triggered with user actions. Below is a table showing which events are supported for each component. All events are also listed (with parameters) in the component's docs.
Change | Click | Submit | Edit | Clear | Play | Pause | Stream | Blur | Upload | |
---|---|---|---|---|---|---|---|---|---|---|
AnnotatedImage |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
Audio |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
BarPlot |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
Button |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
Chatbot |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
Checkbox |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
CheckboxGroup |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
Code |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
ColorPicker |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
Dataframe |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
Dataset |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
Dropdown |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
File |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
Gallery |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
HTML |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
HighlightedText |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
Image |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
Interpretation |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
JSON |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
Label |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
LinePlot |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
Markdown |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
Model3D |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
Number |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
Plot |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
Radio |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
ScatterPlot |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
Slider |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
State |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
Textbox |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
Timeseries |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
UploadButton |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
Video |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
✕ |
AnnotatedImage
gradio.AnnotatedImage(···)
Displays a base image and colored subsections on top of that image. Subsections can take the from of rectangles (e.g. object detection) or masks (e.g. image segmentation).
As input: this component does *not* accept input.
As output: expects a Tuple[numpy.ndarray | PIL.Image | str, List[Tuple[numpy.ndarray | Tuple[int, int, int, int], str]]] consisting of a base image and a list of subsections, that are either (x1, y1, x2, y2) tuples identifying object boundaries, or 0-1 confidence masks of the same shape as the image. A label is provided for each subsection.
import gradio as gr
import numpy as np
import random
with gr.Blocks() as demo:
section_labels = [
"apple",
"banana",
"carrot",
"donut",
"eggplant",
"fish",
"grapes",
"hamburger",
"ice cream",
"juice",
]
with gr.Row():
num_boxes = gr.Slider(0, 5, 2, step=1, label="Number of boxes")
num_segments = gr.Slider(0, 5, 1, step=1, label="Number of segments")
with gr.Row():
img_input = gr.Image()
img_output = gr.AnnotatedImage().style(
color_map={"banana": "#a89a00", "carrot": "#ffae00"}
)
section_btn = gr.Button("Identify Sections")
selected_section = gr.Textbox(label="Selected Section")
def section(img, num_boxes, num_segments):
sections = []
for a in range(num_boxes):
x = random.randint(0, img.shape[1])
y = random.randint(0, img.shape[0])
w = random.randint(0, img.shape[1] - x)
h = random.randint(0, img.shape[0] - y)
sections.append(((x, y, x + w, y + h), section_labels[a]))
for b in range(num_segments):
x = random.randint(0, img.shape[1])
y = random.randint(0, img.shape[0])
r = random.randint(0, min(x, y, img.shape[1] - x, img.shape[0] - y))
mask = np.zeros(img.shape[:2])
for i in range(img.shape[0]):
for j in range(img.shape[1]):
dist_square = (i - y) ** 2 + (j - x) ** 2
if dist_square < r**2:
mask[i, j] = round((r**2 - dist_square) / r**2 * 4) / 4
sections.append((mask, section_labels[b + num_boxes]))
return (img, sections)
section_btn.click(section, [img_input, num_boxes, num_segments], img_output)
def select_section(evt: gr.SelectData):
return section_labels[evt.index]
img_output.select(select_section, None, selected_section)
demo.launch()
Parameter | Description |
---|---|
value
tuple[np.ndarray | _Image.Image | str, list[tuple[np.ndarray | tuple[int, int, int, int], str]]] | None default: None |
Tuple of base image and list of (subsection, label) pairs. |
show_legend
bool default: True |
If True, will show a legend of the subsections. |
label
str | None default: None |
component name in interface. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"annotatedimage" |
Uses default values |
Methods
style
gradio.AnnotatedImage.style(···)
This method can be used to change the appearance of the Image component.
Parameter | Description |
---|---|
height
int | None default: None |
Height of the image. |
width
int | None default: None |
Width of the image. |
color_map
dict[str, str] | None default: None |
A dictionary mapping labels to colors. The colors must be specified as hex codes. |
select
gradio.AnnotatedImage.select(fn, ···)
Event listener for when the user selects Image subsection. Uses event data gradio.SelectData to carry `value` referring to selected subsection label, and `index` to refer to subsection index. See EventData documentation on how to use this event data.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
No guides yet, contribute a guide about AnnotatedImage
Audio
gradio.Audio(···)
Creates an audio component that can be used to upload/record audio (as an input) or display audio (as an output).
As input: passes the uploaded audio as a Tuple(int, numpy.array) corresponding to (sample rate in Hz, audio data as a 16-bit int array whose values range from -32768 to 32767), or as a str filepath, depending on `type`.
As output: expects a Tuple(int, numpy.array) corresponding to (sample rate in Hz, audio data as a float or int numpy array) or as a str filepath or URL to an audio file, which gets displayed
Format expected for examples: a str filepath to a local file that contains audio.
Supported events: check_streamable()
from math import log2, pow
import os
import numpy as np
from scipy.fftpack import fft
import gradio as gr
A4 = 440
C0 = A4 * pow(2, -4.75)
name = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
def get_pitch(freq):
h = round(12 * log2(freq / C0))
n = h % 12
return name[n]
def main_note(audio):
rate, y = audio
if len(y.shape) == 2:
y = y.T[0]
N = len(y)
T = 1.0 / rate
yf = fft(y)
yf2 = 2.0 / N * np.abs(yf[0 : N // 2])
xf = np.linspace(0.0, 1.0 / (2.0 * T), N // 2)
volume_per_pitch = {}
total_volume = np.sum(yf2)
for freq, volume in zip(xf, yf2):
if freq == 0:
continue
pitch = get_pitch(freq)
if pitch not in volume_per_pitch:
volume_per_pitch[pitch] = 0
volume_per_pitch[pitch] += 1.0 * volume / total_volume
volume_per_pitch = {k: float(v) for k, v in volume_per_pitch.items()}
return volume_per_pitch
demo = gr.Interface(
main_note,
gr.Audio(source="microphone"),
gr.Label(num_top_classes=4),
examples=[
[os.path.join(os.path.dirname(__file__),"audio/recording1.wav")],
[os.path.join(os.path.dirname(__file__),"audio/cantina.wav")],
],
interpretation="default",
)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
str | tuple[int, np.ndarray] | Callable | None default: None |
A path, URL, or [sample_rate, numpy array] tuple (sample rate in Hz, audio data as a float or int numpy array) for the default value that Audio component is going to take. If callable, the function will be called whenever the app loads to set the initial value of the component. |
source
str default: "upload" |
Source of audio. "upload" creates a box where user can drop an audio file, "microphone" creates a microphone input. |
type
str default: "numpy" |
The format the audio file is converted to before being passed into the prediction function. "numpy" converts the audio to a tuple consisting of: (int sample rate, numpy.array for the data), "filepath" passes a str path to a temporary file containing the audio. |
label
str | None default: None |
component name in interface. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
interactive
bool | None default: None |
if True, will allow users to upload and edit a audio file; if False, can only be used to play audio. If not provided, this is inferred based on whether the component is used as an input or output. |
visible
bool default: True |
If False, component will be hidden. |
streaming
bool default: False |
If set to True when used in a `live` interface, will automatically stream webcam feed. Only valid is source is 'microphone'. |
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. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"audio" |
Uses default values |
|
"microphone" |
Uses source="microphone" |
Methods
style
gradio.Audio.style(···)
This method can be used to change the appearance of the audio component.
change
gradio.Audio.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
clear
gradio.Audio.clear(fn, ···)
This event is triggered when the user clears the component (e.g. image or audio) using the X button for the component. This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
play
gradio.Audio.play(fn, ···)
This event is triggered when the user plays the component (e.g. audio or video). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
pause
gradio.Audio.pause(fn, ···)
This event is triggered when the user pauses the component (e.g. audio or video). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
stop
gradio.Audio.stop(fn, ···)
This event is triggered when the user stops the component (e.g. audio or video). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
stream
gradio.Audio.stream(fn, ···)
This event is triggered when the user streams the component (e.g. a live webcam component). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
upload
gradio.Audio.upload(fn, ···)
This event is triggered when the user uploads a file into the component (e.g. when the user uploads a video into a video component). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
BarPlot
gradio.BarPlot(···)
Create a bar plot.
As input: this component does *not* accept input.
As output: expects a pandas dataframe with the data to plot.
import gradio as gr
from scatter_plot_demo import scatter_plot
from line_plot_demo import line_plot
from bar_plot_demo import bar_plot
with gr.Blocks() as demo:
with gr.Tabs():
with gr.TabItem("Scatter Plot"):
scatter_plot.render()
with gr.TabItem("Line Plot"):
line_plot.render()
with gr.TabItem("Bar Plot"):
bar_plot.render()
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
pd.DataFrame | Callable | None default: None |
The pandas dataframe containing the data to display in a scatter plot. |
x
str | None default: None |
Column corresponding to the x axis. |
y
str | None default: None |
Column corresponding to the y axis. |
color
str | None default: None |
The column to determine the bar color. Must be categorical (discrete values). |
vertical
bool default: True |
If True, the bars will be displayed vertically. If False, the x and y axis will be switched, displaying the bars horizontally. Default is True. |
group
str | None default: None |
The column with which to split the overall plot into smaller subplots. |
title
str | None default: None |
The title to display on top of the chart. |
tooltip
list[str] | str | None default: None |
The column (or list of columns) to display on the tooltip when a user hovers over a bar. |
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_legend_title
str | None default: None |
The title given to the color legend. By default, uses the value of color parameter. |
group_title
str | None default: None |
The label displayed on top of the subplot columns (or rows if vertical=True). Use an empty string to omit. |
color_legend_position
str | None default: None |
The position of the color legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation. |
height
int | None default: None |
The height of the plot in pixels. |
width
int | None default: None |
The width of the plot in pixels. |
y_lim
list[int] | None default: None |
A tuple of list containing the limits for the y-axis, specified as [y_min, y_max]. |
caption
str | None default: None |
The (optional) caption to display below the plot. |
interactive
bool | None default: True |
Whether users should be able to interact with the plot by panning or zooming with their mouse or trackpad. |
label
str | None default: None |
The (optional) label to display on the top left corner of the plot. |
show_label
bool default: True |
Whether the label should be displayed. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
visible
bool default: True |
Whether the plot should be visible. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"barplot" |
Uses default values |
Methods
change
gradio.BarPlot.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
clear
gradio.BarPlot.clear(fn, ···)
This event is triggered when the user clears the component (e.g. image or audio) using the X button for the component. This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
No guides yet, contribute a guide about BarPlot
Button
gradio.Button(···)
Used to create a button, that can be assigned arbitrary click() events. The label (value) of the button can be used as an input or set via the output of a function.
As input: passes the button value as a str into the function
As output: expects a str to be returned from a function, which is set as the label of the button
import gradio as gr
import os
def combine(a, b):
return a + " " + b
def mirror(x):
return x
with gr.Blocks() as demo:
txt = gr.Textbox(label="Input", lines=2)
txt_2 = gr.Textbox(label="Input 2")
txt_3 = gr.Textbox(value="", label="Output")
btn = gr.Button(value="Submit")
btn.click(combine, inputs=[txt, txt_2], outputs=[txt_3])
with gr.Row():
im = gr.Image()
im_2 = gr.Image()
btn = gr.Button(value="Mirror Image")
btn.click(mirror, inputs=[im], outputs=[im_2])
gr.Markdown("## Text Examples")
gr.Examples(
[["hi", "Adam"], ["hello", "Eve"]],
[txt, txt_2],
txt_3,
combine,
cache_examples=True,
)
gr.Markdown("## Image Examples")
gr.Examples(
examples=[os.path.join(os.path.dirname(__file__), "lion.jpg")],
inputs=im,
outputs=im_2,
fn=mirror,
cache_examples=True,
)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
str | Callable default: "Run" |
Default text for the button to display. If callable, the function will be called whenever the app loads to set the initial value of the component. |
variant
str default: "secondary" |
'primary' for main call-to-action, 'secondary' for a more subdued style, 'stop' for a stop button. |
visible
bool default: True |
If False, component will be hidden. |
interactive
bool default: True |
If False, the Button will be in a disabled state. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"button" |
Uses default values |
Methods
style
gradio.Button.style(···)
This method can be used to change the appearance of the button component.
Parameter | Description |
---|---|
full_width
bool | None default: None |
If True, will expand to fill parent container. |
size
Literal['sm'] | Literal['lg'] | None default: None |
Size of the button. Can be "sm" or "lg". |
click
gradio.Button.click(fn, ···)
This event is triggered when the component (e.g. a button) is clicked. This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
No guides yet, contribute a guide about Button
Chatbot
gradio.Chatbot(···)
Displays a chatbot output showing both user submitted messages and responses. Supports a subset of Markdown including bold, italics, code, and images.
As input: this component does *not* accept input.
As output: expects function to return a List[List[str | None | Tuple]], a list of lists. The inner list should have 2 elements: the user message and the response message. Messages should be strings, tuples, or Nones. If the message is a string, it can include Markdown. If it is a tuple, it should consist of (string filepath to image/video/audio, [optional string alt text]). Messages that are `None` are not displayed.
import gradio as gr
import random
import time
with gr.Blocks() as demo:
chatbot = gr.Chatbot()
msg = gr.Textbox()
clear = gr.Button("Clear")
def respond(message, chat_history):
bot_message = random.choice(["How are you?", "I love you", "I'm very hungry"])
chat_history.append((message, bot_message))
time.sleep(1)
return "", chat_history
msg.submit(respond, [msg, chatbot], [msg, chatbot])
clear.click(lambda: None, None, chatbot, queue=False)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
list[list[str | tuple[str] | tuple[str, str] | None]] | Callable | None default: None |
Default value to show in chatbot. If callable, the function will be called whenever the app loads to set the initial value of the component. |
color_map
dict[str, str] | None default: None |
|
label
str | None default: None |
component name in interface. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"chatbot" |
Uses default values |
Methods
style
gradio.Chatbot.style(···)
This method can be used to change the appearance of the Chatbot component.
Parameter | Description |
---|---|
height
int | None default: None |
change
gradio.Chatbot.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
select
gradio.Chatbot.select(fn, ···)
Event listener for when the user selects message from Chatbot. Uses event data gradio.SelectData to carry `value` referring to text of selected message, and `index` tuple to refer to [message, participant] index. See EventData documentation on how to use this event data.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
Checkbox
gradio.Checkbox(···)
Creates a checkbox that can be set to `True` or `False`.
As input: passes the status of the checkbox as a bool into the function.
As output: expects a bool returned from the function and, if it is True, checks the checkbox.
Format expected for examples: a bool representing whether the box is checked.
import gradio as gr
def sentence_builder(quantity, animal, countries, place, activity_list, morning):
return f"""The {quantity} {animal}s from {" and ".join(countries)} went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""
demo = gr.Interface(
sentence_builder,
[
gr.Slider(2, 20, value=4, label="Count", info="Choose betwen 2 and 20"),
gr.Dropdown(
["cat", "dog", "bird"], label="Animal", info="Will add more animals later!"
),
gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="Countries", info="Where are they from?"),
gr.Radio(["park", "zoo", "road"], label="Location", info="Where did they go?"),
gr.Dropdown(
["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True, label="Activity", info="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl."
),
gr.Checkbox(label="Morning", info="Did they do it in the morning?"),
],
"text",
examples=[
[2, "cat", ["Japan", "Pakistan"], "park", ["ate", "swam"], True],
[4, "dog", ["Japan"], "zoo", ["ate", "swam"], False],
[10, "bird", ["USA", "Pakistan"], "road", ["ran"], False],
[8, "cat", ["Pakistan"], "zoo", ["ate"], True],
]
)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
bool | Callable default: False |
if True, checked by default. If callable, the function will be called whenever the app loads to set the initial value of the component. |
label
str | None default: None |
component name in interface. |
info
str | None default: None |
additional component description. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
interactive
bool | None default: None |
if True, this checkbox can be checked; if False, checking will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"checkbox" |
Uses default values |
Methods
style
gradio.Checkbox.style(···)
This method can be used to change the appearance of the component.
Parameter | Description |
---|---|
container
bool | None default: None |
If True, will place the component in a container - providing some extra padding around the border. |
change
gradio.Checkbox.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
select
gradio.Checkbox.select(fn, ···)
Event listener for when the user selects or deselects Checkbox. Uses event data gradio.SelectData to carry `value` referring to label of checkbox, and `selected` to refer to state of checkbox. See EventData documentation on how to use this event data.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
No guides yet, contribute a guide about Checkbox
CheckboxGroup
gradio.CheckboxGroup(···)
Creates a set of checkboxes of which a subset can be checked.
As input: passes the list of checked checkboxes as a List[str] or their indices as a List[int] into the function, depending on `type`.
As output: expects a List[str], each element of which becomes a checked checkbox.
Format expected for examples: a List[str] representing the values to be checked.
import gradio as gr
def sentence_builder(quantity, animal, countries, place, activity_list, morning):
return f"""The {quantity} {animal}s from {" and ".join(countries)} went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""
demo = gr.Interface(
sentence_builder,
[
gr.Slider(2, 20, value=4, label="Count", info="Choose betwen 2 and 20"),
gr.Dropdown(
["cat", "dog", "bird"], label="Animal", info="Will add more animals later!"
),
gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="Countries", info="Where are they from?"),
gr.Radio(["park", "zoo", "road"], label="Location", info="Where did they go?"),
gr.Dropdown(
["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True, label="Activity", info="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl."
),
gr.Checkbox(label="Morning", info="Did they do it in the morning?"),
],
"text",
examples=[
[2, "cat", ["Japan", "Pakistan"], "park", ["ate", "swam"], True],
[4, "dog", ["Japan"], "zoo", ["ate", "swam"], False],
[10, "bird", ["USA", "Pakistan"], "road", ["ran"], False],
[8, "cat", ["Pakistan"], "zoo", ["ate"], True],
]
)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
choices
list[str] | None default: None |
list of options to select from. |
value
list[str] | str | Callable | None default: None |
default selected list of options. If callable, the function will be called whenever the app loads to set the initial value of the component. |
type
str default: "value" |
Type of value to be returned by component. "value" returns the list of strings of the choices selected, "index" returns the list of indicies of the choices selected. |
label
str | None default: None |
component name in interface. |
info
str | None default: None |
additional component description. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
interactive
bool | None default: None |
if True, choices in this checkbox group will be checkable; if False, checking will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"checkboxgroup" |
Uses default values |
Methods
style
gradio.CheckboxGroup.style(···)
This method can be used to change the appearance of the CheckboxGroup.
Parameter | Description |
---|---|
item_container
bool | None default: None |
If True, will place the items in a container. |
container
bool | None default: None |
If True, will place the component in a container - providing some extra padding around the border. |
change
gradio.CheckboxGroup.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
select
gradio.CheckboxGroup.select(fn, ···)
Event listener for when the user selects or deselects within CheckboxGroup. Uses event data gradio.SelectData to carry `value` referring to label of selected checkbox, `index` to refer to index, and `selected` to refer to state of checkbox. See EventData documentation on how to use this event data.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
No guides yet, contribute a guide about CheckboxGroup
Code
gradio.Code(···)
Creates a Code editor for entering, editing or viewing code.
As input: passes a str of code into the function.
As output: expects the function to return a str of code or a single-elment tuple: (string filepath,)
Parameter | Description |
---|---|
value
str | tuple[str] | None default: None |
Default value to show in the code editor. If callable, the function will be called whenever the app loads to set the initial value of the component. |
language
str | None default: None |
The language to display the code as. Supported languages listed in `gr.Code.languages`. |
lines
int default: 5 |
|
label
str | None default: None |
component name in interface. |
interactive
bool | None default: None |
Whether user should be able to enter code or only view it. |
show_label
bool default: True |
if True, will display label. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"code" |
Uses default values |
Methods
languages
gr.Code.languages
['python', 'markdown', 'json', 'html', 'css', 'javascript', 'typescript', 'yaml', 'dockerfile', 'shell', 'r', None]
change
gradio.Code.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
No guides yet, contribute a guide about Code
ColorPicker
gradio.ColorPicker(···)
Creates a color picker for user to select a color as string input.
As input: passes selected color value as a str into the function.
As output: expects a str returned from function and sets color picker value to it.
Format expected for examples: a str with a hexadecimal representation of a color, e.g. "#ff0000" for red.
import gradio as gr
import numpy as np
import os
from PIL import Image, ImageColor
def change_color(icon, color):
"""
Function that given an icon in .png format changes its color
Args:
icon: Icon whose color needs to be changed.
color: Chosen color with which to edit the input icon.
Returns:
edited_image: Edited icon.
"""
img = icon.convert("LA")
img = img.convert("RGBA")
image_np = np.array(icon)
_, _, _, alpha = image_np.T
mask = alpha > 0
image_np[..., :-1][mask.T] = ImageColor.getcolor(color, "RGB")
edited_image = Image.fromarray(image_np)
return edited_image
inputs = [
gr.Image(label="icon", type="pil", image_mode="RGBA"),
gr.ColorPicker(label="color"),
]
outputs = gr.Image(label="colored icon")
demo = gr.Interface(
fn=change_color,
inputs=inputs,
outputs=outputs,
examples=[
[os.path.join(os.path.dirname(__file__), "rabbit.png"), "#ff0000"],
[os.path.join(os.path.dirname(__file__), "rabbit.png"), "#0000FF"],
],
)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
str | Callable | None default: None |
default text to provide in color picker. If callable, the function will be called whenever the app loads to set the initial value of the component. |
label
str | None default: None |
component name in interface. |
info
str | None default: None |
additional component description. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
interactive
bool | None default: None |
if True, will be rendered as an editable color picker; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"colorpicker" |
Uses default values |
Methods
style
gradio.ColorPicker.style(···)
This method can be used to change the appearance of the component.
Parameter | Description |
---|---|
container
bool | None default: None |
If True, will place the component in a container - providing some extra padding around the border. |
change
gradio.ColorPicker.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
submit
gradio.ColorPicker.submit(fn, ···)
This event is triggered when the user presses the Enter key while the component (e.g. a textbox) is focused. This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
blur
gradio.ColorPicker.blur(fn, ···)
This event is triggered when the component's is unfocused/blurred (e.g. when the user clicks outside of a textbox). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
No guides yet, contribute a guide about ColorPicker
Dataframe
gradio.Dataframe(···)
Accepts or displays 2D input through a spreadsheet-like component for dataframes.
As input: passes the uploaded spreadsheet data as a pandas.DataFrame, numpy.array, List[List], or List depending on `type`
As output: expects a pandas.DataFrame, numpy.array, List[List], List, a Dict with keys `data` (and optionally `headers`), or str path to a csv, which is rendered in the spreadsheet.
Format expected for examples: a str filepath to a csv with data, a pandas dataframe, or a list of lists (excluding headers) where each sublist is a row of data.
import gradio as gr
def filter_records(records, gender):
return records[records["gender"] == gender]
demo = gr.Interface(
filter_records,
[
gr.Dataframe(
headers=["name", "age", "gender"],
datatype=["str", "number", "str"],
row_count=5,
col_count=(3, "fixed"),
),
gr.Dropdown(["M", "F", "O"]),
],
"dataframe",
description="Enter gender as 'M', 'F', or 'O' for other.",
)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
list[list[Any]] | Callable | None default: None |
Default value as a 2-dimensional list of values. If callable, the function will be called whenever the app loads to set the initial value of the component. |
headers
list[str] | None default: None |
List of str header names. If None, no headers are shown. |
row_count
int | tuple[int, str] default: (1, 'dynamic') |
Limit number of rows for input and decide whether user can create new rows. The first element of the tuple is an `int`, the row count; the second should be 'fixed' or 'dynamic', the new row behaviour. If an `int` is passed the rows default to 'dynamic' |
col_count
int | tuple[int, str] | None default: None |
Limit number of columns for input and decide whether user can create new columns. The first element of the tuple is an `int`, the number of columns; the second should be 'fixed' or 'dynamic', the new column behaviour. If an `int` is passed the columns default to 'dynamic' |
datatype
str | list[str] default: "str" |
Datatype of values in sheet. Can be provided per column as a list of strings, or for the entire sheet as a single string. Valid datatypes are "str", "number", "bool", "date", and "markdown". |
type
str default: "pandas" |
Type of value to be returned by component. "pandas" for pandas dataframe, "numpy" for numpy array, or "array" for a Python array. |
max_rows
int | None default: 20 |
Maximum number of rows to display at once. Set to None for infinite. |
max_cols
int | None default: None |
Maximum number of columns to display at once. Set to None for infinite. |
overflow_row_behaviour
str default: "paginate" |
If set to "paginate", will create pages for overflow rows. If set to "show_ends", will show initial and final rows and truncate middle rows. |
label
str | None default: None |
component name in interface. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
interactive
bool | None default: None |
if True, will allow users to edit the dataframe; if False, can only be used to display data. If not provided, this is inferred based on whether the component is used as an input or output. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
wrap
bool default: False |
if True text in table cells will wrap when appropriate, if False the table will scroll horiztonally. Defaults to False. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"dataframe" |
Uses default values |
|
"numpy" |
Uses type="numpy" |
|
"matrix" |
Uses type="array" |
|
"list" |
Uses type="array", col_count=1 |
Methods
style
gradio.Dataframe.style(···)
This method can be used to change the appearance of the DataFrame component.
change
gradio.Dataframe.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
select
gradio.Dataframe.select(fn, ···)
Event listener for when the user selects cell within Dataframe. Uses event data gradio.SelectData to carry `value` referring to value of selected cell, and `index` tuple to refer to index row and column. See EventData documentation on how to use this event data.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
No guides yet, contribute a guide about Dataframe
Dataset
gr.Dataset(components, samples)
Used to create an output widget for showing datasets. Used to render the examples box.
As input: passes the selected sample either as a list of data (if type="value") or as an int index (if type="index")
As output: expects a list of lists corresponding to the dataset data.
Parameter | Description |
---|---|
label
str | None default: None |
|
components
list[IOComponent] | list[str] required |
Which component types to show in this dataset widget, can be passed in as a list of string names or Components instances. The following components are supported in a Dataset: Audio, Checkbox, CheckboxGroup, ColorPicker, Dataframe, Dropdown, File, HTML, Image, Markdown, Model3D, Number, Radio, Slider, Textbox, TimeSeries, Video |
samples
list[list[Any]] | None default: None |
a nested list of samples. Each sublist within the outer list represents a data sample, and each element within the sublist represents an value for each component |
headers
list[str] | None default: None |
Column headers in the Dataset widget, should be the same len as components. If not provided, inferred from component labels |
type
str default: "values" |
'values' if clicking on a sample should pass the value of the sample, or "index" if it should pass the index of the sample |
samples_per_page
int default: 10 |
how many examples to show per page. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"dataset" |
Uses default values |
Methods
style
gradio.Dataset.style(···)
This method can be used to change the appearance of the Dataset component.
click
gradio.Dataset.click(fn, ···)
This event is triggered when the component (e.g. a button) is clicked. This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
select
gradio.Dataset.select(fn, ···)
This event is triggered when the user selects from within the Component. This event has EventData of type gradio.SelectData that carries information, accessible through SelectData.index and SelectData.value. See EventData documentation on how to use this event data.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
No guides yet, contribute a guide about Dataset
Dropdown
gradio.Dropdown(···)
Creates a dropdown of choices from which entries can be selected.
As input: passes the value of the selected dropdown entry as a str or its index as an int into the function, depending on `type`.
As output: expects a str corresponding to the value of the dropdown entry to be selected.
Format expected for examples: a str representing the drop down value to select.
import gradio as gr
def sentence_builder(quantity, animal, countries, place, activity_list, morning):
return f"""The {quantity} {animal}s from {" and ".join(countries)} went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""
demo = gr.Interface(
sentence_builder,
[
gr.Slider(2, 20, value=4, label="Count", info="Choose betwen 2 and 20"),
gr.Dropdown(
["cat", "dog", "bird"], label="Animal", info="Will add more animals later!"
),
gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="Countries", info="Where are they from?"),
gr.Radio(["park", "zoo", "road"], label="Location", info="Where did they go?"),
gr.Dropdown(
["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True, label="Activity", info="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl."
),
gr.Checkbox(label="Morning", info="Did they do it in the morning?"),
],
"text",
examples=[
[2, "cat", ["Japan", "Pakistan"], "park", ["ate", "swam"], True],
[4, "dog", ["Japan"], "zoo", ["ate", "swam"], False],
[10, "bird", ["USA", "Pakistan"], "road", ["ran"], False],
[8, "cat", ["Pakistan"], "zoo", ["ate"], True],
]
)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
choices
list[str] | None default: None |
list of options to select from. |
value
str | list[str] | Callable | None default: None |
default value(s) selected in dropdown. If None, no value is selected by default. If callable, the function will be called whenever the app loads to set the initial value of the component. |
type
str default: "value" |
Type of value to be returned by component. "value" returns the string of the choice selected, "index" returns the index of the choice selected. |
multiselect
bool | None default: None |
if True, multiple choices can be selected. |
max_choices
int | None default: None |
maximum number of choices that can be selected. If None, no limit is enforced. |
label
str | None default: None |
component name in interface. |
info
str | None default: None |
additional component description. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
interactive
bool | None default: None |
if True, choices in this dropdown will be selectable; if False, selection will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
allow_custom_value
bool default: False |
If True, allows user to enter a custom value that is not in the list of choices. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"dropdown" |
Uses default values |
Methods
style
gradio.Dropdown.style(···)
This method can be used to change the appearance of the Dropdown.
Parameter | Description |
---|---|
container
bool | None default: None |
If True, will place the component in a container - providing some extra padding around the border. |
change
gradio.Dropdown.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
blur
gradio.Dropdown.blur(fn, ···)
This event is triggered when the component's is unfocused/blurred (e.g. when the user clicks outside of a textbox). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
select
gradio.Dropdown.select(fn, ···)
Event listener for when the user selects Dropdown option. Uses event data gradio.SelectData to carry `value` referring to label of selected option, and `index` to refer to index. See EventData documentation on how to use this event data.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
No guides yet, contribute a guide about Dropdown
File
gradio.File(···)
Creates a file component that allows uploading generic file (when used as an input) and or displaying generic files (output).
As input: passes the uploaded file as a tempfile._TemporaryFileWrapper or List[tempfile._TemporaryFileWrapper] depending on `file_count` (or a bytes/Listbytes depending on `type`)
As output: expects function to return a str path to a file, or List[str] consisting of paths to files.
Format expected for examples: a str path to a local file that populates the component.
from zipfile import ZipFile
import gradio as gr
def zip_to_json(file_obj):
files = []
with ZipFile(file_obj.name) as zfile:
for zinfo in zfile.infolist():
files.append(
{
"name": zinfo.filename,
"file_size": zinfo.file_size,
"compressed_size": zinfo.compress_size,
}
)
return files
demo = gr.Interface(zip_to_json, "file", "json")
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
str | list[str] | Callable | None default: None |
Default file to display, given as str file path. If callable, the function will be called whenever the app loads to set the initial value of the component. |
file_count
str default: "single" |
if single, allows user to upload one file. If "multiple", user uploads multiple files. If "directory", user uploads all files in selected directory. Return type will be list for each file in case of "multiple" or "directory". |
file_types
list[str] | None default: None |
List of file extensions or types of files to be uploaded (e.g. ['image', '.json', '.mp4']). "file" allows any file to be uploaded, "image" allows only image files to be uploaded, "audio" allows only audio files to be uploaded, "video" allows only video files to be uploaded, "text" allows only text files to be uploaded. |
type
str default: "file" |
Type of value to be returned by component. "file" returns a temporary file object with the same base name as the uploaded file, whose full path can be retrieved by file_obj.name, "binary" returns an bytes object. |
label
str | None default: None |
component name in interface. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
interactive
bool | None default: None |
if True, will allow users to upload a file; if False, can only be used to display files. If not provided, this is inferred based on whether the component is used as an input or output. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"file" |
Uses default values |
|
"files" |
Uses file_count="multiple" |
Methods
style
gradio.File.style(···)
This method can be used to change the appearance of the file component.
change
gradio.File.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
clear
gradio.File.clear(fn, ···)
This event is triggered when the user clears the component (e.g. image or audio) using the X button for the component. This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
upload
gradio.File.upload(fn, ···)
This event is triggered when the user uploads a file into the component (e.g. when the user uploads a video into a video component). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
select
gradio.File.select(fn, ···)
Event listener for when the user selects file from list. Uses event data gradio.SelectData to carry `value` referring to name of selected file, and `index` to refer to index. See EventData documentation on how to use this event data.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
No guides yet, contribute a guide about File
Gallery
gradio.Gallery(···)
Used to display a list of images as a gallery that can be scrolled through.
As input: this component does *not* accept input.
As output: expects a list of images in any format, List[numpy.array | PIL.Image | str], or a List of (image, str caption) tuples and displays them.
# This demo needs to be run from the repo folder.
# python demo/fake_gan/run.py
import random
import gradio as gr
def fake_gan():
images = [
(random.choice(
[
"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80",
"https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=386&q=80",
"https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW4lMjBmYWNlfGVufDB8fDB8fA%3D%3D&w=1000&q=80",
"https://images.unsplash.com/photo-1546456073-92b9f0a8d413?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80",
"https://images.unsplash.com/photo-1601412436009-d964bd02edbc?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=464&q=80",
]
), f"label {i}" if i != 0 else "label" * 50)
for i in range(3)
]
return images
with gr.Blocks() as demo:
with gr.Column(variant="panel"):
with gr.Row(variant="compact"):
text = gr.Textbox(
label="Enter your prompt",
show_label=False,
max_lines=1,
placeholder="Enter your prompt",
).style(
container=False,
)
btn = gr.Button("Generate image").style(full_width=False)
gallery = gr.Gallery(
label="Generated images", show_label=False, elem_id="gallery"
).style(columns=[2], rows=[2], object_fit="contain", height="auto")
btn.click(fake_gan, None, gallery)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
list[np.ndarray | _Image.Image | str | tuple] | Callable | None default: None |
List of images to display in the gallery by default. If callable, the function will be called whenever the app loads to set the initial value of the component. |
label
str | None default: None |
component name in interface. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"gallery" |
Uses default values |
Methods
style
gradio.Gallery.style(···)
This method can be used to change the appearance of the gallery component.
Parameter | Description |
---|---|
grid
int | tuple | None default: None |
('grid' has been renamed to 'columns') Represents the number of images that should be shown in one row, for each of the six standard screen sizes (<576px, <768px, <992px, <1200px, <1400px, >1400px). if fewer that 6 are given then the last will be used for all subsequent breakpoints columns: Represents the number of columns in the image grid, for each of the six standard screen sizes (<576px, <768px, <992px, <1200px, <1400px, >1400px). if fewer that 6 are given then the last will be used for all subsequent breakpoints |
columns
int | tuple | None default: None |
|
rows
int | tuple | None default: None |
Represents the number of rows in the image grid, for each of the six standard screen sizes (<576px, <768px, <992px, <1200px, <1400px, >1400px). if fewer that 6 are given then the last will be used for all subsequent breakpoints |
height
str | None default: None |
Height of the gallery. |
container
bool | None default: None |
If True, will place gallery in a container - providing some extra padding around the border. |
preview
bool | None default: None |
If True, will display the Gallery in preview mode, which shows all of the images as thumbnails and allows the user to click on them to view them in full size. |
object_fit
str | None default: None |
CSS object-fit property for the thumbnail images in the gallery. Can be "contain", "cover", "fill", "none", or "scale-down". |
select
gradio.Gallery.select(fn, ···)
Event listener for when the user selects image within Gallery. Uses event data gradio.SelectData to carry `value` referring to caption of selected image, and `index` to refer to index. See EventData documentation on how to use this event data.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
No guides yet, contribute a guide about Gallery
HTML
gradio.HTML(···)
Used to display arbitrary HTML output.
As input: this component does *not* accept input.
As output: expects a valid HTML str.
import gradio as gr
import os
os.system('python -m spacy download en_core_web_sm')
import spacy
from spacy import displacy
nlp = spacy.load("en_core_web_sm")
def text_analysis(text):
doc = nlp(text)
html = displacy.render(doc, style="dep", page=True)
html = (
""
+ html
+ ""
)
pos_count = {
"char_count": len(text),
"token_count": 0,
}
pos_tokens = []
for token in doc:
pos_tokens.extend([(token.text, token.pos_), (" ", None)])
return pos_tokens, pos_count, html
demo = gr.Interface(
text_analysis,
gr.Textbox(placeholder="Enter sentence here..."),
["highlight", "json", "html"],
examples=[
["What a beautiful morning for a walk!"],
["It was the best of times, it was the worst of times."],
],
)
demo.launch()
Parameter | Description |
---|---|
value
str | Callable default: "" |
Default value. If callable, the function will be called whenever the app loads to set the initial value of the component. |
label
str | None default: None |
component name in interface. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"html" |
Uses default values |
Methods
change
gradio.HTML.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
HighlightedText
gradio.HighlightedText(···)
Displays text that contains spans that are highlighted by category or numerical value.
As input: this component does *not* accept input.
As output: expects a List[Tuple[str, float | str]]] consisting of spans of text and their associated labels, or a Dict with two keys: (1) "text" whose value is the complete text, and "entities", which is a list of dictionaries, each of which have the keys: "entity" (consisting of the entity label), "start" (the character index where the label starts), and "end" (the character index where the label ends). Entities should not overlap.
from difflib import Differ
import gradio as gr
def diff_texts(text1, text2):
d = Differ()
return [
(token[2:], token[0] if token[0] != " " else None)
for token in d.compare(text1, text2)
]
demo = gr.Interface(
diff_texts,
[
gr.Textbox(
label="Text 1",
info="Initial text",
lines=3,
value="The quick brown fox jumped over the lazy dogs.",
),
gr.Textbox(
label="Text 2",
info="Text to compare",
lines=3,
value="The fast brown fox jumps over lazy dogs.",
),
],
gr.HighlightedText(
label="Diff",
combine_adjacent=True,
show_legend=True,
).style(color_map={"+": "red", "-": "green"}),
theme=gr.themes.Base()
)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
list[tuple[str, str | float | None]] | dict | Callable | None default: None |
Default value to show. If callable, the function will be called whenever the app loads to set the initial value of the component. |
color_map
dict[str, str] | None default: None |
|
show_legend
bool default: False |
whether to show span categories in a separate legend or inline. |
combine_adjacent
bool default: False |
If True, will merge the labels of adjacent tokens belonging to the same category. |
adjacent_separator
str default: "" |
Specifies the separator to be used between tokens if combine_adjacent is True. |
label
str | None default: None |
component name in interface. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"highlightedtext" |
Uses default values |
Methods
style
gradio.HighlightedText.style(···)
This method can be used to change the appearance of the HighlightedText component.
Parameter | Description |
---|---|
color_map
dict[str, str] | None default: None |
Map between category and respective colors. |
container
bool | None default: None |
If True, will place the component in a container - providing some extra padding around the border. |
change
gradio.HighlightedText.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
select
gradio.HighlightedText.select(fn, ···)
Event listener for when the user selects Highlighted text span. Uses event data gradio.SelectData to carry `value` referring to selected [text, label] tuple, and `index` to refer to span index. See EventData documentation on how to use this event data.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
Image
gradio.Image(···)
Creates an image component that can be used to upload/draw images (as an input) or display images (as an output).
As input: passes the uploaded image as a numpy.array, PIL.Image or str filepath depending on `type` -- unless `tool` is `sketch` AND source is one of `upload` or `webcam`. In these cases, a dict with keys `image` and `mask` is passed, and the format of the corresponding values depends on `type`.
As output: expects a numpy.array, PIL.Image or str or pathlib.Path filepath to an image and displays the image.
Format expected for examples: a str filepath to a local file that contains the image.
Supported events: check_streamable()
import gradio as gr
import os
def image_mod(image):
return image.rotate(45)
demo = gr.Interface(
image_mod,
gr.Image(type="pil"),
"image",
flagging_options=["blurry", "incorrect", "other"],
examples=[
os.path.join(os.path.dirname(__file__), "images/cheetah1.jpg"),
os.path.join(os.path.dirname(__file__), "images/lion.jpg"),
os.path.join(os.path.dirname(__file__), "images/logo.png"),
os.path.join(os.path.dirname(__file__), "images/tower.jpg"),
],
)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
str | _Image.Image | np.ndarray | None default: None |
A PIL Image, numpy array, path or URL for the default value that Image component is going to take. If callable, the function will be called whenever the app loads to set the initial value of the component. |
shape
tuple[int, int] | None default: None |
(width, height) shape to crop and resize image to; if None, matches input image size. Pass None for either width or height to only crop and resize the other. |
image_mode
str default: "RGB" |
"RGB" if color, or "L" if black and white. |
invert_colors
bool default: False |
whether to invert the image as a preprocessing step. |
source
str default: "upload" |
Source of image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "canvas" defaults to a white image that can be edited and drawn upon with tools. |
tool
str | None default: None |
Tools used for editing. "editor" allows a full screen editor (and is the default if source is "upload" or "webcam"), "select" provides a cropping and zoom tool, "sketch" allows you to create a binary sketch (and is the default if source="canvas"), and "color-sketch" allows you to created a sketch in different colors. "color-sketch" can be used with source="upload" or "webcam" to allow sketching on an image. "sketch" can also be used with "upload" or "webcam" to create a mask over an image and in that case both the image and mask are passed into the function as a dictionary with keys "image" and "mask" respectively. |
type
str default: "numpy" |
The format the image is converted to before being passed into the prediction function. "numpy" converts the image to a numpy array with shape (width, height, 3) and values from 0 to 255, "pil" converts the image to a PIL image object, "filepath" passes a str path to a temporary file containing the image. |
label
str | None default: None |
component name in interface. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
interactive
bool | None default: None |
if True, will allow users to upload and edit an image; if False, can only be used to display images. If not provided, this is inferred based on whether the component is used as an input or output. |
visible
bool default: True |
If False, component will be hidden. |
streaming
bool default: False |
If True when used in a `live` interface, will automatically stream webcam feed. Only valid is source is 'webcam'. |
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. |
mirror_webcam
bool default: True |
If True webcam will be mirrored. Default is True. |
brush_radius
float | None default: None |
Size of the brush for Sketch. Default is None which chooses a sensible default |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"image" |
Uses default values |
|
"webcam" |
Uses source="webcam", interactive=True |
|
"sketchpad" |
Uses image_mode="L", source="canvas", shape=(28, 28), invert_colors=True, interactive=True |
|
"paint" |
Uses source="canvas", tool="color-sketch", interactive=True |
|
"imagemask" |
Uses source="upload", tool="sketch", interactive=True |
|
"imagepaint" |
Uses source="upload", tool="color-sketch", interactive=True |
|
"pil" |
Uses type="pil" |
Methods
style
gradio.Image.style(···)
This method can be used to change the appearance of the Image component.
Parameter | Description |
---|---|
height
int | None default: None |
Height of the image. |
width
int | None default: None |
Width of the image. |
change
gradio.Image.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
edit
gradio.Image.edit(fn, ···)
This event is triggered when the user edits the component (e.g. image) using the built-in editor. This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
clear
gradio.Image.clear(fn, ···)
This event is triggered when the user clears the component (e.g. image or audio) using the X button for the component. This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
stream
gradio.Image.stream(fn, ···)
This event is triggered when the user streams the component (e.g. a live webcam component). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
upload
gradio.Image.upload(fn, ···)
This event is triggered when the user uploads a file into the component (e.g. when the user uploads a video into a video component). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
select
gradio.Image.select(fn, ···)
Event listener for when the user clicks on a pixel within the image. Uses event data gradio.SelectData to carry `index` to refer to the [x, y] coordinates of the clicked pixel. See EventData documentation on how to use this event data.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
Interpretation
gradio.Interpretation(component, ···)
Used to create an interpretation widget for a component.
As input: this component does *not* accept input.
As output: expects a dict with keys "original" and "interpretation".
Parameter | Description |
---|---|
component
Component required |
Which component to show in the interpretation widget. |
visible
bool default: True |
Whether or not the interpretation is 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. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"interpretation" |
Uses default values |
Step-by-step Guides
JSON
gradio.JSON(···)
Used to display arbitrary JSON output prettily.
As input: this component does *not* accept input.
As output: expects a str filepath to a file containing valid JSON -- or a list or dict that is valid JSON
from zipfile import ZipFile
import gradio as gr
def zip_to_json(file_obj):
files = []
with ZipFile(file_obj.name) as zfile:
for zinfo in zfile.infolist():
files.append(
{
"name": zinfo.filename,
"file_size": zinfo.file_size,
"compressed_size": zinfo.compress_size,
}
)
return files
demo = gr.Interface(zip_to_json, "file", "json")
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
str | dict | list | Callable | None default: None |
Default value. If callable, the function will be called whenever the app loads to set the initial value of the component. |
label
str | None default: None |
component name in interface. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"json" |
Uses default values |
Methods
style
gradio.JSON.style(···)
This method can be used to change the appearance of the JSON component.
Parameter | Description |
---|---|
container
bool | None default: None |
If True, will place the JSON in a container - providing some extra padding around the border. |
change
gradio.JSON.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
No guides yet, contribute a guide about JSON
Label
gradio.Label(···)
Displays a classification label, along with confidence scores of top categories, if provided.
As input: this component does *not* accept input.
As output: 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 the structure produced by Label.postprocess().
from math import log2, pow
import os
import numpy as np
from scipy.fftpack import fft
import gradio as gr
A4 = 440
C0 = A4 * pow(2, -4.75)
name = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
def get_pitch(freq):
h = round(12 * log2(freq / C0))
n = h % 12
return name[n]
def main_note(audio):
rate, y = audio
if len(y.shape) == 2:
y = y.T[0]
N = len(y)
T = 1.0 / rate
yf = fft(y)
yf2 = 2.0 / N * np.abs(yf[0 : N // 2])
xf = np.linspace(0.0, 1.0 / (2.0 * T), N // 2)
volume_per_pitch = {}
total_volume = np.sum(yf2)
for freq, volume in zip(xf, yf2):
if freq == 0:
continue
pitch = get_pitch(freq)
if pitch not in volume_per_pitch:
volume_per_pitch[pitch] = 0
volume_per_pitch[pitch] += 1.0 * volume / total_volume
volume_per_pitch = {k: float(v) for k, v in volume_per_pitch.items()}
return volume_per_pitch
demo = gr.Interface(
main_note,
gr.Audio(source="microphone"),
gr.Label(num_top_classes=4),
examples=[
[os.path.join(os.path.dirname(__file__),"audio/recording1.wav")],
[os.path.join(os.path.dirname(__file__),"audio/cantina.wav")],
],
interpretation="default",
)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
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 callable, the function will be called whenever the app loads to set the initial value of the component. |
num_top_classes
int | None default: None |
number of most confident classes to show. |
label
str | None default: None |
component name in interface. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
color
str | None default: None |
The background color of the label (either a valid css color name or hexadecimal string). |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"label" |
Uses default values |
Methods
style
gradio.Label.style(···)
This method can be used to change the appearance of the label component.
Parameter | Description |
---|---|
container
bool | None default: None |
If True, will add a container to the label - providing some extra padding around the border. |
change
gradio.Label.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
select
gradio.Label.select(fn, ···)
Event listener for when the user selects a category from Label. Uses event data gradio.SelectData to carry `value` referring to name of selected category, and `index` to refer to index. See EventData documentation on how to use this event data.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
LinePlot
gradio.LinePlot(···)
Create a line plot.
As input: this component does *not* accept input.
As output: expects a pandas dataframe with the data to plot.
import gradio as gr
from scatter_plot_demo import scatter_plot
from line_plot_demo import line_plot
from bar_plot_demo import bar_plot
with gr.Blocks() as demo:
with gr.Tabs():
with gr.TabItem("Scatter Plot"):
scatter_plot.render()
with gr.TabItem("Line Plot"):
line_plot.render()
with gr.TabItem("Bar Plot"):
bar_plot.render()
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
pd.DataFrame | Callable | None default: None |
The pandas dataframe containing the data to display in a scatter plot. |
x
str | None default: None |
Column corresponding to the x axis. |
y
str | None default: None |
Column corresponding to the y axis. |
color
str | None default: None |
The column to determine the point color. If the column contains numeric data, gradio will interpolate the column data so that small values correspond to light colors and large values correspond to dark values. |
stroke_dash
str | None default: None |
The column to determine the symbol used to draw the line, e.g. dashed lines, dashed lines with points. |
overlay_point
bool | None default: None |
Whether to draw a point on the line for each (x, y) coordinate pair. |
title
str | None default: None |
The title to display on top of the chart. |
tooltip
list[str] | str | None default: None |
The column (or list of columns) to display on the tooltip when a user hovers a point on the plot. |
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_legend_title
str | None default: None |
The title given to the color legend. By default, uses the value of color parameter. |
stroke_dash_legend_title
str | None default: None |
The title given to the stroke_dash legend. By default, uses the value of the stroke_dash parameter. |
color_legend_position
str | None default: None |
The position of the color legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation. |
stroke_dash_legend_position
str | None default: None |
The position of the stoke_dash legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation. |
height
int | None default: None |
The height of the plot in pixels. |
width
int | None default: None |
The width of the plot in pixels. |
x_lim
list[int] | None default: None |
A tuple or list containing the limits for the x-axis, specified as [x_min, x_max]. |
y_lim
list[int] | None default: None |
A tuple of list containing the limits for the y-axis, specified as [y_min, y_max]. |
caption
str | None default: None |
The (optional) caption to display below the plot. |
interactive
bool | None default: True |
Whether users should be able to interact with the plot by panning or zooming with their mouse or trackpad. |
label
str | None default: None |
The (optional) label to display on the top left corner of the plot. |
show_label
bool default: True |
Whether the label should be displayed. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
visible
bool default: True |
Whether the plot should be visible. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"lineplot" |
Uses default values |
Methods
change
gradio.LinePlot.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
clear
gradio.LinePlot.clear(fn, ···)
This event is triggered when the user clears the component (e.g. image or audio) using the X button for the component. This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
No guides yet, contribute a guide about LinePlot
Markdown
gradio.Markdown(···)
Used to render arbitrary Markdown output. Can also render latex enclosed by dollar signs.
As input: this component does *not* accept input.
As output: expects a valid str that can be rendered as Markdown.
import gradio as gr
def welcome(name):
return f"Welcome to Gradio, {name}!"
with gr.Blocks() as demo:
gr.Markdown(
"""
# Hello World!
Start typing below to see the output.
""")
inp = gr.Textbox(placeholder="What is your name?")
out = gr.Textbox()
inp.change(welcome, inp, out)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
str | Callable default: "" |
Value to show in Markdown component. If callable, the function will be called whenever the app loads to set the initial value of the component. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"markdown" |
Uses default values |
Methods
change
gradio.Markdown.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
Model3D
gradio.Model3D(···)
Component allows users to upload or view 3D Model files (.obj, .glb, or .gltf).
As input: This component passes the uploaded file as a str filepath.
As output: expects function to return a str path to a file of type (.obj, glb, or .gltf)
import gradio as gr
import os
def load_mesh(mesh_file_name):
return mesh_file_name
demo = gr.Interface(
fn=load_mesh,
inputs=gr.Model3D(),
outputs=gr.Model3D(
clear_color=[0.0, 0.0, 0.0, 0.0], label="3D Model"),
examples=[
[os.path.join(os.path.dirname(__file__), "files/Bunny.obj")],
[os.path.join(os.path.dirname(__file__), "files/Duck.glb")],
[os.path.join(os.path.dirname(__file__), "files/Fox.gltf")],
[os.path.join(os.path.dirname(__file__), "files/face.obj")],
],
)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
str | Callable | None default: None |
path to (.obj, glb, or .gltf) file to show in model3D viewer. If callable, the function will be called whenever the app loads to set the initial value of the component. |
clear_color
list[float] | None default: None |
background color of scene |
label
str | None default: None |
component name in interface. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"model3d" |
Uses default values |
Methods
style
gradio.Model3D.style(···)
This method can be used to change the appearance of the Model3D component.
change
gradio.Model3D.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
edit
gradio.Model3D.edit(fn, ···)
This event is triggered when the user edits the component (e.g. image) using the built-in editor. This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
clear
gradio.Model3D.clear(fn, ···)
This event is triggered when the user clears the component (e.g. image or audio) using the X button for the component. This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
Number
gradio.Number(···)
Creates a numeric field for user to enter numbers as input or display numeric output.
As input: passes field value as a float or int into the function, depending on `precision`.
As output: expects an int or float returned from the function and sets field value to it.
Format expected for examples: a float or int representing the number's value.
import gradio as gr
def tax_calculator(income, marital_status, assets):
tax_brackets = [(10, 0), (25, 8), (60, 12), (120, 20), (250, 30)]
total_deductible = sum(assets["Cost"])
taxable_income = income - total_deductible
total_tax = 0
for bracket, rate in tax_brackets:
if taxable_income > bracket:
total_tax += (taxable_income - bracket) * rate / 100
if marital_status == "Married":
total_tax *= 0.75
elif marital_status == "Divorced":
total_tax *= 0.8
return round(total_tax)
demo = gr.Interface(
tax_calculator,
[
"number",
gr.Radio(["Single", "Married", "Divorced"]),
gr.Dataframe(
headers=["Item", "Cost"],
datatype=["str", "number"],
label="Assets Purchased this Year",
),
],
"number",
examples=[
[10000, "Married", [["Suit", 5000], ["Laptop", 800], ["Car", 1800]]],
[80000, "Single", [["Suit", 800], ["Watch", 1800], ["Car", 800]]],
],
)
demo.launch()
Parameter | Description |
---|---|
value
float | Callable | None default: None |
default value. If callable, the function will be called whenever the app loads to set the initial value of the component. |
label
str | None default: None |
component name in interface. |
info
str | None default: None |
additional component description. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
interactive
bool | None default: None |
if True, will be editable; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
precision
int | None default: None |
Precision to round input/output to. If set to 0, will round to nearest integer and convert type to int. If None, no rounding happens. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"number" |
Uses default values |
Methods
style
gradio.Number.style(···)
This method can be used to change the appearance of the component.
Parameter | Description |
---|---|
container
bool | None default: None |
If True, will place the component in a container - providing some extra padding around the border. |
change
gradio.Number.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
submit
gradio.Number.submit(fn, ···)
This event is triggered when the user presses the Enter key while the component (e.g. a textbox) is focused. This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
blur
gradio.Number.blur(fn, ···)
This event is triggered when the component's is unfocused/blurred (e.g. when the user clicks outside of a textbox). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
No guides yet, contribute a guide about Number
Plot
gradio.Plot(···)
Used to display various kinds of plots (matplotlib, plotly, or bokeh are supported)
As input: this component does *not* accept input.
As output: expects either a matplotlib.figure.Figure, a plotly.graph_objects._figure.Figure, or a dict corresponding to a bokeh plot (json_item format)
import altair as alt
import gradio as gr
import numpy as np
import pandas as pd
from vega_datasets import data
def make_plot(plot_type):
if plot_type == "scatter_plot":
cars = data.cars()
return alt.Chart(cars).mark_point().encode(
x='Horsepower',
y='Miles_per_Gallon',
color='Origin',
)
elif plot_type == "heatmap":
# Compute x^2 + y^2 across a 2D grid
x, y = np.meshgrid(range(-5, 5), range(-5, 5))
z = x ** 2 + y ** 2
# Convert this grid to columnar data expected by Altair
source = pd.DataFrame({'x': x.ravel(),
'y': y.ravel(),
'z': z.ravel()})
return alt.Chart(source).mark_rect().encode(
x='x:O',
y='y:O',
color='z:Q'
)
elif plot_type == "us_map":
states = alt.topo_feature(data.us_10m.url, 'states')
source = data.income.url
return alt.Chart(source).mark_geoshape().encode(
shape='geo:G',
color='pct:Q',
tooltip=['name:N', 'pct:Q'],
facet=alt.Facet('group:N', columns=2),
).transform_lookup(
lookup='id',
from_=alt.LookupData(data=states, key='id'),
as_='geo'
).properties(
width=300,
height=175,
).project(
type='albersUsa'
)
elif plot_type == "interactive_barplot":
source = data.movies.url
pts = alt.selection(type="single", encodings=['x'])
rect = alt.Chart(data.movies.url).mark_rect().encode(
alt.X('IMDB_Rating:Q', bin=True),
alt.Y('Rotten_Tomatoes_Rating:Q', bin=True),
alt.Color('count()',
scale=alt.Scale(scheme='greenblue'),
legend=alt.Legend(title='Total Records')
)
)
circ = rect.mark_point().encode(
alt.ColorValue('grey'),
alt.Size('count()',
legend=alt.Legend(title='Records in Selection')
)
).transform_filter(
pts
)
bar = alt.Chart(source).mark_bar().encode(
x='Major_Genre:N',
y='count()',
color=alt.condition(pts, alt.ColorValue("steelblue"), alt.ColorValue("grey"))
).properties(
width=550,
height=200
).add_selection(pts)
plot = alt.vconcat(
rect + circ,
bar
).resolve_legend(
color="independent",
size="independent"
)
return plot
elif plot_type == "radial":
source = pd.DataFrame({"values": [12, 23, 47, 6, 52, 19]})
base = alt.Chart(source).encode(
theta=alt.Theta("values:Q", stack=True),
radius=alt.Radius("values", scale=alt.Scale(type="sqrt", zero=True, rangeMin=20)),
color="values:N",
)
c1 = base.mark_arc(innerRadius=20, stroke="#fff")
c2 = base.mark_text(radiusOffset=10).encode(text="values:Q")
return c1 + c2
elif plot_type == "multiline":
source = data.stocks()
highlight = alt.selection(type='single', on='mouseover',
fields=['symbol'], nearest=True)
base = alt.Chart(source).encode(
x='date:T',
y='price:Q',
color='symbol:N'
)
points = base.mark_circle().encode(
opacity=alt.value(0)
).add_selection(
highlight
).properties(
width=600
)
lines = base.mark_line().encode(
size=alt.condition(~highlight, alt.value(1), alt.value(3))
)
return points + lines
with gr.Blocks() as demo:
button = gr.Radio(label="Plot type",
choices=['scatter_plot', 'heatmap', 'us_map',
'interactive_barplot', "radial", "multiline"], value='scatter_plot')
plot = gr.Plot(label="Plot")
button.change(make_plot, inputs=button, outputs=[plot])
demo.load(make_plot, inputs=[button], outputs=[plot])
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
Callable | None | pd.DataFrame default: None |
Optionally, supply a default plot object to display, must be a matplotlib, plotly, altair, or bokeh figure, or a callable. If callable, the function will be called whenever the app loads to set the initial value of the component. |
label
str | None default: None |
component name in interface. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"plot" |
Uses default values |
Methods
change
gradio.Plot.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
clear
gradio.Plot.clear(fn, ···)
This event is triggered when the user clears the component (e.g. image or audio) using the X button for the component. This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
Radio
gradio.Radio(···)
Creates a set of radio buttons of which only one can be selected.
As input: passes the value of the selected radio button as a str or its index as an int into the function, depending on `type`.
As output: expects a str corresponding to the value of the radio button to be selected.
Format expected for examples: a str representing the radio option to select.
import gradio as gr
def sentence_builder(quantity, animal, countries, place, activity_list, morning):
return f"""The {quantity} {animal}s from {" and ".join(countries)} went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""
demo = gr.Interface(
sentence_builder,
[
gr.Slider(2, 20, value=4, label="Count", info="Choose betwen 2 and 20"),
gr.Dropdown(
["cat", "dog", "bird"], label="Animal", info="Will add more animals later!"
),
gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="Countries", info="Where are they from?"),
gr.Radio(["park", "zoo", "road"], label="Location", info="Where did they go?"),
gr.Dropdown(
["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True, label="Activity", info="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl."
),
gr.Checkbox(label="Morning", info="Did they do it in the morning?"),
],
"text",
examples=[
[2, "cat", ["Japan", "Pakistan"], "park", ["ate", "swam"], True],
[4, "dog", ["Japan"], "zoo", ["ate", "swam"], False],
[10, "bird", ["USA", "Pakistan"], "road", ["ran"], False],
[8, "cat", ["Pakistan"], "zoo", ["ate"], True],
]
)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
choices
list[str] | None default: None |
list of options to select from. |
value
str | Callable | None default: None |
the button selected by default. If None, no button is selected by default. If callable, the function will be called whenever the app loads to set the initial value of the component. |
type
str default: "value" |
Type of value to be returned by component. "value" returns the string of the choice selected, "index" returns the index of the choice selected. |
label
str | None default: None |
component name in interface. |
info
str | None default: None |
additional component description. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
interactive
bool | None default: None |
if True, choices in this radio group will be selectable; if False, selection will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"radio" |
Uses default values |
Methods
style
gradio.Radio.style(···)
This method can be used to change the appearance of the radio component.
Parameter | Description |
---|---|
item_container
bool | None default: None |
If True, will place items in a container. |
container
bool | None default: None |
If True, will place the component in a container - providing some extra padding around the border. |
change
gradio.Radio.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
select
gradio.Radio.select(fn, ···)
Event listener for when the user selects Radio option. Uses event data gradio.SelectData to carry `value` referring to label of selected option, and `index` to refer to index. See EventData documentation on how to use this event data.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
No guides yet, contribute a guide about Radio
ScatterPlot
gradio.ScatterPlot(···)
Create a scatter plot.
As input: this component does *not* accept input.
As output: expects a pandas dataframe with the data to plot.
import gradio as gr
from scatter_plot_demo import scatter_plot
from line_plot_demo import line_plot
from bar_plot_demo import bar_plot
with gr.Blocks() as demo:
with gr.Tabs():
with gr.TabItem("Scatter Plot"):
scatter_plot.render()
with gr.TabItem("Line Plot"):
line_plot.render()
with gr.TabItem("Bar Plot"):
bar_plot.render()
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
pd.DataFrame | Callable | None default: None |
The pandas dataframe containing the data to display in a scatter plot, or a callable. If callable, the function will be called whenever the app loads to set the initial value of the component. |
x
str | None default: None |
Column corresponding to the x axis. |
y
str | None default: None |
Column corresponding to the y axis. |
color
str | None default: None |
The column to determine the point color. If the column contains numeric data, gradio will interpolate the column data so that small values correspond to light colors and large values correspond to dark values. |
size
str | None default: None |
The column used to determine the point size. Should contain numeric data so that gradio can map the data to the point size. |
shape
str | None default: None |
The column used to determine the point shape. Should contain categorical data. Gradio will map each unique value to a different shape. |
title
str | None default: None |
The title to display on top of the chart. |
tooltip
list[str] | str | None default: None |
The column (or list of columns) to display on the tooltip when a user hovers a point on the plot. |
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_legend_title
str | None default: None |
The title given to the color legend. By default, uses the value of color parameter. |
size_legend_title
str | None default: None |
The title given to the size legend. By default, uses the value of the size parameter. |
shape_legend_title
str | None default: None |
The title given to the shape legend. By default, uses the value of the shape parameter. |
color_legend_position
str | None default: None |
The position of the color legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation. |
size_legend_position
str | None default: None |
The position of the size legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation. |
shape_legend_position
str | None default: None |
The position of the shape legend. If the string value 'none' is passed, this legend is omitted. For other valid position values see: https://vega.github.io/vega/docs/legends/#orientation. |
height
int | None default: None |
The height of the plot in pixels. |
width
int | None default: None |
The width of the plot in pixels. |
x_lim
list[int | float] | None default: None |
A tuple or list containing the limits for the x-axis, specified as [x_min, x_max]. |
y_lim
list[int | float] | None default: None |
A tuple of list containing the limits for the y-axis, specified as [y_min, y_max]. |
caption
str | None default: None |
The (optional) caption to display below the plot. |
interactive
bool | None default: True |
Whether users should be able to interact with the plot by panning or zooming with their mouse or trackpad. |
label
str | None default: None |
The (optional) label to display on the top left corner of the plot. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
Whether the label should be displayed. |
visible
bool default: True |
Whether the plot should be visible. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"scatterplot" |
Uses default values |
Methods
change
gradio.ScatterPlot.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
clear
gradio.ScatterPlot.clear(fn, ···)
This event is triggered when the user clears the component (e.g. image or audio) using the X button for the component. This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
Slider
gradio.Slider(···)
Creates a slider that ranges from `minimum` to `maximum` with a step size of `step`.
As input: passes slider value as a float into the function.
As output: expects an int or float returned from function and sets slider value to it as long as it is within range.
Format expected for examples: A float or int representing the slider's value.
import gradio as gr
def sentence_builder(quantity, animal, countries, place, activity_list, morning):
return f"""The {quantity} {animal}s from {" and ".join(countries)} went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""
demo = gr.Interface(
sentence_builder,
[
gr.Slider(2, 20, value=4, label="Count", info="Choose betwen 2 and 20"),
gr.Dropdown(
["cat", "dog", "bird"], label="Animal", info="Will add more animals later!"
),
gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="Countries", info="Where are they from?"),
gr.Radio(["park", "zoo", "road"], label="Location", info="Where did they go?"),
gr.Dropdown(
["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True, label="Activity", info="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl."
),
gr.Checkbox(label="Morning", info="Did they do it in the morning?"),
],
"text",
examples=[
[2, "cat", ["Japan", "Pakistan"], "park", ["ate", "swam"], True],
[4, "dog", ["Japan"], "zoo", ["ate", "swam"], False],
[10, "bird", ["USA", "Pakistan"], "road", ["ran"], False],
[8, "cat", ["Pakistan"], "zoo", ["ate"], True],
]
)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
minimum
float default: 0 |
minimum value for slider. |
maximum
float default: 100 |
maximum value for slider. |
value
float | Callable | None default: None |
default value. If callable, the function will be called whenever the app loads to set the initial value of the component. Ignored if randomized=True. |
step
float | None default: None |
increment between slider values. |
label
str | None default: None |
component name in interface. |
info
str | None default: None |
additional component description. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
interactive
bool | None default: None |
if True, slider will be adjustable; if False, adjusting will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
randomize
bool default: False |
If True, the value of the slider when the app loads is taken uniformly at random from the range given by the minimum and maximum. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"slider" |
Uses default values |
Methods
style
gradio.Slider.style(···)
This method can be used to change the appearance of the slider.
Parameter | Description |
---|---|
container
bool | None default: None |
If True, will place the component in a container - providing some extra padding around the border. |
change
gradio.Slider.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
release
gradio.Slider.release(fn, ···)
This event is triggered when the user releases the mouse on this component (e.g. when the user releases the slider). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
State
gradio.State(···)
Special hidden component that stores session state across runs of the demo by the same user. The value of the State variable is cleared when the user refreshes the page.
As input: No preprocessing is performed
As output: No postprocessing is performed
import gradio as gr
demo = gr.Blocks(css="""#btn {color: red} .abc {font-family: "Comic Sans MS", "Comic Sans", cursive !important}""")
with demo:
default_json = {"a": "a"}
num = gr.State(value=0)
squared = gr.Number(value=0)
btn = gr.Button("Next Square", elem_id="btn", elem_classes=["abc", "def"])
stats = gr.State(value=default_json)
table = gr.JSON()
def increase(var, stats_history):
var += 1
stats_history[str(var)] = var**2
return var, var**2, stats_history, stats_history
btn.click(increase, [num, stats], [num, squared, stats, table])
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
Any default: None |
the initial value (of abitrary type) of the state. The provided argument is deepcopied. If a callable is provided, the function will be called whenever the app loads to set the initial value of the state. |
Step-by-step Guides
Textbox
gradio.Textbox(···)
Creates a textarea for user to enter string input or display string output.
As input: passes textarea value as a str into the function.
As output: expects a str returned from function and sets textarea value to it.
Format expected for examples: a str representing the textbox input.
import gradio as gr
def greet(name):
return "Hello " + name + "!"
demo = gr.Interface(fn=greet, inputs="text", outputs="text")
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
str | Callable | None default: "" |
default text to provide in textarea. If callable, the function will be called whenever the app loads to set the initial value of the component. |
lines
int default: 1 |
minimum number of line rows to provide in textarea. |
max_lines
int default: 20 |
maximum number of line rows to provide in textarea. |
placeholder
str | None default: None |
placeholder hint to provide behind textarea. |
label
str | None default: None |
component name in interface. |
info
str | None default: None |
additional component description. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
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 default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
type
str default: "text" |
The type of textbox. One of: 'text', 'password', 'email', Default is 'text'. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"textbox" |
Uses default values |
|
"textarea" |
Uses lines=7 |
Methods
style
gradio.Textbox.style(···)
This method can be used to change the appearance of the Textbox component.
Parameter | Description |
---|---|
show_copy_button
bool | None default: None |
If True, includes a copy button to copy the text in the textbox. Only applies if show_label is True. |
container
bool | None default: None |
If True, will place the component in a container - providing some extra padding around the border. |
change
gradio.Textbox.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
submit
gradio.Textbox.submit(fn, ···)
This event is triggered when the user presses the Enter key while the component (e.g. a textbox) is focused. This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
blur
gradio.Textbox.blur(fn, ···)
This event is triggered when the component's is unfocused/blurred (e.g. when the user clicks outside of a textbox). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
select
gradio.Textbox.select(fn, ···)
Event listener for when the user selects text in the Textbox. Uses event data gradio.SelectData to carry `value` referring to selected subtring, and `index` tuple referring to selected range endpoints. See EventData documentation on how to use this event data.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
Timeseries
gradio.Timeseries(···)
Creates a component that can be used to upload/preview timeseries csv files or display a dataframe consisting of a time series graphically.
As input: passes the uploaded timeseries data as a pandas.DataFrame into the function
As output: expects a pandas.DataFrame or str path to a csv to be returned, which is then displayed as a timeseries graph
Format expected for examples: a str filepath of csv data with time series data.
import random
import os
import gradio as gr
def fraud_detector(card_activity, categories, sensitivity):
activity_range = random.randint(0, 100)
drop_columns = [
column for column in ["retail", "food", "other"] if column not in categories
]
if len(drop_columns):
card_activity.drop(columns=drop_columns, inplace=True)
return (
card_activity,
card_activity,
{"fraud": activity_range / 100.0, "not fraud": 1 - activity_range / 100.0},
)
demo = gr.Interface(
fraud_detector,
[
gr.Timeseries(x="time", y=["retail", "food", "other"]),
gr.CheckboxGroup(
["retail", "food", "other"], value=["retail", "food", "other"]
),
gr.Slider(1, 3),
],
[
"dataframe",
gr.Timeseries(x="time", y=["retail", "food", "other"]),
gr.Label(label="Fraud Level"),
],
examples=[
[os.path.join(os.path.dirname(__file__), "fraud.csv"), ["retail", "food", "other"], 1.0],
],
)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
str | Callable | None default: None |
File path for the timeseries csv file. If callable, the function will be called whenever the app loads to set the initial value of the component. |
x
str | None default: None |
Column name of x (time) series. None if csv has no headers, in which case first column is x series. |
y
str | list[str] | None default: None |
Column name of y series, or list of column names if multiple series. None if csv has no headers, in which case every column after first is a y series. |
colors
list[str] | None default: None |
an ordered list of colors to use for each line plot |
label
str | None default: None |
component name in interface. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
interactive
bool | None default: None |
if True, will allow users to upload a timeseries csv; if False, can only be used to display timeseries data. If not provided, this is inferred based on whether the component is used as an input or output. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"timeseries" |
Uses default values |
Methods
style
gradio.Timeseries.style(···)
This method can be used to change the appearance of the TimeSeries component.
change
gradio.Timeseries.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
No guides yet, contribute a guide about Timeseries
UploadButton
gradio.UploadButton(···)
Used to create an upload button, when cicked allows a user to upload files that satisfy the specified file type or generic files (if file_type not set).
As input: passes the uploaded file as a file-object or List[file-object] depending on `file_count` (or a bytes/Listbytes depending on `type`)
As output: expects function to return a str path to a file, or List[str] consisting of paths to files.
Format expected for examples: a str path to a local file that populates the component.
import gradio as gr
def upload_file(files):
file_paths = [file.name for file in files]
return file_paths
with gr.Blocks() as demo:
file_output = gr.File()
upload_button = gr.UploadButton("Click to Upload a File", file_types=["image", "video"], file_count="multiple")
upload_button.upload(upload_file, upload_button, file_output)
demo.launch()
Parameter | Description |
---|---|
label
str default: "Upload a File" |
Text to display on the button. Defaults to "Upload a File". |
value
str | list[str] | Callable | None default: None |
Default text for the button to display. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
type
str default: "file" |
Type of value to be returned by component. "file" returns a temporary file object with the same base name as the uploaded file, whose full path can be retrieved by file_obj.name, "binary" returns an bytes object. |
file_count
str default: "single" |
if single, allows user to upload one file. If "multiple", user uploads multiple files. If "directory", user uploads all files in selected directory. Return type will be list for each file in case of "multiple" or "directory". |
file_types
list[str] | None default: None |
List of type of files to be uploaded. "file" allows any file to be uploaded, "image" allows only image files to be uploaded, "audio" allows only audio files to be uploaded, "video" allows only video files to be uploaded, "text" allows only text files to be uploaded. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"uploadbutton" |
Uses default values |
Methods
style
gradio.UploadButton.style(···)
This method can be used to change the appearance of the button component.
Parameter | Description |
---|---|
full_width
bool | None default: None |
If True, will expand to fill parent container. |
size
Literal['sm'] | Literal['lg'] | None default: None |
Size of the button. Can be "sm" or "lg". |
click
gradio.UploadButton.click(fn, ···)
This event is triggered when the component (e.g. a button) is clicked. This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
upload
gradio.UploadButton.upload(fn, ···)
This event is triggered when the user uploads a file into the component (e.g. when the user uploads a video into a video component). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
No guides yet, contribute a guide about UploadButton
Video
gradio.Video(···)
Creates a video component that can be used to upload/record videos (as an input) or display videos (as an output). For the video to be playable in the browser it must have a compatible container and codec combination. Allowed combinations are .mp4 with h264 codec, .ogg with theora codec, and .webm with vp9 codec. If the component detects that the output video would not be playable in the browser it will attempt to convert it to a playable mp4 video. If the conversion fails, the original video is returned.
As input: passes the uploaded video as a str filepath or URL whose extension can be modified by `format`.
As output: expects a str filepath to a video which is displayed, or a Tuple[str, str] where the first element is a filepath to a video and the second element is a filepath to a subtitle file.
Format expected for examples: a str filepath to a local file that contains the video, or a Tuple[str, str] where the first element is a filepath to a video file and the second element is a filepath to a subtitle file.
import gradio as gr
import os
def video_identity(video):
return video
demo = gr.Interface(video_identity,
gr.Video(),
"playable_video",
examples=[
os.path.join(os.path.dirname(__file__),
"video/video_sample.mp4")],
cache_examples=True)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
str | tuple[str, str | None] | Callable | None default: None |
A path or URL for the default value that Video component is going to take. Can also be a tuple consisting of (video filepath, subtitle filepath). If a subtitle file is provided, it should be of type .srt or .vtt. Or can be callable, in which case the function will be called whenever the app loads to set the initial value of the component. |
format
str | None default: None |
Format of video format to be returned by component, such as 'avi' or 'mp4'. Use 'mp4' to ensure browser playability. If set to None, video will keep uploaded format. |
source
str default: "upload" |
Source of video. "upload" creates a box where user can drop an video file, "webcam" allows user to record a video from their webcam. |
label
str | None default: None |
component name in interface. |
every
float | None default: None |
If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute. |
show_label
bool default: True |
if True, will display label. |
interactive
bool | None default: None |
if True, will allow users to upload a video; if False, can only be used to display videos. If not provided, this is inferred based on whether the component is used as an input or output. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
str | None default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
elem_classes
list[str] | str | None default: None |
An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles. |
mirror_webcam
bool default: True |
If True webcam will be mirrored. Default is True. |
include_audio
bool | None default: None |
Whether the component should record/retain the audio track for a video. By default, audio is excluded for webcam videos and included for uploaded videos. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"video" |
Uses default values |
|
"playablevideo" |
Uses format="mp4" |
Methods
style
gradio.Video.style(···)
This method can be used to change the appearance of the video component.
Parameter | Description |
---|---|
height
int | None default: None |
Height of the video. |
width
int | None default: None |
Width of the video. |
change
gradio.Video.change(fn, ···)
This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
clear
gradio.Video.clear(fn, ···)
This event is triggered when the user clears the component (e.g. image or audio) using the X button for the component. This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
play
gradio.Video.play(fn, ···)
This event is triggered when the user plays the component (e.g. audio or video). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
pause
gradio.Video.pause(fn, ···)
This event is triggered when the user pauses the component (e.g. audio or video). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
stop
gradio.Video.stop(fn, ···)
This event is triggered when the user stops the component (e.g. audio or video). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
upload
gradio.Video.upload(fn, ···)
This event is triggered when the user uploads a file into the component (e.g. when the user uploads a video into a video component). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable | None required |
the function to wrap an interface around. 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 | list[Component] | set[Component] | 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 | list[Component] | 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 default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
StatusTracker | None default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool | None default: None |
If True, will show progress animation while pending |
queue
bool | None default: None |
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 event 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. |
every
float | None default: None |
Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled. |
Step-by-step Guides
No guides yet, contribute a guide about Video
Helpers
Gradio includes helper classes and methods that interact with existing components. The goal of these classes and methods is to help you add common functionality to your app without having to rewrite common functions.
Error
gradio.Error(message, ···)
This class allows you to pass custom error messages to the user. You can do so by raising a gr.Error("custom message") anywhere in the code, and when that line is executed the custom message will appear in a modal on the demo.
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":
if num2 == 0:
raise gr.Error("Cannot divide by zero!")
return num1 / num2
demo = gr.Interface(
calculator,
[
"number",
gr.Radio(["add", "subtract", "multiply", "divide"]),
"number"
],
"number",
examples=[
[5, "add", 3],
[4, "divide", 2],
[-4, "multiply", 2.5],
[0, "subtract", 1.2],
],
title="Toy Calculator",
description="Here's a sample toy calculator. Allows you to calculate things like $2+2=4$",
)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
message
required |
The error message to be displayed to the user. |
Step-by-step Guides
No guides yet, contribute a guide about Error
load
gradio.load(name, ···)
Method that constructs a Blocks from a Hugging Face repo. Can accept model repos (if src is "models") or Space repos (if src is "spaces"). The input and output components are automatically loaded from the repo.
Example Usage
import gradio as gr
demo = gr.load("gradio/question-answering", src="spaces")
demo.launch()
Parameter | Description |
---|---|
name
str required |
the name of the model (e.g. "gpt2" or "facebook/bart-base") or space (e.g. "flax-community/spanish-gpt2"), can include the `src` as prefix (e.g. "models/facebook/bart-base") |
src
str | None default: None |
the source of the model: `models` or `spaces` (or leave empty if source is provided as a prefix in `name`) |
api_key
str | None default: None |
Deprecated. Please use the `hf_token` parameter instead. |
hf_token
str | None default: None |
optional access token for loading private Hugging Face Hub models or spaces. Find your token here: https://huggingface.co/settings/tokens |
alias
str | None default: None |
optional string used as the name of the loaded model instead of the default name (only applies if loading a Space running Gradio 2.x) |
Step-by-step Guides
No guides yet, contribute a guide about load
Examples
gradio.Examples(examples, inputs, ···)
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.
import gradio as gr
import os
def combine(a, b):
return a + " " + b
def mirror(x):
return x
with gr.Blocks() as demo:
txt = gr.Textbox(label="Input", lines=2)
txt_2 = gr.Textbox(label="Input 2")
txt_3 = gr.Textbox(value="", label="Output")
btn = gr.Button(value="Submit")
btn.click(combine, inputs=[txt, txt_2], outputs=[txt_3])
with gr.Row():
im = gr.Image()
im_2 = gr.Image()
btn = gr.Button(value="Mirror Image")
btn.click(mirror, inputs=[im], outputs=[im_2])
gr.Markdown("## Text Examples")
gr.Examples(
[["hi", "Adam"], ["hello", "Eve"]],
[txt, txt_2],
txt_3,
combine,
cache_examples=True,
)
gr.Markdown("## Image Examples")
gr.Examples(
examples=[os.path.join(os.path.dirname(__file__), "lion.jpg")],
inputs=im,
outputs=im_2,
fn=mirror,
cache_examples=True,
)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
examples
list[Any] | list[list[Any]] | str required |
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
IOComponent | list[IOComponent] required |
the component or list of components corresponding to the examples |
outputs
IOComponent | list[IOComponent] | None default: None |
optionally, provide the component or list of components corresponding to the output of the examples. Required if `cache` is True. |
fn
Callable | None default: None |
optionally, provide the function to run to generate the outputs corresponding to the examples. Required if `cache` is True. |
cache_examples
bool default: False |
if True, caches examples for fast runtime. If True, then `fn` and `outputs` need to be provided |
examples_per_page
int default: 10 |
how many examples to show per page. |
label
str | 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 True. |
postprocess
bool default: True |
if True, postprocesses the example output after running the prediction function and before caching. Only applies if cache_examples is True. |
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 True. |
Step-by-step Guides
Progress
gradio.Progress(···)
The Progress class provides a custom progress tracker that is used in a function signature. To attach a Progress tracker to a function, simply add a parameter right after the input parameters that has a default value set to a `gradio.Progress()` instance. The Progress tracker can then be updated in the function by calling the Progress object or using the `tqdm` method on an Iterable. The Progress tracker is currently only available with `queue()`.
Example Usage
import gradio as gr
import time
def my_function(x, progress=gr.Progress()):
progress(0, desc="Starting...")
time.sleep(1)
for i in progress.tqdm(range(100)):
time.sleep(0.1)
return x
gr.Interface(my_function, gr.Textbox(), gr.Textbox()).queue().launch()
Parameter | Description |
---|---|
track_tqdm
bool default: False |
If True, the Progress object will track any tqdm.tqdm iterations with the tqdm library in the function. |
Methods
__call__
gradio.Progress(progress, ···)
Updates progress tracker with progress and message text.
Parameter | Description |
---|---|
progress
float | tuple[int, int | None] | None required |
If float, should be between 0 and 1 representing completion. If Tuple, first number represents steps completed, and second value represents total steps or None if unknown. If None, hides progress bar. |
desc
str | None default: None |
description to display. |
total
int | None default: None |
estimated total number of steps. |
unit
str default: "steps" |
unit of iterations. |
tqdm
gradio.Progress.tqdm(iterable, ···)
Attaches progress tracker to iterable, like tqdm.
Parameter | Description |
---|---|
iterable
Iterable | None required |
iterable to attach progress tracker to. |
desc
str | None default: None |
description to display. |
total
int | None default: None |
estimated total number of steps. |
unit
str default: "steps" |
unit of iterations. |
Step-by-step Guides
No guides yet, contribute a guide about Progress
update
gradio.update(kwargs, ···)
Updates component properties. When a function passed into a Gradio Interface or a Blocks events returns a typical value, it updates the value of the output component. But it is also possible to update the properties of an output component (such as the number of lines of a `Textbox` or the visibility of an `Image`) by returning the component's `update()` function, which takes as parameters any of the constructor parameters for that component. This is a shorthand for using the update method on a component. For example, rather than using gr.Number.update(...) you can just use gr.update(...). Note that your editor's autocompletion will suggest proper parameters if you use the update method on the component.
Example Usage
# Blocks Example
import gradio as gr
with gr.Blocks() as demo:
radio = gr.Radio([1, 2, 4], label="Set the value of the number")
number = gr.Number(value=2, interactive=True)
radio.change(fn=lambda value: gr.update(value=value), inputs=radio, outputs=number)
demo.launch()
# Interface example
import gradio as gr
def change_textbox(choice):
if choice == "short":
return gr.Textbox.update(lines=2, visible=True)
elif choice == "long":
return gr.Textbox.update(lines=8, visible=True)
else:
return gr.Textbox.update(visible=False)
gr.Interface(
change_textbox,
gr.Radio(
["short", "long", "none"], label="What kind of essay would you like to write?"
),
gr.Textbox(lines=2),
live=True,
).launch()
Parameter | Description |
---|---|
kwargs
required |
Key-word arguments used to update the component's properties. |
Step-by-step Guides
No guides yet, contribute a guide about update
make_waveform
gradio.make_waveform(audio, ···)
Generates a waveform video from an audio file. Useful for creating an easy to share audio visualization. The output should be passed into a `gr.Video` component.
Parameter | Description |
---|---|
audio
str | tuple[int, np.ndarray] required |
Audio file path or tuple of (sample_rate, audio_data) |
bg_color
str default: "#f3f4f6" |
Background color of waveform (ignored if bg_image is provided) |
bg_image
str | None default: None |
Background image of waveform |
fg_alpha
float default: 0.75 |
Opacity of foreground waveform |
bars_color
str | tuple[str, str] default: ('#fbbf24', '#ea580c') |
Color of waveform bars. Can be a single color or a tuple of (start_color, end_color) of gradient |
bar_count
int default: 50 |
Number of bars in waveform |
bar_width
float default: 0.6 |
Width of bars in waveform. 1 represents full width, 0.5 represents half width, etc. |
Step-by-step Guides
No guides yet, contribute a guide about make_waveform
EventData
gradio.EventData(target, ···)
When a subclass of EventData is added as a type hint to an argument of an event listener method, this object will be passed as that argument. It contains information about the event that triggered the listener, such the target object, and other data related to the specific event that are attributes of the subclass.
Example Usage
table = gr.Dataframe([[1, 2, 3], [4, 5, 6]])
gallery = gr.Gallery([("cat.jpg", "Cat"), ("dog.jpg", "Dog")])
textbox = gr.Textbox("Hello World!")
statement = gr.Textbox()
def on_select(evt: gr.SelectData): # SelectData is a subclass of EventData
return f"You selected {evt.value} at {evt.index} from {evt.target}"
table.select(on_select, None, statement)
gallery.select(on_select, None, statement)
textbox.select(on_select, None, statement)
Parameter | Description |
---|---|
target
Block | None required |
The target object that triggered the event. Can be used to distinguish if multiple components are bound to the same listener. |
Step-by-step Guides
No guides yet, contribute a guide about EventData
Routes
Gradio includes some helper functions for exposing and interacting with the FastAPI app used to run your demo.
Request
gradio.Request(···)
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`, and `path_params`. If auth is enabled, the `username` attribute can be used to get the logged in user.
Example Usage
import gradio as gr
def echo(name, request: gr.Request):
print("Request headers dictionary:", request.headers)
print("IP address:", request.client.host)
return name
io = gr.Interface(echo, "textbox", "textbox").launch()
Parameter | Description |
---|---|
request
fastapi.Request | None default: None |
A fastapi.Request |
username
str | None default: None |
mount_gradio_app
gradio.mount_gradio_app(app, blocks, path, ···)
Mount a gradio.Blocks to an existing FastAPI application.
Example Usage
from fastapi import FastAPI
import gradio as gr
app = FastAPI()
@app.get("/")
def read_main():
return {"message": "This is your main app"}
io = gr.Interface(lambda x: "Hello, " + x + "!", "textbox", "textbox")
app = gr.mount_gradio_app(app, io, path="/gradio")
# Then run `uvicorn run:app` from the terminal and navigate to http://localhost:8000/gradio.
Parameter | Description |
---|---|
app
fastapi.FastAPI required |
The parent FastAPI application. |
blocks
gradio.Blocks required |
The blocks object we want to mount to the parent app. |
path
str required |
The path at which the gradio application will be mounted. |
gradio_api_url
str | None default: None |
The full url at which the gradio app will run. This is only needed if deploying to Huggingface spaces of if the websocket endpoints of your deployed app are on a different network location than the gradio app. If deploying to spaces, set gradio_api_url to 'http://localhost:7860/' |
Client libraries
The lightweight Gradio client libraries make it easy to use any Gradio app as an API. We currently support a Python client libraries and are developing client libraries in other languages.
Python client library
The Python client library is `gradio_client`. It is included in the latest versions of the `gradio` package, but for a more lightweight experience, you can install it using `pip` without having to install `gradio`:
pip install gradio_client
Client
gradio_client.Client(src, ···)
The main Client class for the Python client. This class is used to connect to a remote Gradio app and call its API endpoints.
Example Usage
from gradio_client import Client
client = Client("abidlabs/whisper-large-v2") # connecting to a Hugging Face Space
client.predict("test.mp4", api_name="/predict")
>> What a nice recording! # returns the result of the remote API call
client = Client("https://bec81a83-5b5c-471e.gradio.live") # connecting to a temporary Gradio share URL
job = client.submit("hello", api_name="/predict") # runs the prediction in a background thread
job.result()
>> 49 # returns the result of the remote API call (blocking call)
Parameter | Description |
---|---|
src
str required |
Either the name of the Hugging Face Space to load, (e.g. "abidlabs/whisper-large-v2") or the full URL (including "http" or "https") of the hosted Gradio app to load (e.g. "http://mydomain.com/app" or "https://bec81a83-5b5c-471e.gradio.live/"). |
hf_token
str | None default: None |
The Hugging Face token to use to access private Spaces. Automatically fetched if you are logged in via the Hugging Face Hub CLI. Obtain from: https://huggingface.co/settings/token |
max_workers
int default: 40 |
The maximum number of thread workers that can be used to make requests to the remote Gradio app simultaneously. |
serialize
bool default: True |
Whether the client should serialize the inputs and deserialize the outputs of the remote API. If set to False, the client will pass the inputs and outputs as-is, without serializing/deserializing them. E.g. you if you set this to False, you'd submit an image in base64 format instead of a filepath, and you'd get back an image in base64 format from the remote API instead of a filepath. |
verbose
bool default: True |
Whether the client should print statements to the console. |
Methods
predict
gradio_client.Client.predict(args, ···)
Calls the Gradio API and returns the result (this is a blocking call).
Example Usage
from gradio_client import Client
client = Client(src="gradio/calculator")
client.predict(5, "add", 4, api_name="/predict")
>> 9.0
Parameter | Description |
---|---|
args
required |
The arguments to pass to the remote API. The order of the arguments must match the order of the inputs in the Gradio app. |
api_name
str | None default: None |
The name of the API endpoint to call starting with a leading slash, e.g. "/predict". Does not need to be provided if the Gradio app has only one named API endpoint. |
fn_index
int | None default: None |
As an alternative to api_name, this parameter takes the index of the API endpoint to call, e.g. 0. Both api_name and fn_index can be provided, but if they conflict, api_name will take precedence. |
submit
gradio_client.Client.submit(args, ···)
Creates and returns a Job object which calls the Gradio API in a background thread. The job can be used to retrieve the status and result of the remote API call.
Example Usage
from gradio_client import Client
client = Client(src="gradio/calculator")
job = client.submit(5, "add", 4, api_name="/predict")
job.status()
>>
job.result() # blocking call
>> 9.0
Parameter | Description |
---|---|
args
required |
The arguments to pass to the remote API. The order of the arguments must match the order of the inputs in the Gradio app. |
api_name
str | None default: None |
The name of the API endpoint to call starting with a leading slash, e.g. "/predict". Does not need to be provided if the Gradio app has only one named API endpoint. |
fn_index
int | None default: None |
As an alternative to api_name, this parameter takes the index of the API endpoint to call, e.g. 0. Both api_name and fn_index can be provided, but if they conflict, api_name will take precedence. |
result_callbacks
Callable | list[Callable] | None default: None |
A callback function, or list of callback functions, to be called when the result is ready. If a list of functions is provided, they will be called in order. The return values from the remote API are provided as separate parameters into the callback. If None, no callback will be called. |
view_api
gradio_client.Client.view_api(···)
Prints the usage info for the API. If the Gradio app has multiple API endpoints, the usage info for each endpoint will be printed separately. If return_format="dict" the info is returned in dictionary format, as shown in the example below.
Example Usage
from gradio_client import Client
client = Client(src="gradio/calculator")
client.view_api(return_format="dict")
>> {
'named_endpoints': {
'/predict': {
'parameters': [
{
'label': 'num1',
'type_python': 'int | float',
'type_description': 'numeric value',
'component': 'Number',
'example_input': '5'
},
{
'label': 'operation',
'type_python': 'str',
'type_description': 'string value',
'component': 'Radio',
'example_input': 'add'
},
{
'label': 'num2',
'type_python': 'int | float',
'type_description': 'numeric value',
'component': 'Number',
'example_input': '5'
},
],
'returns': [
{
'label': 'output',
'type_python': 'int | float',
'type_description': 'numeric value',
'component': 'Number',
},
]
},
'/flag': {
'parameters': [
...
],
'returns': [
...
]
}
}
'unnamed_endpoints': {
2: {
'parameters': [
...
],
'returns': [
...
]
}
}
}
}
Parameter | Description |
---|---|
all_endpoints
bool | None default: None |
If True, prints information for both named and unnamed endpoints in the Gradio app. If False, will only print info about named endpoints. If None (default), will only print info about unnamed endpoints if there are no named endpoints. |
print_info
bool default: True |
If True, prints the usage info to the console. If False, does not print the usage info. |
return_format
Literal['dict', 'str'] | None default: None |
If None, nothing is returned. If "str", returns the same string that would be printed to the console. If "dict", returns the usage info as a dictionary that can be programmatically parsed, and *all endpoints are returned in the dictionary* regardless of the value of `all_endpoints`. The format of the dictionary is in the docstring of this method. |
duplicate
gradio_client.Client.duplicate(from_id, ···)
Duplicates a Hugging Face Space under your account and returns a Client object for the new Space. No duplication is created if the Space already exists in your account (to override this, provide a new name for the new Space using `to_id`). To use this method, you must provide an `hf_token` or be logged in via the Hugging Face Hub CLI.
The new Space will be private by default and use the same hardware as the original Space. This can be changed by using the `private` and `hardware` parameters. For hardware upgrades (beyond the basic CPU tier), you may be required to provide billing information on Hugging Face: https://huggingface.co/settings/billing
Example Usage
import os
from gradio_client import Client
HF_TOKEN = os.environ.get("HF_TOKEN")
client = Client.duplicate("abidlabs/whisper", hf_token=HF_TOKEN)
client.predict("audio_sample.wav")
>> "This is a test of the whisper speech recognition model."
Parameter | Description |
---|---|
from_id
str required |
The name of the Hugging Face Space to duplicate in the format "{username}/{space_id}", e.g. "gradio/whisper". |
to_id
str | None default: None |
The name of the new Hugging Face Space to create, e.g. "abidlabs/whisper-duplicate". If not provided, the new Space will be named "{your_HF_username}/{space_id}". |
hf_token
str | None default: None |
The Hugging Face token to use to access private Spaces. Automatically fetched if you are logged in via the Hugging Face Hub CLI. Obtain from: https://huggingface.co/settings/token |
private
bool default: True |
Whether the new Space should be private (True) or public (False). Defaults to True. |
hardware
str | None default: None |
The hardware tier to use for the new Space. Defaults to the same hardware tier as the original Space. Options include "cpu-basic", "cpu-upgrade", "t4-small", "t4-medium", "a10g-small", "a10g-large", "a100-large", subject to availability. |
secrets
dict[str, str] | None default: None |
A dictionary of (secret key, secret value) to pass to the new Space. Defaults to None. Secrets are only used when the Space is duplicated for the first time, and are not updated if the duplicated Space already exists. |
sleep_timeout
int default: 5 |
The number of minutes after which the duplicate Space will be puased if no requests are made to it (to minimize billing charges). Defaults to 5 minutes. |
max_workers
int default: 40 |
The maximum number of thread workers that can be used to make requests to the remote Gradio app simultaneously. |
verbose
bool default: True |
Whether the client should print statements to the console. |
Job
gradio_client.Job(future, ···)
A Job is a wrapper over the Future class that represents a prediction call that has been submitted by the Gradio client. This class is not meant to be instantiated directly, but rather is created by the Client.submit() method.
A Job object includes methods to get the status of the prediction call, as well to get the outputs of the prediction call. Job objects are also iterable, and can be used in a loop to get the outputs of prediction calls as they become available for generator endpoints.
Parameter | Description |
---|---|
future
Future required |
The future object that represents the prediction call, created by the Client.submit() method |
communicator
Communicator | None default: None |
The communicator object that is used to communicate between the client and the background thread running the job |
verbose
bool default: True |
Whether to print any status-related messages to the console |
space_id
str | None default: None |
The space ID corresponding to the Client object that created this Job object |
Methods
result
gradio_client.Job.result(···)
Return the result of the call that the future represents. Raises CancelledError: If the future was cancelled, TimeoutError: If the future didn't finish executing before the given timeout, and Exception: If the call raised then that exception will be raised.
Example Usage
from gradio_client import Client
calculator = Client(src="gradio/calculator")
job = calculator.submit("foo", "add", 4, fn_index=0)
job.result(timeout=5)
>> 9
Parameter | Description |
---|---|
timeout
default: None |
The number of seconds to wait for the result if the future isn't done. If None, then there is no limit on the wait time. |
outputs
gradio_client.Job.outputs(···)
Returns a list containing the latest outputs from the Job.
If the endpoint has multiple output components, the list will contain a tuple of results. Otherwise, it will contain the results without storing them in tuples.
For endpoints that are queued, this list will contain the final job output even if that endpoint does not use a generator function.
Example Usage
from gradio_client import Client
client = Client(src="gradio/count_generator")
job = client.submit(3, api_name="/count")
while not job.done():
time.sleep(0.1)
job.outputs()
>> ['0', '1', '2']
status
gradio_client.Job.status(···)
Returns the latest status update from the Job in the form of a StatusUpdate object, which contains the following fields: code, rank, queue_size, success, time, eta, and progress_data.
progress_data is a list of updates emitted by the gr.Progress() tracker of the event handler. Each element of the list has the following fields: index, length, unit, progress, desc. If the event handler does not have a gr.Progress() tracker, the progress_data field will be None.
Example Usage
from gradio_client import Client
client = Client(src="gradio/calculator")
job = client.submit(5, "add", 4, api_name="/predict")
job.status()
>>
job.status().eta
>> 43.241 # seconds