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".

app_kwargs

dict[str, Any] | None

default: None

Additional keyword arguments to pass to the underlying FastAPI app as a dictionary of parameter keys and argument values. For example, `{"docs_url": "/docs"}`

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. Warning: only provide this if you are loading a trusted private Space as it can be read by the Space you are loading.

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".

app_kwargs

dict[str, Any] | None

default: None

Additional keyword arguments to pass to the underlying FastAPI app as a dictionary of parameter keys and argument values. For example, `{"docs_url": "/docs"}`

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. Warning: only provide this if you are loading a trusted private Space as it can be read by the Space you are loading.

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 listener 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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

Group

with gr.Group():

Group is a layout element within Blocks which groups together children so that they do not have any padding or margin between them.


Example Usage

with gr.Group():
    gr.Textbox(label="First")
    gr.Textbox(label="Last")
Parameter Description
visible

bool

default: True

If False, group will be hidden.

elem_id

str | None

default: None

An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.

Step-by-step Guides

No guides yet, contribute a guide about Group

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.themes.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: (, 'ui-sans-serif', 'system-ui', 'sans-serif')

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: (, 'ui-monospace', 'Consolas', 'monospace')

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.themes.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.themes.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 /@. If a semantic version expression is omitted, the latest version will be fetched.

hf_token

str | None

default: None

HuggingFace Token. Only needed to download private themes.

load

gradio.themes.Base.load(path, ···)

Load a theme from a json file.


Parameter Description
path

str

required

The filepath to read.

dump

gradio.themes.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.themes.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.themes.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

gradio.AnnotatedImage

"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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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.

format

Literal['wav', 'mp3']

default: "wav"

The file format to save audio files. Either 'wav' or 'mp3'. wav files are lossless but will tend to be larger files. mp3 files tend to be smaller. Default is wav. Applies both when this component is used as an input (when `type` is "format") and when this component is used as an output.

Class Interface String Shortcut Initialization

gradio.Audio

"audio"

Uses default values

gradio.Microphone

"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 listener is triggered when the component's value changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input. 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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 listener 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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 listener 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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 listener 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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 listener 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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 listener 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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 listener 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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

gradio.BarPlot

"barplot"

Uses default values

Methods

change

gradio.BarPlot.change(fn, ···)

This listener is triggered when the component's value changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input. 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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 listener 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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

gradio.Button

"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 listener 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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

md = """This is some code:

hello

```py def fn(x, y, z): print(x, y, z) """ 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, md)) 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

gradio.Chatbot

"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 listener is triggered when the component's value changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input. 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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 between 2 and 20"),
        gr.Dropdown(
            ["cat", "dog", "bird"], label="Animal", info="Will add more animals later!"
        ),
        gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="Countries", info="Where are they from?"),
        gr.Radio(["park", "zoo", "road"], label="Location", info="Where did they go?"),
        gr.Dropdown(
            ["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True, label="Activity", info="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl."
        ),
        gr.Checkbox(label="Morning", info="Did they do it in the morning?"),
    ],
    "text",
    examples=[
        [2, "cat", ["Japan", "Pakistan"], "park", ["ate", "swam"], True],
        [4, "dog", ["Japan"], "zoo", ["ate", "swam"], False],
        [10, "bird", ["USA", "Pakistan"], "road", ["ran"], False],
        [8, "cat", ["Pakistan"], "zoo", ["ate"], True],
    ]
)

if __name__ == "__main__":
    demo.launch()
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

gradio.Checkbox

"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 listener is triggered when the component's value changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input. 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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.

input

gradio.Checkbox.input(fn, ···)

This listener is triggered when the user changes the value of 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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 between 2 and 20"),
        gr.Dropdown(
            ["cat", "dog", "bird"], label="Animal", info="Will add more animals later!"
        ),
        gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="Countries", info="Where are they from?"),
        gr.Radio(["park", "zoo", "road"], label="Location", info="Where did they go?"),
        gr.Dropdown(
            ["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True, label="Activity", info="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl."
        ),
        gr.Checkbox(label="Morning", info="Did they do it in the morning?"),
    ],
    "text",
    examples=[
        [2, "cat", ["Japan", "Pakistan"], "park", ["ate", "swam"], True],
        [4, "dog", ["Japan"], "zoo", ["ate", "swam"], False],
        [10, "bird", ["USA", "Pakistan"], "road", ["ran"], False],
        [8, "cat", ["Pakistan"], "zoo", ["ate"], True],
    ]
)

if __name__ == "__main__":
    demo.launch()
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 indices 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

gradio.CheckboxGroup

"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 listener is triggered when the component's value changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input. 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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.

input

gradio.CheckboxGroup.input(fn, ···)

This listener is triggered when the user changes the value of 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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

gradio.Code

"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 listener is triggered when the component's value changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input. 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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.

input

gradio.Code.input(fn, ···)

This listener is triggered when the user changes the value of 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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

gradio.ColorPicker

"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 listener is triggered when the component's value changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input. 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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.

input

gradio.ColorPicker.input(fn, ···)

This listener is triggered when the user changes the value of 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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 listener 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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 listener 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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 horizontally. Defaults to False.

Class Interface String Shortcut Initialization

gradio.Dataframe

"dataframe"

Uses default values

gradio.Numpy

"numpy"

Uses type="numpy"

gradio.Matrix

"matrix"

Uses type="array"

gradio.List

"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 listener is triggered when the component's value changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input. 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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.

input

gradio.Dataframe.input(fn, ···)

This listener is triggered when the user changes the value of 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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

gradio.Dataset

"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 listener 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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 listener 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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

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

gradio.File

"file"

Uses default values

gradio.Files

"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 listener is triggered when the component's value changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input. 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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 listener 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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 listener 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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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 listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.

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

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

gradio.HTML

"html"

Uses default values

Methods

change

gradio.HTML.change(fn, ···)

This listener is triggered when the component's value changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input. 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.