New to Gradio? Start here: Getting Started
See the Release History
Building Demos
Interface
gradio.Interface(···)
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
Optional[str | Component | List[str | Component]] 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
Optional[str | Component | List[str | Component]] 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
Optional[List[Any] | List[List[Any]] | str] 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
Optional[bool] 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
Optional[Callable | str] 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
Optional[str] 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
Optional[str] 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
Optional[str] 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
Optional[str] default: None |
path or url to image to use as display image when the web demo is shared on social media. |
theme
Optional[str] default: None |
Theme to use - right now, only "default" is supported. Can be set with the GRADIO_THEME environment variable. |
css
Optional[str] default: None |
custom css or path to custom css file to use with interface. |
allow_flagging
Optional[str] 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 prediction will be automatically flagged. If "manual", samples are flagged when the user clicks flag button. Can be set with environmental variable GRADIO_ALLOW_FLAGGING; otherwise defaults to "manual". |
flagging_options
List[str] default: None |
if provided, allows user to select from the list of options when flagging. Only applies if allow_flagging is "manual". |
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
Optional[bool] 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 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
Optional[bool] 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 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
Optional[Callable | Tuple[str, str] | List[Tuple[str, str]]] 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
Optional[str] 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
Optional[str] 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
Optional[int] 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 default: False |
If True, flagged data will be encrypted by key provided by creator at launch |
favicon_path
Optional[str] 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
Optional[str] 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
Optional[str] 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
Optional[str] 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. |
load
gradio.Interface.load(···)
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
Optional[str] default: None |
the source of the model: `models` or `spaces` (or leave empty if source is provided as a prefix in `name`) |
api_key
Optional[str] default: None |
optional access token for loading private Hugging Face Hub models or spaces. Find your token here: https://huggingface.co/settings/tokens |
alias
Optional[str] 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(···)
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
transformers.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 default: None |
If a comet_ml Experiment object is provided, will integrate with the experiment and appear on Comet dashboard |
wandb
ModuleType('wandb') default: None |
If the wandb module is provided, will integrate with it and appear on WandB dashboard |
mlflow
ModuleType('mlflow') 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(gr.Textbox(), gr.Image(), image_generator)
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 | str 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 default: True |
If True, all event listeners will use queueing by default. |
api_open
bool default: True |
If True, the REST routes of the backend will be open, allowing requests made directly to those endpoints to skip the queue. |
max_size
int | None default: None |
The maximum number of events the queue will store at any given moment. If the queue is full, new events will not be added and a user will receive a message saying that the queue is full. If None, the queue size will be unlimited. |
Step-by-step Guides
Flagging
A Gradio Interface includes a "Flag" button that appears underneath the output. By default, clicking on the Flag button sends the input and output data back to the machine where the gradio demo is running, and saves it to a CSV log file. But this default behavior can be changed. To set what happens when the Flag button is clicked, you pass an instance of a subclass of FlaggingCallback to the flagging_callback parameter in the Interface constructor. You can use one of the FlaggingCallback subclasses that are listed below, or you can create your own, which lets you do whatever you want with the data that is being flagged.
SimpleCSVLogger
gradio.SimpleCSVLogger(···)
A simplified implementation of the FlaggingCallback abstract class provided for illustrative purposes. Each flagged sample (both the input and output data) is logged to a CSV file on the machine running the gradio app.
Example Usage
import gradio as gr
def image_classifier(inp):
return {'cat': 0.3, 'dog': 0.7}
demo = gr.Interface(fn=image_classifier, inputs="image", outputs="label",
flagging_callback=SimpleCSVLogger())
Step-by-step Guides
No guides yet, contribute a guide about SimpleCSVLogger
CSVLogger
gradio.CSVLogger(···)
The default implementation of the FlaggingCallback abstract class. Each flagged sample (both the input and output data) is logged to a CSV file with headers on the machine running the gradio app.
Example Usage
import gradio as gr
def image_classifier(inp):
return {'cat': 0.3, 'dog': 0.7}
demo = gr.Interface(fn=image_classifier, inputs="image", outputs="label",
flagging_callback=CSVLogger())
Step-by-step Guides
HuggingFaceDatasetSaver
gradio.HuggingFaceDatasetSaver(···)
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
Optional[str] 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
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(···)
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
Optional[List[str]] default: None |
a list of tab names. If None, the tab names will be "Tab 1", "Tab 2", etc. |
theme
str default: "default" |
which theme to use - right now, only "default" is supported. |
analytics_enabled
Optional[bool] default: None |
whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable or default to True. |
css
Optional[str] default: None |
custom css or path to custom css file to apply to entire Blocks |
Parallel
gradio.Parallel(···)
Creates a new Interface consisting of multiple Interfaces in parallel (comparing their outputs). The Interfaces to put in Parallel must share the same input components (but can have different output components).
import gradio as gr
greeter_1 = gr.Interface(lambda name: f"Hello {name}!", inputs="textbox", outputs=gr.Textbox(label="Greeter 1"))
greeter_2 = gr.Interface(lambda name: f"Greetings {name}!", inputs="textbox", outputs=gr.Textbox(label="Greeter 2"))
demo = gr.Parallel(greeter_1, greeter_2)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
interfaces
required |
any number of Interface objects that are to be compared in parallel |
options
|
additional kwargs that are passed into the new Interface object to customize it |
Step-by-step Guides
Series
gradio.Series(···)
Creates a new Interface from multiple Interfaces in series (the output of one is fed as the input to the next, and so the input and output components must agree between the interfaces).
import gradio as gr
get_name = gr.Interface(lambda name: name, inputs="textbox", outputs="textbox")
prepend_hello = gr.Interface(lambda name: f"Hello {name}!", inputs="textbox", outputs="textbox")
append_nice = gr.Interface(lambda greeting: f"{greeting} Nice to meet you!",
inputs="textbox", outputs=gr.Textbox(label="Greeting"))
demo = gr.Series(get_name, prepend_hello, append_nice)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
interfaces
required |
any number of Interface objects that are to be connected in series |
options
|
additional kwargs that are passed into the new Interface object to customize it |
Step-by-step Guides
Blocks
with 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
str default: "default" |
which theme to use - right now, only "default" is supported. |
analytics_enabled
Optional[bool] 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 interface being created. |
title
str default: "Gradio" |
The tab title to display when this is opened in a browser window. |
css
Optional[str] default: None |
custom css or path to custom css file to apply to entire Blocks |
Methods
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
Optional[Callable] 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
Optional[List[Component]] 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
Optional[List[Component]] 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
AnyStr 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
Optional[str] 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
Optional[str] 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
Optional[str] 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
Optional[str] default: None |
Class Method - optional string used as the name of the loaded model instead of the default name (only applies if loading a Space running Gradio 2.x) |
Step-by-step Guides
Block Layouts
Customize the layout of your Blocks UI with the layout classes below.
Row
with 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
Optional[str] default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
Step-by-step Guides
Column
with 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
Optional[str] default: None |
An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles. |
Step-by-step Guides
Tab
with gradio.Tab():
Tab 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
Optional[int | str] default: None |
An optional identifier for the tab, required if you wish to control the selected tab from a predict function. |
elem_id
Optional[str] 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
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
Optional[str] 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(···)
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
Optional[str] 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
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.
Textbox
gradio.Textbox(···)
Creates a textarea for user to enter string input or display string output.
As input: passes textarea value as a str into the function.
As output: expects a str returned from function and sets textarea value to it.
Format expected for examples: a str representing the textbox input.
Supported events: change(), submit(), blur()
import gradio as gr
def greet(name):
return "Hello " + name + "!"
demo = gr.Interface(fn=greet, inputs="text", outputs="text")
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
Optional[str | Callable] default: "" |
default text to provide in textarea. If callable, the function will be called whenever the app loads to set the initial value of the component. |
lines
int default: 1 |
minimum number of line rows to provide in textarea. |
max_lines
int default: 20 |
maximum number of line rows to provide in textarea. |
placeholder
Optional[str] default: None |
placeholder hint to provide behind textarea. |
label
Optional[str] 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
Optional[bool] default: None |
if True, will be rendered as an editable textbox; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
Optional[str] 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. |
type
str default: "text" |
The type of textbox. One of: 'text', 'password', 'email', Default is 'text'. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"textbox" |
Uses default values |
|
"textarea" |
Uses lines=7 |
Methods
change
gradio.Textbox.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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.Textbox.submit(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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. |
blur
gradio.Textbox.blur(···)
This event is triggered when the component's is unfocused/blurred (e.g. when the user clicks outside of a textbox). This method can be used when this component is in a Gradio Blocks.
Parameter | Description |
---|---|
fn
Callable required |
Callable function |
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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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. |
style
gradio.Textbox.style(···)
This method can be used to change the appearance of the component.
Parameter | Description |
---|---|
container
Optional[bool] default: None |
If True, will place the component in a container - providing some extra padding around the border. |
Step-by-step Guides
Number
gradio.Number(···)
Creates a numeric field for user to enter numbers as input or display numeric output.
As input: passes field value as a float or int into the function, depending on `precision`.
As output: expects an int or float returned from the function and sets field value to it.
Format expected for examples: a float or int representing the number's value.
Supported events: change(), submit(), blur()
import gradio as gr
def tax_calculator(income, marital_status, assets):
tax_brackets = [(10, 0), (25, 8), (60, 12), (120, 20), (250, 30)]
total_deductible = sum(assets["Cost"])
taxable_income = income - total_deductible
total_tax = 0
for bracket, rate in tax_brackets:
if taxable_income > bracket:
total_tax += (taxable_income - bracket) * rate / 100
if marital_status == "Married":
total_tax *= 0.75
elif marital_status == "Divorced":
total_tax *= 0.8
return round(total_tax)
demo = gr.Interface(
tax_calculator,
[
"number",
gr.Radio(["Single", "Married", "Divorced"]),
gr.Dataframe(
headers=["Item", "Cost"],
datatype=["str", "number"],
label="Assets Purchased this Year",
),
],
"number",
examples=[
[10000, "Married", [["Suit", 5000], ["Laptop", 800], ["Car", 1800]]],
[80000, "Single", [["Suit", 800], ["Watch", 1800], ["Car", 800]]],
],
)
demo.launch()
Parameter | Description |
---|---|
value
Optional[float | Callable] default: None |
default value. If callable, the function will be called whenever the app loads to set the initial value of the component. |
label
Optional[str] 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
Optional[bool] default: None |
if True, will be editable; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
Optional[str] 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. |
precision
Optional[int] default: None |
Precision to round input/output to. If set to 0, will round to nearest integer and covert type to int. If None, no rounding happens. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"number" |
Uses default values |
Methods
change
gradio.Number.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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.Number.submit(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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. |
style
gradio.Number.style(···)
This method can be used to change the appearance of the component.
Parameter | Description |
---|---|
container
Optional[bool] default: None |
If True, will place the component in a container - providing some extra padding around the border. |
Step-by-step Guides
No guides yet, contribute a guide about Number
Slider
gradio.Slider(···)
Creates a slider that ranges from `minimum` to `maximum` with a step size of `step`.
As input: passes slider value as a float into the function.
As output: expects an int or float returned from function and sets slider value to it as long as it is within range.
Format expected for examples: A float or int representing the slider's value.
Supported events: change()
import gradio as gr
def sentence_builder(quantity, animal, place, activity_list, morning):
return f"""The {quantity} {animal}s 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),
gr.Dropdown(["cat", "dog", "bird"]),
gr.Radio(["park", "zoo", "road"]),
gr.CheckboxGroup(["ran", "swam", "ate", "slept"]),
gr.Checkbox(label="Is it 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 |
---|---|
minimum
float default: 0 |
minimum value for slider. |
maximum
float default: 100 |
maximum value for slider. |
value
Optional[float | Callable] default: None |
default value. If callable, the function will be called whenever the app loads to set the initial value of the component. Ignored if randomized=True. |
step
Optional[float] default: None |
increment between slider values. |
label
Optional[str] 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
Optional[bool] default: None |
if True, slider will be adjustable; if False, adjusting will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
Optional[str] 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. |
randomize
bool default: False |
If True, the value of the slider when the app loads is taken uniformly at random from the range given by the minimum and maximum. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"slider" |
Uses default values |
Methods
change
gradio.Slider.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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. |
style
gradio.Slider.style(···)
This method can be used to change the appearance of the slider.
Parameter | Description |
---|---|
container
Optional[bool] default: None |
If True, will place the component in a container - providing some extra padding around the border. |
Step-by-step Guides
Checkbox
gradio.Checkbox(···)
Creates a checkbox that can be set to `True` or `False`.
As input: passes the status of the checkbox as a bool into the function.
As output: expects a bool returned from the function and, if it is True, checks the checkbox.
Format expected for examples: a bool representing whether the box is checked.
Supported events: change()
import gradio as gr
def sentence_builder(quantity, animal, place, activity_list, morning):
return f"""The {quantity} {animal}s 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),
gr.Dropdown(["cat", "dog", "bird"]),
gr.Radio(["park", "zoo", "road"]),
gr.CheckboxGroup(["ran", "swam", "ate", "slept"]),
gr.Checkbox(label="Is it 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
Optional[str] 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
Optional[bool] 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
Optional[str] 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. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"checkbox" |
Uses default values |
Methods
change
gradio.Checkbox.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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. |
style
gradio.Checkbox.style(···)
This method can be used to change the appearance of the component.
Parameter | Description |
---|---|
container
Optional[bool] default: None |
If True, will place the component in a container - providing some extra padding around the border. |
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.
Supported events: change()
import gradio as gr
def sentence_builder(quantity, animal, place, activity_list, morning):
return f"""The {quantity} {animal}s 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),
gr.Dropdown(["cat", "dog", "bird"]),
gr.Radio(["park", "zoo", "road"]),
gr.CheckboxGroup(["ran", "swam", "ate", "slept"]),
gr.Checkbox(label="Is it 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
Optional[List[str]] default: None |
list of options to select from. |
value
List[str] | Callable 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
Optional[str] 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
Optional[bool] 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
Optional[str] 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. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"checkboxgroup" |
Uses default values |
Methods
change
gradio.CheckboxGroup.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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. |
style
gradio.CheckboxGroup.style(···)
This method can be used to change the appearance of the CheckboxGroup.
Parameter | Description |
---|---|
item_container
Optional[bool] default: None |
If True, will place the items in a container. |
container
Optional[bool] default: None |
If True, will place the component in a container - providing some extra padding around the border. |
Step-by-step Guides
No guides yet, contribute a guide about CheckboxGroup
Radio
gradio.Radio(···)
Creates a set of radio buttons of which only one can be selected.
As input: passes the value of the selected radio button as a str or its index as an int into the function, depending on `type`.
As output: expects a str corresponding to the value of the radio button to be selected.
Format expected for examples: a str representing the radio option to select.
Supported events: change()
import gradio as gr
def sentence_builder(quantity, animal, place, activity_list, morning):
return f"""The {quantity} {animal}s 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),
gr.Dropdown(["cat", "dog", "bird"]),
gr.Radio(["park", "zoo", "road"]),
gr.CheckboxGroup(["ran", "swam", "ate", "slept"]),
gr.Checkbox(label="Is it 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
Optional[List[str]] default: None |
list of options to select from. |
value
Optional[str | Callable] default: None |
the button selected by default. If None, no button is selected by default. If callable, the function will be called whenever the app loads to set the initial value of the component. |
type
str default: "value" |
Type of value to be returned by component. "value" returns the string of the choice selected, "index" returns the index of the choice selected. |
label
Optional[str] 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
Optional[bool] default: None |
if True, choices in this radio group will be selectable; if False, selection will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
Optional[str] 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. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"radio" |
Uses default values |
Methods
change
gradio.Radio.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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. |
style
gradio.Radio.style(···)
This method can be used to change the appearance of the radio component.
Parameter | Description |
---|---|
item_container
Optional[bool] default: None |
If True, will place items in a container. |
container
Optional[bool] default: None |
If True, will place the component in a container - providing some extra padding around the border. |
Step-by-step Guides
No guides yet, contribute a guide about Radio
Dropdown
gradio.Dropdown(···)
Creates a dropdown of which only one entry can be selected.
As input: passes the value of the selected dropdown entry as a str or its index as an int into the function, depending on `type`.
As output: expects a str corresponding to the value of the dropdown entry to be selected.
Format expected for examples: a str representing the drop down value to select.
Supported events: change()
import gradio as gr
def sentence_builder(quantity, animal, place, activity_list, morning):
return f"""The {quantity} {animal}s 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),
gr.Dropdown(["cat", "dog", "bird"]),
gr.Radio(["park", "zoo", "road"]),
gr.CheckboxGroup(["ran", "swam", "ate", "slept"]),
gr.Checkbox(label="Is it 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
Optional[List[str]] default: None |
list of options to select from. |
value
Optional[str | Callable] default: None |
default value selected in dropdown. If None, no value is selected by default. If callable, the function will be called whenever the app loads to set the initial value of the component. |
type
str default: "value" |
Type of value to be returned by component. "value" returns the string of the choice selected, "index" returns the index of the choice selected. |
label
Optional[str] 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
Optional[bool] default: None |
if True, choices in this dropdown will be selectable; if False, selection will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
Optional[str] 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. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"dropdown" |
Uses default values |
Methods
change
gradio.Dropdown.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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. |
style
gradio.Dropdown.style(···)
This method can be used to change the appearance of the Dropdown.
Parameter | Description |
---|---|
container
Optional[bool] default: None |
If True, will place the component in a container - providing some extra padding around the border. |
Step-by-step Guides
No guides yet, contribute a guide about Dropdown
Image
gradio.Image(···)
Creates an image component that can be used to upload/draw images (as an input) or display images (as an output).
As input: passes the uploaded image as a numpy.array, PIL.Image or str filepath depending on `type` -- unless `tool` is `sketch` AND source is one of `upload` or `webcam`. In these cases, a dict with keys `image` and `mask` is passed, and the format of the corresponding values depends on `type`.
As output: expects a numpy.array, PIL.Image or str or pathlib.Path filepath to an image and displays the image.
Format expected for examples: a str filepath to a local file that contains the image.
Supported events: change(), clear(), edit(), upload()
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")
])
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
Optional[str | PIL.Image | np.narray] 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] 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 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
Optional[str] 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
Optional[bool] 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
Optional[str] 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. |
mirror_webcam
bool default: True |
If True webcam will be mirrored. Default is True. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"image" |
Uses default values |
|
"webcam" |
Uses source="webcam", interactive=True |
|
"sketchpad" |
Uses image_mode="L", source="canvas", shape=(28, 28), invert_colors=True, interactive=True |
|
"paint" |
Uses source="canvas", tool="color-sketch", interactive=True |
|
"imagemask" |
Uses source="upload", tool="sketch", interactive=True |
|
"imagepaint" |
Uses source="upload", tool="color-sketch", interactive=True |
|
"pil" |
Uses type="pil" |
Methods
edit
gradio.Image.edit(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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. |
change
gradio.Image.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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(···)
This event is triggered when the user streams the component (e.g. a live webcam component)
Parameter | Description |
---|---|
fn
Callable required |
Callable function |
inputs
List[Component] required |
List of inputs |
outputs
List[Component] required |
List of outputs |
api_name
Optional[str] default: None |
|
preprocess
bool default: True |
|
postprocess
bool default: True |
change
gradio.Image.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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. |
style
gradio.Image.style(···)
This method can be used to change the appearance of the Image component.
Parameter | Description |
---|---|
height
Optional[int] default: None |
Height of the image. |
width
Optional[int] default: None |
Width of the image. |
Step-by-step Guides
Video
gradio.Video(···)
Creates a video component that can be used to upload/record videos (as an input) or display videos (as an output). For the video to be playable in the browser it must have a compatible container and codec combination. Allowed combinations are .mp4 with h264 codec, .ogg with theora codec, and .webm with vp9 codec. If the component detects that the output video would not be playable in the browser it will attempt to convert it to a playable mp4 video. If the conversion fails, the original video is returned.
As input: passes the uploaded video as a str filepath or URL whose extension can be modified by `format`.
As output: expects a str filepath to a video which is displayed.
Format expected for examples: a str filepath to a local file that contains the video.
Supported events: change(), clear(), play(), pause(), stop(), upload()
import gradio as gr
import os
def video_identity(video):
return video
demo = gr.Interface(video_identity,
gr.Video(),
"playable_video",
examples=[
os.path.join(os.path.dirname(__file__),
"video/video_sample.mp4")],
cache_examples=True)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
Optional[str | Callable] default: None |
A path or URL for the default value that Video component is going to take. If callable, the function will be called whenever the app loads to set the initial value of the component. |
format
Optional[str] default: None |
Format of video format to be returned by component, such as 'avi' or 'mp4'. Use 'mp4' to ensure browser playability. If set to None, video will keep uploaded format. |
source
str default: "upload" |
Source of video. "upload" creates a box where user can drop an video file, "webcam" allows user to record a video from their webcam. |
label
Optional[str] 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
Optional[bool] default: None |
if True, will allow users to upload a video; if False, can only be used to display videos. If not provided, this is inferred based on whether the component is used as an input or output. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
Optional[str] 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. |
mirror_webcam
bool default: True |
If True webcma will be mirrored. Default is True. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"video" |
Uses default values |
|
"playablevideo" |
Uses format="mp4" |
Methods
change
gradio.Video.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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.Video.clear(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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.Video.play(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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.Video.pause(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
Optional[AnyStr] default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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.Video.stop(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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. |
style
gradio.Video.style(···)
This method can be used to change the appearance of the video component.
Parameter | Description |
---|---|
height
Optional[int] default: None |
Height of the video. |
width
Optional[int] default: None |
Width of the video. |
Step-by-step Guides
No guides yet, contribute a guide about 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.
Supported events: change(), clear(), play(), pause(), stop(), upload()
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
Optional[str | Tuple[int, np.array] | Callable] 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
Optional[str] 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
Optional[bool] 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
Optional[str] 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. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"audio" |
Uses default values |
|
"microphone" |
Uses source="microphone" |
Methods
change
gradio.Audio.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
Optional[AnyStr] default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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(···)
This event is triggered when the user streams the component (e.g. a live webcam component)
Parameter | Description |
---|---|
fn
Callable required |
Callable function |
inputs
List[Component] required |
List of inputs |
outputs
List[Component] required |
List of outputs |
api_name
Optional[str] default: None |
|
preprocess
bool default: True |
|
postprocess
bool default: True |
style
gradio.Audio.style(···)
This method can be used to change the appearance of the audio component.
Step-by-step Guides
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.
Supported events: change(), clear(), upload()
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
Optional[str | List[str] | Callable] 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] default: None |
List of type of files to be uploaded. "file" allows any file to be uploaded, "image" allows only image files to be uploaded, "audio" allows only audio files to be uploaded, "video" allows only video files to be uploaded, "text" allows only text files to be uploaded. |
type
str default: "file" |
Type of value to be returned by component. "file" returns a temporary file object whose path can be retrieved by file_obj.name and original filename can be retrieved with file_obj.orig_name, "binary" returns an bytes object. |
label
Optional[str] 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
Optional[bool] 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
Optional[str] 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. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"file" |
Uses default values |
|
"files" |
Uses file_count="multiple" |
Methods
change
gradio.File.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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. |
style
gradio.File.style(···)
This method can be used to change the appearance of the file component.
Step-by-step Guides
No guides yet, contribute a guide about File
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.
Supported events: change()
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
Optional[List[List[Any]] | Callable] 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
Optional[List[str]] 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
Optional[int | Tuple[int, str]] 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
Optional[int] default: 20 |
Maximum number of rows to display at once. Set to None for infinite. |
max_cols
Optional[int] 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
Optional[str] 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
Optional[bool] 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
Optional[str] 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. |
wrap
bool default: False |
if True text in table cells will wrap when appropriate, if False the table will scroll horiztonally. Defaults to False. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"dataframe" |
Uses default values |
|
"numpy" |
Uses type="numpy" |
|
"matrix" |
Uses type="array" |
|
"list" |
Uses type="array", col_count=1 |
Methods
change
gradio.Dataframe.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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. |
style
gradio.Dataframe.style(···)
This method can be used to change the appearance of the DataFrame component.
Step-by-step Guides
No guides yet, contribute a guide about Dataframe
Timeseries
gradio.Timeseries(···)
Creates a component that can be used to upload/preview timeseries csv files or display a dataframe consisting of a time series graphically.
As input: passes the uploaded timeseries data as a pandas.DataFrame into the function
As output: expects a pandas.DataFrame or str path to a csv to be returned, which is then displayed as a timeseries graph
Format expected for examples: a str filepath of csv data with time series data.
Supported events: change()
import random
import os
import gradio as gr
def fraud_detector(card_activity, categories, sensitivity):
activity_range = random.randint(0, 100)
drop_columns = [
column for column in ["retail", "food", "other"] if column not in categories
]
if len(drop_columns):
card_activity.drop(columns=drop_columns, inplace=True)
return (
card_activity,
card_activity,
{"fraud": activity_range / 100.0, "not fraud": 1 - activity_range / 100.0},
)
demo = gr.Interface(
fraud_detector,
[
gr.Timeseries(x="time", y=["retail", "food", "other"]),
gr.CheckboxGroup(
["retail", "food", "other"], value=["retail", "food", "other"]
),
gr.Slider(1, 3),
],
[
"dataframe",
gr.Timeseries(x="time", y=["retail", "food", "other"]),
gr.Label(label="Fraud Level"),
],
examples=[
[os.path.join(os.path.dirname(__file__), "fraud.csv"), ["retail", "food", "other"], 1.0],
],
)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
Optional[str | Callable] default: None |
File path for the timeseries csv file. If callable, the function will be called whenever the app loads to set the initial value of the component. |
x
Optional[str] default: None |
Column name of x (time) series. None if csv has no headers, in which case first column is x series. |
y
str | List[str] default: None |
Column name of y series, or list of column names if multiple series. None if csv has no headers, in which case every column after first is a y series. |
colors
List[str] default: None |
an ordered list of colors to use for each line plot |
label
Optional[str] 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
Optional[bool] default: None |
if True, will allow users to upload a timeseries csv; if False, can only be used to display timeseries data. If not provided, this is inferred based on whether the component is used as an input or output. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
Optional[str] 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. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"timeseries" |
Uses default values |
Methods
change
gradio.Timeseries.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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. |
style
gradio.Timeseries.style(···)
This method can be used to change the appearance of the TimeSeries component.
Step-by-step Guides
No guides yet, contribute a guide about Timeseries
State
gradio.State(···)
Special hidden component that stores session state across runs of the demo by the same user. The value of the State variable is cleared when the user refreshes the page.
As input: No preprocessing is performed
As output: No postprocessing is performed
import random
import gradio as gr
def chat(message, history):
history = history or []
message = message.lower()
if message.startswith("how many"):
response = random.randint(1, 10)
elif message.startswith("how"):
response = random.choice(["Great", "Good", "Okay", "Bad"])
elif message.startswith("where"):
response = random.choice(["Here", "There", "Somewhere"])
else:
response = "I don't know"
history.append((message, response))
return history, history
chatbot = gr.Chatbot().style(color_map=("green", "pink"))
demo = gr.Interface(
chat,
["text", "state"],
[chatbot, "state"],
allow_flagging="never",
)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
Any default: None |
the initial value of the state. If callable, the function will be called whenever the app loads to set the initial value of the component. |
Step-by-step Guides
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
Supported events: click()
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 |
visible
bool default: True |
If False, component will be hidden. |
elem_id
Optional[str] 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. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"button" |
Uses default values |
Methods
click
gradio.Button.click(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
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. |
style
gradio.Button.style(···)
This method can be used to change the appearance of the button component.
Parameter | Description |
---|---|
full_width
Optional[bool] default: None |
If True, will expand to fill parent container. |
Step-by-step Guides
No guides yet, contribute a guide about Button
UploadButton
gradio.UploadButton(···)
Used to create an upload button, when cicked allows a user to upload files that satisfy the specified file type or generic files (if file_type not set).
As input: passes the uploaded file as a file-object or List[file-object] depending on `file_count` (or a bytes/Listbytes depending on `type`)
As output: expects function to return a str path to a file, or List[str] consisting of paths to files.
Format expected for examples: a str path to a local file that populates the component.
Supported events: click(), upload()
import gradio as gr
def upload_file(files):
file_paths = [file.name for file in files]
return file_paths
with gr.Blocks() as demo:
file_output = gr.File()
upload_button = gr.UploadButton("Click to Upload a File", file_types=["image", "video"], file_count="multiple")
upload_button.upload(upload_file, upload_button, file_output)
demo.launch()
Parameter | Description |
---|---|
label
str default: "Upload a File" |
Text to display on the button. Defaults to "Upload a File". |
value
Optional[str | List[str] | Callable] default: None |
Default text for the button to display. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
Optional[str] 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. |
type
str default: "file" |
Type of value to be returned by component. "file" returns a temporary file object whose path can be retrieved by file_obj.name and original filename can be retrieved with file_obj.orig_name, "binary" returns an bytes object. |
file_count
str default: "single" |
if single, allows user to upload one file. If "multiple", user uploads multiple files. If "directory", user uploads all files in selected directory. Return type will be list for each file in case of "multiple" or "directory". |
file_types
List[str] default: None |
List of type of files to be uploaded. "file" allows any file to be uploaded, "image" allows only image files to be uploaded, "audio" allows only audio files to be uploaded, "video" allows only video files to be uploaded, "text" allows only text files to be uploaded. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"uploadbutton" |
Uses default values |
Methods
click
gradio.UploadButton.click(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
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.UploadButton.upload(···)
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 required |
Callable function |
inputs
List[Component] required |
List of inputs |
outputs
Component | List[Component] | None default: None |
List of outputs |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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
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. |
style
gradio.UploadButton.style(···)
This method can be used to change the appearance of the button component.
Parameter | Description |
---|---|
full_width
Optional[bool] default: None |
If True, will expand to fill parent container. |
Step-by-step Guides
No guides yet, contribute a guide about UploadButton
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.
Supported events: change(), submit()
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 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
Optional[str] 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
Optional[bool] 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
Optional[str] 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. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"colorpicker" |
Uses default values |
Methods
change
gradio.ColorPicker.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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. |
style
gradio.ColorPicker.style(···)
This method can be used to change the appearance of the component.
Parameter | Description |
---|---|
container
Optional[bool] default: None |
If True, will place the component in a container - providing some extra padding around the border. |
Step-by-step Guides
No guides yet, contribute a guide about ColorPicker
Label
gradio.Label(···)
Displays a classification label, along with confidence scores of top categories, if provided.
As input: this component does *not* accept input.
As output: expects a Dict[str, float] of classes and confidences, or str with just the class or an int/float for regression outputs, or a str path to a .json file containing a json dictionary in the structure produced by Label.postprocess().
Supported events: change()
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
Optional[Dict[str, float] | str | float | Callable] default: None |
Default value to show in the component. If a str or number is provided, simply displays the string or number. If a {Dict[str, float]} of classes and confidences is provided, displays the top class on top and the `num_top_classes` below, along with their confidence bars. If callable, the function will be called whenever the app loads to set the initial value of the component. |
num_top_classes
Optional[int] default: None |
number of most confident classes to show. |
label
Optional[str] 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
Optional[str] 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. |
color
Optional[str] default: None |
The background color of the label (either a valid css color name or hexadecimal string). |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"label" |
Uses default values |
Methods
change
gradio.Label.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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. |
style
gradio.Label.style(···)
This method can be used to change the appearance of the label component.
Parameter | Description |
---|---|
container
Optional[bool] default: None |
If True, will add a container to the label - providing some extra padding around the border. |
Step-by-step Guides
HighlightedText
gradio.HighlightedText(···)
Displays text that contains spans that are highlighted by category or numerical value.
As input: this component does *not* accept input.
As output: expects a List[Tuple[str, float | str]]] consisting of spans of text and their associated labels, or a Dict with two keys: (1) "text" whose value is the complete text, and "entities", which is a list of dictionaries, each of which have the keys: "entity" (consisting of the entity label), "start" (the character index where the label starts), and "end" (the character index where the label ends). Entities should not overlap.
Supported events: change()
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="Initial text",
lines=3,
value="The quick brown fox jumped over the lazy dogs.",
),
gr.Textbox(
label="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"}),
)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
Optional[List[Tuple[str, str | float | None]] | Dict | Callable] 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] 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
Optional[str] 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
Optional[str] 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. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"highlightedtext" |
Uses default values |
Methods
change
gradio.HighlightedText.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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. |
style
gradio.HighlightedText.style(···)
This method can be used to change the appearance of the HighlightedText component.
Parameter | Description |
---|---|
color_map
Optional[Dict[str, str]] default: None |
Map between category and respective colors. |
container
Optional[bool] default: None |
If True, will place the component in a container - providing some extra padding around the border. |
Step-by-step Guides
JSON
gradio.JSON(···)
Used to display arbitrary JSON output prettily.
As input: this component does *not* accept input.
As output: expects a valid JSON str -- or a list or dict that is JSON serializable.
Supported events: change()
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
Optional[str | Callable] default: None |
Default value. If callable, the function will be called whenever the app loads to set the initial value of the component. |
label
Optional[str] 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
Optional[str] 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. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"json" |
Uses default values |
Methods
change
gradio.JSON.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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. |
style
gradio.JSON.style(···)
This method can be used to change the appearance of the JSON component.
Parameter | Description |
---|---|
container
Optional[bool] default: None |
If True, will place the JSON in a container - providing some extra padding around the border. |
Step-by-step Guides
No guides yet, contribute a guide about JSON
HTML
gradio.HTML(···)
Used to display arbitrary HTML output.
As input: this component does *not* accept input.
As output: expects a valid HTML str.
Supported events: change()
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
Optional[str] 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
Optional[str] 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. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"html" |
Uses default values |
Methods
change
gradio.HTML.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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
Gallery
gradio.Gallery(···)
Used to display a list of images as a gallery that can be scrolled through.
As input: this component does *not* accept input.
As output: expects a list of images in any format, List[numpy.array | PIL.Image | str], or a List of (image, str caption) tuples and displays them.
# This demo needs to be run from the repo folder.
# python demo/fake_gan/run.py
import os
import random
import gradio as gr
def fake_gan():
images = [
(random.choice(
[
"https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80",
"https://images.unsplash.com/photo-1554151228-14d9def656e4?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=386&q=80",
"https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aHVtYW4lMjBmYWNlfGVufDB8fDB8fA%3D%3D&w=1000&q=80",
"https://images.unsplash.com/photo-1546456073-92b9f0a8d413?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80",
"https://images.unsplash.com/photo-1601412436009-d964bd02edbc?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=464&q=80",
]
), f"label {i}" if i != 0 else "label" * 50)
for i in range(3)
]
return images
with gr.Blocks() as demo:
with gr.Column(variant="panel"):
with gr.Row(variant="compact"):
text = gr.Textbox(
label="Enter your prompt",
show_label=False,
max_lines=1,
placeholder="Enter your prompt",
).style(
container=False,
)
btn = gr.Button("Generate image").style(full_width=False)
gallery = gr.Gallery(
label="Generated images", show_label=False, elem_id="gallery"
).style(grid=[2], height="auto")
btn.click(fake_gan, None, gallery)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
Optional[List[np.ndarray | PIL.Image | str] | Callable] default: None |
List of images to display in the gallery by default. If callable, the function will be called whenever the app loads to set the initial value of the component. |
label
Optional[str] 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
Optional[str] 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. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"gallery" |
Uses default values |
Methods
style
gradio.Gallery.style(···)
This method can be used to change the appearance of the gallery component.
Parameter | Description |
---|---|
grid
Optional[int | Tuple] default: None |
Represents the number of images that should be shown in one row, for each of the six standard screen sizes (<576px, <768px, <992px, <1200px, <1400px, >1400px). if fewer that 6 are given then the last will be used for all subsequent breakpoints |
height
Optional[str] default: None |
Height of the gallery. |
container
Optional[bool] default: None |
If True, will place gallery in a container - providing some extra padding around the border. |
Step-by-step Guides
No guides yet, contribute a guide about Gallery
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 a List[Tuple[str, str]], a list of tuples with user inputs and responses as strings of HTML.
Supported events: change()
import random
import gradio as gr
def chat(message, history):
history = history or []
message = message.lower()
if message.startswith("how many"):
response = random.randint(1, 10)
elif message.startswith("how"):
response = random.choice(["Great", "Good", "Okay", "Bad"])
elif message.startswith("where"):
response = random.choice(["Here", "There", "Somewhere"])
else:
response = "I don't know"
history.append((message, response))
return history, history
chatbot = gr.Chatbot().style(color_map=("green", "pink"))
demo = gr.Interface(
chat,
["text", "state"],
[chatbot, "state"],
allow_flagging="never",
)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
Optional[List[Tuple[str, str]] | Callable] 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] default: None |
|
label
Optional[str] 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
Optional[str] 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. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"chatbot" |
Uses default values |
Methods
change
gradio.Chatbot.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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. |
style
gradio.Chatbot.style(···)
This method can be used to change the appearance of the Chatbot component.
Parameter | Description |
---|---|
color_map
Optional[List[str, str]] default: None |
List containing colors to apply to chat bubbles. |
Step-by-step Guides
No guides yet, contribute a guide about Chatbot
Model3D
gradio.Model3D(···)
Component allows users to upload or view 3D Model files (.obj, .glb, or .gltf).
As input: This component passes the uploaded file as a str filepath.
As output: expects function to return a str path to a file of type (.obj, glb, or .gltf)
Supported events: change(), clear(), edit()
import gradio as gr
import os
def load_mesh(mesh_file_name):
return mesh_file_name, mesh_file_name
demo = gr.Interface(
fn=load_mesh,
inputs=gr.Model3D(),
outputs=[
gr.Model3D(
clear_color=[0.0, 0.0, 0.0, 0.0], label="3D Model"),
gr.File(label="Download 3D Model")
],
examples=[
[os.path.join(os.path.dirname(__file__), "files/Bunny.obj")],
[os.path.join(os.path.dirname(__file__), "files/Duck.glb")],
[os.path.join(os.path.dirname(__file__), "files/Fox.gltf")],
[os.path.join(os.path.dirname(__file__), "files/face.obj")],
],
)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
Optional[str | Callable] default: None |
path to (.obj, glb, or .gltf) file to show in model3D viewer. If callable, the function will be called whenever the app loads to set the initial value of the component. |
clear_color
List[float] default: None |
background color of scene |
label
Optional[str] 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
Optional[str] 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. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"model3d" |
Uses default values |
Methods
change
gradio.Model3D.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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.Model3D.edit(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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.Model3D.clear(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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. |
style
gradio.Model3D.style(···)
This method can be used to change the appearance of the Model3D component.
Step-by-step Guides
Plot
gradio.Plot(···)
Used to display various kinds of plots (matplotlib, plotly, or bokeh are supported)
As input: this component does *not* accept input.
As output: expects either a matplotlib.figure.Figure, a plotly.graph_objects._figure.Figure, or a dict corresponding to a bokeh plot (json_item format)
Supported events: change(), clear()
import altair as alt
import gradio as gr
import numpy as np
import pandas as pd
from vega_datasets import data
def make_plot(plot_type):
if plot_type == "scatter_plot":
cars = data.cars()
return alt.Chart(cars).mark_point().encode(
x='Horsepower',
y='Miles_per_Gallon',
color='Origin',
)
elif plot_type == "heatmap":
# Compute x^2 + y^2 across a 2D grid
x, y = np.meshgrid(range(-5, 5), range(-5, 5))
z = x ** 2 + y ** 2
# Convert this grid to columnar data expected by Altair
source = pd.DataFrame({'x': x.ravel(),
'y': y.ravel(),
'z': z.ravel()})
return alt.Chart(source).mark_rect().encode(
x='x:O',
y='y:O',
color='z:Q'
)
elif plot_type == "us_map":
states = alt.topo_feature(data.us_10m.url, 'states')
source = data.income.url
return alt.Chart(source).mark_geoshape().encode(
shape='geo:G',
color='pct:Q',
tooltip=['name:N', 'pct:Q'],
facet=alt.Facet('group:N', columns=2),
).transform_lookup(
lookup='id',
from_=alt.LookupData(data=states, key='id'),
as_='geo'
).properties(
width=300,
height=175,
).project(
type='albersUsa'
)
elif plot_type == "interactive_barplot":
source = data.movies.url
pts = alt.selection(type="single", encodings=['x'])
rect = alt.Chart(data.movies.url).mark_rect().encode(
alt.X('IMDB_Rating:Q', bin=True),
alt.Y('Rotten_Tomatoes_Rating:Q', bin=True),
alt.Color('count()',
scale=alt.Scale(scheme='greenblue'),
legend=alt.Legend(title='Total Records')
)
)
circ = rect.mark_point().encode(
alt.ColorValue('grey'),
alt.Size('count()',
legend=alt.Legend(title='Records in Selection')
)
).transform_filter(
pts
)
bar = alt.Chart(source).mark_bar().encode(
x='Major_Genre:N',
y='count()',
color=alt.condition(pts, alt.ColorValue("steelblue"), alt.ColorValue("grey"))
).properties(
width=550,
height=200
).add_selection(pts)
plot = alt.vconcat(
rect + circ,
bar
).resolve_legend(
color="independent",
size="independent"
)
return plot
elif plot_type == "radial":
source = pd.DataFrame({"values": [12, 23, 47, 6, 52, 19]})
base = alt.Chart(source).encode(
theta=alt.Theta("values:Q", stack=True),
radius=alt.Radius("values", scale=alt.Scale(type="sqrt", zero=True, rangeMin=20)),
color="values:N",
)
c1 = base.mark_arc(innerRadius=20, stroke="#fff")
c2 = base.mark_text(radiusOffset=10).encode(text="values:Q")
return c1 + c2
elif plot_type == "multiline":
source = data.stocks()
highlight = alt.selection(type='single', on='mouseover',
fields=['symbol'], nearest=True)
base = alt.Chart(source).encode(
x='date:T',
y='price:Q',
color='symbol:N'
)
points = base.mark_circle().encode(
opacity=alt.value(0)
).add_selection(
highlight
).properties(
width=600
)
lines = base.mark_line().encode(
size=alt.condition(~highlight, alt.value(1), alt.value(3))
)
return points + lines
with gr.Blocks() as demo:
button = gr.Radio(label="Plot type",
choices=['scatter_plot', 'heatmap', 'us_map',
'interactive_barplot', "radial", "multiline"], value='scatter_plot')
plot = gr.Plot(label="Plot")
button.change(make_plot, inputs=button, outputs=[plot])
demo.load(make_plot, inputs=[button], outputs=[plot])
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
Optional[Callable] default: None |
Optionally, supply a default plot object to display, must be a matplotlib, plotly, altair, or bokeh figure, or a callable. If callable, the function will be called whenever the app loads to set the initial value of the component. |
label
Optional[str] 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
Optional[str] 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. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"plot" |
Uses default values |
Methods
change
gradio.Plot.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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.Plot.clear(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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
ScatterPlot
gradio.ScatterPlot(···)
Create a scatter plot.
As input: this component does *not* accept input.
As output: expects a pandas dataframe with the data to plot.
Supported events: change(), clear()
import gradio as gr
from scatter_plot_demo import scatter_plot
with gr.Blocks() as demo:
with gr.Tabs():
with gr.TabItem("Scatter Plot"):
scatter_plot.render()
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
Optional[pd.DataFrame | Callable] default: None |
The pandas dataframe containing the data to display in a scatter plot, or a callable. If callable, the function will be called whenever the app loads to set the initial value of the component. |
x
Optional[str] default: None |
Column corresponding to the x axis. |
y
Optional[str] default: None |
Column corresponding to the y axis. |
color
Optional[str] default: None |
The column to determine the point color. If the column contains numeric data, gradio will interpolate the column data so that small values correspond to light colors and large values correspond to dark values. |
size
Optional[str] default: None |
The column used to determine the point size. Should contain numeric data so that gradio can map the data to the point size. |
shape
Optional[str] default: None |
The column used to determine the point shape. Should contain categorical data. Gradio will map each unique value to a different shape. |
title
Optional[str] default: None |
The title to display on top of the chart. |
tooltip
Optional[List[str] | str] default: None |
The column (or list of columns) to display on the tooltip when a user hovers a point on the plot. |
x_title
Optional[str] default: None |
The title given to the x axis. By default, uses the value of the x parameter. |
y_title
Optional[str] default: None |
The title given to the y axis. By default, uses the value of the y parameter. |
color_legend_title
Optional[str] default: None |
The title given to the color legend. By default, uses the value of color parameter. |
size_legend_title
Optional[str] default: None |
The title given to the size legend. By default, uses the value of the size parameter. |
shape_legend_title
Optional[str] default: None |
The title given to the shape legend. By default, uses the value of the shape parameter. |
height
Optional[int] default: None |
The height of the plot in pixels. |
width
Optional[int] default: None |
The width of the plot in pixels. |
caption
Optional[str] default: None |
The (optional) caption to display below the plot. |
interactive
Optional[bool] default: True |
Whether users should be able to interact with the plot by panning or zooming with their mouse or trackpad. |
label
Optional[str] default: None |
The (optional) label to display on the top left corner of the plot. |
every
float | None default: None |
|
show_label
bool default: True |
Whether the label should be displayed. |
visible
bool default: True |
Whether the plot should be visible. |
elem_id
Optional[str] default: None |
Unique id used for custom css targetting. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"scatterplot" |
Uses default values |
Methods
change
gradio.ScatterPlot.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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.ScatterPlot.clear(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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 ScatterPlot
Markdown
gradio.Markdown(···)
Used to render arbitrary Markdown output. Can also render latex enclosed by dollar signs.
As input: this component does *not* accept input.
As output: expects a valid str that can be rendered as Markdown.
Supported events: change()
import gradio as gr
def welcome(name):
return f"Welcome to Gradio, {name}!"
with gr.Blocks() as demo:
gr.Markdown(
"""
# Hello World!
Start typing below to see the output.
""")
inp = gr.Textbox(placeholder="What is your name?")
out = gr.Textbox()
inp.change(welcome, inp, out)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
value
str | Callable default: "" |
Value to show in Markdown component. If callable, the function will be called whenever the app loads to set the initial value of the component. |
visible
bool default: True |
If False, component will be hidden. |
elem_id
Optional[str] 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. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"markdown" |
Uses default values |
Methods
change
gradio.Markdown.change(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
Optional[bool] 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
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.
Supported events: click()
Parameter | Description |
---|---|
label
Optional[str] 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]] 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
Optional[List[str]] 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 |
visible
bool default: True |
If False, component will be hidden. |
elem_id
Optional[str] 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. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"dataset" |
Uses default values |
Methods
click
gradio.Dataset.click(···)
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 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 inputs. If the function returns no outputs, this should be an empty list. |
api_name
AnyStr default: None |
Defining this parameter exposes the endpoint in the api docs |
status_tracker
Optional[StatusTracker] default: None |
|
scroll_to_output
bool default: False |
If True, will scroll to output component on completion |
show_progress
bool default: True |
If True, will show progress animation while pending |
queue
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. |
style
gradio.Dataset.style(···)
This method can be used to change the appearance of the Dataset component.
Step-by-step Guides
No guides yet, contribute a guide about Dataset
Interpretation
gradio.Interpretation(···)
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
Optional[str] 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. |
Class | Interface String Shortcut | Initialization |
---|---|---|
|
"interpretation" |
Uses default values |
Step-by-step Guides
Components Helpers
Gradio includes helper classes that abstract over existing components. The goal of these classes is to help you add common functionality to your app without having to repeatedly create the same components and event listeners.
make_waveform
gradio.make_waveform(···)
Generates a waveform video from an audio file. Useful for creating an easy to share audio visualization. The output should be passed into a `gr.Video` component.
Parameter | Description |
---|---|
audio
str | Tuple[int, np.ndarray] required |
Audio file path or tuple of (sample_rate, audio_data) |
bg_color
str default: "#f3f4f6" |
Background color of waveform (ignored if bg_image is provided) |
bg_image
str default: None |
Background image of waveform |
fg_alpha
float default: 0.75 |
Opacity of foreground waveform |
bars_color
str | Tuple[str, str] default: ('#fbbf24', '#ea580c') |
Color of waveform bars. Can be a single color or a tuple of (start_color, end_color) of gradient |
bar_count
int default: 50 |
Number of bars in waveform |
bar_width
float default: 0.6 |
Width of bars in waveform. 1 represents full width, 0.5 represents half width, etc. |
Step-by-step Guides
No guides yet, contribute a guide about make_waveform
Examples
gradio.Examples(···)
This class is a wrapper over the Dataset component and can be used to create Examples for Blocks / Interfaces. Populates the Dataset component with examples and assigns event listener so that clicking on an example populates the input/output components. Optionally handles example caching for fast inference.
import gradio as gr
import os
def combine(a, b):
return a + " " + b
def mirror(x):
return x
with gr.Blocks() as demo:
txt = gr.Textbox(label="Input", lines=2)
txt_2 = gr.Textbox(label="Input 2")
txt_3 = gr.Textbox(value="", label="Output")
btn = gr.Button(value="Submit")
btn.click(combine, inputs=[txt, txt_2], outputs=[txt_3])
with gr.Row():
im = gr.Image()
im_2 = gr.Image()
btn = gr.Button(value="Mirror Image")
btn.click(mirror, inputs=[im], outputs=[im_2])
gr.Markdown("## Text Examples")
gr.Examples(
[["hi", "Adam"], ["hello", "Eve"]],
[txt, txt_2],
txt_3,
combine,
cache_examples=True,
)
gr.Markdown("## Image Examples")
gr.Examples(
examples=[os.path.join(os.path.dirname(__file__), "lion.jpg")],
inputs=im,
outputs=im_2,
fn=mirror,
cache_examples=True,
)
if __name__ == "__main__":
demo.launch()
Parameter | Description |
---|---|
examples
List[Any] | List[List[Any]] | str required |
example inputs that can be clicked to populate specific components. Should be nested list, in which the outer list consists of samples and each inner list consists of an input corresponding to each input component. A string path to a directory of examples can also be provided but it should be within the directory with the python file running the gradio app. If there are multiple input components and a directory is provided, a log.csv file must be present in the directory to link corresponding inputs. |
inputs
IOComponent | List[IOComponent] required |
the component or list of components corresponding to the examples |
outputs
Optional[IOComponent | List[IOComponent]] default: None |
optionally, provide the component or list of components corresponding to the output of the examples. Required if `cache` is True. |
fn
Optional[Callable] default: None |
optionally, provide the function to run to generate the outputs corresponding to the examples. Required if `cache` is True. |
cache_examples
bool default: False |
if True, caches examples for fast runtime. If True, then `fn` and `outputs` need to be provided |
examples_per_page
int default: 10 |
how many examples to show per page (this parameter currently has no effect) |
label
str default: "Examples" |
the label to use for the examples component (by default, "Examples") |
elem_id
Optional[str] default: None |
an optional string that is assigned as the id of this component in the HTML DOM. |
run_on_click
bool default: False |
if cache_examples is False, clicking on an example does not run the function when an example is clicked. Set this to True to run the function when an example is clicked. Has no effect if cache_examples is True. |
preprocess
bool default: True |
if True, preprocesses the example input before running the prediction function and caching the output. Only applies if cache_examples is True. |
postprocess
bool default: True |
if True, postprocesses the example output after running the prediction function and before caching. Only applies if cache_examples is True. |
batch
bool default: False |
If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. Used only if cache_examples is True. |
Step-by-step Guides
Update
When a function passed into a Gradio Interface or a Blocks events returns a typical value, it updates the value of the output component. But it is also possible to update the properties of an output component (such as the number of lines of a `Textbox` or the visibility of an `Image`) by returning the component's `update()` function, which takes as parameters any of the constructor parameters for that component. Here's an example:
update
gradio.update(···)
Updates component properties. This is a shorthand for using the update method on a component. For example, rather than using gr.Number.update(...) you can just use gr.update(...). Note that your editor's autocompletion will suggest proper parameters if you use the update method on the component.
Example Usage
# Blocks Example
import gradio as gr
with gr.Blocks() as demo:
radio = gr.Radio([1, 2, 4], label="Set the value of the number")
number = gr.Number(value=2, interactive=True)
radio.change(fn=lambda value: gr.update(value=value), inputs=radio, outputs=number)
demo.launch()
# Interface example
import gradio as gr
def change_textbox(choice):
if choice == "short":
return gr.Textbox.update(lines=2, visible=True)
elif choice == "long":
return gr.Textbox.update(lines=8, visible=True)
else:
return gr.Textbox.update(visible=False)
gr.Interface(
change_textbox,
gr.Radio(
["short", "long", "none"], label="What kind of essay would you like to write?"
),
gr.Textbox(lines=2),
live=True,
).launch()
Parameter | Description |
---|---|
kwargs
required |
Key-word arguments used to update the component's properties. |
Routes
Gradio includes some helper functions for exposing and interacting with the FastAPI app used to run your demo.
Request
gradio.Request(···)
A Gradio request object that can be used to access the request headers, cookies, query parameters and other information about the request from within the prediction function. The class is a thin wrapper around the fastapi.Request class. Attributes of this class include: `headers`, `client`, `query_params`, and `path_params`,
Example Usage
import gradio as gr
def echo(name, request: gr.Request):
print("Request headers dictionary:", request.headers)
print("IP address:", request.client.host)
return name
io = gr.Interface(echo, "textbox", "textbox").launch()
Parameter | Description |
---|---|
request
fastapi.Request | None default: None |
mount_gradio_app
gradio.mount_gradio_app(···)
Mount a gradio.Blocks to an existing FastAPI application.
Example Usage
from fastapi import FastAPI
import gradio as gr
app = FastAPI()
@app.get("/")
def read_main():
return {"message": "This is your main app"}
io = gr.Interface(lambda x: "Hello, " + x + "!", "textbox", "textbox")
app = gr.mount_gradio_app(app, io, path="/gradio")
# Then run `uvicorn run:app` from the terminal and navigate to http://localhost:8000/gradio.
Parameter | Description |
---|---|
app
fastapi.FastAPI required |
The parent FastAPI application. |
blocks
gradio.Blocks required |
The blocks object we want to mount to the parent app. |
path
str required |
The path at which the gradio application will be mounted. |
gradio_api_url
Optional[str] default: None |
The full url at which the gradio app will run. This is only needed if deploying to Huggingface spaces of if the websocket endpoints of your deployed app are on a different network location than the gradio app. If deploying to spaces, set gradio_api_url to 'http://localhost:7860/' |