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

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

List of directories that gradio is allowed to serve files from (in addition to the directory containing the gradio python file). Must be absolute paths. Warning: any files in these directories or its children are potentially accessible to all users of your app.

load

gradio.Interface.load(name, ยทยทยท)

Class method that constructs an Interface from a Hugging Face repo. Can accept model repos (if src is "models") or Space repos (if src is "spaces"). The input and output components are automatically loaded from the repo.


Example Usage

import gradio as gr
description = "Story generation with GPT"
examples = [["An adventurer is approached by a mysterious stranger in the tavern for a new quest."]]
demo = gr.Interface.load("models/EleutherAI/gpt-neo-1.3B", description=description, examples=examples)
demo.launch()
Parameter Description
name

str

required

the name of the model (e.g. "gpt2" or "facebook/bart-base") or space (e.g. "flax-community/spanish-gpt2"), can include the `src` as prefix (e.g. "models/facebook/bart-base")

src

str | None

default: None

the source of the model: `models` or `spaces` (or leave empty if source is provided as a prefix in `name`)

api_key

str | None

default: None

optional access token for loading private Hugging Face Hub models or spaces. Find your token here: https://huggingface.co/settings/tokens

alias

str | None

default: None

optional string used as the name of the loaded model instead of the default name (only applies if loading a Space running Gradio 2.x)

from_pipeline

gradio.Interface.from_pipeline(pipeline, ยทยทยท)

Class method that constructs an Interface from a Hugging Face transformers.Pipeline object. The input and output components are automatically determined from the pipeline.


Example Usage

import gradio as gr
from transformers import pipeline
pipe = pipeline("image-classification")
gr.Interface.from_pipeline(pipe).launch()
Parameter Description
pipeline

Pipeline

required

the pipeline object to use.

integrate

gradio.Interface.integrate(ยทยทยท)

A catch-all method for integrating with other libraries. This method should be run after launch()


Parameter Description
comet_ml

comet_ml.Experiment | None

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

No guides yet, contribute a guide about CSVLogger

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.

dataset_name

str

required

The name of the dataset to save the data to, e.g. "image-classifier-1"

organization

str | None

default: None

The organization to save the dataset under. The hf_token must provide write access to this organization. If not provided, saved under the name of the user corresponding to the hf_token.

private

bool

default: False

Whether the dataset should be private (defaults to False).

Step-by-step Guides

No guides yet, contribute a guide about HuggingFaceDatasetSaver

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.Interface.load(
    "huggingface/facebook/fastspeech2-en-ljspeech",
    title=None,
    examples=tts_examples,
    description="Give me something to say!",
)

stt_demo = gr.Interface.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

No guides yet, contribute a guide about Parallel

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

No guides yet, contribute a guide about Series

Blocks

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

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.

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

List of directories that gradio is allowed to serve files from (in addition to the directory containing the gradio python file). Must be absolute paths. Warning: any files in these directories or its children are potentially accessible to all users of your app.

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

comet_ml.Experiment | None

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. Equivalent to gradio.Interface.load()

Instance method: adds event that runs as soon as the demo loads in the browser. Example usage below.


Example Usage

import gradio as gr
import datetime
with gr.Blocks() as demo:
    def get_time():
        return datetime.datetime.now().time()
    dt = gr.Textbox(label="Current time")
    demo.load(get_time, inputs=None, outputs=dt)
demo.launch()
Parameter Description
fn

Callable | None

default: None

Instance Method - the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

List[Component] | None

default: None

Instance Method - List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

List[Component] | None

default: None

Instance Method - List of gradio.components to use as inputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Instance Method - Defining this parameter exposes the endpoint in the api docs

scroll_to_output

bool

default: False

Instance Method - If True, will scroll to output component on completion

show_progress

bool

default: True

Instance Method - If True, will show progress animation while pending

queue

default: None

Instance Method - If True, will place the request on the queue, if the queue exists

batch

bool

default: False

Instance Method - If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Instance Method - Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

Instance Method - If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

Instance Method - If False, will not run postprocessing of component data before returning 'fn' output to the browser.

every

float | None

default: None

Instance Method - Run this event 'every' number of seconds. Interpreted in seconds. Queue must be enabled.

name

str | None

default: None

Class Method - the name of the model (e.g. "gpt2" or "facebook/bart-base") or space (e.g. "flax-community/spanish-gpt2"), can include the `src` as prefix (e.g. "models/facebook/bart-base")

src

str | None

default: None

Class Method - the source of the model: `models` or `spaces` (or leave empty if source is provided as a prefix in `name`)

api_key

str | None

default: None

Class Method - optional access token for loading private Hugging Face Hub models or spaces. Find your token here: https://huggingface.co/settings/tokens

alias

str | None

default: None

Class Method - optional string used as the name of the loaded model instead of the default name (only applies if loading a Space running Gradio 2.x)

Step-by-step Guides

No guides yet, contribute a guide about Blocks

Block Layouts

Customize the layout of your Blocks UI with the layout classes below.

Row

with gradio.Row():

Row is a layout element within Blocks that renders all children horizontally.


Example Usage

with gradio.Blocks() as demo:
    with gradio.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

No guides yet, contribute a guide about Row

Column

with gradio.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 gradio.Blocks() as demo:
    with gradio.Row():
        with gradio.Column(scale=1):
            text1 = gr.Textbox()
            text2 = gr.Textbox()
        with gradio.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

No guides yet, contribute a guide about Column

Tab

with gradio.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 gradio.Blocks() as demo:
    with gradio.Tab("Lion"):
        gr.Image("lion.jpg")
        gr.Button("New Lion")
    with gradio.Tab("Tiger"):
        gr.Image("tiger.jpg")
        gr.Button("New Tiger")
Parameter Description
label

str

required

The visual label for the tab

id

int | str | None

default: None

An optional identifier for the tab, required if you wish to control the selected tab from a predict function.

elem_id

str | None

default: None

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

Methods

select

gradio.Tab.select(fn, ยทยทยท)

This event is triggered when the user selects from within the Component. This event has EventData of type gradio.SelectData that carries information, accessible through SelectData.index and SelectData.value. See EventData documentation on how to use this event data.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

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 Tab

Box

with gradio.Box():

Box is a a layout element which places children in a box with rounded corners and some padding around them.


Example Usage

with gradio.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 gradio.Accordion("See Details"):
    gr.Markdown("lorem ipsum")
Parameter Description
label

required

name of accordion section.

open

bool

default: True

if True, accordion is open by default.

visible

bool

default: True

elem_id

str | None

default: None

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

Step-by-step Guides

No guides yet, contribute a guide about Accordion

Themes

Customize the look of your app by writing your own custom theme

Base

gradio.Base(ยทยทยท)


Parameter Description
primary_hue

colors.Color | str

default: Color()

The primary hue of the theme. Load a preset, like gradio.themes.colors.green (or just the string "green"), or pass your own gradio.themes.utils.Color object.

secondary_hue

colors.Color | str

default: Color()

The secondary hue of the theme. Load a preset, like gradio.themes.colors.green (or just the string "green"), or pass your own gradio.themes.utils.Color object.

neutral_hue

colors.Color | str

default: Color()

The neutral hue of the theme, used . Load a preset, like gradio.themes.colors.green (or just the string "green"), or pass your own gradio.themes.utils.Color object.

text_size

sizes.Size | str

default: Size()

The size of the text. Load a preset, like gradio.themes.sizes.text_sm (or just the string "sm"), or pass your own gradio.themes.utils.Size object.

spacing_size

sizes.Size | str

default: Size()

The size of the spacing. Load a preset, like gradio.themes.sizes.spacing_sm (or just the string "sm"), or pass your own gradio.themes.utils.Size object.

radius_size

sizes.Size | str

default: Size()

The radius size of corners. Load a preset, like gradio.themes.sizes.radius_sm (or just the string "sm"), or pass your own gradio.themes.utils.Size object.

font

fonts.Font | str | Iterable[fonts.Font | str]

default: (, '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.Base.push_to_hub(repo_name, ยทยทยท)

Upload a theme to the HuggingFace hub.
This requires a HuggingFace account.


Parameter Description
repo_name

str

required

The name of the repository to store the theme assets, e.g. 'my_theme' or 'sunset'.

org_name

str | None

default: None

The name of the org to save the space in. If None (the default), the username corresponding to the logged in user, or hฦ’_token is used.

version

str | None

default: None

A semantic version tag for theme. Bumping the version tag lets you publish updates to a theme without changing the look of applications that already loaded your theme.

hf_token

str | None

default: None

API token for your HuggingFace account

theme_name

str | None

default: None

Name for the name. If None, defaults to repo_name

description

str | None

default: None

A long form description to your theme.

private

bool

default: False

from_hub

gradio.Base.from_hub(repo_name, ยทยทยท)

Load a theme from the hub.
This DOES NOT require a HuggingFace account for downloading publicly available themes.


Parameter Description
repo_name

str

required

string of the form /@. 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.Base.load(path, ยทยทยท)

Load a theme from a json file.


Parameter Description
path

str

required

The filepath to read.

dump

gradio.Base.dump(filename, ยทยทยท)

Write the theme to a json file.


Parameter Description
filename

str

required

The path to write the theme too

from_dict

gradio.Base.from_dict(theme, ยทยทยท)

Create a theme instance from a dictionary representation.


Parameter Description
theme

Dict[str, Dict[str, str]]

required

The dictionary representation of the theme.

to_dict

gradio.Base.to_dict(ยทยทยท)

Convert the theme into a python dictionary.


Step-by-step Guides

No guides yet, contribute a guide about Base

Components

Gradio includes pre-built components that can be used as inputs or outputs in your Interface or Blocks with a single line of code. Components include preprocessing steps that convert user data submitted through browser to something that be can used by a Python function, and postprocessing steps to convert values returned by a Python function into something that can be displayed in a browser.

Consider an example with three inputs (Textbox, Number, and Image) and two outputs (Number and Gallery), below is a diagram of what our preprocessing will send to the function and what our postprocessing will require from it.

Components also come with certain events that they support. These are methods that are triggered with user actions. Below is a table showing which events are supported for each component. All events are also listed (with parameters) in the component's docs.

Change Click Submit Edit Clear Play Pause Stream Blur Upload
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

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, data) or as a str filepath, depending on `type`

As output: expects a Tuple(int, numpy.array) corresponding to (sample rate, data) 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.

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
    x = np.linspace(0.0, N * T, N)
    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 for the default value that Audio component is going to take. If callable, the function will be called whenever the app loads to set the initial value of the component.

source

str

default: "upload"

Source of audio. "upload" creates a box where user can drop an audio file, "microphone" creates a microphone input.

type

str

default: "numpy"

The format the audio file is converted to before being passed into the prediction function. "numpy" converts the audio to a tuple consisting of: (int sample rate, numpy.array for the data), "filepath" passes a str path to a temporary file containing the audio.

label

str | None

default: None

component name in interface.

every

float | None

default: None

If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.

show_label

bool

default: True

if True, will display label.

interactive

bool | None

default: None

if True, will allow users to upload and edit a audio file; if False, can only be used to play audio. If not provided, this is inferred based on whether the component is used as an input or output.

visible

bool

default: True

If False, component will be hidden.

streaming

bool

default: False

If set to True when used in a `live` interface, will automatically stream webcam feed. Only valid is source is 'microphone'.

elem_id

str | None

default: None

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

elem_classes

List[str] | str | None

default: None

An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.

Class Interface String Shortcut Initialization

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 event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

every

float | None

default: None

Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.

clear

gradio.Audio.clear(fn, ยทยทยท)

This event is triggered when the user clears the component (e.g. image or audio) using the X button for the component. This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

every

float | None

default: None

Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.

play

gradio.Audio.play(fn, ยทยทยท)

This event is triggered when the user plays the component (e.g. audio or video). This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

every

float | None

default: None

Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.

pause

gradio.Audio.pause(fn, ยทยทยท)

This event is triggered when the user pauses the component (e.g. audio or video). This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

every

float | None

default: None

Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.

stop

gradio.Audio.stop(fn, ยทยทยท)

This event is triggered when the user stops the component (e.g. audio or video). This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

every

float | None

default: None

Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.

stream

gradio.Audio.stream(fn, ยทยทยท)

This event is triggered when the user streams the component (e.g. a live webcam component). This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

every

float | None

default: None

Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.

upload

gradio.Audio.upload(fn, ยทยทยท)

This event is triggered when the user uploads a file into the component (e.g. when the user uploads a video into a video component). This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

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 Audio

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 event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

every

float | None

default: None

Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.

clear

gradio.BarPlot.clear(fn, ยทยทยท)

This event is triggered when the user clears the component (e.g. image or audio) using the X button for the component. This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

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

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 event is triggered when the component (e.g. a button) is clicked. This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

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[Tuple[str | None | Tuple, str | None | Tuple]], a list of tuples with user message and response messages. Messages should be strings, tuples, or Nones. If the message is a string, it can include Markdown. If it is a tuple, it should consist of (string filepath to image/video/audio, [optional string alt text]). Messages that are `None` are not displayed.

import gradio as gr
import random
import time

with gr.Blocks() as demo:
    chatbot = gr.Chatbot()
    msg = gr.Textbox()
    clear = gr.Button("Clear")

    def user(user_message, history):
        return "", history + [[user_message, None]]

    def bot(history):
        bot_message = random.choice(["Yes", "No"])
        history[-1][1] = bot_message
        time.sleep(1)
        return history

    msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
        bot, chatbot, chatbot
    )
    clear.click(lambda: None, None, chatbot, queue=False)

if __name__ == "__main__":
    demo.launch()
Parameter Description
value

List[Tuple[str | None, 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 event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

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 exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

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 Chatbot

Checkbox

gradio.Checkbox(ยทยทยท)

Creates a checkbox that can be set to `True` or `False`.


As input: passes the status of the checkbox as a bool into the function.

As output: expects a bool returned from the function and, if it is True, checks the checkbox.

Format expected for examples: a bool representing whether the box is checked.

import gradio as gr


def sentence_builder(quantity, animal, countries, place, activity_list, morning):
    return f"""The {quantity} {animal}s from {" and ".join(countries)} went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""


demo = gr.Interface(
    sentence_builder,
    [
        gr.Slider(2, 20, value=4, label="Count", info="Choose betwen 2 and 20"),
        gr.Dropdown(
            ["cat", "dog", "bird"], label="Animal", info="Will add more animals later!"
        ),
        gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="Countries", info="Where are they from?"),
        gr.Radio(["park", "zoo", "road"], label="Location", info="Where did they go?"),
        gr.Dropdown(
            ["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True, label="Activity", info="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl."
        ),
        gr.Checkbox(label="Morning", info="Did they do it in the morning?"),
    ],
    "text",
    examples=[
        [2, "cat", "park", ["ran", "swam"], True],
        [4, "dog", "zoo", ["ate", "swam"], False],
        [10, "bird", "road", ["ran"], False],
        [8, "cat", "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 event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

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 exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

every

float | None

default: None

Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.

Step-by-step Guides

No guides yet, contribute a guide about Checkbox

CheckboxGroup

gradio.CheckboxGroup(ยทยทยท)

Creates a set of checkboxes of which a subset can be checked.


As input: passes the list of checked checkboxes as a List[str] or their indices as a List[int] into the function, depending on `type`.

As output: expects a List[str], each element of which becomes a checked checkbox.

Format expected for examples: a List[str] representing the values to be checked.

import gradio as gr


def sentence_builder(quantity, animal, countries, place, activity_list, morning):
    return f"""The {quantity} {animal}s from {" and ".join(countries)} went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}"""


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

if __name__ == "__main__":
    demo.launch()
Parameter Description
choices

List[str] | None

default: None

list of options to select from.

value

List[str] | str | Callable | None

default: None

default selected list of options. If callable, the function will be called whenever the app loads to set the initial value of the component.

type

str

default: "value"

Type of value to be returned by component. "value" returns the list of strings of the choices selected, "index" returns the list of indicies of the choices selected.

label

str | None

default: None

component name in interface.

info

str | None

default: None

additional component description.

every

float | None

default: None

If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.

show_label

bool

default: True

if True, will display label.

interactive

bool | None

default: None

if True, choices in this checkbox group will be checkable; if False, checking will be disabled. If not provided, this is inferred based on whether the component is used as an input or output.

visible

bool

default: True

If False, component will be hidden.

elem_id

str | None

default: None

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

elem_classes

List[str] | str | None

default: None

An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.

Class Interface String Shortcut Initialization

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 event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

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 exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

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

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 event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

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 event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

every

float | None

default: None

Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.

submit

gradio.ColorPicker.submit(fn, ยทยทยท)

This event is triggered when the user presses the Enter key while the component (e.g. a textbox) is focused. This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

every

float | None

default: None

Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.

Step-by-step Guides

No guides yet, contribute a guide about ColorPicker

Dataframe

gradio.Dataframe(ยทยทยท)

Accepts or displays 2D input through a spreadsheet-like component for dataframes.


As input: passes the uploaded spreadsheet data as a pandas.DataFrame, numpy.array, List[List], or List depending on `type`

As output: expects a pandas.DataFrame, numpy.array, List[List], List, a Dict with keys `data` (and optionally `headers`), or str path to a csv, which is rendered in the spreadsheet.

Format expected for examples: a str filepath to a csv with data, a pandas dataframe, or a list of lists (excluding headers) where each sublist is a row of data.

import gradio as gr


def filter_records(records, gender):
    return records[records["gender"] == gender]


demo = gr.Interface(
    filter_records,
    [
        gr.Dataframe(
            headers=["name", "age", "gender"],
            datatype=["str", "number", "str"],
            row_count=5,
            col_count=(3, "fixed"),
        ),
        gr.Dropdown(["M", "F", "O"]),
    ],
    "dataframe",
    description="Enter gender as 'M', 'F', or 'O' for other.",
)

if __name__ == "__main__":
    demo.launch()
Parameter Description
value

List[List[Any]] | Callable | None

default: None

Default value as a 2-dimensional list of values. If callable, the function will be called whenever the app loads to set the initial value of the component.

headers

List[str] | None

default: None

List of str header names. If None, no headers are shown.

row_count

int | Tuple[int, str]

default: (1, 'dynamic')

Limit number of rows for input and decide whether user can create new rows. The first element of the tuple is an `int`, the row count; the second should be 'fixed' or 'dynamic', the new row behaviour. If an `int` is passed the rows default to 'dynamic'

col_count

int | Tuple[int, str] | None

default: None

Limit number of columns for input and decide whether user can create new columns. The first element of the tuple is an `int`, the number of columns; the second should be 'fixed' or 'dynamic', the new column behaviour. If an `int` is passed the columns default to 'dynamic'

datatype

str | List[str]

default: "str"

Datatype of values in sheet. Can be provided per column as a list of strings, or for the entire sheet as a single string. Valid datatypes are "str", "number", "bool", "date", and "markdown".

type

str

default: "pandas"

Type of value to be returned by component. "pandas" for pandas dataframe, "numpy" for numpy array, or "array" for a Python array.

max_rows

int | None

default: 20

Maximum number of rows to display at once. Set to None for infinite.

max_cols

int | None

default: None

Maximum number of columns to display at once. Set to None for infinite.

overflow_row_behaviour

str

default: "paginate"

If set to "paginate", will create pages for overflow rows. If set to "show_ends", will show initial and final rows and truncate middle rows.

label

str | None

default: None

component name in interface.

every

float | None

default: None

If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.

show_label

bool

default: True

if True, will display label.

interactive

bool | None

default: None

if True, will allow users to edit the dataframe; if False, can only be used to display data. If not provided, this is inferred based on whether the component is used as an input or output.

visible

bool

default: True

If False, component will be hidden.

elem_id

str | None

default: None

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

elem_classes

List[str] | str | None

default: None

An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.

wrap

bool

default: False

if True text in table cells will wrap when appropriate, if False the table will scroll horiztonally. Defaults to False.

Class Interface String Shortcut Initialization

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 event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

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 exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

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 event is triggered when the component (e.g. a button) is clicked. This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

every

float | None

default: None

Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.

select

gradio.Dataset.select(fn, ยทยทยท)

This event is triggered when the user selects from within the Component. This event has EventData of type gradio.SelectData that carries information, accessible through SelectData.index and SelectData.value. See EventData documentation on how to use this event data.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

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 file-object or List[file-object] depending on `file_count` (or a bytes/Listbytes depending on `type`)

As output: expects function to return a str path to a file, or List[str] consisting of paths to files.

Format expected for examples: a str path to a local file that populates the component.

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 event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

every

float | None

default: None

Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.

clear

gradio.File.clear(fn, ยทยทยท)

This event is triggered when the user clears the component (e.g. image or audio) using the X button for the component. This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

every

float | None

default: None

Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.

upload

gradio.File.upload(fn, ยทยทยท)

This event is triggered when the user uploads a file into the component (e.g. when the user uploads a video into a video component). This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

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 exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

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 event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

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 HTML

HighlightedText

gradio.HighlightedText(ยทยทยท)

Displays text that contains spans that are highlighted by category or numerical value.


As input: this component does *not* accept input.

As output: expects a List[Tuple[str, float | str]]] consisting of spans of text and their associated labels, or a Dict with two keys: (1) "text" whose value is the complete text, and "entities", which is a list of dictionaries, each of which have the keys: "entity" (consisting of the entity label), "start" (the character index where the label starts), and "end" (the character index where the label ends). Entities should not overlap.

from difflib import Differ

import gradio as gr


def diff_texts(text1, text2):
    d = Differ()
    return [
        (token[2:], token[0] if token[0] != " " else None)
        for token in d.compare(text1, text2)
    ]


demo = gr.Interface(
    diff_texts,
    [
        gr.Textbox(
            label="Text 1",
            info="Initial text",
            lines=3,
            value="The quick brown fox jumped over the lazy dogs.",
        ),
        gr.Textbox(
            label="Text 2",
            info="Text to compare",
            lines=3,
            value="The fast brown fox jumps over lazy dogs.",
        ),
    ],
    gr.HighlightedText(
        label="Diff",
        combine_adjacent=True,
    ).style(color_map={"+": "red", "-": "green"}),
    theme=gr.themes.Base()
)
if __name__ == "__main__":
    demo.launch()
Parameter Description
value

List[Tuple[str, str | float | None]] | Dict | Callable | None

default: None

Default value to show. If callable, the function will be called whenever the app loads to set the initial value of the component.

color_map

Dict[str, str] | None

default: None

show_legend

bool

default: False

whether to show span categories in a separate legend or inline.

combine_adjacent

bool

default: False

If True, will merge the labels of adjacent tokens belonging to the same category.

adjacent_separator

str

default: ""

Specifies the separator to be used between tokens if combine_adjacent is True.

label

str | None

default: None

component name in interface.

every

float | None

default: None

If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.

show_label

bool

default: True

if True, will display label.

visible

bool

default: True

If False, component will be hidden.

elem_id

str | None

default: None

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

elem_classes

List[str] | str | None

default: None

An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.

Class Interface String Shortcut Initialization

gradio.HighlightedText

"highlightedtext"

Uses default values

Methods

style

gradio.HighlightedText.style(ยทยทยท)

This method can be used to change the appearance of the HighlightedText component.


Parameter Description
color_map

Dict[str, str] | None

default: None

Map between category and respective colors.

container

bool | None

default: None

If True, will place the component in a container - providing some extra padding around the border.

change

gradio.HighlightedText.change(fn, ยทยทยท)

This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

every

float | None

default: None

Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.

select

gradio.HighlightedText.select(fn, ยทยทยท)

Event listener for when the user selects Highlighted text span. Uses event data gradio.SelectData to carry `value` referring to selected [text, label] tuple, and `index` to refer to span index. See EventData documentation on how to use this event data.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

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 HighlightedText

Image

gradio.Image(ยทยทยท)

Creates an image component that can be used to upload/draw images (as an input) or display images (as an output).


As input: passes the uploaded image as a numpy.array, PIL.Image or str filepath depending on `type` -- unless `tool` is `sketch` AND source is one of `upload` or `webcam`. In these cases, a dict with keys `image` and `mask` is passed, and the format of the corresponding values depends on `type`.

As output: expects a numpy.array, PIL.Image or str or pathlib.Path filepath to an image and displays the image.

Format expected for examples: a str filepath to a local file that contains the image.

import gradio as gr
import os


def image_mod(image):
    return image.rotate(45)


demo = gr.Interface(
    image_mod,
    gr.Image(type="pil"),
    "image",
    flagging_options=["blurry", "incorrect", "other"],
    examples=[
        os.path.join(os.path.dirname(__file__), "images/cheetah1.jpg"),
        os.path.join(os.path.dirname(__file__), "images/lion.jpg"),
        os.path.join(os.path.dirname(__file__), "images/logo.png"),
        os.path.join(os.path.dirname(__file__), "images/tower.jpg"),
    ],
)

if __name__ == "__main__":
    demo.launch()
Parameter Description
value

str | _Image.Image | np.ndarray | None

default: None

A PIL Image, numpy array, path or URL for the default value that Image component is going to take. If callable, the function will be called whenever the app loads to set the initial value of the component.

shape

Tuple[int, int] | None

default: None

(width, height) shape to crop and resize image to; if None, matches input image size. Pass None for either width or height to only crop and resize the other.

image_mode

str

default: "RGB"

"RGB" if color, or "L" if black and white.

invert_colors

bool

default: False

whether to invert the image as a preprocessing step.

source

str

default: "upload"

Source of image. "upload" creates a box where user can drop an image file, "webcam" allows user to take snapshot from their webcam, "canvas" defaults to a white image that can be edited and drawn upon with tools.

tool

str | None

default: None

Tools used for editing. "editor" allows a full screen editor (and is the default if source is "upload" or "webcam"), "select" provides a cropping and zoom tool, "sketch" allows you to create a binary sketch (and is the default if source="canvas"), and "color-sketch" allows you to created a sketch in different colors. "color-sketch" can be used with source="upload" or "webcam" to allow sketching on an image. "sketch" can also be used with "upload" or "webcam" to create a mask over an image and in that case both the image and mask are passed into the function as a dictionary with keys "image" and "mask" respectively.

type

str

default: "numpy"

The format the image is converted to before being passed into the prediction function. "numpy" converts the image to a numpy array with shape (width, height, 3) and values from 0 to 255, "pil" converts the image to a PIL image object, "filepath" passes a str path to a temporary file containing the image.

label

str | None

default: None

component name in interface.

every

float | None

default: None

If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.

show_label

bool

default: True

if True, will display label.

interactive

bool | None

default: None

if True, will allow users to upload and edit an image; if False, can only be used to display images. If not provided, this is inferred based on whether the component is used as an input or output.

visible

bool

default: True

If False, component will be hidden.

streaming

bool

default: False

If True when used in a `live` interface, will automatically stream webcam feed. Only valid is source is 'webcam'.

elem_id

str | None

default: None

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

elem_classes

List[str] | str | None

default: None

An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.

mirror_webcam

bool

default: True

If True webcam will be mirrored. Default is True.

brush_radius

int | None

default: None

Size of the brush for Sketch. Default is None which chooses a sensible default

Class Interface String Shortcut Initialization

gradio.Image

"image"

Uses default values

gradio.Webcam

"webcam"

Uses source="webcam", interactive=True

gradio.Sketchpad

"sketchpad"

Uses image_mode="L", source="canvas", shape=(28, 28), invert_colors=True, interactive=True

gradio.Paint

"paint"

Uses source="canvas", tool="color-sketch", interactive=True

gradio.ImageMask

"imagemask"

Uses source="upload", tool="sketch", interactive=True

gradio.ImagePaint

"imagepaint"

Uses source="upload", tool="color-sketch", interactive=True

gradio.Pil

"pil"

Uses type="pil"

Methods

style

gradio.Image.style(ยทยทยท)

This method can be used to change the appearance of the Image component.


Parameter Description
height

int | None

default: None

Height of the image.

width

int | None

default: None

Width of the image.

change

gradio.Image.change(fn, ยทยทยท)

This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

every

float | None

default: None

Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.

edit

gradio.Image.edit(fn, ยทยทยท)

This event is triggered when the user edits the component (e.g. image) using the built-in editor. This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

every

float | None

default: None

Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.

clear

gradio.Image.clear(fn, ยทยทยท)

This event is triggered when the user clears the component (e.g. image or audio) using the X button for the component. This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

every

float | None

default: None

Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.

stream

gradio.Image.stream(fn, ยทยทยท)

This event is triggered when the user streams the component (e.g. a live webcam component). This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

every

float | None

default: None

Run this event 'every' number of seconds while the client connection is open. Interpreted in seconds. Queue must be enabled.

upload

gradio.Image.upload(fn, ยทยทยท)

This event is triggered when the user uploads a file into the component (e.g. when the user uploads a video into a video component). This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

batch

bool

default: False

If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.

max_batch_size

int

default: 4

Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)

preprocess

bool

default: True

If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).

postprocess

bool

default: True

If False, will not run postprocessing of component data before returning 'fn' output to the browser.

cancels

Dict[str, Any] | List[Dict[str, Any]] | None

default: None

A list of other events to cancel when this event is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method.

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 Image

Interpretation

gradio.Interpretation(component, ยทยทยท)

Used to create an interpretation widget for a component.


As input: this component does *not* accept input.

As output: expects a dict with keys "original" and "interpretation".

Parameter Description
component

Component

required

Which component to show in the interpretation widget.

visible

bool

default: True

Whether or not the interpretation is visible.

elem_id

str | None

default: None

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

elem_classes

List[str] | str | None

default: None

An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.

Class Interface String Shortcut Initialization

gradio.Interpretation

"interpretation"

Uses default values

Step-by-step Guides

No guides yet, contribute a guide about Interpretation

JSON

gradio.JSON(ยทยทยท)

Used to display arbitrary JSON output prettily.


As input: this component does *not* accept input.

As output: expects a str filepath to a file containing valid JSON -- or a list or dict that is valid JSON

from zipfile import ZipFile

import gradio as gr


def zip_to_json(file_obj):
    files = []
    with ZipFile(file_obj.name) as zfile:
        for zinfo in zfile.infolist():
            files.append(
                {
                    "name": zinfo.filename,
                    "file_size": zinfo.file_size,
                    "compressed_size": zinfo.compress_size,
                }
            )
    return files


demo = gr.Interface(zip_to_json, "file", "json")

if __name__ == "__main__":
    demo.launch()
Parameter Description
value

str | Dict | List | Callable | None

default: None

Default value. If callable, the function will be called whenever the app loads to set the initial value of the component.

label

str | None

default: None

component name in interface.

every

float | None

default: None

If `value` is a callable, run the function 'every' number of seconds while the client connection is open. Has no effect otherwise. Queue must be enabled. The event can be accessed (e.g. to cancel it) via this component's .load_event attribute.

show_label

bool

default: True

if True, will display label.

visible

bool

default: True

If False, component will be hidden.

elem_id

str | None

default: None

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

elem_classes

List[str] | str | None

default: None

An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.

Class Interface String Shortcut Initialization

gradio.JSON

"json"

Uses default values

Methods

style

gradio.JSON.style(ยทยทยท)

This method can be used to change the appearance of the JSON component.


Parameter Description
container

bool | None

default: None

If True, will place the JSON in a container - providing some extra padding around the border.

change

gradio.JSON.change(fn, ยทยทยท)

This event is triggered when the component's input value changes (e.g. when the user types in a textbox or uploads an image). This method can be used when this component is in a Gradio Blocks.


Parameter Description
fn

Callable | None

required

the function to wrap an interface around. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.

inputs

Component | List[Component] | Set[Component] | None

default: None

List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.

outputs

Component | List[Component] | None

default: None

List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.

api_name

str | None

default: None

Defining this parameter exposes the endpoint in the api docs

status_tracker

StatusTracker | None

default: None

scroll_to_output

bool

default: False

If True, will scroll to output component on completion

show_progress

bool | None

default: None

If True, will show progress animation while pending

queue

bool | None

default: None

If True, will place the request on the queue, if the queue exists

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