You are on page 1of 550

Custom Components GalleryNEW Explore

<§, gradio =

New to Gradio? Start here: Getting Started See the Release History

C h a tIn te rfa ce

Interface

gradio.Interface(fn, inputs, outputs, •••)

Description
In terface is G ra d io 's m a in h ig h -le v e l cla ss, a n d a llo w s yo u to cre a te a w e b -b a s e d

GUI / d e m o a ro u n d a m a c h in e le a rn in g m o d e l (or a n y P y th o n fu n c tio n ) in a fe w

lin e s o f co d e . You m u s t s p e c ify th re e p a ra m e te rs: (1) th e fu n c tio n to cre a te a GUI

fo r (2) th e d e s ire d in p u t c o m p o n e n ts a n d (3) th e d e s ire d o u t p u t c o m p o n e n ts .

A d d it io n a l p a ra m e te rs can be u se d to c o n tro l th e a p p e a ra n c e a n d b e h a v io r o f th e

dem o.

Exampíe 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()

Initiaíization
Parameter Description

fn The function to wrap an interface around. Often a

Callable m achine learning m odel's prediction function.

required Each parameter of the function corresponds to one

input com ponent, and the function should return a

single value or a tuple of values, with each elem ent

in the tuple corresponding to one output

component.

in p u t s A single Gradio com ponent, or list of Gradio

str | Component |list[str | com ponents. Com ponents can either be passed as

Component] |None instantiated objects, or referred to by their string

required shortcuts. The num ber of input com ponents

should match the num ber of parameters in fn. If

set to None, then only the output com ponents w ill

be displayed.

o u tp u ts A single Gradio com ponent, or list of Gradio

str | Component |list[str | com ponents. Com ponents can either be passed as

Component] | None instantiated objects, or referred to by their string

required shortcuts. The num ber of output com ponents

should match the num ber of values returned by fn.

If set to None, then only the input com ponents w ill

be displayed.

e x a m p le s Sam ple inputs for the function; if provided, appear

list[Any] | list[list[Any]] |str | None below the UI com ponents and can be clicked to

default: None populate the interface. Should be nested list, in

which the outer list consists of sam ples and each

inner list consists of an input corresponding to

each input com ponent. A string path to a directory


Parameter Description

of examples can also be provided, but it should be

w ithin the directory with the python file running

the gradio app. If there are m últiple input

com ponents and a directory is provided, a log.csv

file must be present in the directory to link

corresponding inputs.

c a c h e _ e x a m p le s If True, caches examples in the server for fast

bool | Literal['lazy'] | None runtime in examples. If "lazy", then examples are

default: None cached after their first use. If f n is a generator

function, then the last yielded value w ill be used as

the output. Can also be set by the

GRADIO_CACHE_EXAMPLES environm ent variable,

which takes a case-insensitive value, one of:

"tru e ", " f a ls e " , " l a z y " . The default option

in HuggingFace Spaces is True. The default option

elsewhere is False.

e x a m p le s _ p e r _ p a g e If examples are provided, how many to display per

int page.

default: 10

liv e W hether the interface should autom atically rerun if

bool any of the inputs change.

default: False

t it le A title for the interface; if provided, appears above

str 1None the input and output com ponents in large font.

default: None Also used as the tab title when opened in a

browser window.
Parameter Description

d e s c r ip t io n A description for the interface; if provided, appears

str | None above the input and output com ponents and

default: None beneath the title in regular font. Accepts

Markdown and HTML content.

a r t ic le An expanded article explaining the interface; if

str 1None provided, appears below the input and output

default: None com ponents in regular font. Accepts Markdown

and HTML content. If it is an HTTP(S) link to a

dow nloadable remote file, the content of this file is

displayed.

t h u m b n a il String path or url to image to use as display image

str 1None when the web dem o is shared on social media.

default: None

th e m e A Theme object or a string representing a theme. If

Theme |str | None a string, w ill look for a built-in theme with that

default: None name (e.g. "soft" or "default"), or w ill attempt to

load a theme from the Hugging Face Hub (e.g.

"gradio/m onochrom e"). If None, w ill use the

Default theme.

css Custom css as a string or path to a css file. This css

str 1None w ill be included in the demo webpage.

default: None

a llo w _ f la g g in g One of "never", "auto", or "manual". If "never" or

Literal['never'] | Literal['auto'] | "auto", users w ill not see a button to flag an input

Literal['m anual'] | None and output. If "manual", users w ill see a button to
Parameter Description

default: None flag. If "auto", every input the user subm its w ill be

autom atically flagged, along with the generated

output. If "manual", both the input and outputs are

flagged when the user clicks flag button. This

parameter can be set with environm ental variable

GRADIO_ALLOW_FLAGGING; otherwise defaults to

"manual".

f la g g in g _ o p t io n s If provided, allows user to select from the list of

list[str] | list[tuple[str, str]] | None options when flagging. Only applies if

default: None allow_flagging is "manual". Can either be a list of

tuples of the form (label, value), where label is the

string that w ill be displayed on the button and

value is the string that w ill be stored in the flagging

CSV; or it can be a list of strings ["X", "Y"], in which

case the values w ill be the list of strings and the

labels w ill ["Flag as X", "Flag as Y"], etc.

f la g g in g _ d ir What to name the directory where flagged data is

str stored.

default: "flagged"

f la g g in g _ c a llb a c k None or an instance of a subclass of

FlaggingCallback | None FlaggingCallback which w ill be called when a

default: None sam ple is flagged. If set to None, an instance of

gradio.flagging.CSVLogger w ill be created and logs

w ill be saved to a local CSV file in flagging_dir.

Default to None.
Parameter Description

a n a ly t ic s _ e n a b le d Whether to allow basic telemetry. If None, will use

bool |None GRADIO_ANALYTICS_ENABLED environment

default: None variable if defined, or default to True.

b a tc h If True, then the function should process a batch of

bool inputs, meaning that it should accept a list of input

default: False values for each parameter. The lists should be of

equal length (and be up to length

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

m a x _ b a tch _ size Maximum number of inputs to batch together if

int this is called from the queue (only relevant if

default: 4 batch=True)

api_nam e Defines how the endpoint appears in the API docs.

str 1Literal[False] |None Can be a string, None, or False. If set to a string, the

default: "predict" endpoint will be exposed in the API docs with the

given name. If None, the name of the prediction

function will be used as the API endpoint. If False,

the endpoint will not be exposed in the API docs

and downstream apps (including those that

g r .lo a d this app) will not be able to use this

event.

a llo w _ d u p li c a t io n If True, then will show a 'Duplicate Spaces' button

bool on Hugging Face Spaces.


Parameter Description

default: False

c o n c u r r e n c y _ lim it If set, this is the máximum num ber of this event

int | None | Literal['default'] that can be running simultaneously. Can be set to

default: "default" None to mean no concurrency_lim it (any num ber

of this event can be running simultaneously). Set

to "default" to use the default concurrency lim it

(defined by the d e f a u lt _ c o n c u r r e n c y _ lim it

parameter in . q u e u e ( ) , which itself is 1 by

default).

js Custom js as a string or path to a js file. The custom

str I None js should be in the form of a single js function. This

default: None function w ill autom atically be executed when the

page loads. For more flexibility, use the head

parameter to insert js inside <script> tags.

head Custom html to insert into the head of the demo

str I None webpage. This can be used to add custom meta

default: None tags, scripts, stylesheets, etc. to the page.

a d d it io n a l_ in p u t s A single Gradio com ponent, or list of Gradio

str I Component | list[str | com ponents. Com ponents can either be passed as

Component] | None instantiated objects, or referred to by their string

default: None shortcuts. These com ponents w ill be rendered in

an accordion below the main input components.

By default, no additional input com ponents w ill be

displayed.
Parameter Description

a d d it io n a l_ in p u t s _ a c c o If a string is provided, this is the label of the

r d io n g r.A c c o rd io n to use to contain additional

str |Accordion |None inputs. A g r.A c c o rd io n object can be provided

default: None as well to configure other properties of the

container holding the additional inputs. Defaults to

a g r .A c c o r d io n ( la b e l= " A d d itio n a l

In p u ts", open= False). This parameter is only

used if a d d itio n a l_ in p u ts is provided.

s u b m it _ b t n The button to use for submitting inputs. Defaults to

str 1Button a g r.B u tto n ("S u b m it",

default: "Submit" v a ria n t= "p rim a ry "). This parameter does not

apply if the Interface is output-only, in which case

the submit button always displays "Generate". Can

be set to a string (which becomes the button label)

or a g r.B u tto n object (which allows for more

customization).

s to p _ b tn The button to use for stopping the interface.

str 1Button Defaults to a g r.B u tto n (" S to p " ,

default: "Stop" v a ria n t= " s to p " , v is ib le = F a ls e ) .Can be

set to a string (which becomes the button label) or

a g r.B u tto n object (which allows for more

customization).

c le a r _ b t n The button to use for clearing the inputs. Defaults

str 1Button to a g r .B u tt o n ( " C le a r " ,

default: "Clear" v a ria n t= "se co n d a ry "). Can be set to a string


Parameter Description

(which becomes the button label) or a g r . B u t t o n

object (which allows for more customization).

d e le t e _ c a c h e A tuple corresponding [frequency, age] both

tuple[int, int] | None expressed in num ber of seconds. Every

default: None f r e q u e n c y seconds, the tem porary files created

by this Blocks instance w ill be deleted if more than

age seconds have passed since the file was

created. For example, setting this to (86400, 86400)

w ill delete tem porary files every day. The cache

w ill be deleted entirely when the server resta rts. If

None, no cache deletion w ill occur.

Demos

hello_world h e llo _ w o rld _ 2 h e llo _ w o rld _ 3

import gradio as gr

def greet(name) :

return "Helio " + name + "!

demo = gr.Interface(fn=greet, inputs="textbox", outputs="textbox")

if name == " main

demo.launch()
Loading...

g ra d io / h e llo _ w o rld built with Gradio. Hosted on Efi Spaces

Methods

launch

gradio.Interface.launch(^••)

Description
L a u n c h e s a s im p le w e b s e rv e r t h a t se rv e s th e d e m o . C an a ls o be u sed to

c re a te a p u b lic lin k u sed by a n y o n e to a cc e ss th e d e m o fro m t h e ir b ro w s e r

b y s e ttin g share= True. <br>

Exampíe Usage

import gradio as gr

def reverse(text):

return text[::-1]

demo = gr.Interface(reverse, "text", "text")

demo.launch(share=True, auth=("username", "password"))

Agruments
Parameter Description

in lin e whether to display in the gradio app inline in

bool | None an iframe. Defaults to True in python

default: None notebooks; False otherwise.


Parameter Description

in b r o w s e r whether to autom atically launch the gradio

bool app in a new tab on the default browser.

default: False

sh a re whether to create a publicly shareable link for

bool | None the gradio app. Creates an SSH tunnel to make

default: None 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.

Can be set by environm ent variable

GRADIO_SHARE=True.

debug if True, blocks the main thread from running. If

bool running in Google Colab, this is needed to

default: False print the errors in the cell output.

m a x _ th re a d s the maximum num ber of total threads that the

int Gradio app can generate in parallel. The

default: 40 default is inherited from the starlette library

(currently 40).

a u th If provided, username and password (or list of

Callable | tuple[str, str] | username-password tuples) required to access

list[tuple[str, str]] | None app. Can also provide function that takes

default: None username and password and returns True if

valid login.
Parameter Description

a u th _ m e s s a g e If provided, HTML message provided on login

str | None page.

default: None

p re v e n t_ th re a d lo c k By default, the gradio app blocks the main

bool thread w hile the server is running. If set to

default: False True, the gradio app w ill not block and the

gradio server w ill term inate as soon as the

script finishes.

sh o w _ e rro r If True, any errors in the gradio app w ill be

bool displayed in an alert modal and printed in the

default: False browser console log

se rv e r_ n a m e to make app accessible on local network, set

str I None this to "0.0.0.0". Can be set by environm ent

default: None variable GRADIO_SERVER_NAME. If None, w ill

use "127.0.0.1".

se rv e r_ p o rt w ill start gradio app on this port (if available).

int I None Can be set by environm ent variable

default: None GRADIO_SERVER_PORT. If None, w ill search for

an available port starting at 7860.

h e ig h t The height in pixels of the iframe elem ent

int containing the gradio app (used if inline=True)

default: 500

w id t h The width in pixels of the iframe elem ent

int Istr containing the gradio app (used if inline=True)


Parameter Description

default: "100%"

f a v ic o n _ p a t h If a path to a file (.png, .gif, or .ico) is provided,

str | None it w ill be used as the favicon for the web page.

default: None

s s l_ k e y f ile If a path to a file is provided, w ill use this as

str 1None the private key file to create a local server

default: None running on https.

s s l_ c e r t f ile If a path to a file is provided, w ill use this as

str 1None the signed certificate for https. Needs to be

default: None provided if ssl_keyfile is provided.

s s l_ k e y f ile _ p a s s w o r d If a password is provided, w ill use this with the

str 1None ssl certificate for https.

default: None

s s l_ v e r if y If False, skips certificate validation which

bool allow s self-signed certificates to be used.

default: True

q u ie t If True, suppresses most print statements.

bool

default: False

show _api If True, shows the api docs in the footer of the

bool app. Default True.

default: True
Parameter Description

a l lo w e d _ p a t h s List of com plete filepaths or parent directories

list[str] | None that gradio is allowed to serve. Must be

default: None absolute paths. Warning: if you provide

directories, any files in these directories or

their subdirectories are accessible to all users

of your app.

b lo c k e d _ p a t h s List of com plete filepaths or parent directories

list[str] 1None that gradio is not allowed to serve (i.e. users of

default: None your app are not allowed to access). Must be

absolute paths. Warning: takes precedence

over a llo w e d _ p a t h s and all other directories

exposed by Gradio by default.

ro o t_ p a th The root path (or "m ount point") of the

str 1None application, if it's not served from the root

default: None ("/") of the domain. Often used when the

application is behind a reverse proxy that

forwards requests to the application. For

example, if the application is served at

"https://example.com/myapp", the

r o o t _ p a t h should be set to "/myapp". A full

URL beginning with http:// or https:// can be

provided, which w ill be used as the root path

in its entirety. Can be set by environm ent

variable GRADIO_ROOT_PATH. Defaults to "".


Parameter Description

a p p _ k w a rg s Additional keyword arguments to pass to the

dict[str, Any] | None underlying FastAPI app as a dictionary of

default: None parameter keys and argument valúes. For

example, " d o c s _ u r l" : "/d o cs"

s t a t e _ s e s s io n _ c a p a c i The maximum num ber of sessions whose

ty inform ation to store in memory. If the num ber

int of sessions exceeds this number, the oldest

default: 10000 sessions w ill be removed. Reduce capacity to

reduce m em ory usage when using

gradio.State or returning updated com ponents

from functions. Defaults to 10000.

sh a re _ se rv e r_ a d d re ss Use this to specify a custom FRP server and

str 1None port for sharing Gradio apps (only applies if

default: None share=True). If not provided, w ill use the

default FRP server at https://gradio.live. See

https://github.com/huggingface/frp for more

information.

s h a re _ s e rv e r_ p ro to c o Use this to specify the protocol to use for the

l share links. Defaults to "https", unless a

Literal[('http', 'https')] | None custom share_server_address is provided, in

default: None which case it defaults to "http". If you are using

a custom share_server_address and want to

use https, you must set this to "https".

a u th _ d e p e n d e n c y A function that takes a FastAPI request and

Callable[[fastapi.Request], str returns a string user ID or None. If the function

1None] 1None returns None for a specific request, that user is


Parameter Description

default: None not authorized to access the app (they w ill see

a 401 Unauthorized response). To be used with

external authentication systems like OAuth.

Cannot be used with a u th .

m a x _ f ile _ s iz e The maximum file size in bytes that can be

str | int | None uploaded. Can be a string of the form "<value>

default: None <unit>", where value is any positive integer

and unit is one of "b", "kb", "mb", "gb", "tb". If

None, no lim it is set.

load

gradio.Interface.load(block, •••)

Description
T h is lis te n e r is trig g e re d w h e n th e Interface in it ia lly lo a d s in th e b row ser.

Agruments
Parameter Description

b lo c k

Block 1None

required

fn the function to call when this event is

Callable | None | triggered. Often a machine learning m odel's

Literal['decorator'] prediction function. Each parameter of the

default: "decorator" function corresponds to one input


Parameter Description

com ponent, and the function should return a

single value or a tupie of valúes, with each

elem ent in the tupie corresponding to one

output component.

in p u t s List of gradio.com ponents to use as inputs. If

Component | list[Component] | the function takes no inputs, this should be an

set[Component] | None em pty list.

default: None

o u tp u ts List of gradio.com ponents to use as outputs. If

Component | list[Component] | the function returns no outputs, this should be

None an empty list.

default: None

a p i_ n a m e defines how the endpoint appears in the API

str | None | Literal[False] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r .lo a d this app) w ill

not be able to use this event.

s c r o ll_ t o _ o u t p u t If True, w ill scroll to output com ponent on

bool com pletion

default: False
Parameter Description

sh o w _ p ro g re ss If True, w ill show progress anim ation w hile

L¡teral[('full', 'minimal', pending

'hidden')]

default: "full"

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

b a tc h If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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.

m a x _ b a t c h _ s iz e Maximum num ber of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

p re p ro ce ss If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).


Parameter Description

p o s tp ro c e s s If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

c a n c e ls A list of other events to cancel when this

dict[str, Any] | list[dict[str, listener is triggered. For example, setting

Any]] 1None cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another com ponents .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running w ill be

allowed to finish.

e v e ry Run this event 'every' num ber of seconds

float 1None w hile the client connection is open.

default: None Interpreted in seconds.

t r ig g e r _ m o d e If "once" (default for all events except

L¡teral[('once', 'múltiple, . c h a n g e ( ) ) would not allow any subm issions

'a lw a y sjast')] | None w hile an event is pending. If set to "multiple",

default: None unlim ited subm issions are allowed while

pending, and "always_last" (default for

.c h a n g e ( ) and .k e y _ u p ( ) events) would

allow a second subm ission after the pending

event is complete.
Parameter Description

js Optional frontend js method to run before

str | None running 'fn'. Input arguments for js method are

default: None valúes of 'inputs' and 'outputs', return should

be a list of valúes for output components.

c o n c u r r e n c y _ lim it If set, this is the maximum num ber of this

int 1None | Literal['default'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_lim it

(any num ber of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

c o n c u r r e n c y _ id If set, this is the id of the concurrency group.

str 1None Events with the same concurrency_id w ill be

default: None lim ited by the lowest set concurrency_lim it.

show _api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting

api_nam e to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api w ill

autom atically be set to False.

from_pipeline
gradio. Interface.from_pipeline(pipeline, •••)

Description
C la s s m e th o d t h a t c o n s tru c ts an In terface fro m a H u g g in g Face

t ra n s fo rm e rs .P ip e lin e o r d iffu s e rs .D iffu s io n P ip e lin e o b je ct. T h e in p u t an d

o u t p u t c o m p o n e n ts are a u to m a t ic a lly d e te rm in e d fro m th e p ip e lin e .

Exampíe Usage

import gradio as gr

from transformers import pipeline

pipe = pipeline("image-classification")

gr.Interface.from_pipeline(pipe).launch()

Agruments
Parameter Description

p ip e lin e the pipeline object to use.

Pipeline | DiffusionPipeline

required

integrate

gradio.Interface.integrate(•••)

Description
A c a tc h -a ll m e th o d fo r in te g ra tin g w ith o th e r lib ra rie s . T h is m e th o d s h o u ld

be run a fte r laun ch ()

Agruments
Parameter Description

c o m e t_ m l If a com et_m l Experiment object is provided,

<class 'inspect._empty'> w ill intégrate with the experim ent and appear

default: None on Com et dashboard

w an db If the wandb module is provided, w ill integrate

ModuleType | None with it and appear on WandB dashboard

default: None

m lf lo w If the m lflow module is provided, w ill integrate

ModuleType | None with the experim ent and appear on ML Flow

default: None dashboard

queue

gradio. Interface .queue( — ^)

Description
By e n a b lin g th e q u e u e y o u can c o n tro l w h e n u se rs k n o w t h e ir p o s itio n in

th e q u e u e , a n d s e t a lim it on m a x im u m n u m b e r o f e v e n ts a llo w e d .

Exampíe Usage

demo = gr.Interface(image_generator, gr.Textbox(), gr.Image())

demo.queue(max_size=20)

demo.launch()

Agruments
Parameter Description

s ta tu s _ u p d a te _ ra te If "auto", Queue w ill send status estim ations to

float | Literal['auto'] all clients whenever a job is finished.

default: "auto" Otherwise Queue w ill send status at regular

intervals set by this parameter as the num ber

of seconds.

a p i_ o p e n If True, the REST routes of the backend w ill be

bool 1None open, allow ing requests made directly to

default: None those endpoints to skip the queue.

m a x _ s iz e The maximum num ber of events the queue

int 1None w ill store at any given moment. If the queue is

default: None full, new events w ill not be added and a user

w ill receive a message saying that the queue is

full. If None, the queue size w ill be unlimited.

co n c u rre n cy _ c o u n t Deprecated. Set the concurrency_lim it directly

int 1None on event listeners e.g. btn.click(fn, ...,

default: None concurrency_limit=10) or

gr.Interface(concurrency_limit=10). If

necessary, the total num ber of workers can be

configured via m a x _ th re a d s in launch().

d e fa u lt _ c o n c u r r e n c y _ The default value of c o n c u r r e n c y _ lim it to

lim it use for event listeners that don't specify a

int 1None | Literal['not_set'] value. Can be set by environm ent variable

default: "not_set" GRADIO_DEFAULT_CONCURRENCY_LIMIT.

Defaults to 1 if not set otherwise.


Guides

Quickstart

Key Features

Sharing Your App

Interface State

Reactive Interfaces

C h a tIn te rfa ce

gradio Status X O
Custom Components GalleryNEW Explore

gradio =

New to Gradio? Start here: Getting Started See the Release History

^ G ro u p C o m p o n e n ts

Accordion

gradio.Accordion(•••)

Description
A c c o rd io n is a la y o u t e le m e n t w h ic h can be to g g le d to s h o w /h id e th e c o n ta in e d

c o n te n t.

Exampíe Usage

with gr.Accordion("See Details"):

gr.Markdown("lorem ipsum")

Initiaíization
Parameter Description

la b e l name of accordion section.

str | None

default: None

open if True, accordion is open by default.

bool

default: True

v is ib le
Parameter Description

bool

default: True

e le m _ id An optional string that is assigned as the id of this

str | None com ponent in the HTML DOM. Can be used for

default: None targeting CSS styles.

e l e m _ c la s s e s An optional string or list of strings that are

list[str] 1str 1None assigned as the class of this com ponent in the

default: None HTML DOM. Can be used for targeting CSS styles.

re n d e r If False, this layout w ill not be rendered in the

bool Blocks context. Should be used if the intention is to

default: True assign event listeners now but render the

com ponent later.

^ G ro u p C o m p o n e n ts

0 . gradio Status
Custom Components GalleryNEW Explore

<§, gradio

New to Gradio? Start here: Getting Started See the Release History

^ Components Audio

AnnotatedImage

gradio.AnnotatedImage(•••)

0 Annotated Image

buildings

gradio/annotatedimage_component built with Gradio. Hosted on EB Spaces

Description
Creates a component to displays a base image and colored annotations on top of
that image. Annotations can take the from of rectangles (e.g. object detection) or
masks (e.g. image segmentation). As this component does not accept user input,
it is rarely used as an input component.

Behavior
As input component: Passes its value as a tupie consisting of a s tr filepath to a

base image and l i s t of annotations. Each annotation itself is tupie of a mask (as
a s tr filepath to image) and a s tr label.

Your function should accept one of these types:

def predict(

value: tuple[str, list[tuple[str, str]]] | None

As output component: Expects a a tuple of a base image and list of annotations:


a tu p le [ I m a g e , l i s t [ A n n o t a t i o n ] ] . The Image itself can be s t r filepath,
n u m p y .n d a rra y , or P IL .Im a g e . Each A n n o ta t io n is a tu p le [ M a s k , s t r ] . The Mask

can be either a t u p le of 4 i n t 's representing the bounding box coordinates (x1,


y1, x2, y2), or 0-1 confidence mask in the form of a n u m p y.n d a rra y of the same
shape as the image, while the second element of the A n n o ta t io n tuple is a s t r
label.

Your function should return one of these types:

def predict(^ " ) -> tuple[np.ndarray | PIL.Image.Image | str, list[tuple[np.ndarra

y | tuple[int, int, int, int], str]]] | None

return value

Initiaiization
Parameter Description

v a lu e Tuple of base image and list of (annotation, label)

tuple[np.ndarray | pairs.

PIL.Image.Image |str,
Parameter Description

list[tuple[np.ndarray | tuple[int,

int, int, int], str]]] | None

default: None

fo rm a t Format used to save images before it is returned to

str the front end, such as 'jpeg' or 'png'. This

default: "webp" parameter only takes effect when the base image is

returned from the prediction function as a numpy

array or a PIL Image. The format should be

supported by the PIL library.

s h o w _ le g e n d If True, w ill show a legend of the annotations.

bool

default: True

h e ig h t The height of the image, specified in pixels if a

int 1str 1None number is passed, or in CSS units if a string is

default: None passed.

w id t h The width of the image, specified in pixels if a

int 1str 1None number is passed, or in CSS units if a string is

default: None passed.

c o lo r _ m a p A dictionary mapping labels to colors. The colors

dict[str, str] |None must be specified as hex codes.

default: None

la b e l The label for this component. Appears above the

str 1None component and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r . I n t e r f a c e , the label w ill be the


Parameter Description

name of the parameter this component is assigned

to.

e v e ry If v a lu e is a callable, run the function 'every'

float |None number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

s h o w _ la b e l if True, w ill display label.

bool 1None

default: None

c o n t a in e r If True, w ill place the component in a container -

bool providing some extra padding around the border.

default: True

s c a le Relative width compared to adjacent Components

int 1None in a Row. For example, if Component A has scale=2,

default: None and Component B has scale=1, A will be twice as

wide as B. Should be an integer.

m in _ w id t h Minimum pixel width, will wrap if not sufficient

int screen space to satisfy this value. If a certain scale

default: 160 value results in this Component being narrower

than min_width, the min_width parameter will be

respected first.

v is ib le If False, component will be hidden.

bool

default: True
Parameter Description

e le m _ id An optional string that is assigned as the id of this

str |None component in the HTML DOM. Can be used for

default: None targeting CSS styles.

e le m _ c la s s e s An optional list of strings that are assigned as the

list[str] 1str 1None classes of this component in the HTML DOM. Can

default: None be used for targeting CSS styles.

re n d e r If False, component will not render be rendered in

bool the Blocks context. Should be used if the intention

default: True is to assign event listeners now but render the

component later.

Shortcuts
Interface String
Class imtialization
Shortcut

g r a d io . A n n o t a t e d I m a g e "annotatedimage" Uses default values

Demos

image_segmentation

import gradio as gr

import numpy as np

import random
1
with gr.Blocks() as demo:

section_labels = [

"apple",

"banana",

"carrot",

donut",
Event Listeners

Description
Event listeners allow you to capture and respond to user interactions with
the UI components you've defined in a Gradio Blocks app. When a user
interacts with an element, such as changing a slider value or uploading an
image, a function is called.

Supported Event Listeners


The A n n o ta te d Im a g e component supports the following event
listeners. Each event listener takes the same parameters, which are listed
in the Event Arguments table below.

Listener Description

g ra d io .A n n o ta te d Im a g e . s Event listener for when the user selects or


e le c t ( f n , •••) deselects the AnnotatedImage. Uses event
data gradio.SelectData to carry v a lu e
referring to the label of the AnnotatedImage,
and s e le c t e d to refer to state of the
AnnotatedImage. See EventData
documentation on how to use this event data
Event Arguments
Parameter Description

fn the function to call when this event is

Callable | None | triggered. Often a machine learning model's

Literal['decorator'] prediction function. Each parameter of the

default: "decorator" 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.

in p u t s List of gradio.components to use as inputs. If

Component | list[Component] | the function takes no inputs, this should be an

set[Component] | None empty list.

default: None

o u tp u ts List of gradio.components to use as outputs. If

Component | list[Component] | the function returns no outputs, this should be

None an empty list.

default: None

api_name defines how the endpoint appears in the API


str | None |Literal[False] docs. Can be a string, None, or False. If set to a
default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function will be used as the

API endpoint. If False, the endpoint will not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.


Parameter Description

s c r o ll_ t o _ o u t p u t If True, will scroll to output component on

bool completion

default: False

sh ow _ p rog ress If True, will show progress animation while

Literal[(’fu ll’, ’m inim al’, pending

’hidden’)]

default: "ful!"

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


bool |None the queue has been enabled. If False, w ill not
default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

b atch If True, then the function should process a


bool batch of inputs, meaning that it should accept
default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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.

m a x _ b a tch _ size Maximum number of inputs to batch together

int if this is called from the queue (only relevant if


default: 4 batch=True)

p re p ro c e s s If False, w ill not run preprocessing of

bool component data before running 'fn' (e.g.


Parameter Description

default: True leaving it as a base64 string if this method is

called with the Image component).

p o s tp ro c e s s If False, w ill not run postprocessing of

bool component data before returning 'fn' output


default: True to the browser.

c a n c e ls A list of other events to cancel when this


dict[str, Any] |list[dict[str, listener is triggered. For example, setting
Any]] 1None cancels=[click_event] w ill cancel the
default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) will be cancelled, but

functions that are currently running w ill be

allowed to finish.

e v e ry Run this event 'every' number of seconds


float 1None while the client connection is open.
default: None Interpreted in seconds.

trig g e r_ m o d e If "once" (default for all events except

Literal[('once','m últiple, .c h a n g e ( ) ) would not allow any submissions

’a lw a y s ja s t’)] |None while an event is pending. If set to "multiple",


default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p () events) would

allow a second submission after the pending

event is complete.
Parameter Description

js Optional frontend js method to run before

str | None running 'fn'. Input arguments for js method are

default: None valúes of 'inputs' and 'outputs', return should

be a list of valúes for output components.

c o n c u r r e n c y _ lim it If set, this is the maximum number of this

int 1None |Literal['default'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

c o n c u rre n c y _ id If set, this is the id of the concurrency group.

str 1None Events with the same concurrency_id will be

default: None limited by the lowest set concurrency_limit.

show _api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_api()"

default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

automatically be set to False.

Components Audio
$ gradio Status X o
Custom Components GalleryNEW Explore

<§, gradio =

New to Gradio? Start here: Getting Started See the Release History

^ AnnotatedImage BarPlot

Audio

gradio.Audio(•••)

<f3 Audio

t!_i
i_
Coloque el audio aquí
-o -
Haga click para cargar

& #

gradio/audio_component built with Gradio. Hosted on B Spaces

Description
Creates an audio component that can be used to upload/record audio (as an
input) or display audio (as an output).

Behavior
As input component: passes audio as one of these formats (depending on t y p e ):

a s t r filepath, or t u p ie of (sample rate in Hz, audio data as numpy array). If the


latter, the audio data is a 16-bit i n t array whose values range from -32768 to
32767 and shape of the audio data array is (samples,) for mono audio or
(samples, channels) for multi-channel audio.
Your function should accept one of these types:

def predict(

value: str | tuple[int, np.ndarray] | None

As output component: expects audio data in any of these formats: a s tr or

pathlib.Path filepath or URL to an audio file, or a bytes object (recommended


for streaming), or a tupie of (sample rate in Hz, audio data as numpy array). Note:
if audio is supplied as a numpy array, the audio will be normalized by its peak
value to avoid distortion or clipping in the resulting audio.

Your function should return one of these types:

def predict(---) -> str | Path | bytes | tuple[int, np.ndarray] | None

return value

Initiaiization
Parameter Description

v a lu e A path, URL, or [sample_rate, numpy array] tuple

str |Path | tuple[int, np.ndarray] | (sample rate in Hz, audio data as a float or int

Callable |None numpy array) for the default value that Audio

default: None component is going to take. If callable, the

function w ill be called whenever the app loads to

set the initial value of the component.

so u rc e s A list of sources permitted for audio. "upload"

list[Literal[('upload, creates a box where user can drop an audio file,

’microphone')]] | None "microphone" creates a microphone input. The

default: None first element in the list w ill be used as the default

source. If None, defaults to ["upload",

"microphone"], or ["microphone"] if s tre a m in g is

True.
Parameter Description

ty p e The format the audio file is converted to before

Literal[('numpy', 'filepath')] being passed into the prediction function.

default: "numpy" "numpy" converts the audio to a tupie consisting

of: (int sample rate, numpy.array for the data),

"filepath" passes a str path to a temporary file

containing the audio.

la b e l The label for this component. Appears above the

str |None component and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r . I n t e r f a c e , the label w ill be the

name of the parameter this component is assigned

to.

e v e ry If v a lu e is a callable, run the function 'every'

float |None number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

s h o w _ la b e l if True, w ill display label.

bool 1None

default: None

c o n t a in e r If True, w ill place the component in a container -

bool providing some extra padding around the border.

default: True

s c a le Relative width compared to adjacent Components

int 1None in a Row. For example, if Component A has scale=2,

default: None
Parameter Description

and Component B has scale=1, A will be twice as

wide as B. Should be an integer.

m in _ w id t h Mínimum pixel width, will wrap if not sufficient

int screen space to satisfy this value. If a certain scale

default: 160 value results in this Component being narrower

than min_width, the min_width parameter will be

respected first.

in t e r a c t iv e If True, w ill allow users to upload and edit an audio

bool | None file. If False, can only be used to play audio. If not

default: None provided, this is inferred based on whether the

component is used as an input or output.

v is ib le If False, component will be hidden.

bool

default: True

s t r e a m in g If set to True when used in a l i v e interface as an

bool input, will automatically stream webcam feed.

default: False When used set as an output, takes audio chunks

yield from the backend and combines them into

one streaming audio output.

e le m _ id An optional string that is assigned as the id of this

str I None component in the HTML DOM. Can be used for

default: None targeting CSS styles.

e le m _ c la s s e s An optional list of strings that are assigned as the

list[str] Istr I None classes of this component in the HTML DOM. Can

default: None be used for targeting CSS styles.


Parameter Description

re n d e r If False, component will not render be rendered in

bool the Blocks context. Should be used if the intention

default: True is to assign event listeners now but render the

component later.

fo rm a t The file format to save audio files. Either 'wav' or

Literal[('wav', ’mp3')] 'mp3'. wav files are lossless but will tend to be

default: "wav" larger files. mp3 files tend to be smaller. Default is

wav. Applies both when this component is used as

an input (when ty p e is "format") and when this

component is used as an output.

a u t o p la y Whether to automatically play the audio when the

bool component is used as an output. Note: browsers

default: False w ill not autoplay audio files if the user has not

interacted with the page yet.

s h o w _ d o w n lo a d _ b u tto n If True, w ill show a download button in the corner

bool | None of the component for saving audio. If False, icon

default: None does not appear. By default, it w ill be True for

output components and False for input

components.

sh o w _ sh a re _ b u tto n If True, w ill show a share icon in the corner of the

bool | None component that allows user to share outputs to

default: None Hugging Face Spaces Discussions. If False, icon

does not appear. If set to None (default behavior),

then the icon appears if this Gradio app is

launched on Spaces, but not otherwise.


Parameter Description

e d it a b le If True, allows users to manipúlate the audio file if

bool the component is interactive. Defaults to True.

default: True

m in _ le n g t h The minimum length of audio (in seconds) that the

int |None user can pass into the prediction function. If None,

default: None there is no minimum length.

m a x _ le n g t h The maximum length of audio (in seconds) that the

int 1None user can pass into the prediction function. If None,

default: None there is no maximum length.

w a v e f o r m _ o p t io n s A dictionary of options for the waveform display.

WaveformOptions | dict | None Options include: waveform_color (str),

default: None waveform_progress_color (str), show_controls

(bool), skip_length (int), trim_region_color (str).

Default is None, which uses the default values for

these options.

Shortcuts
Interface String
Class Initialization
Shortcut

g r a d io . A u d io "audio" Uses default values

Uses sources=
g r a d i o . M ic r o p h o n e "microphone"
["microphone"]

Demos

generate_tone reverse_audio
import numpy as np

import gradio as gr

notes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]

def generate_tone(note, octave, duration):

sr = 48000

a4_freq, tones_from_a4 = 440, 12 * (octave - 4 ) + (note - 9)

frequency = a4_freq * 2 ** (tones_from_a4 / 12)

duration = int(duration)

audio = np.linspace(0, duration, duration * sr)

Loading...

gradio/generate_tone built with Gradio. Hosted on B Spaces

Event Listeners

Description
Event listeners allow you to capture and respond to user interactions with
the UI components you've defined in a Gradio Blocks app. When a user
interacts with an element, such as changing a slider value or uploading an
image, a function is called.

Supported Event Listeners


The A u d io component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Arguments
table below.

Listener Description

g r a d io . A u d io . s tre a m ( fn , This listener is triggered when the user


•••) streams the Audio.

g r a d io .A u d io .c h a n g e ( fn , Triggered when the value of the Audio changes


•••) either because of user input (e.g. a user types
in a textbox) OR because of a function update
(e.g. an image receives a value from the output
of an event trigger). See . in p u t ( ) for a
listener that is only triggered by user input.

g r a d io . A u d io . c l e a r ( f n , This listener is triggered when the user clears


•••) the Audio using the X button for the
component.

g r a d io . A u d io . p la y ( f n , This listener is triggered when the user plays


•••) the media in the Audio.

g r a d io . A u d io . p a u s e (fn , This listener is triggered when the media in the


•••) Audio stops for any reason.

g r a d io . A u d io . s t o p ( f n , This listener is triggered when the user


•••) reaches the end of the media playing in the
Audio.

g r a d io . A u d io . p a u s e (fn , This listener is triggered when the media in the


•••) Audio stops for any reason.

g r a d io . A u d io . s t a r t _ r e c o This listener is triggered when the user starts


r d in g ( f n , •••) recording with the Audio.

g r a d io . A u d io . p ause _reco This listener is triggered when the user pauses


r d in g ( f n , •••) recording with the Audio.

g r a d io . A u d io . s to p _ r e c o r This listener is triggered when the user stops


d in g ( f n , •••) recording with the Audio.
Listener Description

g r a d io . A u d io . u p lo a d ( fn , This listener is triggered when the user


•••) uploads a file into the Audio.

Event Arguments
Parameter Description

fn the function to call when this event is

Callable | None | triggered. Often a machine learning model's

Literal['decorator'] prediction function. Each parameter of the

default: "decorator" 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.

in p u t s List of gradio.components to use as inputs. If

Component | list[Component] | the function takes no inputs, this should be an

set[Component] | None empty list.

default: None

o u tp u ts List of gradio.components to use as outputs. If

Component | list[Component] | the function returns no outputs, this should be

None an empty list.

default: None

api_name defines how the endpoint appears in the API


str | None |Literal[False] docs. Can be a string, None, or False. If set to a
default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function will be used as the

API endpoint. If False, the endpoint will not be


Parameter Description

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

s c r o ll_ t o _ o u t p u t If True, will scroll to output component on


bool completion

default: False

sh ow _ p rog ress If True, will show progress animation while

Literal[(’fu ll’, ’m inim al’, pending

’hidden’)]

default: "hidden"

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

bool |None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

b atch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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.
Parameter Description

m a x _ b a tch _ size Máximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

p re p ro c e s s If False, w ill not run preprocessing of

bool component data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

p o s tp ro c e s s If False, w ill not run postprocessing of

bool component data before returning 'fn' output

default: True to the browser.

c a n c e ls A list of other events to cancel when this

dict[str, Any] |list[dict[str, listener is triggered. For example, setting

Any]] 1None cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) will be cancelled, but

functions that are currently running w ill be

allowed to finish.

e v e ry Run this event 'every' number of seconds

float 1None while the client connection is open.

default: None Interpreted in seconds.

trig g e r_ m o d e If "once" (default for all events except

Literal[('once','m últiple, .c h a n g e ( ) ) would not allow any submissions

’a lw a y s ja s t’)] |None while an event is pending. If set to "multiple",


default: None unlimited submissions are allowed while
Parameter Description

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p () events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before


str | None running 'fn'. Input arguments for js method are
default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

c o n c u r r e n c y _ lim it If set, this is the maximum number of this


int 1None |Literal['default'] event that can be running simultaneously. Can
default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

c o n c u rre n c y _ id If set, this is the id of the concurrency group.


str 1None Events with the same concurrency_id will be
default: None limited by the lowest set concurrency_limit.

show _api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_api()"


default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

automatically be set to False.


Guides

Real Time Speech Recognition

^ Annotatedlmage BarPlot

0 gradio Status X o
Custom Components GalleryNEW Explore

<§, gradio

New to Gradio? Start here: Getting Started See the Release History

^ Audio Button

BarPlot

gradio.BarPlot(•••)

Loading...

gradio/barplot_component built with Gradio. Hosted on EB Spaces

Description ¿¡P
Creates a bar plot component to display data from a pandas DataFrame (as
output). As this component does not accept user input, it is rarely used as an
input component.

Behavior
As input component: (Rarely used) passes the data displayed in the bar plot as

an AltairPlotData dataclass, which includes the plot information as a JSON string,


as well as the type of plot (in this case, "bar").

Your function should accept one of these types:


def predict(

value: AltairPlotData

As output component: Expects a pandas DataFrame containing the data to


display in the bar plot. The DataFrame should contain at least two columns, one
for the x-axis (corresponding to this component's x argument) and one for the y-

axis (corresponding to y).

Your function should return one of these types:

def predict(---) -> pd.DataFrame | None

return value

Initiaiization
Parameter Description

v a lu e The pandas dataframe containing the data to

pd.DataFrame | Callable |None display in a scatter plot. If a callable is provided,

default: None the function w ill be called whenever the app loads

to set the initial value of the plot.

x Column corresponding to the x axis.

str 1None

default: None

y Column corresponding to the y axis.

str 1None

default: None

c o lo r The column to determine the bar color. Must be

str 1None categorical (discrete values).

default: None
Parameter Description

v e r t ic a l If True, the bars w ill be displayed vertically. If False,

bool the x and y axis w ill be switched, displaying the

default: True bars horizontally. Default is True.

g ro u p The column with which to split the overall plot into

str |None sm aller subplots.

default: None

t it le The title to display on top of the chart.

str 1None

default: None

t o o lt ip The column (or list of columns) to display on the

list[str] 1str 1None tooltip when a user hovers over a bar.

default: None

x _ t it le The title given to the x axis. By default, uses the

str 1None value of the x parameter.

default: None

y _ t it le The title given to the y axis. By default, uses the

str 1None value of the y parameter.

default: None

x _ l a b e l_ a n g le The angle (in degrees) of the x axis labels. Positive

float 1None values are clockwise, and negative values are

default: None counter-clockwise.

y _ la b e l _ a n g l e The angle (in degrees) of the y axis labels. Positive

float 1None values are clockwise, and negative values are

default: None counter-clockwise.


Parameter Description

c o lo r _ le g e n d _ t it le The title given to the color legend. By default, uses

str |None the value of color parameter.

default: None

g r o u p _ t it le The label displayed on top of the subplot columns

str 1None (or rows if vertical=True). Use an empty string to

default: None omit.

c o lo r _ le g e n d _ p o s it io n The position of the color legend. If the string value

Literal[('left', 'right', 'top', 'none' is passed, this legend is omitted. For other

bottom, 'top-left, 'top-right, valid position values see:

bottom-left, bottom-right, https://vega.github.io/vega/docs/legends/#orienta

'none')] | None tion.

default: None

h e ig h t The height of the plot, specified in pixels if a

int 1str 1None number is passed, or in CSS units if a string is

default: None passed.

w id t h The width of the plot, specified in pixels if a

int 1str 1None number is passed, or in CSS units if a string is

default: None passed.

y _ lim A tuple of list containing the limits for the y-axis,

list[int] 1None specified as [y_min, y_max].

default: None

c a p t io n The (optional) caption to display below the plot.

str 1None

default: None
Parameter Description

in t e r a c t iv e Whether users should be able to interact with the

bool | None plot by panning or zooming with their mouse or

default: True trackpad.

la b e l The (optional) label to display on the top left

str I None corner of the plot.

default: None

s h o w _ la b e l Whether the label should be displayed.

bool | None

default: None

c o n t a in e r

bool

default: True

s c a le

int I None

default: None

m in _ w id t h

int

default: 160

e v e ry If v a lu e is a callable, run the function 'every'

float I None number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

v is ib le Whether the plot should be visible.


Parameter Description

bool

default: True

e le m _ id An optional string that is assigned as the id of this

str |None component in the HTML DOM. Can be used for

default: None targeting CSS styles.

e le m _ c la s s e s An optional list of strings that are assigned as the

list[str] 1str 1None classes of this component in the HTML DOM. Can

default: None be used for targeting CSS styles.

re n d e r If False, component will not render be rendered in

bool the Blocks context. Should be used if the intention

default: True is to assign event listeners now but render the

component later.

so rt Specifies the sorting axis as either "x", "y", "-x" or "

Literal[('x ', 'y, '-x', '-y')] |None y". If None, no sorting is applied.

default: None

s h o w _ a c t io n s _ b u t t o n Whether to show the actions button on the top

bool right corner of the plot.

default: False

Shortcuts
Interface String
Class initialization
Shortcut

g r a d io . B a r P lo t "barplot" Uses default values

Demos
bar_plot


import gradio as gr

import pandas as pd
I
import random

simple = pd.DataFrame(

"a": ["A", "B", "C", "D", "E", "F", "G", "H", "I"],

"b": [28, 55, 43, 91, 81, 53, 19, 87, 52],

Loading...

gradio/bar_plot built with Gradio. Hosted on EB Spaces

Event Listeners

Description
Event listeners allow you to capture and respond to user interactions with
the UI components you've defined in a Gradio Blocks app. When a user
interacts with an element, such as changing a slider value or uploading an
image, a function is called.
Supported Event Listeners
The B a r P lo t component supports the following event listeners. Each
event listener takes the same parameters, which are listed in the Event
Arguments table below.

Listener Description

g r a d io . B a r P lo t . c h a n g e (f Triggered when the value of the Plot changes


n, •••) either because of user input (e.g. a user types
in a textbox) OR because of a function update
(e.g. an image receives a value from the output
of an event trigger). See . in p u t ( ) for a
listener that is only triggered by user input.

g r a d io . B a r P lo t . c le a r ( f n This listener is triggered when the user clears


, •••) the Plot using the X button for the component.

Event Arguments
Parameter Description

fn the function to call when this event is

Callable | None | triggered. Often a machine learning model's

Literal['decorator'] prediction function. Each parameter of the

default: "decorator" 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.

in p u t s List of gradio.components to use as inputs. If

Component | list[Component] | the function takes no inputs, this should be an

set[Component] | None empty list.

default: None
Parameter Description

o u tp u ts List of gradio.components to use as outputs. If

Component | list[Component] | the function returns no outputs, this should be

None an empty list.

default: None

api_name defines how the endpoint appears in the API

str 1None |Literal[False] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function will be used as the

API endpoint. If False, the endpoint will not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

s c r o ll_ t o _ o u t p u t If True, will scroll to output component on

bool completion

default: False

sh ow _ p rog ress If True, will show progress animation while

Literal[(’fu ll’, ’m inim al’, pending


’hidden’)]

default: "ful!"

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

bool 1None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.


Parameter Description

b atch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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.

m a x _ b a tch _ size Maximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

p re p ro c e s s If False, w ill not run preprocessing of

bool component data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

p o s tp ro c e s s If False, w ill not run postprocessing of

bool component data before returning 'fn' output

default: True to the browser.

c a n c e ls A list of other events to cancel when this

dict[str, Any] |list[dict[str, listener is triggered. For example, setting

Any]] 1None cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) will be cancelled, but


Parameter Description

functions that are currently running w ill be

allowed to finish.

e v e ry Run this event 'every' number of seconds


float | None while the client connection is open.
default: None Interpreted in seconds.

trig g e r_ m o d e If "once" (default for all events except

Literal[('once', 'múltiple', .c h a n g e ( ) ) would not allow any submissions


’a lw a y s ja s t’)] |None while an event is pending. If set to "multiple",
default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p () events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before


str 1None running 'fn'. Input arguments for js method are
default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

c o n c u r r e n c y _ lim it If set, this is the maximum number of this


int 1None |Literal['default'] event that can be running simultaneously. Can
default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).


Parameter Description

c o n c u rre n c y _ id If set, this is the id of the concurrency group.

str | None Events with the same concurrency_id will be

default: None limited by the lowest set concurrencyjim it.

show _api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

automatically be set to False.

Audio Button -

^ gradio Status O
Custom Components GalleryNEW Explore

gradio =

New to Gradio? Start here: Getting Started See the Release History

^ T a b b e d In te rfa c e R ow

Blocks

with gradio.Blocks():

Description
B lo c k s is G ra d io 's lo w -le v e l API t h a t a llo w s yo u to cre a te m o re c u s to m w e b

a p p lic a t io n s a n d d e m o s th a n In terface s (yet s t ill e n tire ly in P y th o n ).

C o m p a re d to th e In terface c la ss, B lo c k s o ffe rs m o re fle x ib ilit y an d c o n tro l over:

(1) th e la y o u t o f c o m p o n e n ts (2) th e e v e n ts th a t trig g e r th e e x e c u tio n o f fu n c tio n s

(3) d a ta flo w s (e.g. in p u ts can trig g e r o u tp u ts , w h ic h can trig g e r th e next le v e l o f

o u tp u ts). B lo c k s a ls o o ffe rs w a y s to g ro u p to g e th e r re la te d d e m o s su ch as w ith

ta b s.

T h e b a sic u sag e o f B lo c k s is as fo llo w s : cre a te a B lo c k s o b je c t, th e n use it as a

c o n te x t (w ith th e " w ith " sta te m e n t), a n d th e n d e fin e la y o u ts , c o m p o n e n ts , o r

e v e n ts w ith in th e B lo c k s co n te x t. F in a lly , c a ll th e lau n ch () m e th o d to la u n c h th e

dem o.

Exampíe 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()

Initiaíization
Parameter Description

th e m e A Theme object or a string representing a theme. If

Theme |str | None a string, w ill look for a built-in theme with that

default: None name (e.g. "soft" or "default"), or w ill attempt to

load a theme from the Hugging Face Hub (e.g.

"gradio/m onochrom e"). If None, w ill use the

Default theme.

a n a ly t ic s _ e n a b le d W hether to allow basic telemetry. If None, w ill use

bool I None GRADIO_ANALYTICS_ENABLED environm ent

default: None variable or default to True.

mode A hum an-friendly name for the kind of Blocks or

str Interface being created. Used internally for

default: "blocks" analytics.

t it le The tab title to display when this is opened in a

str browser window.

default: "Gradio"
Parameter Description

css Custom css as a string or path to a css file. This css

str | None w ill be included in the demo webpage.

default: None

js Custom js as a string or path to a js file. The custom

str 1None js should be in the form of a single js function. This

default: None function w ill autom atically be executed when the

page loads. For more flexibility, use the head

parameter to insert js inside <script> tags.

head Custom html to insert into the head of the demo

str 1None webpage. This can be used to add custom meta

default: None tags, m ultiple scripts, stylesheets, etc. to the page.

f ill_ h e ig h t W hether to vertically expand top-level child

bool com ponents to the height of the window. If True,

default: False expansion occurs when the scale value of the child

com ponents >= 1.

d e le t e _ c a c h e A tuple corresponding [frequency, age] both

tuple[int, int] | None expressed in num ber of seconds. Every

default: None frequency seconds, the tem porary files created

by this Blocks instance w ill be deleted if more than

age seconds have passed since the file was

created. For example, setting this to (86400, 86400)

w ill delete tem porary files every day. The cache

w ill be deleted entirely when the server resta rts. If

None, no cache deletion w ill occur.

Demos
blocks helio b lo c k s _ flip p e r b lo c k s _ k in e m a tic s

import gradio as gr

def welcome(name):

return f'Welcome to Gradio, {name} !

with gr.Blocks() as demo:

g r .Markdown(

# Hello World!

Start typing below to see the output.

.. )

Loading...

g ra d io / b lo c k s _ h e llo built with Gradio. Hosted on Efi Spaces

Methods

launch

gradio.Blocks.launch(•••)
Description
L a u n c h e s a s im p le w e b s e rv e r t h a t se rv e s th e d e m o . C an a ls o be u sed to

c re a te a p u b lic lin k u sed by a n y o n e to a cc e ss th e d e m o fro m t h e ir b ro w s e r

b y s e ttin g share= True. <br>

Exampíe Usage

import gradio as gr

def reverse(text):

return text[::-1]

with gr.Blocks() as demo:

button = gr.Button(value="Reverse")

button.click(reverse, gr.Textbox(), gr .Textbox())

demo.launch(share=True, auth=("username", "password"))

Agruments
Parameter Description

in lin e whether to display in the gradio app inline in

bool | None an iframe. Defaults to True in python

default: None notebooks; False otherwise.

in b r o w s e r whether to autom atically launch the gradio

bool app in a new tab on the default browser.

default: False

sh a re whether to create a publicly shareable link for

bool | None the gradio app. Creates an SSH tunnel to make

default: None 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.


Parameter Description

Can be set by environm ent variable

GRADIO_SHARE=True.

debug if True, blocks the main thread from running. If

bool running in Google Colab, this is needed to

default: False print the errors in the cell output.

m a x _ th re a d s the maximum num ber of total threads that the

int Gradio app can generate in parallel. The

default: 40 default is inherited from the starlette library

(currently 40).

a u th If provided, username and password (or list of

Callable | tuple[str, str] | username-password tuples) required to access

list[tuple[str, str]] | None app. Can also provide function that takes

default: None username and password and returns True if

valid login.

a u th _ m e s s a g e If provided, HTML message provided on login

str 1None page.

default: None

p r e v e n t _ t h r e a d _ lo c k By default, the gradio app blocks the main

bool thread w hile the server is running. If set to

default: False True, the gradio app w ill not block and the

gradio server w ill term inate as soon as the

script finishes.

sh o w _ e rro r If True, any errors in the gradio app w ill be

bool displayed in an alert modal and printed in the


Parameter Description

default: False browser consolé log

se rv e r_ n a m e to make app accessible on local network, set

str | None this to "0.0.0.0". Can be set by environm ent

default: None variable GRADIO_SERVER_NAME. If None, w ill

use "127.0.0.1".

se rv e r_ p o rt w ill start gradio app on this port (if available).

int 1None Can be set by environm ent variable

default: None GRADIO_SERVER_PORT. If None, w ill search for

an available port starting at 7860.

h e ig h t The height in pixels of the iframe elem ent

int containing the gradio app (used if inline=True)

default: 500

w id t h The width in pixels of the iframe elem ent

int 1str containing the gradio app (used if inline=True)

default: "100%"

f a v ic o n _ p a t h If a path to a file (.png, .gif, or .ico) is provided,

str 1None it w ill be used as the favicon for the web page.

default: None

s s l_ k e y f ile If a path to a file is provided, w ill use this as

str 1None the private key file to create a local server

default: None running on https.

s s l_ c e r t f ile If a path to a file is provided, w ill use this as

str 1None the signed certificate for https. Needs to be

default: None provided if ssl_keyfile is provided.


Parameter Description

s s l_ k e y f ile _ p a s s w o r d If a password is provided, w ill use this with the

str | None ssl certificate for https.

default: None

s s l_ v e r if y If False, skips certificate validation which

bool allow s self-signed certificates to be used.

default: True

q u ie t If True, suppresses most print statements.

bool

default: False

show _api If True, shows the api docs in the footer of the

bool app. Default True.

default: True

a l lo w e d _ p a t h s List of com plete filepaths or parent directories

list[str] I None that gradio is allowed to serve. Must be

default: None absolute paths. Warning: if you provide

directories, any files in these directories or

their subdirectories are accessible to all users

of your app.

b lo c k e d _ p a t h s List of com plete filepaths or parent directories

list[str] I None that gradio is not allowed to serve (i.e. users of

default: None your app are not allowed to access). Must be

absolute paths. Warning: takes precedence

over a llo w e d _ p a t h s and all other directories

exposed by Gradio by default.


Parameter Description

ro o t_ p a th The root path (or "m ount point") of the

str | None application, if it's not served from the root

default: None ("/") of the domain. Often used when the

application is behind a reverse proxy that

forwards requests to the application. For

example, if the application is served at

"https://example.com/myapp", the

r o o t _ p a t h should be set to "/myapp". A full

URL beginning with http:// or https:// can be

provided, which w ill be used as the root path

in its entirety. Can be set by environm ent

variable GRADIO_ROOT_PATH. Defaults to "".

a p p _ k w a rg s Additional keyword arguments to pass to the

dict[str, Any] | None underlying FastAPI app as a dictionary of

default: None parameter keys and argument values. For

example, " d o c s _ u r l" : "/d o cs"

s t a t e _ s e s s io n _ c a p a c i The maximum num ber of sessions whose

ty inform ation to store in memory. If the num ber

int of sessions exceeds this number, the oldest

default: 10000 sessions w ill be removed. Reduce capacity to

reduce m em ory usage when using

gradio.State or returning updated com ponents

from functions. Defaults to 10000.

sh a re _ se rv e r_ a d d re ss Use this to specify a custom FRP server and

str 1None port for sharing Gradio apps (only applies if

default: None share=True). If not provided, w ill use the

default FRP server at https://gradio.live. See


Parameter Description

https://github.com/huggingface/frp for more

information.

s h a re _ s e rv e r_ p ro to c o Use this to specify the protocol to use for the

l share links. Defaults to "https", unless a

Literal[('http', 'https')] | None custom share_server_address is provided, in

default: None which case it defaults to "http". If you are using

a custom share_server_address and want to

use https, you must set this to "https".

a u th _ d e p e n d e n c y A function that takes a FastAPI request and

Callable[[fastapi.Request], str returns a string user ID or None. If the function

I None] I None returns None for a specific request, that user is

default: None not authorized to access the app (they w ill see

a 401 Unauthorized response). To be used with

external authentication systems like OAuth.

Cannot be used with a u th .

m a x _ f ile _ s iz e The maximum file size in bytes that can be

str I int I None uploaded. Can be a string of the form "<value>

default: None <unit>", where value is any positive integer

and unit is one of "b", "kb", "mb", "gb", "tb". If

None, no lim it is set.

queue

gradio.Blocks.queue(- ••)

Description
By e n a b lin g th e q u e u e y o u can c o n tro l w h e n u se rs k n o w th e ir p o s itio n in

th e q u e u e , a n d s e t a lim it on m á x im u m n u m b e r o f e v e n ts a llo w e d .

Exampíe Usage

with gr.Blocks() as demo:

button = gr.Button(label="Generate Image")

button.click(fn=image_generator, inputs=gr.Textbox(), outputs=gr.Image

())

demo.queue(max_size=10)

demo.launch()

Agruments
Parameter Description

s ta tu s _ u p d a te _ ra te If "auto", Queue w ill send status estim ations to

float | Literal['auto'] all clients whenever a job is finished.

default: "auto" Otherwise Queue w ill send status at regular

intervals set by this parameter as the num ber

of seconds.

a p i_ o p e n If True, the REST routes of the backend w ill be

bool I None open, allow ing requests made directly to

default: None those endpoints to skip the queue.

m a x _ s iz e The maximum num ber of events the queue

int I None w ill store at any given moment. If the queue is

default: None full, new events w ill not be added and a user

w ill receive a message saying that the queue is

full. If None, the queue size w ill be unlimited.


Parameter Description

co n c u rre n cy _ c o u n t Deprecated. Set the concurrency_lim it directly

int | None on event listeners e.g. btn.click(fn,

default: None concurrency_limit=10) or

gr.Interface(concurrency_limit=10). If

necessary, the total num ber of workers can be

configured via m a x _ th re a d s in launch().

d e fa u lt _ c o n c u r r e n c y _ The default value of c o n c u r r e n c y _ lim it to

lim it use for event listeners that don't specify a

int 1None | Literal['not_set'] value. Can be set by environm ent variable

default: "not_set" GRADIO_DEFAULT_CONCURRENCY_LIMIT.

Defaults to 1 if not set otherwise.

intégrate

gradio.Blocks.integrate(•••)

Description
A c a tc h -a ll m e th o d fo r in te g ra tin g w ith o th e r lib ra rie s . T h is m e th o d s h o u ld

be run a fte r laun ch ()

Agruments
Parameter Description

c o m e t_ m l If a com et_m l Experiment object is provided,

<class 'inspect._empty'> w ill integrate with the experim ent and appear

default: None on Com et dashboard


Parameter Description

w an db If the wandb module is provided, w ill intégrate

ModuleType | None with it and appear on WandB dashboard

default: None

m lf lo w If the m lflow module is provided, w ill intégrate

ModuleType | None with the experim ent and appear on ML Flow

default: None dashboard

load

gradio.Blocks.load(block, •••)

Description
T h is lis te n e r is trig g e re d w h e n th e B lo c k s in it ia lly lo a d s in th e b row ser.

Agruments
Parameter Description

b lo c k

Block I None

required

fn the function to call when this event is

Callable | None | triggered. Often a machine learning m odel's

Literal['decorator'] prediction function. Each parameter of the

default: "decorator" function corresponds to one input

com ponent, and the function should return a

single value or a tuple of values, with each


Parameter Description

elem ent in the tupie corresponding to one

output component.

in p u t s List of gradio.com ponents to use as inputs. If

Component | list[Component] | the function takes no inputs, this should be an

set[Component] | None em pty list.

default: None

o u tp u ts List of gradio.com ponents to use as outputs. If

Component | list[Component] | the function returns no outputs, this should be

None an empty list.

default: None

a p i_ n a m e defines how the endpoint appears in the API

str | None | Literal[False] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . l o a d this app) w ill

not be able to use this event.

s c r o ll_ t o _ o u t p u t If True, w ill scroll to output com ponent on

bool com pletion

default: False

sh o w _ p ro g re ss If True, w ill show progress anim ation w hile

Literal[('full', 'm inim al' pending

'hidden')]
Parameter Description

default: "full"

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

b a tc h If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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.

m a x _ b a t c h _ s iz e Maximum num ber of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

p re p ro ce ss If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

p o s tp ro c e s s If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.


Parameter Description

c a n c e ls A list of other events to cancel when this

dict[str, Any] | list[dict[str, listener is triggered. For example, setting

Any]] 1None cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another com ponents .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running w ill be

allowed to finish.

e v e ry Run this event 'every' num ber of seconds

float 1None w hile the client connection is open.

default: None Interpreted in seconds.

t r ig g e r _ m o d e If "once" (default for all events except

L¡teral[('once', 'múltiple, . c h a n g e ( ) ) would not allow any subm issions

'a lw a y sjast')] | None w hile an event is pending. If set to "multiple",

default: None unlim ited subm issions are allowed while

pending, and "always_last" (default for

.c h a n g e ( ) and .k e y _ u p ( ) events) would

allow a second subm ission after the pending

event is complete.

js Optional frontend js method to run before

str 1None running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

c o n c u r r e n c y _ lim it If set, this is the maximum num ber of this

int 1None | Literal['default'] event that can be running simultaneously. Can


Parameter Description

default: "default" be set to None to mean no concurrency_lim it

(any num ber of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

c o n c u r r e n c y _ id If set, this is the id of the concurrency group.

str | None Events with the same concurrency_id w ill be

default: None lim ited by the lowest set concurrency_lim it.

show _api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting

api_nam e to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api w ill

autom atically be set to False.

unload

gradio.Blocks.unload(fn, •••)

Description
T h is lis te n e r is trig g e re d w h e n th e u se r c lo s e s o r re fre sh e s th e ta b , e n d in g

th e u se r s e ssio n . It is u se fu l fo r c le a n in g u p re s o u rce s w h e n th e a p p is

c lo se d .

Exampíe Usage
import gradio as gr

with gr.Blocks() as demo:

gr.Markdown("# When you close the tab, helio will be printed to the cons

ole")

demo.unload(lambda: print("hello"))

demo.launch()

Agruments
Parameter Description

fn Callable function to run to clear resources. The

Callable function should not take any arguments and

required the output is not used.

Guides

Blocks And Event Listeners

Controlling Layout

State In Blocks

Custom CSS And JS

Using Blocks Like Functions

T a b b e d In te rfa c e R ow
$ gradio Status X O
Custom Components GalleryNEW Explore

<§, gradio

New to Gradio? Start here: Getting Started See the Release History

^ BarPlot Chatbot

Button

gradio.Button(•••)

Run

gradio/button_component built with Gradio. Hosted on ES Spaces

Description
Creates a button that can be assigned arbitrary .clickO events. The value (label) of
the button can be used as an input to the function (rarely used) or set via the
output of a function.

Behavior
As input component: (Rarely used) the s tr corresponding to the button label

when the button is clicked

Your function should accept one of these types:

def predict( cP
value: str | None

As output component: string corresponding to the button label

Your function should return one of these types:

def predictp " ) -> str | None


return value

Initiaiization
Parameter Description

v a lu e Default text for the button to display. If callable,

str | Callable the function w ill be called whenever the app loads

default: "Run" to set the initial value of the component.

e v e ry If v a lu e is a callable, run the function 'every'

float 1None number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

v a r ia n t 'primary' for main call-to-action, 'secondary' for a

Literal[('primary', 'secondary', more subdued style, 'stop' for a stop button.

'stop')]

default: "secondary"

s iz e Size of the button. Can be "sm" or "lg".

Literal[('sm', 'lg')] |None

default: None

ic o n URL or path to the icon file to display within the

str 1None button. If None, no icon will be displayed.

default: None

lin k URL to open when the button is clicked. If None, no

str 1None link will be used.

default: None

v is ib le If False, component will be hidden.


Parameter Description

bool

default: True

in t e r a c t iv e If False, the Button w ill be in a disabled state.

bool

default: True

e le m _ id An optional string that is assigned as the id of this

str |None component in the HTML DOM. Can be used for

default: None targeting CSS styles.

e le m _ c la s s e s An optional list of strings that are assigned as the

list[str] 1str 1None classes of this component in the HTML DOM. Can

default: None be used for targeting CSS styles.

re n d e r If False, component will not render be rendered in

bool the Blocks context. Should be used if the intention

default: True is to assign event listeners now but render the

component later.

s c a le relative size compared to adjacent Components.

int 1None For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A w ill be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

m in _ w id t h minimum pixel width, will wrap if not sufficient

int 1None screen space to satisfy this value. If a certain scale

default: None value results in this Component being narrower


Parameter Description

than min_width, the min_width parameter will be

respected first.

Interface String
Class Initialization
Shortcut

g r a d io . B u tto n "button" Uses default values

g r a d io . C le a r B u t t o n "clearbutton" Uses default values

g r a d i o . D u p li c a t e B u t t o n "duplicatebutton" Uses default values

g r a d i o . L o g in B u t t o n "loginbutton" Uses default values

g r a d io . L o g o u tB u tto n "logoutbutton" Uses default values

Event Listeners

Description
Event listeners allow you to capture and respond to user ¡nteractions with
the UI components you've defined ¡n a Gradio Blocks app. When a user
¡nteracts with an element, such as changing a slider value or uploading an
image, a function is called.

Supported Event Listeners


The B u tto n component supports the following event listeners. Each
event listener takes the same parameters, which are listed in the Event
Arguments table below.

Listener Description

g r a d io . B u t t o n . c l i c k ( f n , Triggered when the Button is clicked.


•••)
Event Arguments
Parameter Description

fn the function to call when this event is


Callable | None | triggered. Often a machine learning model's
Literal['decorator'] prediction function. Each parameter of the
default: "decorator" 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.

in p u t s List of gradio.components to use as inputs. If


Component | list[Component] | the function takes no inputs, this should be an
set[Component] | None empty list.
default: None

o u tp u ts List of gradio.components to use as outputs. If

Component | list[Component] | the function returns no outputs, this should be

None an empty list.

default: None

api_name defines how the endpoint appears in the API

str | None |Literal[False] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function will be used as the

API endpoint. If False, the endpoint will not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.


Parameter Description

s c r o ll_ t o _ o u t p u t If True, will scroll to output component on

bool completion

default: False

sh ow _ p rog ress If True, will show progress animation while

Literal[(’fu ll’, ’m inim al’, pending

’hidden’)]

default: "ful!"

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


bool |None the queue has been enabled. If False, w ill not
default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

b atch If True, then the function should process a


bool batch of inputs, meaning that it should accept
default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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.

m a x _ b a tch _ size Maximum number of inputs to batch together

int if this is called from the queue (only relevant if


default: 4 batch=True)

p re p ro c e s s If False, w ill not run preprocessing of

bool component data before running 'fn' (e.g.


Parameter Description

default: True leaving it as a base64 string if this method is

called with the Image component).

p o s tp ro c e s s If False, w ill not run postprocessing of

bool component data before returning 'fn' output


default: True to the browser.

c a n c e ls A list of other events to cancel when this


dict[str, Any] |list[dict[str, listener is triggered. For example, setting
Any]] 1None cancels=[click_event] w ill cancel the
default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) will be cancelled, but

functions that are currently running w ill be

allowed to finish.

e v e ry Run this event 'every' number of seconds


float 1None while the client connection is open.
default: None Interpreted in seconds.

trig g e r_ m o d e If "once" (default for all events except

Literal[('once','m últiple, .c h a n g e ( ) ) would not allow any submissions

’a lw a y s ja s t’)] |None while an event is pending. If set to "multiple",


default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p () events) would

allow a second submission after the pending

event is complete.
Parameter Description

js Optional frontend js method to run before

str | None running 'fn'. Input arguments for js method are

default: None valúes of 'inputs' and 'outputs', return should

be a list of valúes for output components.

concurrency_limit If set, this is the maximum number of this

int 1None |Literal['default'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

default_concurrency_lim it parameter in

Blocks.queue() , which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.

str 1None Events with the same concurrency_id will be

default: None limited by the lowest set concurrency_limit.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_api()"

default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

automatically be set to False.

BarPlot Chatbot
$ gradio Status X o
Custom Components GalleryNEW Explore

<§, gradio =

New to Gradio? Start here: Getting Started See the Release History

^ Button Checkbox

Chatbot

gradio.Chatbot(•••)

Loading...

gradio/chatbot_component built with Gradio. Hosted on B Spaces

Description
Creates a chatbot that displays user-submitted messages and responses.
Supports a subset of Markdown including bold, italics, code, tables. Also
supports audio/video/image files, which are displayed in the Chatbot, and other
kinds of files which are displayed as links. This component is usually used as an
output component.

Behavior
As input component: Passes the messages in the chatbot as a l i s t [ l i s t [ s t r |
None | tu p ie ]], i.e. a list of lists. The inner list has 2 elements: the user message
and the response message. Each message can be (1) a string in valid Markdown,
(2) a tupie if tiñere are displayed files: (a filepath or URL to a file, [optional string
alt text]), or (3) None, if there is no message displayed.

Your function should accept one of these types:

def predict(

value: list[list[str | tuple[str] | tuple[str, str] | None]] | None

As output component: expects a l i s t [ l i s t [ s t r | None | t u p ie ] ] , i.e. a list of

lists. The inner list should have 2 elements: the user message and the response
message. The individual messages can be (1) strings in valid Markdown, (2) tuples
if sending files: (a filepath or URL to a file, [optional string alt text]) -- if the file is
image/video/audio, it is displayed in the Chatbot, or (3) None, in which case the
message is not displayed.

Your function should return one of these types:

def predict(---) -> list[list[str | tuple[str] | tuple[str, str] | None] | tupie]

| None

return value

Initiaiization
Parameter Description

v a lu e Default value to show in chatbot. If callable, the

list[list[str | tuple[str] | tuple[str | function w ill be called whenever the app loads to

Path, str] I None]] | Callable | set the initial value of the component.

None

default: None

la b e l The label for this component. Appears above the

str |None component and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r .I n t e r fa c e , the label w ill be the


Parameter Description

name of the parameter this component is assigned

to.

e v e ry If v a lu e is a callable, run the function 'every'

float |None number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

s h o w _ la b e l if True, w ill display label.

bool 1None

default: None

c o n t a in e r If True, w ill place the component in a container -

bool providing some extra padding around the border.

default: True

s c a le relative size compared to adjacent Components.

int 1None For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A w ill be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

m in _ w id t h minimum pixel width, will wrap if not sufficient

int screen space to satisfy this value. If a certain scale

default: 160 value results in this Component being narrower

than min_width, the min_width parameter will be

respected first.

v is ib le If False, component will be hidden.

bool
Parameter Description

default: True

e le m _ id An optional string that is assigned as the id of this

str |None component in the HTML DOM. Can be used for

default: None targeting CSS styles.

e le m _ c la s s e s An optional list of strings that are assigned as the

list[str] 1str 1None classes of this component in the HTML DOM. Can

default: None be used for targeting CSS styles.

re n d e r If False, component will not render be rendered in

bool the Blocks context. Should be used if the intention

default: True is to assign event listeners now but render the

component later.

h e ig h t The height of the component, specified in pixels if

int 1str 1None a number is passed, or in CSS units if a string is

default: None passed.

la t e x _ d e lim it e r s A list of dicts of the form " l e f t " : open

list[dict[str, str | bool]] | None d e l im i t e r ( s t r ) , " r ig h t " : c lo s e

default: None d e l im i t e r ( s t r ) , " d is p la y " : w h e th e r t o

d is p la y in n e w lin e ( b o o l) that will be used

to render LaTeX expressions. If not provided,

la t e x _ d e l im i t e r s is set to [ " l e f t " : "$ $ ",

" r ig h t " : "$ $ ", " d is p la y " : T ru e ] , so only

expressions enclosed in $$ delimiters will be

rendered as LaTeX, and in a new line. Pass in an

empty list to disable LaTeX rendering. For more

information, see the [KaTeX documentation]

(https://katex.org/docs/autorender.html).
Parameter Description

rtl If True, sets the direction of the rendered text to

bool right-to-left. Default is False, which renders text

default: False left-to-right.

sh o w _ sh a re _ b u tto n If True, w ill show a share icon in the corner of the

bool | None component that allows user to share outputs to

default: None Hugging Face Spaces Discussions. If False, icon

does not appear. If set to None (default behavior),

then the icon appears if this Gradio app is

launched on Spaces, but not otherwise.

sh o w _ c o p y _ b u tto n If True, w ill show a copy button for each chatbot

bool message.

default: False

a v a t a r _ im a g e s Tuple of two avatar image paths or URLs for user

tuple[str 1Path |None, str | Path | and bot (in that order). Pass None for either the

None] |None user or bot image to skip. Must be within the

default: None working directory of the Gradio app or an external

URL.

s a n it iz e _ h t m l If False, will disable HTML sanitization for chatbot

bool messages. This is not recommended, as it can lead

default: True to security vulnerabilities.

re n d e r_ m a rk d o w n If False, will disable Markdown rendering for

bool chatbot messages.

default: True

b u b b le _ f u ll_ w id t h If False, the chat bubble will fit to the content of

bool the message. If True (default), the chat bubble will


Parameter Description

default: True be the full width of the component.

lin e _ b r e a k s If True (default), w ill enable Github-flavored

bool Markdown line breaks in chatbot messages. If

default: True False, single new lines w ill be ignored. Only applies

if render_m arkdow n is True.

lik e a b le Whether the chat messages display a like or dislike

bool button. Set automatically by the .like method but

default: False has to be present in the signature for it to show up

in the config.

la y o u t If "panel", will display the chatbot in a llm style

Literal[('panel', 'bubble')] | None layout. If "bubble", w ill display the chatbot with

default: None message bubbles, with the user and bot messages

on alterating sides. Will default to "bubble".

p la c e h o l d e r a placeholder message to display in the chatbot

str 1None when it is empty. Centered vertically and

default: None horizontally in the Chatbot. Supports Markdown

and HTML. If None, no placeholder is displayed.

Shortcuts
Interface String
Class Initialization
Shortcut

g r a d io . C h a t b o t "chatbot" Uses default values

Demos

chatbot_simple chatbot multimodal


import gradio as gr

import random

import time

with gr.Blocks() as demo:

chatbot = gr.Chatbot()

msg = gr.Textbox()

clear = gr.ClearButton([msg, chatbot])

def respond(message, chat_history):

bot_message = random.choice(["How are you?", "I love you", "I'm ver

Loading...

gradio/chatbot_simple built with Gradio. Hosted on B Spaces

Event Listeners

Description
Event listeners allow you to capture and respond to user interactions with
the UI components you've defined in a Gradio Blocks app. When a user
interacts with an element, such as changing a slider value or uploading an
image, a function is called.

Supported Event Listeners


The C h a t b o t component supports the following event listeners. Each
event listener takes the same parameters, which are listed in the Event
Arguments table below.

Listener Description

gradio.Chatbot. change(f Triggered when the value of the Chatbot


n, •••) changes either because of user input (e.g. a
user types in a textbox) OR because of a
function update (e.g. an image receives a value
from the output of an event trigger). See
.inp ut() for a listener that is only triggered
by user input.

gradio.Chatbot. s e le c t(f Event listener for when the user selects or


n, •••) deselects the Chatbot. Uses event data
gradio.SelectData to carry value referring to
the label of the Chatbot, and selected to
refer to state of the Chatbot. See EventData
documentation on how to use this event data

gradio.Chatbot. lik e (fn , This listener is triggered when the user


•••) likes/dislikes from within the Chatbot. This
event has EventData of type gradio.LikeData
that carries information, accessible through
LikeData.index and LikeData.value. See
EventData documentation on how to use this
event data.

Event Arguments
Parameter Description

fn the function to call when this event is


C a lla b le |N o n e | triggered. Often a machine learning model's
L ite ra l['d e c o ra to r'] prediction function. Each parameter of the
default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tuple of values, with each


Parameter Description

element in the tupie corresponding to one

output component.

inputs List of gradio.components to use as inputs. If


Component | list[Component] | the function takes no inputs, this should be an
set[Component] | None empty list.
default: None

outputs List of gradio.components to use as outputs. If


Component | list[Component] | the function returns no outputs, this should be
None an empty list.
default: None

api_name defines how the endpoint appears in the API


str | None |Literal[False] docs. Can be a string, None, or False. If set to a
default: None string, the endpoint will be exposed in the API

docs with the given name. If None (default),

the name of the function will be used as the

API endpoint. If False, the endpoint will not be

exposed in the API docs and downstream apps

(including those that g r.lo ad this app) will

not be able to use this event.

scroll_to_output If True, will scroll to output component on


bool completion
default: False

show_progress If True, will show progress animation while


Literal[(’fu ll’, ’m inim al’, pending
’hidden’)]

default: "ful!
Parameter Description

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


bool |N o n e the queue has been enabled. If False, will not
default: None put this event on the queue, even if the queue

has been enabled. If None, will use the queue

setting of the gradio app.

batch If True, then the function should process a


bool batch of inputs, meaning that it should accept
default: False 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 Maximum number of inputs to batch together


in t if this is called from the queue (only relevant if
default: 4 batch=True)

preprocess If False, will not run preprocessing of


bool component data before running 'fn' (e.g.
default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, will not run postprocessing of


bool component data before returning 'fn' output
default: True to the browser.

cancels A list of other events to cancel when this

listener is triggered. For example, setting


Parameter Description

dict[str, Any] |list[dict[str, cancels=[click_event] will cancel the

Any]] 1None click_event, where click_event is the return

default: None value of another components .click method.

Functions that have not yet run (or generators

that are iterating) will be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds


float 1None while the client connection is open.
default: None Interpreted in seconds.

trigger_mode If "once" (default for all events except


Literal[('once','m últiple, .change()) would not allow any submissions
’a lw a y s ja s t’)] |None while an event is pending. If set to "multiple",
default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.change() and .key_up() events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before


str 1None running 'fn'. Input arguments for js method are
default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

concurrency_limit If set, this is the maximum number of this


int 1None |Literal['default'] event that can be running simultaneously. Can
default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the


Parameter Description

default concurrency limit (defined by the

default_concurrency_lim it parameter in

Blocks.queue(), which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.


str |N o n e Events with the same concurrency_id will be
default: None limited by the lowest set concurrency_limit.

show_api whether to show this event in the "view API"


bool page of the Gradio app, or in the ".view_api()"
default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

will still allow downstream apps to use this

event. If fn is None, show_api will

automatically be set to False.

Button Checkbox

^ gradio Status X o
Custom Com ponents GalleryNEW Explore

$ gradio =

New to Gradio? Start here: Getting Started See the Release History

^ Interface TabbedInterface

ChatInterface

g r a d io . C h a t I n t e r f a c e ( f n , •••)

Description
ChatInterface is Gradio's high-level abstraction for creating chatbot UIs, and allows you to create a
based dem o around a chatbot model in a few lines of code. Only one parameter is required: fn, wh
takes a function that governs the response of the chatbot based on the user input and chat history
Additional parameters can be used to control the appearance and behavior of the demo.

Example Usage

im port g r a d io as gr

d e f ech o ( m essage, h i s t o r y ) :

r e t u r n message

demo = g r . C h a t I n t e r f a c e ( f n =ech o , exam ples=[ " h e l l o " , " h o l a " , "m erh ab a"] , t i t l e ="E ch o B o t " )

demo. la u n c h ( )

Initialization
Parameter Description

fn The function to wrap the chat interface around. Should accep'

C a lla b le parameters: a string input message and list of two-element lis

required the form [[user_message, bot_message], ...] representing the

history, and return a string response. See the Chatbot

documentation for more information on the chat history form


Parameter Description

m u lt im o d a l If True, the chat interface will use a gr.MultimodalTextbox

bool com ponent for the input, which allows for the uploading of

default: False multimedia files. If False, the chat interface will use a gr.Textbi

com ponent for the input.

ch a tb o t An instance of the gr.Chatbot com ponent to use for the chat

C h a tb o t |N on e interface, if you would like to customize the chatbot propertie

default: None not provided, a default gr.Chatbot com ponent will be created

te x tb o x An instance of the gr.Textbox or gr.MultimodalTextbox compoi

Textbox 1M u ltim o d a lT e x tb o x |N o n e to use for the chat interface, if you would like to customize the

default: None textbox properties. If not provided, a default gr.Textbox or

gr.MultimodalTextbox com ponent will be created.

a d d it io n a l_ in p u t s An instance or list of instances of gradio com ponents (or their

str 1C o m p o n e n t |list[str |C o m p o n e n t] | string shortcuts) to use as additional inputs to the chatbot. If

N on e com ponents are not already rendered in a surrounding Block;

default: None then the com ponents will be displayed under the chatbot, in ;

accordion.

a d d it io n a l_ in p u t s _ a c c o r d io n _ n Deprecated. Will be removed in a future version of Gradio. Use

ame a d d it io n a l_ i n p u t s _ a c c o r d i o n parameter instead.

str |N on e

default: None

a d d it io n a l_ in p u t s _ a c c o r d io n If a string is provided, this is the label of the g r . A c c o r d io n t

str |A c c o r d io n |N on e to contain additional inputs. A g r . A c c o r d io n object can be

default: None provided as well to configure other properties of the containe

holding the additional inputs. Defaults to a

g r .A c c o r d io n ( la b e l= " A d d it io n a l In p u ts ",

o p e n = F a ls e ) . This parameter is only used if

a d d i t i o n a l _ i n p u t s is provided.
Parameter Description

e x a m p le s Sample inputs for the function; if provided, appear below the

list[str] |list[dict[str, s tr |list]] |list[list] | chatbot and can be clicked to popúlate the chatbot input.

N on e

default: None

c a c h e _ e x a m p le s If True, caches examples in the server for fast runtime in

b o o l |L ite ra l['la z y '] |N on e examples. The default option in HuggingFace Spaces is True. '

default: None default option elsewhere is False.

t it le a title for the interface; if provided, appears above chatbot in

str |N on e font. Also used as the tab title when opened in a browser wind

default: None

d e s c r ip t io n a description for the interface; if provided, appears above the

str |N on e chatbot and beneath the title in regular font. Accepts Markdo\

default: None and HTML content.

th e m e Them e to use, loaded from gradio.themes.

T h e m e |s tr |N on e

default: None

css Custom css as a string or path to a css file. This css will be incl

str |N on e in the demo webpage.

default: None

js Custom js as a string or path to a js file. The custom js should 1

str |N on e the form of a single js function. This function will automatical

default: None executed when the page loads. For more flexibility, use the he

parameter to insert js inside <script> tags.

head Custom html to insert into the head of the demo webpage. Th

str |N on e can be used to add custom meta tags, multiple scripts,

default: None stylesheets, etc. to the page.


Parameter Description

a n a ly t ic s _ e n a b le d Whether to allow basic telemetry. If None, will use

b o o l |N o n e GRADIO_ANALYTICS_ENABLED environment variable if define

default: None default to True.

s u b m it_ b tn Text to display on the submit button. If None, no button will b

str 1N o n e |B u tto n displayed. If a Button object, that button will be used.

default: "Subm it"

sto p _ b tn Text to display on the stop button, which replaces the submit.

str 1N o n e |B u tto n when the subm it.btn or retry.btn is clicked and response is

default: "Stop" streaming. Clicking on the stop.btn will halt the chatbot

response. If set to None, stop button functionality does not

appear in the chatbot. If a Button object, that button will be u

as the stop button.

re try _ b tn Text to display on the retry button. If None, no button will be

str 1N o n e |B u tto n displayed. If a Button object, that button will be used.

default: " Retry"

u n d o _ b tn Text to display on the delete last button. If None, no button wi

str |N o n e |B u tto n displayed. If a Button object, that button will be used.

default: " Undo"

c le a r _ b t n Text to display on the clear button. If None, no button will be

str |N o n e |B u tto n displayed. If a Button object, that button will be used.

default: " Clear"

a u to fo c u s If True, autofocuses to the textbox when the page loads.

bool

default: True

c o n c u r r e n c y _ lim it If set, this is the maximum number of chatbot submissions th.

in t |N o n e |L ite ra l['d e fa u lt'] can be running simultaneously. Can be set to None to mean n

default: "default" limit (any number of chatbot submissions can be running


Parameter Description

simultaneously). Set to "default" to use the default concurren

limit (defined by the d e f a u l t _ c o n c u r r e n c y _ l i m i t param<

in .q u e u e ( ) , which is 1 by default).

fill_ h e ig h t If True, the chat interface will expand to the height of window.

bool

default: True

d e le t e _ c a c h e A tuple corresponding [frequency, age] both expressed in nun

tuple[int, int] |N on e of seconds. Every f r e q u e n c y seconds, the temporary files

default: None created by this Blocks instance will be deleted if more than ag

seconds have passed since the file was created. For example,

setting this to (86400, 86400) will delete temporary files every

The cache will be deleted entirely when the server restarts. If

None, no cache deletion will occur.

Demos

chatinterface_multimodal chatinterface_random _response chatinterface_streaming_€

im port g r a d io as gr

d e f ech o ( m essage, h i s t o r y ) :

r e t u r n m essage[ " t e x t " ]

demo = g r . C h a t I n t e r f a c e ( f n =ech o , exam ples=[ { " t e x t " : " h e l i o " } , { " t e x t " : "h o la "} , { " t e x t " : "m e rh ab a"}]

t i t l e ="E ch o B o t " , m u ltim o d a l=T ru e )

demo. la u n c h ( )
Loading...

g r a d io / c h a t in t e r f a c e _ m u lt im o d a l built with Gradio. Hosted on ffi Space

Guides

Creating A Chatbot Fast

Sharing Your App

^ Interface TabbedInterface

$ gradio Status xO
Custom Components GalleryNEW Explore

<§, gradio

New to Gradio? Start here: Getting Started See the Release History

^ Chatbot CheckboxGroup

Checkbox

g r a d io . C h a tb o t( •••)

Loading...

gradio/checkbox_component built with Gradio. Hosted on B Spaces

Description
Creates a checkbox that can be set to True or False . Can be used as an input to

pass a boolean value to a function or as an output to display a boolean value.

Behavior
As input component: Passes the status of the checkbox as a bool.

Your function should accept one of these types:

d e f p r e d ic t (

v a lu e : l i s t [ l i s t [ s t r | tu p le [ s t r ] | tu p le [ s t r , s t r ] | None] ] | None

. . . d e f p r e d ic t (
v a lu e : bool | None

As output component: Expects a bool value that is set as the status of the

checkbox

Your function should return one of these types:

d e f p r e d ic t ( ^ " ) -> l i s t [ l i s t [ stn | tu p le [ s tn ] | tu p le [ s t r , s tn ] | None] | tu p ie ] | None

re tu rn v a lu e d e f p r e d ic t ( ^ " ) -> bool | None

re tu rn v a lu e

Initialization
Parameter Description

v a lu e if True, checked by default. If callable, the function

bool | Callable will be called whenever the app loads to set the

default: False initial value of the component.

la b e l The label for this component. Appears above the

str I None component and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r.In te rfa c e , the label will be the

name of the parameter this component is assigned

to.

in f o additional component description.

str I None

default: None
Parameter Description

every If value is a callable, run the function 'every'

flo a t |N o n e number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

show _label if True, will display label.

b o o l 1N o n e

default: None

c o n ta in e r If True, will place the component in a container -

bool providing some extra padding around the border.

default: True

s c a le relative size compared to adjacent Components.

in t 1N o n e For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A will be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

min_width minimum pixel width, will wrap if not sufficient

in t screen space to satisfy this value. If a certain scale

default: 160 value results in this Component being narrower

than min_width, the min_width parameter will be

respected first.

in t e r a c t iv e if True, this checkbox can be checked; if False,

b o o l |N o n e checking will be disabled. If not provided, this is

default: None inferred based on whether the component is used

as an input or output.
Parameter Description

v is ib le If False, component will be hidden.

bool

default: True

e le m _ id An optional string that is assigned as the id of this

str |None component in the HTML DOM. Can be used for

default: None targeting CSS styles.

e le m _ c la s s e s An optional list of strings that are assigned as the

list[str] Istr I None classes of this component in the HTML DOM. Can

default: None be used for targeting CSS styles.

re n d e r If False, component will not render be rendered in

bool the Blocks context. Should be used if the intention

default: True is to assign event listeners now but render the

component later.

Shortcuts
Interface String
Class Initialization
Shortcut

gradio.Chatbot "checkbox" Uses default values

Demos

sentence_builder hello_world_3

im port g ra d io as gr

im port random

im port tim e
I
w ith g r . B lo c k s ( ) as demo:

c h atb o t = gn. C h a tb o t( )

msg = gn. Textbox( )

c le a n = gn. C le a n B u tto n ( [ msg, c h a tb o t] )


I
d e f nespond( message, c h a t _ h is t o n y ) :

bot messase = nandom. c h o ic e ( [ ''How ane v o u ? " . " I lo v e v o u " . " I 'm venv hunsn

Loading...

gradio/sentence_builder built with Gradio. Hosted on B Spaces

Event Listeners

Description
Event listeners allow you to capture and respond to user interactions with
the UI components you've defined in a Gradio Blocks app. When a user
interacts with an element, such as changing a slider value or uploading an
image, a function is called.

Supported Event Listeners


The C h e ck b o x component supports the following event listeners. Each
event listener takes the same parameters, which are listed in the Event
Arguments table below.

Listener Description

gnadio.Chatbot.change(f Triggered when the value of the Checkbox


changes either because of user input (e.g. a
n, •••)
Listener Description

user types in a textbox) OR because of a


function update (e.g. an image receives a value
from the output of an event trigger). See
.inp ut() for a listener that is only triggered
by user input.

gradio.Chatbot.select(f This listener is triggered when the user

n, •••) changes the value of the Checkbox.

gradio.Chatbot.like(fn, Event listener for when the user selects or

•••) deselects the Checkbox. Uses event data


gradio.SelectData to carry value referring to
the label of the Checkbox, and selected to
refer to state of the Checkbox. See EventData
documentation on how to use this event data

Event Arguments
Parameter Description

fn the function to call when this event is


Callable | None | triggered. Often a machine learning model's
Literal['decorator'] prediction function. Each parameter of the
default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tuple of values, with each

element in the tuple corresponding to one

output component.

inputs List of gradio.components to use as inputs. If


Component | list[Component] | the function takes no inputs, this should be an
set[Component] | None empty list.
default: None
Parameter Description

outputs List of gradio.components to use as outputs. If


Component | list[Component] | the function returns no outputs, this should be
None an empty list.
default: None

api_name defines how the endpoint appears in the API


str 1None |Literal[False] docs. Can be a string, None, or False. If set to a
default: None string, the endpoint will be exposed in the API

docs with the given name. If None (default),

the name of the function will be used as the

API endpoint. If False, the endpoint will not be

exposed in the API docs and downstream apps

(including those that g r.lo ad this app) will

not be able to use this event.

scroll_to_output If True, will scroll to output component on


bool completion
default: False

show_progress If True, will show progress animation while


Literal[(’fu ll’, ’m inim al’, pending
’hidden’)]

default: "ful!"

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


bool 1None the queue has been enabled. If False, will not
default: None put this event on the queue, even if the queue

has been enabled. If None, will use the queue

setting of the gradio app.


Parameter Description

batch If True, then the function should process a


bool batch of inputs, meaning that it should accept
default: False 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 r e q u ir e d 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 Maximum number of inputs to batch together


in t if this is called from the queue (only relevant if
default: 4 batch=True)

preprocess If False, will not run preprocessing of


bool component data before running 'fn' (e.g.
default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, will not run postprocessing of


bool component data before returning 'fn' output
default: True to the browser.

cancels A list of other events to cancel when this


dict[str, A n y ] |list[dict[str, listener is triggered. For example, setting
A ny]] 1N o n e cancels=[click_event] will cancel the
default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) will be cancelled, but


Parameter Description

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds


float | None while the client connection is open.
default: None Interpreted in seconds.

trigger_mode If "once" (default for all events except


Literal[('once', 'múltiple', .change()) would not allow any submissions
’a lw a y s ja s t’)] |None while an event is pending. If set to "multiple",
default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.change() and .key_up() events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before


str 1None running 'fn'. Input arguments for js method are
default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

concurrency_limit If set, this is the maximum number of this


int 1None |Literal['default'] event that can be running simultaneously. Can
default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency limit (defined by the

default_concurrency_lim it parameter in

Blocks.queue(), which itself is 1 by default).


Parameter Description

c o n c u rre n c y _ id If set, this is the id of the concurrency group.

str | None Events with the same concurrency_id will be

default: None limited by the lowest set concurrencyjim it.

show _api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

automatically be set to False.

Chatbot CheckboxGroup -

^ gradio Status O
Custom Components GalleryNEW Explore

<§, gradio

New to Gradio? Start here: Getting Started See the Release History

^ Checkbox ClearButton

CheckboxGroup

g r a d io . C h a tb o t( •••)

Loading...

gradio/checkbox_component built with Gradio. Hosted on B Spaces

Description
Creates a checkbox that can be set to True or F a lse . Can be used as an input to

pass a boolean value to a function or as an output to display a boolean value.

Behavior
As input component: Passes the status of the checkbox as a bool.

Your function should accept one of these types:

d e f p r e d ic t (

v a lu e : l i s t [ l i s t [ s t r | tu p le [ s t r ] | tu p le [ s t r , s t r ] | None] ] | None

. . . d e f p r e d ic t (
v a lu e : bool | None

As output component: Expects a bool value that is set as the status of the

checkbox

Your function should return one of these types:

d e f p r e d ic t ( ^ " ) -> l i s t [ l i s t [ stn | tu p le [ s tn ] | tu p le [ s t r , s tn ] | None] | tu p ie ] | None

re tu rn v a lu e d e f p r e d ic t ( ^ " ) -> bool | None

re tu rn v a lu e

Initialization
Parameter Description

v a lu e if True, checked by default. If callable, the function

bool | Callable will be called whenever the app loads to set the

default: False initial value of the component.

la b e l The label for this component. Appears above the

str I None component and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r.In te rfa c e , the label will be the

name of the parameter this component is assigned

to.

in f o additional component description.

str I None

default: None
Parameter Description

every If value is a callable, run the function 'every'

flo a t |N o n e number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

show _label if True, will display label.

b o o l 1N o n e

default: None

c o n ta in e r If True, will place the component in a container -

bool providing some extra padding around the border.

default: True

s c a le relative size compared to adjacent Components.

in t 1N o n e For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A will be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

min_width minimum pixel width, will wrap if not sufficient

in t screen space to satisfy this value. If a certain scale

default: 160 value results in this Component being narrower

than min_width, the min_width parameter will be

respected first.

in t e r a c t iv e if True, this checkbox can be checked; if False,

b o o l |N o n e checking will be disabled. If not provided, this is

default: None inferred based on whether the component is used

as an input or output.
Parameter Description

v is ib le If False, component will be hidden.

bool

default: True

e le m _ id An optional string that is assigned as the id of this

str |None component in the HTML DOM. Can be used for

default: None targeting CSS styles.

e le m _ c la s s e s An optional list of strings that are assigned as the

list[str] Istr I None classes of this component in the HTML DOM. Can

default: None be used for targeting CSS styles.

re n d e r If False, component will not render be rendered in

bool the Blocks context. Should be used if the intention

default: True is to assign event listeners now but render the

component later.

Shortcuts
Interface String
Class Initialization
Shortcut

gradio.Chatbot "checkbox" Uses default values

Demos

sentence_builder hello_world_3

im port g ra d io as gr

im port random

im port tim e
I
w ith g r . B lo c k s ( ) as demo:

c h atb o t = gn. C h a tb o t( )

msg = gn. Textbox( )

c le a n = gn. C le a n B u tto n ( [ msg, c h a tb o t] )


I
d e f nespond( message, c h a t _ h is t o n y ) :

bot messase = nandom. c h o ic e ( [ ''How ane v o u ? " . " I lo v e v o u " . " I 'm venv hunsn

Loading...

gradio/sentence_builder built with Gradio. Hosted on B Spaces

Event Listeners

Description
Event listeners allow you to capture and respond to user interactions with
the UI components you've defined in a Gradio Blocks app. When a user
interacts with an element, such as changing a slider value or uploading an
image, a function is called.

Supported Event Listeners


The C h e ck b o x component supports the following event listeners. Each
event listener takes the same parameters, which are listed in the Event
Arguments table below.

Listener Description

gnadio.Chatbot.change(f Triggered when the value of the Checkbox


changes either because of user input (e.g. a
n, •••)
Listener Description

user types in a textbox) OR because of a


function update (e.g. an image receives a value
from the output of an event trigger). See
.inp ut() for a listener that is only triggered
by user input.

gradio.Chatbot.select(f This listener is triggered when the user

n, •••) changes the value of the Checkbox.

gradio.Chatbot.like(fn, Event listener for when the user selects or

•••) deselects the Checkbox. Uses event data


gradio.SelectData to carry value referring to
the label of the Checkbox, and selected to
refer to state of the Checkbox. See EventData
documentation on how to use this event data

Event Arguments
Parameter Description

fn the function to call when this event is


Callable | None | triggered. Often a machine learning model's
Literal['decorator'] prediction function. Each parameter of the
default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tuple of values, with each

element in the tuple corresponding to one

output component.

inputs List of gradio.components to use as inputs. If


Component | list[Component] | the function takes no inputs, this should be an
set[Component] | None empty list.
default: None
Parameter Description

outputs List of gradio.components to use as outputs. If


Component | list[Component] | the function returns no outputs, this should be
None an empty list.
default: None

api_name defines how the endpoint appears in the API


str 1None |Literal[False] docs. Can be a string, None, or False. If set to a
default: None string, the endpoint will be exposed in the API

docs with the given name. If None (default),

the name of the function will be used as the

API endpoint. If False, the endpoint will not be

exposed in the API docs and downstream apps

(including those that g r.lo ad this app) will

not be able to use this event.

scroll_to_output If True, will scroll to output component on


bool completion
default: False

show_progress If True, will show progress animation while


Literal[(’fu ll’, ’m inim al’, pending
’hidden’)]

default: "ful!"

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


bool 1None the queue has been enabled. If False, will not
default: None put this event on the queue, even if the queue

has been enabled. If None, will use the queue

setting of the gradio app.


Parameter Description

batch If True, then the function should process a


bool batch of inputs, meaning that it should accept
default: False 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 r e q u ir e d 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 Maximum number of inputs to batch together


in t if this is called from the queue (only relevant if
default: 4 batch=True)

preprocess If False, will not run preprocessing of


bool component data before running 'fn' (e.g.
default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, will not run postprocessing of


bool component data before returning 'fn' output
default: True to the browser.

cancels A list of other events to cancel when this


dict[str, A n y ] |list[dict[str, listener is triggered. For example, setting
A ny]] 1N o n e cancels=[click_event] will cancel the
default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) will be cancelled, but


Parameter Description

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds


float | None while the client connection is open.
default: None Interpreted in seconds.

trigger_mode If "once" (default for all events except


Literal[('once', 'múltiple', .change()) would not allow any submissions
’a lw a y s ja s t’)] |None while an event is pending. If set to "multiple",
default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.change() and .key_up() events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before


str 1None running 'fn'. Input arguments for js method are
default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

concurrency_limit If set, this is the maximum number of this


int 1None |Literal['default'] event that can be running simultaneously. Can
default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency limit (defined by the

default_concurrency_lim it parameter in

Blocks.queue(), which itself is 1 by default).


Parameter Description

c o n c u rre n c y _ id If set, this is the id of the concurrency group.

str | None Events with the same concurrency_id will be

default: None limited by the lowest set concurrencyjim it.

show _api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

automatically be set to False.

Chatbot CheckboxGroup -

^ gradio Status O
Custom Components GalleryNEW Explore

<§, gradio =

New to Gradio? Start here: Getting Started See the Release History

^ CheckboxGroup Code

ClearButton

gradio.ClearButton(•••)

Textbox

This issome text


J

Clear

gradio/clearbutton_component built with Gradio. Hosted on B Spaces

Description
Button that clears the value of a component or a list of components when
clicked. It is instantiated with the list of components to clear.

Behavior &

As input component: (Rarely used) the s tr corresponding to the button label

when the button is clicked

Your function should accept one of these types:

def predict(

value: str | None

As output component: string corresponding to the button label


Your function should return one of these types:

def predict(^ " ) -> str | None

return value

Initiaiization
Parameter Description

components

None |lis t[C o m p o n e n t] |

Com ponent

default: None

value Default text for the button to display. If callable,

s tr the function will be called whenever the app loads

default: "Clear" to set the initial value of the component.

every If value is a callable, run the function 'every'

flo a t I N o n e number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

v a r ia n t 'primary' for main call-to-action, 'secondary' for a

L ite r a l[ C p rim a ry ’, 's e c o n d a ry , more subdued style, 'stop' for a stop button.

'stop')]

default: "secondary"

s iz e Size of the button. Can be "sm" or "Ig".

Literal[('sm ', ’lg')] |N o n e

default: None
Parameter Description

icon URL or path to the icon file to display within the

str |N o n e button. If None, no icon will be displayed.

default: None

lin k URL to open when the button is clicked. If None, no

s t r 1N o n e link will be used.

default: None

v is ib le If False, component will be hidden.

bool

default: True

in t e r a c t iv e If False, the Button will be in a disabled state.

bool

default: True

elem_id An optional string that is assigned as the id of this

s t r 1N o n e component in the HTML DOM. Can be used for

default: None targeting CSS styles.

elem _classes An optional list of strings that are assigned as the

list[str] 1s t r 1N o n e classes of this component in the HTML DOM. Can

default: None be used for targeting CSS styles.

render If False, component will not render be rendered in

bool the Blocks context. Should be used if the intention

default: True is to assign event listeners now but render the

component later.
Parameter Description

s c a le relative size compared to adjacent Components.

in t |N o n e For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A will be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

min_width minimum pixel width, will wrap if not sufficient

in t I N o n e screen space to satisfy this value. If a certain scale

default: None value results in this Component being narrower

than min_width, the min_width parameter will be

respected first.

api_name

s t r IN o n e |L ite ra l['F a ls e ']

default: None

show_api

bool

default: False

Shortcuts
Interface String
Class Initialization
Shortcut

g r a d io . C lea rB u tto n "clearbutton" Uses default values

Event Listeners

Description
Event listeners allow you to capture and respond to user interactions with
the UI components you've defined in a Gradio Blocks app. When a user
interacts with an element, such as changing a slider value or uploading an
image, a function is called.

Supported Event Listeners


The C le a r B u t t o n component supports the following event listeners.
Each event listener takes the same parameters, which are listed in the
Event Arguments table below.

Listener Description

gradio.ClearButton.add( Adds a component or list of components to


fn, •••) the list of components that will be cleared
when the button is clicked.

gradio.ClearButton. c lic Triggered when the Button is clicked.


k(fn, •••)

Event Arguments
Parameter Description

components

None |C o m p o n e n t |

lis t[C o m p o n e n t]

r e q u ir e d

CheckboxGroup Code

0 gradio Status >£ O


Custom Components GalleryNEW Explore

<§, gradio =

New to Gradio? Start here: Getting Started See the Release History

^ ClearButton ColorPicker

Code

gradio.Code(•••)

Loading...

gradio/code_component built with Gradio. Hosted on EB Spaces

Description ¿¡P
Creates a code editor for viewing code (as an output component), or for entering

and editing code (as an input component).

Behavior
As input component: Passes the code entered as a s t r .

Your function should accept one of these types:

def predict(

value: str | None

)
As output component: Expects a s tr of code or a single-element tu p ie :

(filepath,) with the s tr path to a file containing the code.

Your function should return one of these types:

def predict(---) -> tuple[str] | str | None

return value

Initiaiization
Parameter Description

value Default value to show in the code editor. If callable,

s t r |C a lla b le |tu p le[str] |N o n e the function will be called whenever the app loads

default: None to set the initial value of the component.

language The language to display the code as. Supported

L ite r a l[C p y t h o n ', ’m a r k d o w n ’, languages listed in gr.Code.languages.

’j s o n ’, h t m l , ’c s s , ja v a s c r ip t ,

’ty p e s c r ip t, ’y a m l , ’d o c k e r file '

’s h e ll, 'r, S q l, S q l-m sS Q L , Sq l-

m y S Q L , S q l- m a r ia D B , S q l-s q lite ,

S q l- c a s s a n d r a , S q l-p lS Q L , Sq l-

h iv e , S q l-p g S Q L , S q l- g q l, S q l-

g p S Q L , S q l-s p a rk S Q L , Sq l-

e s p e r ’)] |N o n e

default: None

every If value is a callable, run the function 'every'

flo a t |N o n e number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

lin e s
Parameter Description

in t

default: 5

la b e l The label for this component. Appears above the

str |N o n e component and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r.In te rfa c e , the label will be the

name of the parameter this component is assigned

to.

in t e r a c t iv e Whether user should be able to enter code or only

b o o l 1N o n e view it.

default: None

show _label if True, will display label.

b o o l 1N o n e

default: None

c o n ta in e r If True, will place the component in a container -

bool providing some extra padding around the border.

default: True

s c a le relative size compared to adjacent Components.

in t 1N o n e For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A will be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.


Parameter Description

min_width mínimum pixel width, will wrap if not sufficient

in t screen space to satisfy this value. If a certain scale

default: 160 value results in this Component being narrower

than min_width, the min_width parameter will be

respected first.

v is ib le If False, component will be hidden.

bool

default: True

elem_id An optional string that is assigned as the id of this

str |N o n e component in the HTML DOM. Can be used for

default: None targeting CSS styles.

elem _classes An optional list of strings that are assigned as the

list[str] Is t r I N o n e classes of this component in the HTML DOM. Can

default: None be used for targeting CSS styles.

render If False, component will not render be rendered in

bool the Blocks context. Should be used if the intention

default: True is to assign event listeners now but render the

component later.

Shortcuts
Interface String
Class Initialization
Shortcut

g ra d io .C o d e "code" Uses default values

Event Listeners
Description
Event listeners allow you to capture and respond to user interactions with
the UI components you've defined in a Gradio Blocks app. When a user
interacts with an element, such as changing a slider value or uploading an
image, a function is called.

Supported Event Listeners


The Code component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Arguments
table below.

Listener Description

gradio.Code. languages(f ['python', 'markdown', 'json', 'html', 'css',


n, •••) 'javascript', 'typescript', 'yaml', 'dockerfile',
'shell', 'r', 'sql', 'sql-msSQL', 'sql-mySQL', 'sq l-
mariaDB', 'sql-sqlite', 'sql-cassandra', 'sq l-
plSQL', 'sql-hive', 'sql-pgSQL', 'sql-gql', 'sq l-
gpSQL', 'sql-sparkSQL', 'sql-esper', None]

gradio.Code. change(fn, Triggered when the value of the Code changes


•••) either because of user input (e.g. a user types
in a textbox) OR because of a function update
(e.g. an image receives a value from the output
of an event trigger). See .inp ut() for a
listener that is only triggered by user input.

gradio.Code. input(fn, This listener is triggered when the user


•••) changes the value of the Code.

gradio.Code. focus(fn, This listener is triggered when the Code is


•••) focused.

gradio.Code.blur(fn, This listener is triggered when the Code is


•••) unfocused/blurred.

Event Arguments
Parameter Description

^ ClearButton ColorPicker

^ gradio Status X o
Custom Components GalleryNEW Explore

<§, gradio

New to Gradio? Start here: Getting Started See the Release History

^ Code Dataframe

ColorPicker

gradio.ColorPicker(•••)

ColorPicker

gradio/colorpicker_component built with Gradio. Hosted on B Spaces

Description
Creates a color picker for user to select a color as string input. Can be used as an
input to pass a color value to a function or as an output to display a color value.

Behavior
As input component: Passes selected color value as a hex s tr into the function.

Your function should accept one of these types:

def predict( cP
value: str | None

As output component: Expects a hex s tr returned from function and sets color

picker value to it.

Your function should return one of these types:

def predictp " ) -> str | None


return value

Initiaiization
Parameter Description

value default text to provide in color picker. If callable,

str |C a lla b le |N o n e the function will be called whenever the app loads

default: None to set the initial value of the component.

la b e l The label for this component. Appears above the

s t r 1N o n e component and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r.In te rfa c e , the label will be the

name of the parameter this component is assigned

to.

in fo additional component description.

s t r 1N o n e

default: None

every If value is a callable, run the function 'every'

flo a t 1N o n e number of seconds while the client connection is

default: None open. Has no effect otherwise.sed (e.g. to cancel it)

via this component's .load_event attribute.

show _label if True, will display label.

b o o l 1N o n e

default: None

c o n ta in e r If True, will place the component in a container -

bool providing some extra padding around the border.

default: True
Parameter Description

s c a le relative size compared to adjacent Components.

in t |N o n e For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A will be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

min_width minimum pixel width, will wrap if not sufficient

in t screen space to satisfy this value. If a certain scale

default: 160 value results in this Component being narrower

than min_width, the min_width parameter will be

respected first.

in t e r a c t iv e if True, will be rendered as an editable color picker;

b o o l IN o n e if False, editing will be disabled. If not provided,

default: None this is inferred based on whether the component is

used as an input or output.

v is ib le If False, component will be hidden.

bool

default: True

elem_id An optional string that is assigned as the id of this

s t r IN o n e component in the HTML DOM. Can be used for

default: None targeting CSS styles.

elem _classes An optional list of strings that are assigned as the

list[str] Is t r I N o n e classes of this component in the HTML DOM. Can

default: None be used for targeting CSS styles.


Parameter Description

render If False, component will not render be rendered in

bool the Blocks context. Should be used if the intention

default: True is to assign event listeners now but render the

component later.

Shortcuts
Interface String
Class Initialization
Shortcut

g r a d io . C o lo rP ic k e r "colorpicker" Uses default values

Demos

color_picker


import gradio as gr

import numpy as np

import os

from PIL import Image, ImageColor


I
def change_color(icon, color):

Function that given an icon in .png format changes its color

Args:

O
Loading...

gradio/color_picker built with Gradio. Hosted on EB Spaces

Event Listeners

Description
Event listeners allow you to capture and respond to user interactions with
the UI components you've defined in a Gradio Blocks app. When a user
interacts with an element, such as changing a slider value or uploading an
image, a function is called.

Supported Event Listeners


The C o l o r P i c k e r component supports the following event listeners.
Each event listener takes the same parameters, which are listed in the
Event Arguments table below.

Listener Description

g rad io.C olorP icker. chan Triggered when the value of the ColorPicker
ge(fn, •••) changes either because of user input (e.g. a
user types in a textbox) OR because of a
function update (e.g. an image receives a value
from the output of an event trigger). See
.inp ut() for a listener that is only triggered
by user input.

g rad io.C olorP icker. inpu This listener is triggered when the user
t ( f n, •••) changes the value of the ColorPicker.

g rad io.C olorP icker. subm This listener is triggered when the user presses
it ( f n , •••) the Enter key while the ColorPicker is focused.

g rad io.C olorP icker. focu This listener is triggered when the ColorPicker
s(fn, •••) is focused.

gradio.C olorP icker.blur This listener is triggered when the ColorPicker


Listener Description

(fn, •••) is unfocused/blurred.

Event Arguments
Parameter Description

fn the function to call when this event is


C a lla b le |N o n e | triggered. Often a machine learning model's
L ite ra l['d e c o ra to r'] prediction function. Each parameter of the
default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tuple of values, with each

element in the tuple corresponding to one

output component.

inputs List of gradio.components to use as inputs. If


Com ponent |lis t[C o m p o n e n t] | the function takes no inputs, this should be an
s e t[C o m p o n e n t] |N o n e empty list.
default: None

outputs List of gradio.components to use as outputs. If


C o m p o n e n t |lis t[C o m p o n e n t] | the function returns no outputs, this should be
None an empty list.
default: None

api_name defines how the endpoint appears in the API


str |N o n e |L ite ra l[F a ls e ] docs. Can be a string, None, or False. If set to a
default: None string, the endpoint will be exposed in the API

docs with the given name. If None (default),

the name of the function will be used as the

API endpoint. If False, the endpoint will not be

exposed in the API docs and downstream apps


Parameter Description

(including those that g r.lo ad this app) will

not be able to use this event.

scroll_to_output If True, will scroll to output component on


bool completion
default: False

show_progress If True, will show progress animation while


L ite ra l[(’f u ll’, ’m in im a l’, pending
’h id d e n ’)]

default: "ful!"

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


bool |N o n e the queue has been enabled. If False, will not
default: None put this event on the queue, even if the queue

has been enabled. If None, will use the queue

setting of the gradio app.

batch If True, then the function should process a


bool batch of inputs, meaning that it should accept
default: False 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 r e q u ir e d 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 Maximum number of inputs to batch together


in t if this is called from the queue (only relevant if
default: 4 batch=True)
Parameter Description

preprocess If False, will not run preprocessing of


bool component data before running 'fn' (e.g.
default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, will not run postprocessing of


bool component data before returning 'fn' output
default: True to the browser.

cancels A list of other events to cancel when this


dict[str, A n y ] |list[dict[str, listener is triggered. For example, setting
A ny]] 1N o n e cancels=[click_event] will cancel the
default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) will be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds


flo a t 1N o n e while the client connection is open.
default: None Interpreted in seconds.

trigger_mode If "once" (default for all events except


L ite r a l[ ( 'o n c e ','m ú lt ip le , .change()) would not allow any submissions
’a l w a y s j a s t ’) ] |N o n e while an event is pending. If set to "multiple",
default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.change() and .key_up() events) would


Parameter Description

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before


str |N o n e running 'fn'. Input arguments for js method are
default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

concurrency_limit If set, this is the maximum number of this


in t 1N o n e |L ite ra l['d e fa u lt'] event that can be running simultaneously. Can
default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency limit (defined by the

default_concurrency_lim it parameter in

Blocks.queue(), which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.


s t r 1N o n e Events with the same concurrency_id will be
default: None limited by the lowest set concurrency_limit.

show_api whether to show this event in the "view API"


bool page of the Gradio app, or in the ".view_api()"
default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

will still allow downstream apps to use this

event. If fn is None, show_api will

automatically be set to False.

Code Dataframe
$ gradio Status X o
Custom Components Gallery NEW Explore

0 , gradio
New to Gradio? Start here: Getting Started See the Release History

R ow Tab

Column

with gradio.Column():

Description
C o lu m n is a la y o u t e le m e n t w ith in B lo c k s t h a t re n d e rs a ll c h ild re n v e rtic a lly . T he

w id t h s o f c o lu m n s can be s e t th ro u g h th e s c a le a n d m in_w idth p a ra m e te rs. If a

c e rta in s c a le re s u lts in a c o lu m n n a rro w e r th a n m in _ w id th , th e m in _ w id th

p a ra m e te r w ill w in .

Exampíe Usage

with gr.Blocks() as demo:

with gr.Row():

with gr.Column(scale=1 ):

textl = gr.Textbox()

text2 = gr.Textbox()

with gr.Column(scale=4 ):

btnl = gr.Button("Button 1")

btn2 = gr.Button("Button 2")

Initiaíization
Parameter Description

scale relative width compared to adjacent Columns. For

int example, if Column A has scale=2, and Column B


Parameter Description

default: 1 has scale=1, A w ill be twice as wide as B.

m in _ w id t h m ínim um pixel width of Column, w ill wrap if not

int sufficient screen space to satisfy this value. If a

default: 320 certain scale value results in a colum n narrower

than min_width, the min_width parameter w ill be

respected first.

v a r ia n t colum n type, 'default' (no background), 'panel'

Literal[('default', 'panel', (gray background color and rounded corners), or

'compact')] 'com pact' (rounded corners and no internal gap).

default: "default"

v is ib le If False, column w ill be hidden.

bool

default: True

e le m _ id An optional string that is assigned as the id of this

str | None com ponent in the HTML DOM. Can be used for

default: None targeting CSS styles.

e l e m _ c la s s e s An optional string or list of strings that are

list[str] 1str 1None assigned as the class of this com ponent in the

default: None HTML DOM. Can be used for targeting CSS styles.

re n d e r If False, com ponent w ill not render be rendered in

bool the Blocks context. Should be used if the intention

default: True is to assign event listeners now but render the

com ponent later.


Guides

Controlling Layout

R ow Tab

^ gradio Status X O
Custom Components GalleryNEW Explore

*§ gradio

New to Gradio? Start here: Getting Started See the Release History

^ Accordion AnnotatedIm age

Components

G radio in cludes pre-built com ponents that can be used as in puts o r o utputs in yo ur Interface or B lo cks w ith a single line of code. Com ponents include preprocessing steps that convert user data subm itted through brow ser to
som ething th a t be can used by a Python fun ctio n, and postprocessin g steps to convert va lu e s returned by a Python function into som ething th a t can be displayed in a browser.

C on sider an exam ple w ith three in puts (Textbox, Number, and Image) and tw o o utputs (N um ber and G a lle ry), below is a diagram of w hat o ur preprocessing w ill send to the function and w hat our postprocessing w ill require from it.

C om ponents also come w ith certain events th a t th e y suppo rt. These are m ethods th a t are triggered w ith user actio ns. Below is a table show ing w hich eve nts are supported for each com ponent. All eve nts are also listed (w ith
param eters) in the com ponent's docs.

submit stop_recording edit like start_recording click change upload release blur play apply pause_recording

AnnotatedImage X X X X X X X X X X X X X X X X X X X X X y

Audio X y y y y X X y X y X y y X X y X y X X X X

BarPlot X X X X X X X y X X X y X X X X X X X X X X

Button X X X X X X X X X X y X X X X X X X X X X X

Chatbot X X X X X X y X X X X y X X X X X X X X X y

Checkbox X X X X X X X X X X X y X X X X X X X X y y •.

^ Accordion AnnotatedIm age

-o gradio Status
Custom Com ponents G a lle ry NEW E x p lo re

*§ gradio =

New to Gradio? Start here: G ettíng Started See the Release Hístory

^ C o lo r P ic k e r D a ta se t

Dataframe

g r a d i o .Dat a f r a m e ( ■■■)

1 ▲ 2 ▲ 3 ▲ ^

4 ►

•4» N ew row -> N ew c o lu m n

gradio/dat af ra me _c om po ne nt b u ilt w ith G ra d io . H osted on 83 Spaces

Description
T h is c o m p o n e n t d is p la y s a ta b le o f v a lu e s p re a d s h e e t-lik e c o m p o n e n t. C a n be u se d to d is p la y d a ta as an o u t p u t c o m p o n e n t, o r as an

in p u t to c o lle c t d a ta fro m th e user.

Behavior
A s in p u t c o m p o n e n t: P asses th e u p lo a d e d s p r e a d s h e e t d a ta as a p a n d a s .D a ta F ra m e , n u m p y .a rr a y , p o la r s .D a t a F r a m e , o r n a tiv e 2D

P y th o n l i s t [ l i s t ] d e p e n d in g o n t y p e

Your function should accept one of these types:

def p r e d i c t (

v a l u e : p d .DataFrame | n p .ndarray | p l .DataFrame | li s t [li s t ]

A s o u t p u t c o m p o n e n t : E x p e c ts d a ta a n y o f th e s e fo rm a ts: p a n d a s .D a ta F ra m e , p a n d a s . S t y le r , n u m p y .a rr a y , p o la r s .D a t a F r a m e ,

l i s t [ l i s t ] , l i s t , o r a d i c t w ith ke ys 'd a ta ' (and o p tio n a lly 'h e a d e rs'), o r s t r p a th to a csv, w h ic h is re n d e re d as th e sp re a d s h e e t.

Your function should return one of these types:

def p r e d i c t ( ■■■) -> p d .DataFrame | Styler | n p .ndarray | p l .DataFrame | list | l i s t [li s t ] | dict | str | None

Initialization
Param eter D escription

v a lu e Default value to display in the DataFrame. If a Styler is provided, it w ill be used to set

pd.DataFrame | Styler |np.ndarray |pl.DataFrame | list | the displayed value in the DataFrame (e.g. to set precision of numbers) if the

list[list] | dict |str | Callable |None I n t e r a c t i v e is False. If a Callable function is provided, the function w ill be called

default: None whenever the app loads to set the initial value of the com ponent.

h e a d e rs List of str header names. If None, no headers are shown.

list[str] |None

default: None

row _count Lim it num ber of rows for input and decide whether user can create new rows. The

int | tuple[int, str] first elem ent of the tuple is an i n t , the row count; the second should be 'fixed' or

default: (1, 'dynamic') 'dynamic', the new row behaviour. If an i n t is passed the rows default to 'dynam ic'

c o l_ c o u n t Lim it num ber of colum ns for input and decide whether user can create new columns.

int | tuple[int, str] |None The first elem ent of the tuple is an i n t , the num ber of columns; the second should be

default: None 'fixed' or 'dynamic', the new colum n behaviour. If an i n t is passed the colum ns

default to 'dynam ic'


Parameter Descríptíon

d a ta ty p e Datatype of valúes in sheet. Can be provided per colum n as a list of strings, or for the

str | list[str] entire sheet as a single string. Valid datatypes are "str", "number", "bool", "date", and

default: "str" "markdown".

ty p e Type of value to be returned by com ponent. "pandas" for pandas dataframe,

Literal[('pandas', 'numpy', 'array', 'polars')] "num py" for numpy array, "polars" for polars dataframe, or "array" for a Python list of

default: "pandas" lists.

la t e x _ d e lim ite r s A list of dicts of the form " l e f t " : open d e l i m i t e r ( s t r ) , " r ig h t " : c lo s e

!¡st[dict[str, str | bool]] |None d e lim it e r ( s t r ) , " d is p la y " : w h e th e r t o d i s p l a y in n e w lin e ( b o o l)

default: None that w ill be used to render LaTeX expressions. If not provided, l a t e x _ d e l i m i t e r s is

set to [ " l e f t " : "$ $ ", " r ig h t " : "$ $ ", " d is p la y " : T r u e ] , so only

expressions enclosed in $$ delim iters w ill be rendered as LaTeX, and in a new line.

Pass in an em pty list to disable LaTeX rendering. For more inform ation, see the [KaTeX

docum entation](https://katex.org/docs/autorender.html). Only applies to colum ns

whose datatype is "markdown".

la b e l The label for this com ponent. Appears above the com ponent and is also used as the

str |None header if there are a table of examples for this com ponent. If None and used in a

default: None g r . I n t e r f a c e , the label w ill be the name of the parameter this com ponent is

assigned to.

s h o w _ la b e l if True, w ill display label.

boo! I None

default: None

e ve ry If v a lu e is a callable, run the function 'every' num ber of seconds while the client

float INone connection is open. Has no effect otherwise. The event can be accessed (e.g. to cancel

default: None it) via this com ponent's .load_event attribute.

h e ig h t The m aximum height of the dataframe, specified in pixels if a num ber is passed, or in

int CSS units if a string is passed. If more rows are created than can fit in the height, a

default: 500 scrollbar w ill appear.

s c a le relative size com pared to adjacent Com ponents. For example if Com ponents A and B

int INone are in a Row, and A has scale=2, and B has scale=1, A w ill be twice as wide as B.

default: None Should be an integer. scale applies in Rows, and to top-level Com ponents in Blocks

where fill_height=True.

m in_w idth m inim um pixel width, w ill wrap if not sufficient screen space to satisfy this value. If a

int certain scale value results in this Com ponent being narrower than m in_width, the

default: 160 m in_w idth parameter w ill be respected first.

in t e r a c t iv e if True, w ill a llow users to edit the dataframe; if False, can only be used to display

boo! |None data. If not provided, this is inferred based on w hether the com ponent is used as an

default: None input or output.

v is ib le If False, com ponent w ill be hidden.

boo!

default: True

e le m _ id An optional string that is assigned as the id of this com ponent in the HTML DOM. Can

str |None be used for targeting CSS styles.

default: None

e le m _ c la s s e s An optional list of strings that are assigned as the classes of this com ponent in the

!ist[str] |str |None HTML DOM. Can be used for targeting CSS styles.
Parameter Descríptíon

default: None

ren d er If False, com ponent w ill not render be rendered in the Blocks context. Should be used

bool if the intention is to assign event listeners now but render the com ponent later.

default: True

wrap If True, the text in table cells w ill wrap when appropriate. If False and the

bool c o lu m n _ w id th parameter is not set, the colum n widths w ill expand based on the cell

default: False contents and the table may need to be horizontally scrolled. If c o lu m n _ w id th is set,

then any overflow text w ill be hidden.

lin e _ b r e a k s If True (default), w ill enable Github-flavored Markdown line breaks in chatbot

bool messages. If False, single new lines w ill be ignored. Only applies for colum ns of type

default: True "markdown."

c o lu m n _ w idth s An optional list representing the w idth of each colum n. The elem ents of the list

list[str |int] | None should be in the form at "100px" (ints are also accepted and converted to pixel values)

default: None or "10%". If not provided, the colum n w idths w ill be autom atically determ ined based

on the content of the cells. Setting this parameter w ill cause the browser to try to fit

the table w ithin the page width.

Shortcuts
Class Interface Stríng Shortcut Initialization

g n a d io . Datafname "dataframe" Uses default values

g n a d io . Numpy "num py" Uses type="numpy"

g r a d io . M a trix "m atrix" Uses type="array"

g n a d io . L is t "list" Uses type="array", col_count=1

Demos

f ilt e r _ r e c o r d s m a tr ix _ tr a n s p o s e t a x _ c a lc u la to r s o rt_ re c o rd s

import g r adio as gr

def filt e r _ r e c o r d s (r e c ords, ge n d e r ) :

return r e c o r d s [r e c o rds["gender"] == ge n d e r ]

demo = g r .Int e r f a c e (

filt e r _ r e c o r d s ,

g r .Data f r a m e (

Loading...

gr adio/filter_records b u ilt w ith G ra d io . H osted on ffi Spaces


Event Listeners

Description
E ve n t lis te n e rs a llo w y o u to c a p tu r e a n d re s p o n d to u s e r in te r a c tio n s w ith th e UI c o m p o n e n t s y o u 'v e d e fin e d in a G ra d io

B lo c k s a p p . W h en a u s e r in te ra c ts w ith an e le m e n t, su c h as c h a n g in g a s lid e r v a lu e o r u p lo a d in g an im a g e , a fu n c tio n is c a lle d .

Supported Event Listeners


T h e D a t a f r a m e c o m p o n e n t s u p p o rt s th e fo llo w in g e v e n t lis te n e rs . E ach e v e n t lis te n e r ta k e s th e s a m e p a ra m e te rs , w h ic h are

liste d in th e Event Arguments ta b le b e lo w .

Listener Description

g n a d io . Datafname. change(f n , •••) Triggered when the valúe of the Dataframe changes either because of user input
(e.g. a user types in a textbox) OR because of a function update (e.g. an image
receives a value from the output of an event trigger). See .in p u t ( ) for a listener
that is o nly triggered by user input.

g n a d io . Datafname. in p u t (f n , •••) This listener is triggered when the user changes the value of the Dataframe.

g n a d io . Datafname. s e le c t (f n , •••) Event listener for when the user selects or deselects the Dataframe. Uses event
data gradio.SelectData to carry v a lu e referring to the label of the Dataframe, and
s e le c te d to refer to state of the Dataframe. See EventData docum entation on
how to use this event data

Event Arguments
Parameter Description

fn the function to call when this event is triggered. Often a m achine learning

Callable | None | Literal['decorator'] m odel's prediction function. Each parameter of the function corresponds to one

default: "decorator" input com ponent, and the function should return a single value or a tuple of

values, with each elem ent in the tuple corresponding to one output com ponent.

in p u t s List of gradio.com ponents to use as inputs. If the function takes no inputs, this

Component |list[Component] |set[Component] | None should be an em pty list.

default: None

o u tp u ts List of gradio.com ponents to use as outputs. If the function returns no outputs,

Component |list[Component] |None this should be an em pty list.

default: None

api_nam e defines how the endpoint appears in the API docs. Can be a string, None, or False.

str | None |Literal[False] If set to a string, the endpoint w ill be exposed in the API docs with the given

default: None name. If None (default), the name of the function w ill be used as the API

endpoint. If False, the endpoint w ill not be exposed in the API docs and

downstream apps (including those that g r .lo a d this app) w ill not be able to use

this event.

s c r o ll_ t o _ o u t p u t If True, w ill scroll to output com ponent on com pletion

bool

default: False

sh o w _ p ro g re ss If True, w ill show progress anim ation while pending

Literal[('full', 'minimal', 'hidden')]

default: "full"

queue If True, w ill place the request on the queue, if the queue has been enabled. If

bool | None False, w ill not put this event on the queue, even if the queue has been enabled. If

default: None None, w ill use the queue setting of the gradio app.

b a tc h If True, then the function should process a batch of inputs, meaning that it should

bool accept a list of input values for each parameter. The lists should be of equal
Parameter Descríptíon

default: False length (and be up to length m ax_batch_size). The function is then required to

return a tupie of lists (even if there is only 1 output com ponent), with each list in

the tuple corresponding to one o utput com ponent.

m a x _ b a tc h _ s iz e Maximum num ber of inputs to batch together if this is called from the queue

int (only relevant if batch=True)

default: 4

p re p r o c e s s If False, w ill not run preprocessing of com ponent data before running 'fn' (e.g.

bool leaving it as a base64 string if this m ethod is called with the Image component).

default: True

p o s tp r o c e s s If False, w ill not run postprocessing of com ponent data before returning 'fn'

bool output to the browser.

default: True

c a n c e ls A list of other events to cancel when this listener is triggered. For example, setting

dict[str, Any] |list[dict[str, Any]] | None cancels=[click_event] w ill cancel the click_event, where click_event is the return

default: None value of another com ponents .click method. Functions that have not yet run (or

generators that are iterating) w ill be cancelled, but functions that are currently

running w ill be allow ed to finish.

e v e ry Run this event 'every' num ber of seconds w hile the client connection is open.

float 1None Interpreted in seconds.

default: None

t rig g e r _ m o d e If "once" (default for a ll events except .ch a nge ()) would not a llow any

Llterai[('once'í ' e,'a iw a y sja st')] |None subm issions w hile an event is pending. If set to "m ultiple", unlim ited subm issions
ltip
ú
m

default: None are allowed w hile pending, and "always_last" (default for .change() and

.key_up() events) w ould allow a second subm ission after the pending event is

complete.

js O ptional frontend js method to run before running 'fn'. Input arguments for js

str 1None method are values of 'inputs' and 'outputs', return should be a list of values for

default: None output com ponents.

c o n c u r r e n c y _ lim it If set, this is the maximum num ber of this event that can be running

int 1None | Literai['defauit'] sim ultaneously. Can be set to None to mean no concurrency_lim it (any number

default: "default" of this event can be running sim ultaneously). Set to "default" to use the default

concurrency lim it (defined by the d e fa u lt_ c o n c u rre n c y _ lim it parameter in

B lo c k s.q u e u e (), w hich itself is 1 by default).

c o n c u r r e n c y _ id If set, this is the id of the concurrency group. Events with the same

str | None concurrency_id w ill be lim ited by the low est set concurrency_lim it.

default: None

sh o w _ a p i whether to show this event in the "view API" page of the Gradio app, or in the

bool ".view_api()" m ethod of the Gradio clients. Unlike setting api_nam e to False,

default: True setting show_api to False w ill still a llow downstream apps to use this event. If fn

is None, show_api w ill autom atically be set to False.

C o lo r P ic k e r D a ta se t

*§, gradio Status X


Custom Components GalleryNEW Explore

^ gradio =

New to Gradio? Start here: Getting Started See the Release History

^ Dataframe DownloadButton

Dataset

gr.Dataset(components, samples)

:= Text Dataset

The quick brown fox jumps over the lazy dog

Build & share delightful machine learning apps She sells seashells by the seashore

Supercalifragilisticexpialidocious Lorem ipsum That's all folks!

gradio/dataset_com ponent built with Gradio. Hosted on BB Spaces

Description
Creates a gallery or table to display data samples. This com ponent is designed for

internal use to display examples.

Behavior
As input com ponent: Passes the selected sample either as a l i s t of data

corresponding to each input com ponent (if type is "value") or as an in t index (if

type is "index")

Your function should accept one of these types:

d e f p r e d ic t (
[P
v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (

v a lu e : in t | lis t | None
)

As output com ponent: Expects a l i s t [ l i s t ] corresponding to the dataset data,

can be used to update the dataset.

Your function should return one of these types:

d e f p r e d ic t ( " 0 -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( " 0 -> l i s t [ l i s t ]

re t u r n v a lu e

InitiaMzation
Parameter Description

la b e l The label for this component, appears above the

str |None component.

default: None

c o m p o n e n ts Which com ponent types to show in this dataset

list[Component] | list[str] widget, can be passed in as a list of string names or

required 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

c o m p o n e n t_ p r o p s

list[dict[str, Any]] | None

default: None
Parameter Description

s a m p le s a nested list of samples. Each sublist within the

list[list[Any]] | None outer list represents a data sample, and each

default: None element within the sublist represents an value for

each com ponent

h e a d e rs Column headers in the Dataset widget, should be

list[str] 1None the same len as components. If not provided,

default: None inferred from com ponent labels

ty p e 'values' if clicking on a sample should pass the

Literal[('values', ’index’)] value of the sample, or "index" if it should pass the

default: "valúes" index of the sample

s a m p le s _ p e r _ p a g e how many examples to show per page.

int

default: 10

v is ib le If False, com ponent w ill be hidden.

bool

default: True

e le m _ id An optional string that is assigned as the id of this

str 1None com ponent in the HTML DOM. Can be used for

default: None targeting CSS styles.

e le m _ c la s s e s An optional list of strings that are assigned as the

list[str] 1str 1None classes of this com ponent in the HTML DOM. Can

default: None be used for targeting CSS styles.

re n d e r If False, com ponent w ill not render be rendered in

bool the Blocks context. Should be used if the intention


Parameter Description

default: True is to assign event listeners now but render the

com ponent later.

c o n t a in e r If True, w ill place the com ponent in a container -

bool providing some extra padding around the border.

default: True

s c a le relative size compared to adjacent Components.

int | None For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A w ill be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

m in _ w id t h minimum pixel width, w ill wrap if not sufficient

int screen space to satisfy this value. If a certain scale

default: 160 value results in this Com ponent being narrower

than min_width, the min_width parameter w ill be

respected first.

p ro x y _ u rl The URL of the external Space used to load this

str 1None component. Set autom atically when using

default: None g r . l o a d ( ) . This should not be set manually.

Shortcuts
Interface String
Class Initialization
Shortcut

g r a d io . Dataframe "dataset" Uses default values

Event Listeners
Description
Event listeners allow you to capture and respond to user interactions with

the UI components you've defined in a Gradio Blocks app. When a user


interacts with an element, such as changing a slider value or uploading an

image, a function is called.

Supported Event Listeners


The D a t a s e t com ponent supports the following event listeners. Each

event listener takes the same parameters, which are listed in the Event

Arguments table below.

Listener Description

g r a d io . Datafram e. change Triggered when the Dataset is clicked.

(f n , • • • )

g r a d io . Datafram e. in p u t (f Event listener for when the user selects or

n, •••) deselects the Dataset. Uses event data


gradio.SelectData to carry v a lu e referring to
the label of the Dataset, and s e le c t e d to
refer to state of the Dataset. See EventData
documentation on how to use this event data

Event Arguments
Parameter Description

fn the function to call when this event is

Callable |None | triggered. Often a machine learning model's

Litem l[’decom tor’] prediction function. Each parameter of the

default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tuple of values, with each


Parameter Description

element in the tupie corresponding to one

output component.

in p u t s List of gradio.components to use as inputs. If

Component | list[Component] | the function takes no inputs, this should be an

set[Component] | None empty list.

default: None

o u tp u ts List of gradio.components to use as outputs. If

Component | list[Component] | the function returns no outputs, this should be

None an empty list.

default: None

api_nam e defines how the endpoint appears in the API

str |None |Literal[False] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

s c r o ll_ t o _ o u t p u t If True, w ill scroll to output com ponent on

bool completion

default: False

sh o w _ p ro g re ss If True, w ill show progress animation while

Literal[(’fu ll’, ’m inim al’, pending

’hidden’)]

default: "full
Parameter Description

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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 Maximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this

listener is triggered. For example, setting


Parameter Description

dict[str, Any] | list[dict[str, cancels=[click_event] w ill cancel the

Any]] 1None click_event, where click_event is the return

default: None value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

e v e ry Run this event 'every' number of seconds

float 1None while the client connection is open.

default: None Interpreted in seconds.

trig g e r_ m o d e If "once" (default for all events except

Literal[(’once’, 'm últiple, .c h a n g e ( ) ) would not allow any submissions

’a lw a y s ja s t’)] | None while an event is pending. If set to "multiple",


default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before

str |None running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

c o n c u r r e n c y _ lim it If set, this is the maximum number of this

int 1None | Literal['default'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the


Parameter Description

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

c o n c u rre n c y _ id If set, this is the id of the concurrency group.


str |None Events with the same concurrency_id w ill be

default: None limited by the lowest set co ncurrencyjim it.

show _api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"


default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

autom atically be set to False.

^ Dataframe DownloadButton

^ gradio Status J C
Custom Components GalleryNEW Explore

^ gradio

New to Gradio? Start here: Getting Started See the Release History

^ Dataset Dropdown

DownloadButton

gradio.DownloadButton(•••)

Click to download file

gradio/downloadbutton_component built with Gradio. Hosted on Efi Spaces

Description
Creates a button, that when clicked, allows a user to download a single file of
arbitrary type.

Behavior
As input com ponent: (Rarely used) passes the file as a s t r into the function.

Your function should accept one of these types:

d e f p r e d ic t (
[P
v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (

v a lu e : s t r | None

As output com ponent: Expects a s t r or p a th lib .P a th filepath

Your function should return one of these types:


d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( " 0 -> s t r | Pa th | None

re t u r n v a lu e

InitiaMzation
Parameter Description

la b e l Text to display on the button. Defaults to

str "Download".

default: "Download"

v a lu e A str or pathlib.Path filepath or URL to download,

str |Path | Callable |None or a Callable that returns a str or pathlib.Path

default: None filepath or URL to download.

e v e ry If v a lu e is a callable, run the function 'every'

float 1None number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

v a r ia n t 'primary' for main call-to-action, 'secondary' for a

Literal[(’prim ary’, ’secondary’, more subdued style, 'stop' for a stop button.

'stop')]

default: "secondary"

v is ib le If False, com ponent w ill be hidden.

bool

default: True
Parameter Description

s iz e Size of the button. Can be "sm" or "lg".

Literal[('sm', 'lg')] |None

default: None

ic o n URL or path to the icon file to display within the

str I None button. If None, no icon w ill be displayed.

default: None

s c a le relative size compared to adjacent Components.

int I None For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A w ill be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

m in _ w id t h minimum pixel width, w ill wrap if not sufficient

int I None screen space to satisfy this value. If a certain scale

default: None value results in this Com ponent being narrower

than min_width, the min_width parameter w ill be

respected first.

in t e r a c t iv e If False, the UploadButton will be in a disabled

bool state.

default: True

e le m _ id An optional string that is assigned as the id of this

str I None com ponent in the HTML DOM. Can be used for

default: None targeting CSS styles.

e le m _ c la s s e s An optional list of strings that are assigned as the

list[str] Istr I None classes of this com ponent in the HTML DOM. Can
Parameter Description

default: None be used for targeting CSS styles.

re n d e r If False, com ponent w ill not render be rendered in

bool the Blocks context. Should be used if the intention

default: True is to assign event listeners now but render the

com ponent later.

Shortcuts
Interface String
Class Initialization
Shortcut

g r a d io . Dataframe "downloadbutton" Uses default valúes

Demos

upload_and_download

from pathlib import Path

import gradio as gr

def upload_file(filepath):

name = Path(filepath).name

return [gr.UploadButton(visible=False), gr.DownloadButton(label=f"Downl

oad {name}", value=filepath, visible=True)]

def download_file():

return [gr.UploadButton(visible=T rue), gr.DownloadButton(visible=Fals

e)]
Loading...

gradio/upload_and_download built with Gradio. Hosted on Efi Spaces

Event Listeners

Description
Event listeners allow you to capture and respond to user interactions with

the UI components you've defined in a Gradio Blocks app. When a user


interacts with an element, such as changing a slider value or uploading an

image, a function is called.

Supported Event Listeners


The D o w n lo a d B u t t o n com ponent supports the following event

listeners. Each event listener takes the same parameters, which are listed

in the Event Arguments table below.

Listener Description

g r a d io . Datafram e. change Triggered when the DownloadButton is


(f n , • • • ) d icked.

Event Arguments
Parameter Description

fn the function to call when this event is

Callable |None | triggered. Often a machine learning model's

Litem l[’decom tor’] prediction function. Each parameter of the

default: "decorator" function corresponds to one input

component, and the function should return a


Parameter Description

single value or a tupie of valúes, with each

element in the tupie corresponding to one

output component.

in p u t s List of gradio.components to use as inputs. If

Component | list[Component] | the function takes no inputs, this should be an

set[Component] | None empty list.

default: None

o u tp u ts List of gradio.components to use as outputs. If

Component | list[Component] | the function returns no outputs, this should be

None an empty list.

default: None

api_nam e defines how the endpoint appears in the API

str |None |Literal[False] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

s c r o ll_ t o _ o u t p u t If True, w ill scroll to output com ponent on

bool completion

default: False

sh o w _ p ro g re ss If True, w ill show progress animation while

Literal[(’fu ll’, ’m inim al’, pending

’hidden’)]
Parameter Description

default: "full"

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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 Maximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.


Parameter Description

cancels A list of other events to cancel when this

dict[str, Any] | list[dict[str, listener is triggered. For example, setting

Any]] I None cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

float I None while the client connection is open.

default: None Interpreted in seconds.

trigger_mode If "once" (default for all events except

Literal[(’once’, 'm últiple, .c h a n g e ( ) ) would not allow any submissions

’a lw a y s ja s t’)] | None while an event is pending. If set to "multiple",

default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before

str |None running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.


Parameter Description

concurrency_limit If set, this is the máximum number of this

int | None | Literal['default'] event that can be running simultaneously. Can

default: "default" be set to None to mean no co n cu rre n cy jim it

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.

str 1None Events with the same concurrency_id w ill be

default: None limited by the lowest set co ncurrencyjim it.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

autom atically be set to False.

^ Dataset Dropdown

^ gradio Status J C
Custom Components GalleryNEW Explore

^ gradio

New to Gradio? Start here: Getting Started See the Release History

^ DownloadButton DuplicateButton

Dropdown

gradio.Dropdown(•••)

<30

Loading...

gradio/dropdown_component built with Gradio. Hosted on Efi Spaces

Description
Creates a dropdown of choices from which a single entry or múltiple entries can

be selected (as an input component) or displayed (as an output component).

Behavior
As input com ponent: Passes the value of the selected dropdown choice as a s t r

| in t | f lo a t or its index as an in t into the function, depending on ty p e . Or, if

m u ltis e le c t is True, passes the values of the selected dropdown choices as a list

of correspoding values/indices instead.

Your function should accept one of these types:


d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (

v a lu e : s t r | in t | flo a t | l i s t [ s tr | in t | flo a t] | l i s t [ in t | None] | None

As output com ponent: Expects a s t r | in t | f lo a t corresponding to the value

of the dropdown entry to be selected. Or, if m u ltis e le c t is True, expects a l i s t

of values corresponding to the selected dropdown entries.

Your function should return one of these types:

d e f p r e d ic t ( " 0 -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( ^ " ) -> s t r | in t | flo a t | l i s t [ s tr | in t | flo a t] | None

re t u r n v a lu e

Imtiaíization
Parameter Description

c h o ic e s A list of string options to choose from. An option

list[str |int | float | tuple[str, str | can also be a tuple of the form (name, value),

int | float]] | None where name is the displayed name of the

default: None dropdown choice and value is the value to be

passed to the function, or returned by the function.

v a lu e default value(s) selected in dropdown. If None, no

str |int | float | list[str |int | float] | value is selected by default. If callable, the function

Callable |None w ill be called whenever the app loads to set the

default: None initial value of the component.


Parameter Description

ty p e Type of value to be returned by component.

Literal[('value', 'índex')] "value" returns the string of the choice selected,

default: "value" "index" returns the index of the choice selected.

m u lt is e le c t if True, m ultiple choices can be selected.

bool | None

default: None

a llo w _ c u s t o m _ v a lu e If True, allows user to enter a custom value that is

bool not in the list of choices.

default: False

m a x _ c h o ic e s maximum number of choices that can be selected.

int I None If None, no lim it is enforced.

default: None

f ilt e r a b le If True, user will be able to type into the dropdown

bool and filter the choices by typing. Can only be set to

default: True False if a llo w _ c u s to m _ v a lu e is False.

la b e l The label for this component. Appears above the

str I None com ponent and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r . I n t e r f a c e , the label w ill be the

name of the parameter this com ponent is assigned

to.

in f o additional com ponent description.

str |None

default: None
Parameter Description

e v e ry If v a lu e is a callable, run the function 'every'

float |None number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

s h o w _ la b e l if True, w ill display label.

bool 1None

default: None

c o n t a in e r If True, w ill place the com ponent in a container -

bool providing some extra padding around the border.

default: True

s c a le relative size compared to adjacent Components.

int 1None For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A w ill be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

m in _ w id t h minimum pixel width, w ill wrap if not sufficient

int screen space to satisfy this value. If a certain scale

default: 160 value results in this Com ponent being narrower

than min_width, the min_width parameter w ill be

respected first.

in t e r a c t iv e if True, choices in this dropdown w ill be selectable;

bool | None if False, selection w ill be disabled. If not provided,

default: None
Parameter Description

this is inferred based on whether the com ponent is

used as an input or output.

v is ib le If False, com ponent w ill be hidden.

bool

default: True

e le m _ id An optional string that is assigned as the id of this

str |None com ponent in the HTML DOM. Can be used for

default: None targeting CSS styles.

e le m _ c la s s e s An optional list of strings that are assigned as the

list[str] Istr I None classes of this com ponent in the HTML DOM. Can

default: None be used for targeting CSS styles.

re n d e r If False, com ponent w ill not be rendered in the

bool Blocks context. Should be used if the intention is to

default: True assign event listeners now but render the

com ponent later.

Shortcuts
Interface String
Class Initialization
Shortcut

g r a d io . Dataframe "dropdown" Uses default values

Demos

sentence builder


import gradio as gr

I

def se n ten ce_ build er(q u a n t it y , anim al, c o u n t r ie s , p la c e , a c t i v i t y _ l i s t , mor

ning) :

return f .....The {q u a n t it y } {anim al}s from {" and " . j o i n (c o u n t r ie s )} went

to the {p la c e } where they {" and " . j o i n (a c t i v i t y _ l i s t )} u n t i l the {"mornin


I
g" i f morning e ls e " n ig h t " }.....

demo = g r . I n t e r f a c e (

<30

Loading...

g ra d io /se n te n ce _ b u ild e r built with Gradio. Hosted on E9SSpaces

Event Listeners

Description
Event listeners allow you to capture and respond to user interactions with

the UI components you've defined in a Gradio Blocks app. When a user


interacts with an element, such as changing a slider value or uploading an

image, a function is called.

Supported Event Listeners


The D ropdow n com ponent supports the following event listeners. Each

event listener takes the same parameters, which are listed in the Event

Arguments table below.


Listener Description

g r a d io . Datafram e. change Triggered when the value of the Dropdown

(f n , • • • ) changes either because of user input (e.g. a


user types in a textbox) OR because of a
function update (e.g. an image receives a value
from the output of an event trigger). See
. in p u t ( ) for a listener that is only triggered
by user input.

g r a d io .D r o p d o w n .in p u t ( f This listener is triggered when the user


n, •••) changes the value of the Dropdown.

g ra d io .D ro p d o w n . s e l e c t ( Event listener for when the user selects or


fn , •••) deselects the Dropdown. Uses event data
gradio.SelectData to carry v a lu e referring to
the label of the Dropdown, and s e le c t e d to
refer to state of the Dropdown. See EventData
documentation on how to use this event data

g r a d io .D r o p d o w n .fo c u s ( f This listener is triggered when the Dropdown


n, •••) is focused.

g ra d io .D ro p d o w n . b lu r ( f n This listener is triggered when the Dropdown


, •••) is unfocused/blurred.

g ra d io .D ro p d o w n . key_up( This listener is triggered when the user presses


fn , •••) a key while the Dropdown is focused.

Event Arguments
Parameter Description

fn the function to call when this event is

Callable |None | triggered. Often a machine learning model's

Litem l[’decom tor’] prediction function. Each parameter of the

default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tuple of values, with each


Parameter Description

element in the tupie corresponding to one

output component.

in p u t s List of gradio.components to use as inputs. If

Component | list[Component] | the function takes no inputs, this should be an

set[Component] | None empty list.

default: None

o u tp u ts List of gradio.components to use as outputs. If

Component | list[Component] | the function returns no outputs, this should be

None an empty list.

default: None

api_nam e defines how the endpoint appears in the API

str |None |Literal[False] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

s c r o ll_ t o _ o u t p u t If True, w ill scroll to output com ponent on

bool completion

default: False

sh o w _ p ro g re ss If True, w ill show progress animation while

Literal[(’fu ll’, ’m inim al’, pending

’hidden’)]

default: "full
Parameter Description

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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 Maximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this

listener is triggered. For example, setting


Parameter Description

dict[str, Any] | list[dict[str, cancels=[click_event] w ill cancel the

Any]] 1None click_event, where click_event is the return

default: None value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

e v e ry Run this event 'every' number of seconds

float 1None while the client connection is open.

default: None Interpreted in seconds.

trig g e r_ m o d e If "once" (default for all events except

Literal[(’once’, 'm últiple, .c h a n g e ( ) ) would not allow any submissions

’a lw a y s ja s t’)] | None while an event is pending. If set to "multiple",


default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before

str |None running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

c o n c u r r e n c y _ lim it If set, this is the maximum number of this

int 1None | Literal['default'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the


Parameter Description

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

c o n c u rre n c y _ id If set, this is the id of the concurrency group.


str |None Events with the same concurrency_id w ill be

default: None limited by the lowest set co ncurrencyjim it.

show _api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"


default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

autom atically be set to False.

^ DownloadButton DuplicateButton

^ gradio Status J C
Custom Components GalleryNEW Explore

^ gradio =

New to Gradio? Start here: Getting Started See the Release History

^ Dropdown File

DuplicateButton

gradio.DuplicateButton(•••)

Duplicate Space

gradio/duplicatebutton_component built with Gradio. Hosted on B Spaces

Description
Button that triggers a Spaces Duplication, when the demo is on Hugging Face

Spaces. Does nothing locally.

Behavior
As input com ponent: (Rarely used) the s t r corresponding to the button label

when the button is clicked

Your function should accept one of these types:

d e f p r e d ic t (
[P
v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (

v a lu e : s t r | None

As output com ponent: string corresponding to the button label

Your function should return one of these types:


d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( " 0 -> s t r | None

re t u r n v a lu e

InitiaMzation
Parameter Description

v a lu e Default text for the button to display. If callable,

str the function w ill be called whenever the app loads

default: "Duplícate Space" to set the initial value of the component.

e v e ry If v a lu e is a callable, run the function 'every'

float |None number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

v a r ia n t 'primary' for main call-to-action, 'secondary' for a

Literal[(’prim ary’, ’secondary’, more subdued style, 'stop' for a stop button.

'stop')]

default: "secondary"

s iz e Size of the button. Can be "sm" or "lg".

Literal[('sm, 'lg')] |None

default: "sm"

ic o n URL or path to the icon file to display within the

str 1None button. If None, no icon w ill be displayed.

default: None
Parameter Description

lin k URL to open when the button is clicked. If None, no

str |None link w ill be used.

default: None

v is ib le If False, com ponent w ill be hidden.

bool

default: True

in t e r a c t iv e If False, the Button will be in a disabled state.

bool

default: True

e le m _ id An optional string that is assigned as the id of this

str 1None com ponent in the HTML DOM. Can be used for

default: None targeting CSS styles.

e le m _ c la s s e s An optional list of strings that are assigned as the

list[str] 1str 1None classes of this com ponent in the HTML DOM. Can

default: None be used for targeting CSS styles.

re n d e r If False, com ponent w ill not render be rendered in

bool the Blocks context. Should be used if the intention

default: True is to assign event listeners now but render the

com ponent later.

s c a le relative size compared to adjacent Components.

int 1None For example if Components A and B are in a Row,

default: 0 and A has scale=2, and B has scale=1, A w ill be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.


Parameter Description

m in _ w id t h mínimum pixel width, w ill wrap if not sufficient

int | None screen space to satisfy this value. If a certain scale

default: None value results in this Com ponent being narrower

than min_width, the min_width parameter w ill be

respected first.

Shortcuts
Interface String
Class Initialization
Shortcut

g r a d io . Dataframe "duplicatebutton" Uses default values

Event Listeners

Description
Event listeners allow you to capture and respond to user interactions with

the UI components you've defined in a Gradio Blocks app. When a user


interacts with an element, such as changing a slider value or uploading an

image, a function is called.

Supported Event Listeners


The D u p l i c a t e B u t t o n com ponent supports the following event

listeners. Each event listener takes the same parameters, which are listed

in the Event Arguments table below.

Listener Description

g r a d io . Datafram e. change Triggered when the Button is clicked.

(f n , • • • )

Event Arguments
Parameter Description

fn the function to call when this event is

Callable |None | triggered. Often a machine learning model's

Litem l[’decom tor’] prediction function. Each parameter of the

default: "decorator" 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.

in p u t s List of gradio.components to use as inputs. If

Component | list[Component] | the function takes no inputs, this should be an

set[Component] | None empty list.

default: None

o u tp u ts List of gradio.components to use as outputs. If

Component | list[Component] | the function returns no outputs, this should be

None an empty list.

default: None

api_nam e defines how the endpoint appears in the API

str |None |Literal[False] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.


Parameter Description

scroll_to_output If True, w ill scroll to output com ponent on

bool completion

default: False

show_progress If True, w ill show progress animation while

Literal[('fuW, ’m inim al’, pending

’hidden’)]

default: "full"

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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 Maximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.


Parameter Description

default: True leaving it as a base64 string if this method is

called with the Image component).

p o s tp ro c e s s If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

c a n c e ls A list of other events to cancel when this


dict[str, Any] | list[dict[str, listener is triggered. For example, setting

Any]] 1None cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

e v e ry Run this event 'every' number of seconds

float 1None while the client connection is open.

default: None Interpreted in seconds.

trig g e r_ m o d e If "once" (default for all events except

Literal[(’once’, 'm últiple, .c h a n g e ( ) ) would not allow any submissions

’a lw a y s ja s t’)] | None while an event is pending. If set to "multiple",


default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.
Parameter Description

js Optional frontend js method to run before

str |None running 'fn'. Input arguments for js method are

default: None valúes of 'inputs' and 'outputs', return should

be a list of valúes for output components.

concurrency_limit If set, this is the maximum number of this

int 1None | Literal['default'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.

str 1None Events with the same concurrency_id w ill be

default: None limited by the lowest set concurrency_limit.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

autom atically be set to False.

Dropdown File
^ gradio Status J C
Custom Components GalleryNEW Explore

$ gradio

New to Gradio? Start here: Getting Started See the Release History

EventData Warning

Error

gradio.Error(•••)

Description

This class allows you to pass custom error messages to the user. You can do so by

raising a gr.Error("custom message") anywhere in the code, and when that line is

executed the custom message will appear in a modal on the demo.

Exampíe Usage

import gradio as gr

def divide(numerator, denominator):

if denominator == 0 :

raise gr.Error("Cannot divide by zero!")

gr.Interface(divide, ["number", "number"], "number").launch()


InitiaMzation

Parameter Description

m e s sa g e The error message to be displayed to the user.

<class 'str'>

default: "Error raised."

Demos

calculator blocks_chained_events

import gradio as gr

#from foo import BAR

def calculator(num1, operation., num2):

if operation == "add":

return numl + num2

elif operation == "subtract":

return numl - num2

elif operation == "multiply":

return num1 * num2

elif operation == "divide":


Loading...

g ra d io / c a lc u la t o r built with Gradio. Hosted on ^^^9 Spaces

EventData Warning

Status

^ gradio o
Custom Components GalleryNEW Explore

$ gradio

New to Gradio? Start here: Getting Started See the Release History

set_static_paths Examples

EventData

gradio.EventData(target, •••)

Description

When a subclass of EventData is added as a type hint to an argument of an event

listener method, this object will be passed as that argument. It contains

information about the event that triggered the listener, such the target object,

and other data related to the specific event that are attributes of the subclass.

Exampíe Usage &

table = gr.Dataframe([[1, 2, 3], [4 , 5, 6]])

gallery = gr.G a U e r y ([("cat.jpg", "Cat"), ("dog.jpg", "Dog")])

textbox = gr.Textbox("Hello World!")

statement = gr.Textbox()
def on_select(evt: gr.SelectData): # SelectData is a subclass of EventData

return f"You selected {evt.value} at {evt.index} from {evt.target}"

table.select(on_select, None, statement)

gallery.select(on_select, None, statement)

textbox.select(on_select, None, statement)

InitiaMzation

Parameter Description

ta rg e t The target object that triggered the event. Can be

Block |None used to distinguish if m últiple components are

required bound to the same listener.

Demos

gallery_select¡ons tictactoe


import gradio as gr

import numpy as np

with gr.Blocks() as demo:

imgs = gr.State()
I
gallery = gr.Gallery(allow_preview=False)

def deselect_images():

return gr.Gallery(selected_index=None)

def generate_images():
Loading...

g r a d io / g a lle r y _ s e le c t io n s built with Gradio. Hosted on Spaces

set_static_paths Examples

Status

^ gradio o
Custom Components GalleryNEW Explore

$ gradio

New to Gradio? Start here: Getting Started See the Release History

EventData Progress

Examples

gradio.Examples(examples, inputs, •••)

Description

This class is a wrapper over the Dataset com ponent and can be used to create

Examples for Blocks / Interfaces. Populates the Dataset com ponent with

examples and assigns event listener so that clicking on an example populates the

input/output components. Optionally handles example caching for fast

inference.

Initialization
Parameter Description

e x a m p le s example inputs that can be clicked to popúlate

list[Any] |list[list[Any]] |str specific components. Should be nested list, in

required 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 m ultiple input

components and a directory is provided, a log.csv

file must be present in the directory to link

corresponding inputs.

in p u t s the com ponent or list of components

Component | list[Component] corresponding to the examples

required

o u tp u ts optionally, provide the com ponent or list of

Component | list[Component] | components corresponding to the output of the

None examples. Required if ca c h e _ e xa m p le s is not

default: None False.

fn optionally, provide the function to run to generate

Callable |None the outputs corresponding to the examples.

default: None Required if ca ch e _ e x a m p le s is not False. Also

required if r u n _ o n _ c lic k is True.

c a c h e _ e x a m p le s If True, caches examples in the server for fast

bool | Literal['lazy‘] | None runtime in examples. If "lazy", then examples are

default: None cached after their first use. Can also be set by the

GRADIO_CACHE_EXAMPLES environment variable,


Parameter Description

which takes a case-insensitive value, one of:

"tru e ", " la z y " , o r " f a l s e " (for the first two

to take effect, f n and o u t p u t s should also be

provided). In HuggingFace Spaces, this is True (as

long as f n and o u t p u t s are also provided). The

default option otherwise is False.

e x a m p le s _ p e r _ p a g e how many examples to show per page.

int

default: 10

la b e l the label to use for the examples com ponent (by

str |None default, "Examples")

default: "Examples"

e le m _ id an optional string that is assigned as the id of this

str I None com ponent in the HTML DOM.

default: None

r u n _ o n _ c lic k if cache_examples is False, clicking on an example

bool does not run the function when an example is

default: False clicked. Set this to True to run the function when

an example is clicked. Has no effect if

cache_examples is True.

p re p ro ce ss if True, preprocesses the example input before

bool running the prediction function and caching the

default: True output. Only applies if ca c h e _ e xa m p le s is not

False.
Parameter Description

p o s tp ro c e s s if True, postprocesses the example output after

bool running the prediction function and before

default: True caching. Only applies if ca c h e _ e xa m p le s is not

False.

a p i_ n a m e Defines how the event associated with clicking on

str |Literal[False] the examples appears in the API docs. Can be a

default: "load_example" string or False. If set to a string, the endpoint w ill

be exposed in the API docs with the given name. If

False, the endpoint will not be exposed in the API

docs and downstream apps (including those that

g r . lo a d this app) w ill not be able to use the

example function.

b a tc h If True, then the function should process a batch of

bool inputs, meaning that it should accept a list of input

default: False values for each parameter. Used only if

cache_examples is not False.

Demos

fake_gan


# This demo needs to be run from the repo folder.

# python demo/fake_gan/run.py

import random

import gradio as gr
I

def fake_gan():

images = [

(random.choice(

[
I

Loading...

gradio/fake_gan built with Gradio. Hosted on Spaces

Guides

Using Hugging Face Integrations

Image Classification In Pytorch

Image Classification In Tensorflow

Image Classification With Vision Transformers

Create Your Own Friends With A Gan


EventData Progress

Status

^ gradio o
Custom Components GalleryNEW Explore

^ gradio =

New to Gradio? Start here: Getting Started See the Release History

^ DuplicateButton FileExplorer

File

gradio.File(•••)

Loading...

grad io /file_ co m p o nen t built with Gradio. Hosted on HS Spaces

Description
Creates a file com ponent that allows uploading one or more generic files (when

used as an input) or displaying generic files or URLs for download (as output).

Behavior
As input com ponent: Passes the file as a s t r or bytes object, or a list of s t r or list

of bytes objects, depending on type and file _ c o u n t .

Your function should accept one of these types:

d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

)
. . . d e f p r e d ic t (

v a l u e : b yte s | str | l i s t [ b y te s] | lis t [str] | None

As output com ponent: Expects a s t r filepath or URL, or a l i s t [ s t r ] of

filepaths/URLs.

Your function should return one of these types:

d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( " 0 -> s t r | lis t [s tr] | None

re t u r n v a lu e

InitiaMzation
Parameter Description

v a lu e Default file(s) to display, given as a str file path or

str |list[str] | Callable | None URL, or a list of str file paths / URLs. If callable, the

default: None function w ill be called whenever the app loads to

set the initial value of the component.

f ile count if single, allows user to upload one file. If

Literal[Csingle', 'm ultiple, "multiple", user uploads m ultiple files. If

'directory')] "directory", user uploads all files in selected

default: "single" directory. Return type w ill be list for each file in

case of "m ultiple" or "directory".

f ile _ t y p e s List of file extensions or types of files to be

list[str] |None uploaded (e.g. ['image', '.json', '.mp4']). "file"

default: None allows any file to be uploaded, "image" allows only

image files to be uploaded, "audio" allows only


Parameter Description

audio files to be uploaded, "video" allows only

video files to be uploaded, "text" allows only text

files to be uploaded.

ty p e Type of value to be returned by component. "file"

Literal[('filepath', ’binary')] returns a temporary file object with the same base

default: "filepath" name as the uploaded file, whose full path can be

retrieved by file_obj.name, "binary" returns an

bytes object.

la b e l The label for this component. Appears above the

str |None com ponent and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r . I n t e r f a c e , the label w ill be the

name of the parameter this com ponent is assigned

to.

e v e ry If v a lu e is a callable, run the function 'every'

float |None number of seconds while the client connection is

default: None open. Has no effect otherwise.sed (e.g. to cancel it)

via this com ponent's .load_event attribute.

s h o w _ la b e l if True, w ill display label.

bool 1None

default: None

c o n t a in e r If True, w ill place the com ponent in a container -

bool providing some extra padding around the border.

default: True
Parameter Description

s c a le relative size compared to adjacent Components.

int | None For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A w ill be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

m in _ w id t h minimum pixel width, w ill wrap if not sufficient

int screen space to satisfy this value. If a certain scale

default: 160 value results in this Com ponent being narrower

than min_width, the min_width parameter w ill be

respected first.

h e ig h t The maximum height of the file component,

int I float I None specified in pixels if a number is passed, or in CSS

default: None units if a string is passed. If more files are uploaded

than can fit in the height, a scrollbar w ill appear.

in t e r a c t iv e if True, w ill allow users to upload a file; if False, can

bool I None only be used to display files. If not provided, this is

default: None inferred based on whether the com ponent is used

as an input or output.

v is ib le If False, com ponent w ill be hidden.

bool

default: True

e le m _ id An optional string that is assigned as the id of this

str I None com ponent in the HTML DOM. Can be used for

default: None targeting CSS styles.


Parameter Description

e le m _ c la s s e s An optional list of strings that are assigned as the

list[str] |str | None classes of this com ponent in the HTML DOM. Can

default: None be used for targeting CSS styles.

re n d e r If False, com ponent w ill not render be rendered in

bool the Blocks context. Should be used if the intention

default: True is to assign event listeners now but render the

com ponent later.

Shortcuts
Interface String
Class Initialization
Shortcut

g r a d io . Dataframe "file" Uses default values

Uses
g r a d io . F ile s "files"
file count="multiple"

Event Listeners

Description
Event listeners allow you to capture and respond to user interactions with

the UI components you've defined in a Gradio Blocks app. When a user


interacts with an element, such as changing a slider value or uploading an

image, a function is called.

Supported Event Listeners


The F i l e com ponent supports the following event listeners. Each event

listener takes the same parameters, which are listed in the Event Arguments

table below.
Listener Description

gradio.Dataframe.change Triggered when the value of the File changes

(fn, •••) either because of user input (e.g. a user types


in a textbox) OR because of a function update
(e.g. an image receives a value from the output
of an event trigger). See . in p u t ( ) for a
listener that is only triggered by user input.

gradio.File.select(fn, Event listener for when the user selects or


•••) deselects the File. Uses event data
gradio.SelectData to carry v a lu e referring to
the label of the File, and s e le c t e d to refer to
state of the File. See EventData
documentation on how to use this event data

gradio.File.clear(fn, This listener is triggered when the user clears


•••) the File using the X button for the component.

gradio.File.upload(fn, This listener is triggered when the user


•••) uploads a file into the File.

Event Arguments
Parameter Description

fn the function to call when this event is

Callable |None | triggered. Often a machine learning model's

Litem l[’decom tor’] prediction function. Each parameter of the

default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tuple of values, with each

element in the tuple corresponding to one

output component.

inputs List of gradio.components to use as inputs. If

the function takes no inputs, this should be an


Parameter Description

Component | list[Component] | empty list.

set[Component] | None

default: None

o u tp u ts List of gradio.components to use as outputs. If

Component | list[Component] | the function returns no outputs, this should be


None an empty list.

default: None

api_nam e defines how the endpoint appears in the API

str |None |Literal[False] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

s c r o ll_ t o _ o u t p u t If True, w ill scroll to output com ponent on

bool completion

default: False

sh o w _ p ro g re ss If True, w ill show progress animation while

Literal[(’fu ll’, ’m inim al’, pending

’hidden’)]

default: "full"

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue
Parameter Description

has been enabled. If None, w ill use the queue

setting of the gradio app.

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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 Maximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this


dict[str, Any] | list[dict[str, listener is triggered. For example, setting

Any]] 1None cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.


Parameter Description

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

float |None while the client connection is open.

default: None Interpreted in seconds.

trigger_mode If "once" (default for all events except

Literal[('once', 'm últiple' .c h a n g e ( ) ) would not allow any submissions

’a lw a y s ja s t’)] | None while an event is pending. If set to "multiple",


default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before


str 1None running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

concurrency_limit If set, this is the maximum number of this

int 1None | Literal['default'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the


Parameter Description

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

c o n c u rre n c y _ id If set, this is the id of the concurrency group.


str |None Events with the same concurrency_id w ill be

default: None limited by the lowest set co ncurrencyjim it.

show _api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"


default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

autom atically be set to False.

^ DuplicateButton FileExplorer

^ gradio Status J C
Custom Components GalleryNEW Explore

^ gradio =

New to Gradio? Start here: Getting Started See the Release History

^ File Gallery

FileExplorer

gradio.FileExplorer(•••)

Loading...

g ra d io /file e x p lo re r_ co m p o n e n t built with Gradio. Hosted on HS Spaces

Description
Creates a file explorer com ponent that allows users to browse files on the

machine hosting the Gradio app. As an input component, it also allows users to

select files to be used as input to a function, while as an output component, it

displays selected files.

Behavior
As input com ponent: Passes the selected file or directory as a s t r path (relative

to ro o t) or l i s t [ s t r ] depending on file _ c o u n t

Your function should accept one of these types:


d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (

v a lu e : l i s t [ s t r ] | str | None

As output com ponent: Expects function to return a s t r path to a file, or

l i s t [ s t r ] consisting of paths to files.

Your function should return one of these types:

d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( " 0 -> s t r | lis t [s tr] | None

re t u r n v a lu e

Initiaíization
Parameter Description

g lo b The glob-style pattern used to select which files to

str display, e.g. "" to match a ll files, ".png" to match

default: "**/*" all .png files, "/*.txt" to match any .txt file in any

subdirectory, etc. The default value matches all

files and folders recursively. See the Python glob

documentation at

https://docs.python.org/3/library/glob.html for

more information.

v a lu e The file (or list of files, depending on the

str |list[str] | Callable | None f i l e _ c o u n t parameter) to show as "selected"

default: None when the com ponent is first loaded. If a callable is


Parameter Description

provided, it will be called when the app loads to

set the initial value of the component. If not

provided, no files are shown as selected.

f ile _ c o u n t Whether to allow single or m ultiple files to be

Literal[('single, 'múltiple )] selected. If "single", the com ponent w ill return a

default: "múltiple" single absolute file path as a string. If "multiple",

the com ponent w ill return a list of absolute file

paths as a list of strings.

r o o t _ d ir Path to root directory to select files from. If not

str |Path provided, defaults to current working directory.

default: "."

ig n o r e _ g l o b The glob-style, case-sensitive pattern that w ill be

str 1None used to exclude files from the list. For example,

default: None "*.py" w ill exclude all .py files from the list. See the

Python glob documentation at

https://docs.python.org/3/library/glob.html for

more information.

la b e l The label for this component. Appears above the

str |None com ponent and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r . I n t e r f a c e , the label w ill be the

name of the parameter this com ponent is assigned

to.

e v e ry If v a lu e is a callable, run the function 'every'

float 1None number of seconds while the client connection is

default: None
Parameter Description

open. Has no effect otherwise.sed (e.g. to cancel it)

via this com ponent's .load_event attribute.

s h o w _ la b e l if True, w ill display label.

bool | None

default: None

c o n t a in e r If True, w ill place the com ponent in a container -

bool providing some extra padding around the border.

default: True

s c a le relative size compared to adjacent Components.

int 1None For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A w ill be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

m in _ w id t h minimum pixel width, w ill wrap if not sufficient

int screen space to satisfy this value. If a certain scale

default: 160 value results in this Com ponent being narrower

than min_width, the min_width parameter w ill be

respected first.

h e ig h t The maximum height of the file component,

int 1float 1None specified in pixels if a number is passed, or in CSS

default: None units if a string is passed. If more files are uploaded

than can fit in the height, a scrollbar w ill appear.

in t e r a c t iv e if True, w ill allow users to select file(s); if False, w ill

bool 1None only display files. If not provided, this is inferred


Parameter Description

default: None based on whether the com ponent is used as an

input or output.

v is ib le If False, com ponent w ill be hidden.

bool

default: True

e le m _ id An optional string that is assigned as the id of this

str |None com ponent in the HTML DOM. Can be used for

default: None targeting CSS styles.

e le m _ c la s s e s An optional list of strings that are assigned as the

list[str] Istr I None classes of this com ponent in the HTML DOM. Can

default: None be used for targeting CSS styles.

re n d e r If False, com ponent w ill not render be rendered in

bool the Blocks context. Should be used if the intention

default: True is to assign event listeners now but render the

com ponent later.

ro o t

None

default: None

Shortcuts
Interface String
Class Initialization
Shortcut

g r a d io . Dataframe "fileexplorer" Uses default values

Demos
file_explorer


import gradio as gr

from pathlib import Path

current_file_path = Path(__file__).resolve()
I
relative_path = "path/to/file"

absolute_path = (current_file_path.parent / ".." / / "gradio").resolve

()

def get_file_content(file):

return (file,)

Loading...

g r a d io / file _ e x p lo r e r built with Gradio. Hosted on Efi Spaces

Event Listeners

Description
Event listeners allow you to capture and respond to user interactions with

the UI components you've defined in a Gradio Blocks app. When a user


interacts with an element, such as changing a slider value or uploading an

image, a function is called.


Supported Event Listeners
The F i l e E x p l o r e r com ponent supports the following event listeners.

Each event listener takes the same parameters, which are listed in the

Event Arguments table below.

Listener Description

gradio.Dataframe.change

(fn, •••)

Event Arguments
Parameter Description

fn the function to call when this event is

Callable |None | triggered. Often a machine learning model's

Literal['decorator'] prediction function. Each parameter of the

default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tuple of values, with each

element in the tuple corresponding to one

output component.

inputs List of gradio.components to use as inputs. If

Component | list[Component] | the function takes no inputs, this should be an

set[Component] | None empty list.

default: None

outputs List of gradio.components to use as outputs. If

Component | list[Component] | the function returns no outputs, this should be

None an empty list.

default: None
Parameter Description

api_nam e defines how the endpoint appears in the API

str |None |Literal[False] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

s c r o ll_ t o _ o u t p u t If True, w ill scroll to output com ponent on

bool completion

default: False

sh o w _ p ro g re ss If True, w ill show progress animation while

Literal[(’fu ll’, ’m inim al’, pending

’hidden’)]

default: "fu ll"

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

b atch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). The function is

then required to return a tuple of lists (even if


Parameter Description

there is only 1 output component), with each

list in the tupie corresponding to one output

component.

max_batch_size Máximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this


dict[str, Any] | list[dict[str, listener is triggered. For example, setting

Any]] 1None cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

float 1None while the client connection is open.

default: None Interpreted in seconds.


Parameter Description

trigger_mode If "once" (default for all events except

Literal[('once', 'm últiple' .c h a n g e ( ) ) would not allow any submissions

’a lw a y s ja s t’)] | None while an event is pending. If set to "múltiple",

default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before

str 1None running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

concurrency_limit If set, this is the maximum number of this

int 1None | Literal['default'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.

str 1None Events with the same concurrency_id w ill be

default: None limited by the lowest set concurrency_limit.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting


Parameter Description

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

autom atically be set to False.

File Gallery

^ gradio Status J C
Custom Com ponents G alleryNEW Explore

$ gradio

New to Gradio? Start here: Getting Started See the Release History

mount_gradio_app Themes

Flagging

Description

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 F la g g in g C a llb a ck to the


fla g g in g _ ca llb a ck parameter in the Interface constructor. You can use one of the
F la g g in g C a llb a ck 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(•••)
Descri ption

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.

Exampíe 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())

CSVLogger

gradio.CSVLogger(•••)

Description

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.

Exampíe 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())

InitiaMzation

Parameter Description

s im p lif y _ f ile _ d a t a

bool

default: True

Guides

Using Flagging

HuggingFaceDatasetSaver

gradio.HuggingFaceDatasetSaver(hf_token, dataset_name, •••)

Description
A callback that saves each flagged sample (both the input and output data) to a

HuggingFace dataset.

Exampíe Usage

import gradio as gr

hf_writer = gr.HuggingFaceDatasetSaver(HF_API_TOKEN, "image-classification-mistake

s")

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)

Initiaíization

Parameter Description

h f_ to k e n The HuggingFace token to use to create (and write

str the flagged sample to) the HuggingFace dataset

required (defaults to the registered one).

d a ta s e t _ n a m e The repo_id of the dataset to save the data to, e.g.

str "image-classifier-1" or "username/image-

required classifier-1".

p r ív a t e Whether the dataset should be private (defaults to

bool False).

default: False

in f o _ f ile n a m e The name of the file to save the dataset info

str (defaults to "dataset_infos.json").


Parameter Description

default: "d a ta se tjn fo .jso n "

s e p a r a t e _ d ir s If True, each flagged item w ill be saved in a

bool sepárate directory. This makes the flagging more

default: False robust to concurrent editing, but may be less

convenient to use.

Guides

Using Flagging

mount_gradio_app Themes

Status

$ gradio X o
Custom Com ponents G alleryNEW Explore

^ gradio =

New to Gradio? Start here: Getting Started See the Release History

^ FileExplorer HTML

Gallery

gradio.Gallery(•••)

Loading...

gradio/gallery_com ponent built with Gradio. Hosted on HS Spaces

Description
Creates a gallery com ponent that allows displaying a grid of images, and

optionally captions. If used as an input, the user can upload images to the
gallery. If used as an output, the user can click on individual images to view them

at a higher resolution.

Behavior
As input com ponent: Passes the list of images as a list of (image, caption) tuples,

or a list of (image, None) tuples if no captions are provided (which is usually the

case). The image can be a s t r file path, a numpy array, or a PlL.lm age object

depending on ty p e .

Your function should accept one of these types:


d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (

v a lu e : L i s t [ t u p le [ s t r , s t r | None] ] | L i s t [ t u p l e [ P I L . Im age. Im age, s t r | None] ] | L i s t [ tu

p l e [ np . n d a r ra y , s t r | None] ] | None

As output com ponent: Exp ects th e fu n c tio n to retu rn a l i s t o f im ages, o r l i s t o f

(im age, s t r ca p tio n ) tu p ie s. Each im a g e can be a s t r file p ath, a numpy array, o r a

P lL .lm a g e o b je ct.

Your function should return one of these types:

d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( " 0 -> l i s t [ G alle ry Im a g e T y p e | C a p tio n e d G a lle ry lm a g e T y p e ] | Non

re t u r n v a lu e

Initiaíization
Param eter Description

v a lu e List of images to display in the gallery by default. If

list[np.ndarray |PIL.Image.Image callable, the function w ill be called whenever the

|str I Path I tupie] | Callable | app loads to set the initial value of the component.

None

default: None

fo rm a t Format to save images before they are returned to

str the frontend, such as 'jpeg' or 'png'. This

default: "w ebp" parameter only applies to images that are returned

from the prediction function as numpy arrays or


Parameter Description

PIL Images. The format should be supported by the

PIL library.

la b e l The label for this component. Appears above the

str |None com ponent and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r . I n t e r f a c e , the label w ill be the

name of the parameter this com ponent is assigned

to.

e v e ry If v a lu e is a callable, run the function 'every'

float 1None number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

s h o w _ la b e l if True, w ill display label.

bool 1None

default: None

c o n t a in e r If True, w ill place the com ponent in a container -

bool providing some extra padding around the border.

default: True

s c a le relative size compared to adjacent Components.

int 1None For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A w ill be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.


Parameter Description

m in _ w id t h mínimum pixel width, w ill wrap if not sufficient

int screen space to satisfy this value. If a certain scale

default: 160 value results in this Com ponent being narrower

than min_width, the min_width parameter w ill be

respected first.

v is ib le If False, com ponent w ill be hidden.

bool

default: True

e le m _ id An optional string that is assigned as the id of this

str |None com ponent in the HTML DOM. Can be used for

default: None targeting CSS styles.

e le m _ c la s s e s An optional list of strings that are assigned as the

list[str] Istr I None classes of this com ponent in the HTML DOM. Can

default: None be used for targeting CSS styles.

re n d e r If False, com ponent w ill not render be rendered in

bool the Blocks context. Should be used if the intention

default: True is to assign event listeners now but render the

com ponent later.

c o lu m n s Represents the number of images that should be

int I tupie I None shown in one row, for each of the six standard

default: 2 screen sizes (<576px, <768px, <992px, <1200px,

<1400px, >1400px). If fewer than 6 are given then

the last w ill be used for all subsequent breakpoints

ro w s Represents the number of rows in the image grid,

int I tupie I None for each of the six standard screen sizes (<576px,
Parameter Description

default: None <768px, <992px, <1200px, <1400px, >1400px). If

fewer than 6 are given then the last w ill be used for

all subsequent breakpoints

h e ig h t The height of the gallery component, specified in

int | float | None pixels if a number is passed, or in CSS units if a

default: None string is passed. If more images are displayed than

can fit in the height, a scrollbar w ill appear.

a llo w _ p r e v ie w If True, images in the gallery w ill be enlarged when

bool they are clicked. Default is True.

default: True

p r e v ie w If True, Gallery w ill start in preview mode, which

bool | None shows all of the images as thum bnails and allows

default: None the user to click on them to view them in full size.

Only works if allow_preview is True.

s e le c t e d _ in d e x The index of the image that should be initially

int 1None selected. If None, no image w ill be selected at start.

default: None If provided, w ill set Gallery to preview mode unless

allow_preview is set to False.

o b je c t _ f it CSS object-fit property for the thum bnail images in

Literal[('contain', 'cover', ’fill’, the gallery. Can be "contain", "cover", "fill", "none",

'none', ’scale-down’)] |None or "scale-down".

default: None

s h o w _ s h a re _ b u tto n If True, w ill show a share icon in the corner of the

bool 1None com ponent that allows user to share outputs to

default: None Hugging Face Spaces Discussions. If False, icon


Parameter Description

does not appear. If set to None (default behavior),

then the icon appears if this Gradio app is

launched on Spaces, but not otherwise.

s h o w _ d o w n lo a d _ b u t t o n If True, w ill show a download button in the corner

bool | None of the selected image. If False, the icon does not

default: True appear. Default is True.

in t e r a c t iv e If True, the gallery will be interactive, allowing the

bool 1None user to upload images. If False, the gallery w ill be

default: None static. Default is True.

ty p e The format the image is converted to before being

Literal[('numpy', 'pil, 'filepath')] passed into the prediction function. "numpy"

default: "filepath" converts the image to a numpy array with shape

(height, width, 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. If the image is SVG, the t y p e

is ignored and the filepath of the SVG is returned.

Shortcuts
Interface String
Class Initialization
Shortcut

g r a d io . Dataframe "gallery" Uses default values

Demos

fake_gan
I

# This demo needs to be run from the repo folder.

# python demo/fake_gan/run.py

import random

import gradio as gr

def fake_gan():

images = [

(random.choice(

Loading...

gradio/fake_gan built with Gradio. Hosted on HS Spaces

Event Listeners

Description
Event listeners allow you to capture and respond to user interactions with

the UI components you've defined in a Gradio Blocks app. When a user


interacts with an element, such as changing a slider value or uploading an

image, a function is called.

Supported Event Listeners


The G a l l e r y com ponent supports the following event listeners. Each

event listener takes the same parameters, which are listed in the Event
Arguments table below.

Listener Description

gradio.Dataframe.change Event listener for when the user selects or

(fn, •••) deselects the Gallery. Uses event data


gradio.SelectData to carry v a lu e referring to
the label of the Gallery, and s e le c t e d to refer
to state of the Gallery. See EventData
documentation on how to use this event data

gradio.Gallery.upload(f This listener is triggered when the user


n, •••) uploads a file into the Gallery.

gradio.Gallery.change(f Triggered when the value of the Gallery


n, •••) changes either because of user input (e.g. a
user types in a textbox) OR because of a
function update (e.g. an image receives a value
from the output of an event trigger). See
. in p u t ( ) for a listener that is only triggered
by user input.

Event Arguments
Parameter Description

fn the function to call when this event is

Callable |None | triggered. Often a machine learning model's

Literal['decorator'] prediction function. Each parameter of the

default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tuple of values, with each

element in the tuple corresponding to one

output component.

inputs List of gradio.components to use as inputs. If

the function takes no inputs, this should be an


Parameter Description

Component | list[Component] | empty list.

set[Component] | None

default: None

o u tp u ts List of gradio.components to use as outputs. If

Component | list[Component] | the function returns no outputs, this should be


None an empty list.

default: None

api_nam e defines how the endpoint appears in the API

str |None |Literal[False] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

s c r o ll_ t o _ o u t p u t If True, w ill scroll to output com ponent on

bool completion

default: False

sh o w _ p ro g re ss If True, w ill show progress animation while

Literal[(’fu ll’, ’m inim al’, pending

’hidden’)]

default: "fu ll"

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue
Parameter Description

has been enabled. If None, w ill use the queue

setting of the gradio app.

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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 Maximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this


dict[str, Any] | list[dict[str, listener is triggered. For example, setting

Any]] 1None cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.


Parameter Description

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

float |None while the client connection is open.

default: None Interpreted in seconds.

trigger_mode If "once" (default for all events except

Literal[('once', 'm últiple' .c h a n g e ( ) ) would not allow any submissions

’a lw a y s ja s t’)] | None while an event is pending. If set to "multiple",


default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before


str 1None running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

concurrency_limit If set, this is the maximum number of this

int 1None | Literal['default'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the


Parameter Description

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

c o n c u rre n c y _ id If set, this is the id of the concurrency group.


str |None Events with the same concurrency_id w ill be

default: None limited by the lowest set co ncurrencyjim it.

show _api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"


default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

autom atically be set to False.

FileExplorer HTML ^

^ gradio Status J C
Custom Components GalleryNEW Explore

gradio =

New to Gradio? Start here: Getting Started See the Release History

^ Tab A c c o rd io n

Group

with gradio.Group():

Description
G ro u p is a la y o u t e le m e n t w ith in B lo c k s w h ic h g ro u p s to g e th e r c h ild re n so th a t

th e y d o n o t h ave a n y p a d d in g o r m a rg in b e tw e e n th e m .

Exampíe Usage

with gr.Group():

gr.Textbox(label="First")

gr.Textbox(label="Last")

Initiaíization ¿¡P
Parameter Description

v is ib le If False, group w ill be hidden.

bool

default: True

e le m _ id An optional string that is assigned as the id of this

str | None com ponent in the HTML DOM. Can be used for

default: None targeting CSS styles.


Param eter D escription

e l e m _ c la s s e s An optional string or list of strings that are

list[str] |str | None assigned as the class of this com ponent in the

default: None HTML DOM. Can be used for targeting CSS styles.

re n d e r If False, this layout w ill not be rendered in the

bool Blocks context. Should be used if the intention is to

default: True assign event listeners now but render the

com ponent later.

^ Tab A c c o rd io n

<§, gradio Status JC


Custom Com ponents G alleryNEW Explore

^ gradio =

New to Gradio? Start here: Getting Started See the Release History

^ HTML Image

HighlightedText

gradio.HighlightedText(•••)

Loading...

g rad io/high lig hted text_ com p on ent built with Gradio. Hosted on HS Spaces

Description
Displays text that contains spans that are highlighted by category or numerical

value.

Behavior
As input com ponent: Passes the value as a list of tuples as a li s t [ t u p le ] into

the function. Each tu p ie consists of a s t r substring of the text (so the entire text

is included) and s t r | f lo a t | None label, which is the category or confidence

of that substring.

Your function should accept one of these types:


d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (

v a lu e : l i s t [ t u p le [ s t r , s t r | flo a t | None] ] | None

As output com ponent: Expects a list of (word, category) tupies, or a dictionary of

two keys: "text", and "entities", which itself is a list of dictionaries, each of which

have the keys: "entity" (or "entity_group"), "start", and "end"

Your function should return one of these types:

d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( " 0 -> l i s t [ t u p l e [ s t r , s t r | flo a t | None] ] | d ic t | None

re t u r n v a lu e

Initiaíization
Param eter Description

v a lu e Default value to show. If callable, the function w ill

list[tuple[str, str | float | None]] | be called whenever the app loads to set the initial

dict I Callable |None value of the component.

default: None

c o lo r _ m a p A dictionary mapping labels to colors. The colors

dict[str, str] | None may be specified as hex codes or by their names.

default: None For example: " p e r s o n " : "re d ", " l o c a t io n " :

#FFEE22
Parameter Description

s h o w _ le g e n d whether to show span categories in a sepárate

bool legend or inline.

default: False

c o m b in e _ a d ja c e n t If True, w ill merge the la bels of adjacent tokens

bool belonging to the same category.

default: False

a d ja c e n t_ s e p a ra to r Specifies the separator to be used between tokens

str if combine_adjacent is True.

default: ""

la b e l The label for this component. Appears above the

str |None com ponent and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r . I n t e r f a c e , the label w ill be the

name of the parameter this com ponent is assigned

to.

e v e ry If v a lu e is a callable, run the function 'every'

float I None number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

s h o w _ la b e l if True, w ill display label.

bool | None

default: None
Parameter Description

c o n t a in e r If True, w ill place the com ponent in a container -

bool providing some extra padding around the border.

default: True

s c a le relative size compared to adjacent Components.

int | None For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A w ill be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

m in _ w id t h minimum pixel width, w ill wrap if not sufficient

int screen space to satisfy this value. If a certain scale

default: 160 value results in this Com ponent being narrower

than min_width, the min_width parameter w ill be

respected first.

v is ib le If False, com ponent w ill be hidden.

bool

default: True

e le m _ id An optional string that is assigned as the id of this

str I None com ponent in the HTML DOM. Can be used for

default: None targeting CSS styles.

e le m _ c la s s e s An optional list of strings that are assigned as the

list[str] Istr I None classes of this com ponent in the HTML DOM. Can

default: None be used for targeting CSS styles.

re n d e r If False, com ponent w ill not render be rendered in

bool the Blocks context. Should be used if the intention


Parameter Description

default: True is to assign event listeners now but render the

com ponent later.

in t e r a c t iv e If True, the com ponent w ill be editable, and allow

bool | None user to select spans of text and label them.

default: None

Shortcuts
Interface String
Class Initialization
Shortcut

gradio.Dataframe "highlightedtext" Uses default values

Demos

diff_texts

I

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)

]
Loading...

g r a d io / d iff_ t e x t s built with Gradio. Hosted on Efi Spaces

Event Listeners

Description
Event listeners allow you to capture and respond to user interactions with

the UI components you've defined in a Gradio Blocks app. When a user


interacts with an element, such as changing a slider value or uploading an

image, a function is called.

Supported Event Listeners


The H i g h l i g h t e d T e x t com ponent supports the following event

listeners. Each event listener takes the same parameters, which are listed

in the Event Arguments table below.

Listener Description

gradio.Dataframe.change Triggered when the value of the

(fn, •••) HighlightedText changes either because of


user input (e.g. a user types in a textbox) OR
because of a function update (e.g. an image
receives a value from the output of an event
trigger). See . in p u t ( ) for a listener that is
only triggered by user input.

g r a d io . H ig h lig h t e d T e x t . Event listener for when the user selects or


s e le c t ( f n , •••) deselects the HighlightedText. Uses event data
gradio.SelectData to carry v a lu e referring to
the label of the HighlightedText, and
s e le c t e d to refer to state of the
Listener Description

HighlightedText. See EventData


documentation on h o w to use this event data

Event Arguments
Parameter Description

fn the function to call when this event is

Callable |None | triggered. Often a machine learning model's


Litem l[’decom tor’] prediction function. Each parameter of the

default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tuple of values, with each

element in the tuple corresponding to one

output component.

inputs List of gradio.components to use as inputs. If

Component | list[Component] | the function takes no inputs, this should be an

set[Component] | None empty list.

default: None

outputs List of gradio.components to use as outputs. If

Component | list[Component] | the function returns no outputs, this should be

None an empty list.

default: None

api_name defines h o w the endpoint appears in the API

str |None |Literal[False] docs. Can be a string, None, or False. Ifset to a

default: None string, the endpoint will be exposed in the API

docs with the given name. IfNone (default),

the na m e of the function will be used as the

API endpoint. IfFalse, the endpoint will not be


Parameter Description

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

scroll_to_output If True, w ill scroll to output com ponent on

bool completion

default: False

show_progress If True, w ill show progress animation while

Literal[('fuW, ’m inim al’, pending

’hidden’)]

default: "fu ll"

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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 Maximum number of inputs to batch together

int if this is called from the queue (only relevant if


Parameter Description

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this


dict[str, A n y ] |list[dict[str, listener is triggered. For example, setting

A ny]] 1N o n e cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

flo a t 1N o n e while the client connection is open.

default: None Interpreted in seconds.

trigger_mode If "once" (default for all events except

L ite ra l[(’o n c e ’, 'm ú lt ip le , .c h a n g e ( ) ) would not allow any submissions

’a l w a y s j a s t ’)] |N o n e while an event is pending. If set to "multiple",


default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would


Parameter Description

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before


str |None running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

concurrency_limit If set, this is the maximum number of this

int 1None | Literal['default'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.


str 1None Events with the same concurrency_id w ill be

default: None limited by the lowest set concurrency_limit.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"


default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

autom atically be set to False.


Guides

N a m e d Entity Recognition

HTML Im age

^ gradio Status J C
Custom Com ponents G alleryNEW Explore


*§, gradio

N e w to Gradio? Start here: Getting Started See the Release History

^ Gallery HighlightedText

HTML

gradio.HTML(•••)

This ex a m ple was written in HTML

gradio/html_component built with Gradio. Hosted on E9SSpaces

Description
Creates a com ponent to display arbitrary HTM L output. As this com ponent does

not accept user input, it is rarely used as an input component.

Behavior
As input com ponent: (Rarely used) passes the HTML as a s t r .

Your function should accept one of these types:

d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (

v a lu e : s t r | None

As output com ponent: Expects a s t r consisting of valid HTML.

Your function should return one of these types:


d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( " 0 -> s t r | None

re t u r n v a lu e

Initiaíization
Parameter Description

value Default value. If callable, the function w ill be called

str | Callable | None whenever the app loads to set the initial value of

default: None the component.

label The label for this component. Is used as the header

str |None if there are a table of examples for this component.

default: None If None and used in a g r . I n t e r f a c e , the label

w ill be the name of the parameter this com ponent

is assigned to.

every If v a lu e is a callable, run the function 'every'

float I None number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

show_label This parameter has no effect.

bool | None

default: None

visible If False, com ponent w ill be hidden.

bool
Parameter Description

default: True

elem_id An optional string that is assigned as the id of this

str |None component in the H T M L DOM. Can be used for

default: None targeting CSS styles.

elem_classes An optional list of strings that are assigned as the

list[str] Istr I None classes of this component in the H T M L DOM. Can

default: None be used for targeting CSS styles.

render IfFalse, component will not render be rendered in

bool the Blocks context. Should be used ifthe intention

default: True is to assign event listeners n o w but render the

component later.

Shortcuts
Interface String
Class Initialization
Shortcut

gradio.Dataframe "html" Uses default values

Demos

blocks_scroll

import gradio as gr

demo = gr.Blocks()

with demo:

inp = gr.Textbox(placeholder= "Enter text.")

scroll_btn = gr.Button("Scroll")
no_scroll_btn = gr.Button("No Scroll")

big_block = gr.HTML(..

<div style='height: 800px; width: 100px; background-color: pink;'></div

<6

Loading...

g r a d io / b lo c k s _ s c r o ll built with Gradio. Hosted on BB Spaces

Event Listeners

Description
E ven t lis te n e rs a llo w y o u to c a p tu re an d re sp o n d to u ser in te ra c tio n s w ith

th e UI c o m p o n e n ts y o u 'v e d e fin e d in a G ra d io B lo c k s app. W hen a u ser


in te ra c ts w ith an e le m e n t, su ch as c h a n g in g a s lid e r v a lu e o r u p lo a d in g an

im age, a fu n c tio n is c a lle d .

Supported Event Listeners


T he H TM L c o m p o n e n t s u p p o rts th e fo llo w in g e v e n t listen e rs. Each e v e n t

lis te n e r ta k e s th e sa m e p a ra m e te rs, w h ic h are liste d in th e Event Arguments

ta b le below .
Listener Description

gradio.Dataframe.change Triggered when the value of the HTML changes

(fn, •••) either because of user input (e.g. a user types


in a textbox) OR because of a function update
(e.g. an image receives a value from the output
of an event trigger). See . in p u t ( ) for a
listener that is only triggered by user input.

Event Arguments
Parameter Description

fn the function to call when this event is

Callable |None | triggered. Often a machine learning model's

Literal['decorator'] prediction function. Each parameter of the

default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tuple of values, with each

element in the tuple corresponding to one

output component.

inputs List of gradio.components to use as inputs. If

Component | list[Component] | the function takes no inputs, this should be an

set[Component] | None empty list.

default: None

outputs List of gradio.components to use as outputs. If

Component | list[Component] | the function returns no outputs, this should be

None an empty list.

default: None
Parameter Description

api_nam e defines how the endpoint appears in the API

str |None |Literal[False] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

s c r o ll_ t o _ o u t p u t If True, w ill scroll to output com ponent on

bool completion

default: False

sh o w _ p ro g re ss If True, w ill show progress animation while

Literal[(’fu ll’, ’m inim al’, pending

’hidden’)]

default: "fu ll"

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

b atch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). The function is

then required to return a tuple of lists (even if


Parameter Description

there is only 1 output component), with each

list in the tupie corresponding to one output

component.

max_batch_size Máximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this


dict[str, Any] | list[dict[str, listener is triggered. For example, setting

Any]] 1None cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

float 1None while the client connection is open.

default: None Interpreted in seconds.


Parameter Description

trigger_mode If "once" (default for all events except

Literal[('once', 'm últiple' .c h a n g e ( ) ) would not allow any submissions

’a lw a y s ja s t’)] | None while an event is pending. If set to "múltiple",

default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before

str 1None running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

concurrency_limit If set, this is the maximum number of this

int 1None | Literal['default'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.

str 1None Events with the same concurrency_id w ill be

default: None limited by the lowest set concurrency_limit.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting


Parameter Description

api_name to False, setting show_api to False

will still allow downstream apps to use this

event. Iffn is None, show_api will

automatically be set to False.

Guides

Key Features

^ Gallery HighlightedText

^ gradio Status J C
Custom Com ponents G allery NEW E x p lo r e

^ gradio =

N e w to Gradio? Start here: Getting Started See the Release History

^ HighlightedText ImageEditor

Image

gradio.Image(•••)

0 Image

i_!_i
C o lo q u e la im a g e n a q u í

-o -

H aga c lic k p a ra c a rg a r

£ ©s
gradio/image_component built with Gradio. Hosted on B Spaces

Description
Creates an image com ponent that can be used to upload images (as an input) or

display images (as an output).

Behavior
As input com ponent: Passes the uploaded image as a numpy.array, PlL.lm age

or s t r filepath depending on typ e . For SVGs, the type parameter is ignored and

the filepath of the SVG is returned.

Your function should accept one of these types:


d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (

v a l u e : np. n d a rra y | P I L . Im age. Image | s t r | None

As output com ponent: Exp ects a n u m p y .a rra y , P IL .Im a g e , o r s t r o r

p a t h lib . P a t h file p a th to an im a g e w h ic h is d is p la y e d .

Your function should return one of these types:

d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( " 0 -> np. n d a rra y | P I L . Im age. Image | s t r | Pa th | None

re t u r n v a lu e

Initiaíization
Param eter Description

v a lu e A PIL Image, n u m p y array, path or URL for the

str |PIL.Image.Image | default value that Image component is going to

np.ndarray |None take. Ifcallable, the function will be called

default: None whenever the app loads to set the initial value of

the component.

fo rm a t Format to save image ifitdoes not already have a

str valid format (e.g. ifthe image is being returned to

default: "w ebp" the frontend as a n u m p y array or PIL Image). The

format should be supported by the PIL library. This

parameter has no effect on SVG files.


Parameter Description

h e ig h t The height of the displayed image, specified in

int |str | None pixels if a number is passed, or in CSS units if a

default: None string is passed.

w id t h The width of the displayed image, specified in

int 1str 1None pixels if a number is passed, or in CSS units if a

default: None string is passed.

im age_ m od e "RGB" if color, or "L" if black and white. See

Literal[('1', 'L', 'P', 'RGB', 'RGBA', https://pillow.readthedocs.io/en/stable/handbook

'CMYK', YCbCr, 'LAB, HSV, 'I, /concepts.html for other supported image modes

'F')] and their meaning.

default: "RGB"

so u rc e s List of sources for the image. "upload" creates a

list[Literal[(’upload, 'webcam, box where user can drop an image file, "webcam"

'clipboard')]] | None allows user to take snapshot from their webcam,

default: None "clipboard" allows users to paste an image from

the clipboard. If None, defaults to ["upload",

"webcam", "clipboard"] if streaming is False,

otherwise defaults to ["webcam"].

ty p e The format the image is converted before being

Literal[('numpy, p il, 'filepath ’)] passed into the prediction function. "numpy"

default: "num py" converts the image to a numpy array with shape

(height, width, 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. If the image is SVG, the t y p e

is ignored and the filepath of the SVG is returned.


Parameter Description

la b e l The label for this component. Appears above the

str |None com ponent and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r . I n t e r f a c e , the label w ill be the

name of the parameter this com ponent is assigned

to.

e v e ry If v a lu e is a callable, run the function 'every'

float I None number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

s h o w _ la b e l if True, w ill display label.

bool I None

default: None

s h o w _ d o w n lo a d b u tto n If True, w ill display button to download image.

bool

default: True

c o n t a in e r If True, w ill place the com ponent in a container -

bool providing some extra padding around the border.

default: True

s c a le relative size compared to adjacent Components.

int I None For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A w ill be

twice as wide as B. Should be an integer. scale


Parameter Description

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

m in _ w id t h mínimum pixel width, w ill wrap if not sufficient

int screen space to satisfy this value. If a certain scale

default: 160 value results in this Com ponent being narrower

than min_width, the min_width parameter w ill be

respected first.

in t e r a c t iv e if True, w ill allow users to upload and edit an

bool | None image; if False, can only be used to display images.

default: None If not provided, this is inferred based on whether

the com ponent is used as an input or output.

v is ib le If False, com ponent w ill be hidden.

bool

default: True

s t r e a m in g If True when used in a l i v e interface, w ill

bool autom atically stream webcam feed. Only valid is

default: False source is 'webcam'.

e le m _ id An optional string that is assigned as the id of this

str 1None com ponent in the HTML DOM. Can be used for

default: None targeting CSS styles.

e le m _ c la s s e s An optional list of strings that are assigned as the

list[str] 1str 1None classes of this com ponent in the HTML DOM. Can

default: None be used for targeting CSS styles.

re n d e r If False, com ponent w ill not render be rendered in

bool the Blocks context. Should be used if the intention


Parameter Description

default: True is to assign event listeners now but render the

com ponent later.

m ir r o r _ w e b c a m If True webcam w ill be mirrored. Default is True.

bool

default: True

s h o w _ s h a re _ b u tto n If True, w ill show a share icon in the corner of the

bool | None com ponent that allows user to share outputs to

default: None Hugging Face Spaces Discussions. If False, icon

does not appear. If set to None (default behavior),

then the icon appears if this Gradio app is

launched on Spaces, but not otherwise.

Shortcuts
Interface String
Class Initialization
Shortcut

gradio.Dataframe "image" Uses default values

Demos

sepia_filter fake_d¡ffu s¡on

import numpy as np

import gradio as gr

def sepia(input_img):

sepia_filter = np.array([

[0.393, 0.769, 0.189],

[0.349, 0.686, 0.168],

[0.272, 0.534, 0.131]

])

sepia_img = input_img.dot(sepia_filter.T)

sepia_img /= sepia_img.max()

___ 1
<6

Loading...

gradio/sepia_filter built with Gradio. Hosted on E9SSpaces

Event Listeners

Description
E ven t lis te n e rs a llo w y o u to c a p tu re an d re sp o n d to u ser in te ra c tio n s w ith

th e UI c o m p o n e n ts y o u 'v e d e fin e d in a G ra d io B lo c k s app. W hen a u ser


in te ra c ts w ith an e le m e n t, su ch as c h a n g in g a s lid e r v a lu e o r u p lo a d in g an

im age, a fu n c tio n is c a lle d .

Supported Event Listeners


T he I m a g e c o m p o n e n t s u p p o rts th e fo llo w in g e v e n t liste n e rs. Each e v e n t

lis te n e r ta k e s th e sa m e p a ra m e te rs, w h ic h are listed in th e Event Arguments

ta b le below .

Listener Description

gradio.Dataframe.change This listener is triggered when the user clears

(fn, •••) the Image using the X button for the


component.

gradio.Image.change(fn, Triggered when the value of the Image


•••) changes either because of user input (e.g. a
user types in a textbox) O R because of a
Listener Description

function update (e.g. an image receives a value


from the output of an event trigger). See
. in p u t ( ) for a listener that is only triggered
by user input.

gradio.Image.stream(fn, This listener is triggered when the user


•••) streams the Image.

gradio.Image.select(fn, Event listener for when the user selects or


•••) deselects the Image. Uses event data
gradio.SelectData to carry v a lu e referring to
the label of the Image, and s e le c t e d to refer
to state of the Image. See EventData
documentation on how to use this event data

gradio.Image.upload(fn, This listener is triggered when the user


•••) uploads a file into the Image.

Event Arguments
Parameter Description

fn the function to call when this event is

Callable |None | triggered. Often a machine learning model's


Litem l[’decom tor’] prediction function. Each parameter of the

default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tuple of values, with each

element in the tuple corresponding to one

output component.

inputs List of gradio.components to use as inputs. If

Component | list[Component] | the function takes no inputs, this should be an

set[Component] | None empty list.

default: None
Parameter Description

o u tp u ts List of gradio.components to use as outputs. If

Component | list[Component] | the function returns no outputs, this should be

None an empty list.

default: None

api_nam e defines how the endpoint appears in the API

str 1None |Literal[False] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

s c r o ll_ t o _ o u t p u t If True, w ill scroll to output com ponent on

bool completion

default: False

sh o w _ p ro g re ss If True, w ill show progress animation while

Literal[(’fu ll’, ’m inim al’, pending


’hidden’)]

default: "fu ll"

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.


Parameter Description

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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 Maximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this

dict[str, Any] | list[dict[str, listener is triggered. For example, setting

Any]] 1None cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but


Parameter Description

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

float |None while the client connection is open.

default: None Interpreted in seconds.

trigger_mode If "once" (default for all events except

Literal[('once', 'm últiple' .c h a n g e ( ) ) would not allow any submissions

’a lw a y s ja s t’)] | None while an event is pending. If set to "multiple",


default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before


str 1None running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

concurrency_limit If set, this is the maximum number of this

int 1None | Literal['default'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).


Parameter Description

concurrency_id Ifset, this is the id of the concurrency group.

str |None Events with the same concurrency_id will be

default: None limited by the lowest set concurrencyjimit.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

will still allow downstream apps to use this

event. Iffn is None, show_api will

automatically be set to False.

Guides

Image Classification In Pytorch

Image Classification In Tensorflow

Image Classification With Vision Transformers

Create Your O w n Friends With A Gan

^ HighlightedText ImageEditor

^ gradio Status J C
Custom Com ponents G alleryNEW Explore

^ gradio =

N e w to Gradio? Start here: Getting Started See the Release History

^ Image JSON

ImageEditor

gradio.ImageEditor(•••)

Loading...

gradio/im ageeditor_com ponent built with Gradio. Hosted on HS Spaces

Description
Creates an image com ponent that, as an input, can be used to upload and edit

images using simple editing tools such as brushes, strokes, cropping, and layers.

Or, as an output, this com ponent can be used to display images.

Behavior
As input com ponent: Passes the uploaded images as an instance of EditorValue,

which is just a d ic t with keys: 'background', 'layers', and 'composite'. The values

corresponding to 'background' and 'composite' are images, while 'layers' is a

l i s t of images. The images are of type PlL.lm age, n p .a rra y , or s t r filepath,

depending on the type parameter.

Your function should accept one of these types:


d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (

v a l u e : E d it o r V a lu e | None

As output com ponent: Exp ects a E d ito rV a lu e , w h ic h is ju s t a d ic tio n a ry w ith keys:

'b a ck g ro u n d ', 'layers', an d 'co m p o site '. T he v a lú e s c o rre s p o n d in g to 'b a c k g ro u n d '

and 'c o m p o s ite ' s h o u ld be im a g e s o r N one, w h ile la y e r s s h o u ld be a lis t o f

im ages. Im ages can be o f ty p e P lL . lm a g e , n p . a r r a y , o r s t r file p a th /U R L . Or, th e

v a lu e can be s im p ly a s in g le im a g e (Im ageType), in w h ic h ca se it w ill be used as

th e b a ck g ro u n d .

Your function should return one of these types:

d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( " 0 -> E d it o r V a lu e | ImageType | None

re t u r n v a lu e

Initiaíization
Param eter Description

v a lu e Optional initial image(s) to populate the image

EditorValue | ImageType | None editor. Should be a dictionary with keys:

default: None b a ck g ro u n d , l a y e r s , and c o m p o s ite . The

values corresponding to b a ckg ro u n d and

c o m p o s ite should be images or None, while

la y e r s should be a list of images. Images can be

of type PIL.Image, np.array, or str filepath/URL. Or,

the value can be a callable, in which case the


Parameter Description

function w ill be called whenever the app loads to

set the initial value of the component.

h e ig h t The height of the com ponent container, specified

int |str | None in pixels if a number is passed, or in CSS units if a

default: None string is passed.

w id t h The width of the com ponent container, specified in

int 1str 1None pixels if a number is passed, or in CSS units if a

default: None string is passed.

im age_ m od e "RGB" if color, or "L" if black and white. See

Literal[('1', 'L', 'P', 'RGB', 'RGBA', https://pillow.readthedocs.io/en/stable/handbook

'CMYK', YCbCr, 'LAB, HSV, 'I, /concepts.html for other supported image modes

'F')] and their meaning.

default: "RGBA"

so u rc e s List of sources that can be used to set the

Iterable[Literal[(’upload, background image. "upload" creates a box where

'webcam, ’clipboard’)]] |None user can drop an image file, "webcam" allows user

default: ('upload', 'webcam', to take snapshot from their webcam, "clipboard"

'clipboard') allows users to paste an image from the clipboard.

ty p e The format the images are converted to before

Literal[('numpy, p il, 'filepath ’)] being passed into the prediction function.

default: "num py" "numpy" converts the images to numpy arrays

with shape (height, width, 3) and values from 0 to

255, "pil" converts the images to PIL image objects,

"filepath" passes images as str filepaths to

temporary copies of the images.


Parameter Description

la b e l The label for this component. Appears above the

str |None com ponent and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r . I n t e r f a c e , the label w ill be the

name of the parameter this com ponent is assigned

to.

e v e ry If v a lu e is a callable, run the function 'every'

float I None number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

s h o w _ la b e l if True, w ill display label.

bool I None

default: None

s h o w _ d o w n lo a d b u tto n If True, w ill display button to download image.

bool

default: True

c o n t a in e r If True, w ill place the com ponent in a container -

bool providing some extra padding around the border.

default: True

s c a le relative size compared to adjacent Components.

int I None For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A w ill be

twice as wide as B. Should be an integer. scale


Parameter Description

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

m in _ w id t h mínimum pixel width, will wrap ifnot sufficient

int screen space to satisfy this value. Ifa certain scale

default: 160 value results in this Component being narrower

than min_width, the min_width parameter will be

respected first.

in t e r a c t iv e ifTrue, will allow users to upload and edit an

bool | None image; if False, can only be used to display images.

default: None Ifnot provided, this is inferred based on whether

the component is used as an input or output.

v is ib le IfFalse, component will be hidden.

bool

default: True

e le m _ id An optional string that is assigned as the id of this

str I None component in the H T M L DOM. Can be used for

default: None targeting CSS styles.

e le m _ c la s s e s An optional list of strings that are assigned as the

list[str] Istr I None classes of this component in the H T M L DOM. Can

default: None be used for targeting CSS styles.

re n d e r IfFalse, component will not render be rendered in

bool the Blocks context. Should be used ifthe intention

default: True is to assign event listeners n o w but render the

component later.
Param eter Description

m ir r o r _ w e b c a m If True webcam w ill be mirrored. Default is True.

bool

default: True

sh o w _ s h a re _ b u tto n If True, w ill show a share icon in the córner of the

bool | None com ponent that allows user to share outputs to

default: None Hugging Face Spaces Discussions. If False, icon

does not appear. If set to None (default behavior),

then the icon appears if this Gradio app is

launched on Spaces, but not otherwise.

c r o p _ s iz e The size of the crop box in pixels. If a tuple, the first

tuple[int I float, int | float] |str | value is the width and the second value is the

None height. If a string, the value must be a ratio in the

default: None form w id t h : h e ig h t (e.g. "16:9").

tra n s fo rm s The transforms tools to make available to users.

Iterable[Literal[’crop’]] "crop" allows the user to crop the image.

default: ('crop',)

e ra se r The options for the eraser tool in the image editor.

Eraser | None | Literal[False] Should be an instance of the g r . E r a s e r class, or

default: None None to use the default settings. Can also be False

to hide the eraser tool.

b ru sh The options for the brush tool in the image editor.

Brush | None | Literal[False] Should be an instance of the g r .B r u s h class, or

default: None None to use the default settings. Can also be False

to hide the brush tool, which w ill also hide the

eraser tool.
Parameter Description

format Format to save image ifitdoes not already have a

str valid format (e.g. ifthe image is being returned to

default: "w ebp" the frontend as a n u m p y array or PIL Image). The

format should be supported by the PIL library. This

parameter has no effect on SVG files.

layers IfTrue, will allow users to add layers to the image.

bool IfFalse, the layers option will be hidden.

default: True

canvas_size The size of the default canvas in pixels. Ifa tuple,

tu p le [in t, int] |N o n e the first value is the width and the second value is

default: None the height. If None, the canvas size will be the

same as the background image or 800 x 600 if no

background image is provided.

Shortcuts
Interface String
Class Initialization
Shortcut

gradio.Dataframe "imageeditor" Uses default values

Uses sources=(),
brush=Brush(colors=
g r a d i o .S k e t c h p a d "sketchpad"
["#000000"],
color_mode="fixed")

g r a d i o .P a int "paint" Uses sources=()

Uses
brush=Brush(colors=
g r a d i o .I m a g e M a s k "imagemask"
["#000000"],
color_mode="fixed")
Demos

image_editor

import gradio as gr

import time

def sleep(im):

time.sleep(5)

return [im["background"], im["layers"][0], im["layers"][1], im["composi

te"]]

def predict(im):

<30

Loading...

gradio/image_editor built with Gradio. Hosted on HS Spaces

Event Listeners

Description
E ven t lis te n e rs a llo w y o u to c a p tu re an d re sp o n d to u ser in te ra c tio n s w ith

th e UI c o m p o n e n ts y o u 'v e d e fin e d in a G ra d io B lo c k s app. W hen a u ser


in te ra c ts w ith an e le m e n t, su ch as c h a n g in g a s lid e r v a lu e o r u p lo a d in g an

im age, a fu n c tio n is c a lle d .


Supported Event Listeners
T he I m a g e E d i t o r c o m p o n e n t s u p p o rts th e fo llo w in g e v e n t listen e rs.

Each e v e n t lis te n e r ta k e s th e sa m e p a ra m e te rs, w h ic h are listed in th e

Event Arguments ta b le below .

Listener Description

gradio.Dataframe.change This listener is triggered when the user clears

(fn, •••) the ImageEditor using the X button for the


component.

gradio.ImageEditor.chan Triggered when the value of the ImageEditor


ge(fn, •••) changes either because of user input (e.g. a
user types in a textbox) OR because of a
function update (e.g. an image receives a value
from the output of an event trigger). See
. in p u t ( ) for a listener that is only triggered
by user input.

gradio.ImageEditor.inpu This listener is triggered when the user


t(fn, •••) changes the value of the ImageEditor.

gradio.ImageEditor.sele Event listener for when the user selects or


ct(fn, •••) deselects the ImageEditor. Uses event data
gradio.SelectData to carry v a lu e referring to
the label of the ImageEditor, and s e le c t e d to
refer to state of the ImageEditor. See
EventData documentation on how to use this
event data

gradio.ImageEditor.uplo This listener is triggered when the user


ad(fn, •••) uploads a file into the ImageEditor.

gradio.ImageEditor.appl This listener is triggered when the user applies


y(fn, •••) changes to the ImageEditor through an
integrated UI action.

Event Arguments
Parameter Description

fn the function to call when this event is

C a lla b le |N o n e | triggered. Often a machine learning model's

L it e m l[ ’d e c o m t o r ’] prediction function. Each parameter of the

default: "decorator" 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.

in p u t s List of gradio.components to use as inputs. If

Com ponent |lis t[ C o m p o n e n t] | the function takes no inputs, this should be an

s e t[C o m p o n e n t] |N o n e empty list.

default: None

o u tp u ts List of gradio.components to use as outputs. If

C o m p o n e n t |lis t[ C o m p o n e n t] | the function returns no outputs, this should be

None an empty list.

default: None

api_nam e defines how the endpoint appears in the API

s t r |N o n e |L ite ra l[F a ls e ] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.


Parameter Description

scroll_to_output If True, w ill scroll to output com ponent on

bool completion

default: False

show_progress If True, w ill show progress animation while

Literal[('fuW, ’m inim al’, pending

’hidden’)]

default: "fu ll"

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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 Maximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.


Parameter Description

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this


dict[str, A n y ] |list[dict[str, listener is triggered. For example, setting

A ny]] 1N o n e cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

flo a t 1N o n e while the client connection is open.

default: None Interpreted in seconds.

trigger_mode If "once" (default for all events except

L ite ra l[(’o n c e ’, 'm ú lt ip le , .c h a n g e ( ) ) would not allow any submissions

’a l w a y s j a s t ’)] |N o n e while an event is pending. If set to "multiple",


default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.
Parameter Description

js Optional frontend js method to run before

str |None running 'fn'. Input arguments for js method are

default: None valúes of 'inputs' and 'outputs', return should

be a list of valúes for output components.

concurrency_limit If set, this is the maximum number of this

int 1None | Literal['default'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.

str 1None Events with the same concurrency_id w ill be

default: None limited by the lowest set concurrency_limit.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

autom atically be set to False.

Image JSON ^
^ gradio Status J C
Custom Com ponents G alleryNEW E xp lore

$ gradio

N e w to Gradio? Start here: Getting Started See the Release History

W a rn in g R e q u e st

Info

gradio.Info(•••)

Description

T h is fu n c tio n a llo w s you to p ass cu sto m in fo m essa g e s to th e user. You can d o so

s im p ly by w ritin g g r . ln f o ( 'm e s s a g e h e r e ') in y o u r fu n c tio n , and w h e n th a t lin e

is e xe cu te d th e cu sto m m e ssag e w ill a p p e a r in a m o d a l on th e d e m o . T he m o d a l

is gray by d e fa u lt a n d has th e headin g: "Info." Q u e u e m u s t be e n a b le d fo r th is

b e h a v io r; o th e rw is e , th e m e ssa g e w ill be p rin te d to th e co n so le .

Exampíe Usage &

import gradio as gr

def hello_world():

gr.Info('This is some info.')

return "helio world"

with gr.Blocks() as demo:


md = gr.Markdown()

demo.load(hello_world, inputs=None, outputs= [md])

demo.queue().launch()

InitiaMzation

Param eter Description

m e s sa g e The info message to be displayed to the user.

str

default: "Info issued."

Demos

blocks_chained_events


import gradio as gr

import time

I
def failure():

raise gr.Error("This should fail!")

def exception():

raise ValueError("Something went wrong")

def success():
Loading...

g r a d i o / b l o c k s _ c h a i n e d _ e v e n t s b u ilt w ith G ra d io . H o s te d o n Spaces

W a rn in g R e q u e st

Status

^ gradio o
Custom Com ponents G alleryNEW E xp lore

^ gradio =

N e w to Gradio? Start here: Getting Started See the Release History

Im a g e E d ito r L ab e l

JSON

gradio.JSON(•••)

Loading...

g r a d io / j s o n _ c o m p o n e n t b u ilt w ith G ra d io . H o s te d o n Efi S p a c e s

Description
U sed to d is p la y a rb itra ry JS O N o u tp u t p rettily. A s th is c o m p o n e n t d o e s n ot

a c c e p t u se r in p u t, it is ra re ly used as an in p u t c o m p o n e n t.

Behavior
As input com ponent: P asses th e JS O N v a lu e as a d i c t o r l i s t d e p e n d in g on th e

valu e.

Your function should accept one of these types:

d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

)
. . . d e f p r e d ic t (

v a lu e : d ic t | lis t | None

As output com ponent: Exp ects a v a lid JS O N s t r -- o r a l i s t o r d i c t th a t can be

s e ria liz e d to a JS O N strin g . T he l i s t o r d i c t v a lu e can c o n ta in n u m p y arrays.

Your function should return one of these types:

d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( ^ " ) -> d i c t | lis t | s tr | None

re t u r n v a lu e

InitiaMzation
Parameter Description

v a lu e Default value as a valid JSON s t r -- or a l i s t or

str |dict | list | Callable |None d i c t that can be serialized to a JSON string. If

default: None callable, the function w ill be called whenever the

app loads to set the initial value of the component.

la b e l The label for this component. Appears above the

str |None com ponent and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r . I n t e r f a c e , the label w ill be the

name of the parameter this com ponent is assigned

to.

e v e ry If v a lu e is a callable, run the function 'every

float |None number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be


Parameter Description

accessed (e.g. to cancel it) via this component's

.load_event attribute.

s h o w _ la b e l ifTrue, will display label.

bool |N o n e

default: None

c o n t a in e r IfTrue, will place the component in a container -

bool providing some extra padding around the border.

default: True

s c a le relative size compared to adjacent Components.

in t I N o n e For example ifComponents A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A will be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

m in _ w id t h minimum pixel width, will wrap ifnot sufficient

in t screen space to satisfy this value. Ifa certain scale

default: 160 value results in this Component being narrower

than min_width, the min_width parameter will be

respected first.

v is ib le IfFalse, component will be hidden.

bool

default: True

e le m _ id An optional string that is assigned as the id of this

s t r IN o n e component in the H T M L DOM. Can be used for

default: None targeting CSS styles.


Parameter Description

elem_classes An optional list of strings that are assigned as the

list[str] |s t r |N o n e classes of this component in the H T M L DOM. Can

default: None be used for targeting CSS styles.

render IfFalse, component will not render be rendered in

bool the Blocks context. Should be used ifthe intention

default: True is to assign event listeners n o w but render the

component later.

Shortcuts
Interface String
Class Initialization
Shortcut

gradio.Dataframe "json" Uses default valúes

Demos

z ip _ to js o n b lo ck s_ x ra y

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(

{
Loading...

g r a d i o / z i p _ t o _ j s o n b u ilt w ith G ra d io . H o s te d o n Efi S p a c e s

Event Listeners

Description
E ven t lis te n e rs a llo w y o u to c a p tu re an d re sp o n d to u ser in te ra c tio n s w ith

th e UI c o m p o n e n ts y o u 'v e d e fin e d in a G ra d io B lo c k s app. W hen a u ser


in te ra c ts w ith an e le m e n t, su ch as c h a n g in g a s lid e r v a lu e o r u p lo a d in g an

im age, a fu n c tio n is c a lle d .

Supported Event Listeners


T he JS O N c o m p o n e n t s u p p o rts th e fo llo w in g e v e n t listen e rs. Each e v e n t

lis te n e r ta k e s th e sa m e p a ra m e te rs, w h ic h are liste d in th e Event Arguments

ta b le below .

Listener Description

gradio.Dataframe.change Triggered when the value of the JSON changes

(fn, •••) either because of user input (e.g. a user types


in a textbox) OR because of a function update
(e.g. an image receives a value from the output
of an event trigger). See . in p u t ( ) for a
listener that is only triggered by user input.

Event Arguments
Parameter Description

fn the function to call when this event is

C a lla b le |N o n e | triggered. Often a machine learning model's

L it e m l[ ’d e c o m t o r ’] prediction function. Each parameter of the

default: "decorator" 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.

in p u t s List of gradio.components to use as inputs. If

Com ponent |lis t[ C o m p o n e n t] | the function takes no inputs, this should be an

s e t[C o m p o n e n t] |N o n e empty list.

default: None

o u tp u ts List of gradio.components to use as outputs. If

C o m p o n e n t |lis t[ C o m p o n e n t] | the function returns no outputs, this should be

None an empty list.

default: None

api_nam e defines how the endpoint appears in the API

s t r |N o n e |L ite ra l[F a ls e ] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.


Parameter Description

scroll_to_output If True, w ill scroll to output com ponent on

bool completion

default: False

show_progress If True, w ill show progress animation while

Literal[('fuW, ’m inim al’, pending

’hidden’)]

default: "fu ll"

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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 Maximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.


Parameter Description

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this


dict[str, A n y ] |list[dict[str, listener is triggered. For example, setting

A ny]] 1N o n e cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

flo a t 1N o n e while the client connection is open.

default: None Interpreted in seconds.

trigger_mode If "once" (default for all events except

L ite ra l[(’o n c e ’, 'm ú lt ip le , .c h a n g e ( ) ) would not allow any submissions

’a l w a y s j a s t ’)] |N o n e while an event is pending. If set to "multiple",


default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.
Parameter Description

js Optional frontend js method to run before

str |None running 'fn'. Input arguments for js method are

default: None valúes of 'inputs' and 'outputs', return should

be a list of valúes for output components.

concurrency_limit If set, this is the maximum number of this

int 1None | Literal['default'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.

str 1None Events with the same concurrency_id w ill be

default: None limited by the lowest set concurrency_limit.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

autom atically be set to False.

Im a g e E d ito r L ab e l
^ gradio Status J C
Custom Com ponents G alleryNEW E xp lore

^ gradio =

N e w to Gradio? Start here: Getting Started See the Release History

^ JSON LinePlot ^

Label

gradio.Label(•••)

Loading...

g r a d i o / l a b e l _ c o m p o n e n t b u ilt w ith G ra d io . H o s te d o n HS S p a c e s

Description
Displays a classification label, along with confidence scores of top categories, if

provided. As this com ponent does not accept user input, it is rarely used as an

input component.

Behavior
As input com ponent: Depending on the value, passes the label as a s t r | in t |

f l o a t , or the labels and confidences as a d i c t [ s t r , flo a t ] .

Your function should accept one of these types:

d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]


)

. . . d e f p r e d ic t (

v a lu e : d i c t [ s t r , f l o a t ] | s tr | in t | flo a t | None

As output com ponent: Exp ects a d i c t [ s t r , f l o a t ] o f cla s s e s an d c o n fid e n ce s,

o r s t r w ith ju s t th e c la s s o r an i n t | f l o a t fo r reg ressio n o u tp u ts , o r a s t r path

to a .json file c o n ta in in g a js o n d ic tio n a ry in o n e o f th e p re c e d in g fo rm a ts.

Your function should return one of these types:

d e f p r e d ic t ( " 0 -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( " 0 -> d i c t [ s t r , f l o a t ] | s tr | in t | flo a t | None

re t u r n v a lu e

Imtiaíization
Param eter Description

v a lu e Default value to show in the component. If a str or

dict[str, flo a t] |s t r |flo a t | number is provided, sim ply displays the string or

C a lla b le |N o n e number. If a D i c t [ s t r , f l o a t ] of classes and

default: None confidences is provided, displays the top class on

top and the n u m _ to p _ c la s s e s below, along with

their confidence bars. If callable, the function w ill

be called whenever the app loads to set the initial

value of the component.

n u m _ t o p _ c la s s e s number of most confident classes to show.

in t |N o n e

default: None
Parameter Description

la b e l The label for this component. Appears above the

str |None com ponent and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r . I n t e r f a c e , the label w ill be the

name of the parameter this com ponent is assigned

to.

e v e ry If v a lu e is a callable, run the function 'every'

float 1None number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

s h o w _ la b e l if True, w ill display label.

bool 1None

default: None

c o n t a in e r If True, w ill place the com ponent in a container -

bool providing some extra padding around the border.

default: True

s c a le relative size compared to adjacent Components.

int 1None For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A w ill be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.


Parameter Description

m in _ w id t h mínimum pixel width, will wrap ifnot sufficient

in t screen space to satisfy this value. Ifa certain scale

default: 160 value results in this Component being narrower

than min_width, the min_width parameter will be

respected first.

v is ib le IfFalse, component will be hidden.

bool

default: True

e le m _ id An optional string that is assigned as the id of this

str |N o n e component in the H T M L DOM. Can be used for

default: None targeting CSS styles.

e le m _ c la s s e s An optional list of strings that are assigned as the

list[str] Is t r I N o n e classes of this component in the H T M L DOM. Can

default: None be used for targeting CSS styles.

re n d e r IfFalse, component will not render be rendered in

bool the Blocks context. Should be used ifthe intention

default: True is to assign event listeners n o w but render the

component later.

c o lo r The background color of the label (either a valid

s t r |N o n e css color na m e or hexadecimal string).

default: None

Shortcuts
Interface String
Class Initialization
Shortcut

g r a d io . Dataframe "label" Uses default values

Event Listeners

Description
E ven t lis te n e rs a llo w y o u to c a p tu re an d re sp o n d to u ser in te ra c tio n s w ith

th e UI c o m p o n e n ts y o u 'v e d e fin e d in a G ra d io B lo c k s app. W hen a u ser


in te ra c ts w ith an e le m e n t, su ch as c h a n g in g a s lid e r v a lu e o r u p lo a d in g an

im age, a fu n c tio n is c a lle d .

Supported Event Listeners


T he L a b e l c o m p o n e n t s u p p o rts th e fo llo w in g e v e n t liste n e rs. Each e v e n t

lis te n e r ta k e s th e sa m e p a ra m e te rs, w h ic h are listed in th e Event Arguments

ta b le below .

Listener Description

gradio.Dataframe.change Triggered when the value of the Label changes

(fn, •••) either because of user input (e.g. a user types


in a textbox) OR because of a function update
(e.g. an image receives a value from the output
of an event trigger). See . in p u t ( ) for a
listener that is only triggered by user input.

gradio.Label.select(fn, Event listener for when the user selects or


•••) deselects the Label. Uses event data
gradio.SelectData to carry v a lu e referring to
the label of the Label, and s e le c t e d to refer
to state of the Label. See EventData
documentation on how to use this event data

Event Arguments
Parameter Description

fn the function to call when this event is

C a lla b le |N o n e | triggered. Often a machine learning model's

L it e m l[ ’d e c o m t o r ’] prediction function. Each parameter of the

default: "decorator" 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.

in p u t s List of gradio.components to use as inputs. If

Com ponent |lis t[ C o m p o n e n t] | the function takes no inputs, this should be an

s e t[C o m p o n e n t] |N o n e empty list.

default: None

o u tp u ts List of gradio.components to use as outputs. If

C o m p o n e n t |lis t[ C o m p o n e n t] | the function returns no outputs, this should be

None an empty list.

default: None

api_nam e defines how the endpoint appears in the API

s t r |N o n e |L ite ra l[F a ls e ] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.


Parameter Description

scroll_to_output If True, w ill scroll to output com ponent on

bool completion

default: False

show_progress If True, w ill show progress animation while

Literal[('fuW, ’m inim al’, pending

’hidden’)]

default: "fu ll"

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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 Maximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.


Parameter Description

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this


dict[str, A n y ] |list[dict[str, listener is triggered. For example, setting

A ny]] 1N o n e cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

flo a t 1N o n e while the client connection is open.

default: None Interpreted in seconds.

trigger_mode If "once" (default for all events except

L ite ra l[(’o n c e ’, 'm ú lt ip le , .c h a n g e ( ) ) would not allow any submissions

’a l w a y s j a s t ’)] |N o n e while an event is pending. If set to "multiple",


default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.
Parameter Description

js Optional frontend js method to run before

str |None running 'fn'. Input arguments for js method are

default: None valúes of 'inputs' and 'outputs', return should

be a list of valúes for output components.

concurrency_limit If set, this is the maximum number of this

int 1None | Literal['default'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.

str 1None Events with the same concurrency_id w ill be

default: None limited by the lowest set concurrency_limit.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

autom atically be set to False.

Guides

Image Classification In Pytorch


Image Classification In Tensorflow

Image Classification With Visión Transformers

JS O N L in e P lo t

^ gradio Status J C
Custom Com ponents G alleryNEW E xp lore

^ gradio =

N e w to Gradio? Start here: Getting Started See the Release History

^ Label LoginButton

LinePlot

gradio.LinePlot(•••)

Loading...

g r a d i o / l i n e p l o t _ c o m p o n e n t b u ilt w ith G ra d io . H o s te d o n HS S p a c e s

Description
Creates a line plot com ponent to display data from a pandas DataFrame (as

output). As this com ponent does not accept user input, it is rarely used as an

input component.

Behavior
As input com ponent: (Rarely used) passes the data displayed in the line plot as

an AltairPlotData dataclass, which includes the plot information as a JSON string,

as well as the type of plot (in this case, "line").

Your function should accept one of these types:


d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (

v a l u e : A l t a ir P lo t D a t a | None

As output com ponent: Exp ects a p a n d a s D ataFram e c o n ta in in g th e data to

d is p la y in th e lin e p lo t. T h e D ataFram e sh o u ld c o n ta in a t le a st tw o c o lu m n s , o n e

fo r th e x-axis (c o rre s p o n d in g to th is c o m p o n e n t's x arg u m en t) an d o n e fo r th e y-

axis (c o rre s p o n d in g to y ).

Your function should return one of these types:

d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( " 0 -> pd. DataFrame | d ic t | None

re t u r n v a lu e

Initiaíization
Param eter Description

value The pandas dataframe containing the data to

p d .D a t a F r a m e |C a lla b le |N o n e display in a scatter plot.

default: None

x Column corresponding to the x axis.

s t r IN o n e

default: None

y Column corresponding to the y axis.

s t r |N o n e
Parameter Description

default: None

color The column to determine the point color. Ifthe

str |N o n e column contains numeric data, gradio will

default: None interpolate the column data so that small values

correspond to light colors and large values

correspond to dark values.

stroke_dash The column to determine the symbol used to draw

s t r 1N o n e the line, e.g. dashed lines, dashed lines with

default: None points.

overlay_point Whether to draw a point on the line for each (x, y)

b o o l 1N o n e coordinate pair.

default: None

title The title to display on top of the chart.

s t r 1N o n e

default: None

tooltip The column (or list of columns) to display on the

list[str] 1s t r 1N o n e tooltip when a user hovers a point on the plot.

default: None

x_title The title given to the x axis. By default, uses the

s t r 1N o n e value of the x parameter.

default: None

y_title The title given to the y axis. By default, uses the

s t r 1N o n e value of the y parameter.

default: None
Parameter Description

x_label_angle The angle for the x axis labels. Positive valúes are

flo a t |N o n e clockwise, and negative valúes are counter-

default: None clockwise.

y_label_angle The angle for the y axis labels. Positive valúes are

flo a t 1N o n e clockwise, and negative valúes are counter-

default: None clockwise.

color_legend_title The title given to the color legend. By default, uses

s t r 1N o n e the value of color parameter.

default: None

stroke_dash_legend_tit The title given to the stroke_dash legend. By

le default, uses the value of the stroke_dash

s t r |N o n e parameter.

default: None

color_legend_position The position of the color legend. Ifthe string value

L ite ra l[(’le ft’, ’r ig h t ’, ’t o p ’, 'none' is passed, this legend is omitted. For other

’b o tto m ', 'to p -le ft, 'to p -rig h t, valid position values see:

'b o tto m -le ft, b o t t o m - r ig h t , https://vega.github.io/vega/docs/legends/#orienta

'n o n e 1)] |N o n e tion.

default: None

stroke_dash_legend_pos The position of the stoke_dash legend. Ifthe string

ition value 'none' is passed, this legend is omitted. For

L ite ra l[(’le ft’, 'r ig h t , ’to p , other valid position values see:

b o t t o m , 'to p -le ft, 't o p - rig h t, https://vega.github.io/vega/docs/legends/#orienta

'b o tto m -le ft, b o t t o m - r ig h t , tion.

'n o n e ')] |N o n e
Parameter Description

default: None

height The height of the plot, specified in pixels ifa

in t |s t r |N o n e number is passed, or in CSS units ifa string is

default: None passed.

width The width of the plot, specified in pixels ifa

in t 1s t r 1N o n e number is passed, or in CSS units ifa string is

default: None passed.

x_lim A tuple or list containing the limits for the x-axis,

list[int] 1N o n e specified as [x_min, x_max].

default: None

y_lim A tuple of list containing the limits for the y-axis,

list[int] 1N o n e specified as [y_min, y_max].

default: None

caption The (optional) caption to display below the plot.

s t r 1N o n e

default: None

interactive Whether users should be able to interact with the

b o o l 1N o n e plot by panning or zooming with their mouse or

default: True trackpad.

lab e l The (optional) label to display on the top left

s t r 1N o n e corner of the plot.

default: None

show_label Whether the label should be displayed.

b o o l |N o n e
Parameter Description

default: None

c o n t a in e r

bool

default: True

s c a le

int | None

default: None

m in _ w id t h

int

default: 160

e v e ry If v a lu e is a callable, run the function 'every'

float 1None number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

v is ib le Whether the plot should be visible.

bool

default: True

e le m _ id An optional string that is assigned as the id of this

str 1None com ponent in the HTML DOM. Can be used for

default: None targeting CSS styles.

e le m _ c la s s e s An optional list of strings that are assigned as the

list[str] 1str 1None classes of this com ponent in the HTML DOM. Can

default: None be used for targeting CSS styles.


Parameter Description

render IfFalse, component will not render be rendered in

bool the Blocks context. Should be used ifthe intention

default: True is to assign event listeners n o w but render the

component later.

show_actions_button Whether to show the actions button on the top

bool right corner of the plot.

default: False

Shortcuts
Interface String
Class Initialization
Shortcut

gradio.Dataframe "lineplot" Uses default values

Demos

live_dashboard


import math

import pandas as pd I
import gradio as gr

import datetime

import numpy as np

def get_time():

return datetime.datetime.now()
Loading...

g r a d i o / l i v e _ d a s h b o a r d b u ilt w ith G ra d io . H o s te d o n Efi S p a c e s

Event Listeners

Description
E ven t lis te n e rs a llo w y o u to c a p tu re an d re sp o n d to u ser in te ra c tio n s w ith

th e UI c o m p o n e n ts y o u 'v e d e fin e d in a G ra d io B lo c k s app. W hen a u ser


in te ra c ts w ith an e le m e n t, su ch as c h a n g in g a s lid e r v a lu e o r u p lo a d in g an

im age, a fu n c tio n is c a lle d .

Supported Event Listeners


T he L i n e P l o t c o m p o n e n t s u p p o rts th e fo llo w in g e v e n t listen e rs. Each

e v e n t lis te n e r ta k e s th e s a m e p a ra m e te rs, w h ic h are listed in th e Event

Arguments ta b le b elow .

Listener Description

gradio.Dataframe.change Triggered when the value of the Plot changes

(fn, •••) either because of user input (e.g. a user types


in a textbox) OR because of a function update
(e.g. an image receives a value from the output
of an event trigger). See . in p u t ( ) for a
listener that is only triggered by user input.

gradio.LinePlot.clear(f This listener is triggered when the user clears


n, •••) the Plot using the X button for the component.

Event Arguments
Parameter Description

fn the function to call when this event is

C a lla b le |N o n e | triggered. Often a machine learning model's

L it e m l[ ’d e c o m t o r ’] prediction function. Each parameter of the

default: "decorator" 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.

in p u t s List of gradio.components to use as inputs. If

Com ponent |lis t[ C o m p o n e n t] | the function takes no inputs, this should be an

s e t[C o m p o n e n t] |N o n e empty list.

default: None

o u tp u ts List of gradio.components to use as outputs. If

C o m p o n e n t |lis t[ C o m p o n e n t] | the function returns no outputs, this should be

None an empty list.

default: None

api_nam e defines how the endpoint appears in the API

s t r |N o n e |L ite ra l[F a ls e ] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.


Parameter Description

scroll_to_output If True, w ill scroll to output com ponent on

bool completion

default: False

show_progress If True, w ill show progress animation while

Literal[('fuW, ’m inim al’, pending

’hidden’)]

default: "fu ll"

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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 Maximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.


Parameter Description

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this


dict[str, A n y ] |list[dict[str, listener is triggered. For example, setting

A ny]] 1N o n e cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

flo a t 1N o n e while the client connection is open.

default: None Interpreted in seconds.

trigger_mode If "once" (default for all events except

L ite ra l[(’o n c e ’, 'm ú lt ip le , .c h a n g e ( ) ) would not allow any submissions

’a l w a y s j a s t ’)] |N o n e while an event is pending. If set to "multiple",


default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.
Parameter Description

js Optional frontend js method to run before

str |None running 'fn'. Input arguments for js method are

default: None valúes of 'inputs' and 'outputs', return should

be a list of valúes for output components.

concurrency_limit If set, this is the maximum number of this

int 1None | Literal['default'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.

str 1None Events with the same concurrency_id w ill be

default: None limited by the lowest set concurrency_limit.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

autom atically be set to False.

L ab e l L o g in B u tto n
^ gradio Status J C
Custom Com ponents G alleryNEW E xp lore

$ gradio

N e w to Gradio? Start here: Getting Started See the Release History

m a k e _ w a v e fo rm Erro r

load

gradio.load(name, •••)

Description

C o n s tru c ts a d e m o fro m a H u g g in g Face repo. Can a c c e p t m o d e l re p o s (if src is

"m o d e ls ") o r S p a ce re p o s (if src is "sp ace s"). T h e in p u t and o u tp u t c o m p o n e n ts

are a u to m a tic a lly lo a d e d fro m th e repo. N ote th a t if a S p a ce is lo a d e d , ce rta in

h ig h -le v e l a ttrib u te s o f th e B lo c k s (e.g. c u sto m c s s , j s , an d head a ttrib u te s) w ill

n o t be lo a d e d .

Example Usage &

import gradio as gr

demo = gr.load("gradio/question-answering", src="spaces")

demo.launch()
InitiaMzation

Parameter Description

name the name of the model (e.g. "gpt2" or

str "facebook/bart-base") or space (e.g. "flax-

required community/spanish-gpt2"), can include the s r c as

prefix (e.g. "models/facebook/bart-base")

src the source of the model: m odels or sp a c e s (or

str |None leave empty if source is provided as a prefix in

default: None name)

h f_ to k e n optional access token for loading prívate Hugging

str |None Face Hub models or spaces. Find your token here:

default: None https://huggingface.co/settings/tokens. Warning:

only provide this if you are loading a trusted

private Space as it can be read by the Space you

are loading.

a lia s optional string used as the name of the loaded

str 1None model instead of the default name (only applies if

default: None loading a Space running Gradio 2.x)

^ make_waveform Error

Status

$$ gradio O
Custom Com ponents G alleryNEW E xp lore

^ gradio =

N e w to Gradio? Start here: Getting Started See the Release History

^ LinePlot LogoutButton

LoginButton

gradio.LoginButton(•••)

Loading...

g r a d i o / l o g i n b u t t o n _ c o m p o n e n t b u ilt w ith G ra d io . H o s te d o n HS S p a c e s

Description
Creates a button that redirects the user to Sign with Hugging Face using OAuth.

Behavior
As input com ponent: (Rarely used) the s t r corresponding to the button label

when the button is clicked

Your function should accept one of these types:

d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (
v a lu e : s t r | None

As output com ponent: s trin g c o rre s p o n d in g to th e b u tto n la b e l

Your function should return one of these types:

d e f p r e d ic t ( " 0 -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( " 0 -> s t r | None

re t u r n v a lu e

Initiaíization
Param eter Description

value

str

default: "Sign in w ith Hugging

Face"

logout_value The text to display when the user is signed in. The

s tr string should contain a placeholder for the

default: "Logout ({})" username with a call-to-action to logout, e.g.

"Logout ()".

every

flo a t |N o n e

default: None

variant

L ite ra l[(’p r im a r y ’, ’s e c o n d a r y ’,

'stop')]
Parameter Description

default: "secondary"

si z e

L iteral[('sm ', 'lg')] |N o n e

default: None

icon

s t r |N o n e

default:

" https://huggingface.co/front/a

ssets/huggingface_logo-

noborder.svg"

link

s t r IN o n e

default: None

visible

bool

default: True

interactive

bool

default: True

elem_id

s t r IN o n e

default: None

elem_classes

list[str] Is t r I N o n e
Parameter Description

default: None

render

bool

default: True

scale

in t |N o n e

default: 0

min_width

in t I N o n e

default: None

signed_in_value

str

default: "Signed in as {}"

Shortcuts
Interface String
Class Initialization
Shortcut

gnadio.Datafname "loginbutton" Uses default valúes

Event Listeners

Description
E ven t lis te n e rs a llo w y o u to c a p tu re an d re sp o n d to u ser in te ra c tio n s w ith

th e UI c o m p o n e n ts y o u 'v e d e fin e d in a G ra d io B lo c k s app. W hen a u ser


in te ra c ts w ith an e le m e n t, su ch as c h a n g in g a s lid e r v a lu e o r u p lo a d in g an

im age, a fu n c tio n is c a lle d .


Supported Event Listeners
T he L o g i n B u t t o n c o m p o n e n t s u p p o rts th e fo llo w in g e v e n t listen e rs.

Each e v e n t lis te n e r ta k e s th e sa m e p a ra m e te rs, w h ic h are listed in th e

Event Arguments ta b le below .

Listener Description

gradio.Dataframe.change Triggered when the Button is clicked.

(fn, •••)

Event Arguments
Parameter Description

fn the function to call when this event is

C a lla b le |N o n e | triggered. Often a machine learning model's

L ite r a l['d e c o r a to r'] prediction function. Each parameter of the

default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tuple of values, with each

element in the tuple corresponding to one

output component.

inputs List of gradio.components to use as inputs. If

Com ponent |lis t[ C o m p o n e n t] | the function takes no inputs, this should be an

s e t[C o m p o n e n t] |N o n e empty list.

default: None

outputs List of gradio.components to use as outputs. If

C o m p o n e n t |lis t[ C o m p o n e n t] | the function returns no outputs, this should be

None an empty list.

default: None
Parameter Description

api_nam e defines how the endpoint appears in the API

str |None |Literal[False] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

s c r o ll_ t o _ o u t p u t If True, w ill scroll to output com ponent on

bool completion

default: False

sh o w _ p ro g re ss If True, w ill show progress animation while

Literal[(’fu ll’, ’m inim al’, pending

’hidden’)]

default: "fu ll"

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

b atch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). The function is

then required to return a tuple of lists (even if


Parameter Description

there is only 1 output component), with each

list in the tupie corresponding to one output

component.

max_batch_size Máximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this


dict[str, Any] | list[dict[str, listener is triggered. For example, setting

Any]] 1None cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

float 1None while the client connection is open.

default: None Interpreted in seconds.


Parameter Description

trigger_mode If "once" (default for all events except

L iteral[('o n ce', '


m ú lt ip le ' .c h a n g e ( ) ) would not allow any submissions

’a l w a y s j a s t ’)] |N o n e while an event is pending. If set to "múltiple",

default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before

s t r 1N o n e running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

concurrency_limit If set, this is the maximum number of this

in t 1N o n e |L ite ra l['d e fa u lt'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.

s t r 1N o n e Events with the same concurrency_id w ill be

default: None limited by the lowest set concurrency_limit.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting


Parameter Description

api_name to False, setting show_api to False

will still allow downstream apps to use this

event. Iffn is None, show_api will

automatically be set to False.

L in e P lo t L o g o u tB u tto n

^ gradio Status J C
Custom Com ponents G alleryNEW E xp lore

^ gradio

N e w to Gradio? Start here: Getting Started See the Release History

^ LoginButton Markdown

LogoutButton

gradio.LogoutButton(•••)

<*>

Loading...

g r a d io / lo g o u t b u t t o n _ c o m p o n e n t b u ilt w ith G ra d io . H o s te d o n HS S p a c e s

Description
Creates a Button to log out a user from a Space using OAuth.

which handles both the login and logout processes.

Behavior
As input com ponent: (Rarely used) the s t r corresponding to the button label

when the button is clicked

Your function should accept one of these types:

d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

)
. . . d e f p r e d ic t (

v a lu e : s t r | None

As output com ponent: s trin g c o rre s p o n d in g to th e b u tto n la b e l

Your function should return one of these types:

d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( " 0 -> s t r | None

re t u r n v a lu e

InitiaMzation
Parameter Description

value Default text for the button to display. If callable,

str the function w ill be called whenever the app loads

default: "Logout" to set the initial value of the component.

every If v a lu e is a callable, run the function 'every

flo a t |N o n e number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

variant 'primary' for main call-to-action, 'secondary' for a

L ite ra l[('p rim a ry ', 'se co n d a ry ', more subdued style, 'stop' for a stop button.

'stop')]

default: "secondary"

si z e Size of the button. Can be "sm" or "lg".

L iteral[('sm ', 'lg')] |N o n e


Parameter Description

default: None

icon URL or path to the icon file to display within the

str |N o n e button. IfNone, no icon will be displayed.

default:

" https://huggmgface.co/front/a

ssets/huggingface_logo-

noborder.svg"

link URL to open when the button is clicked. IfNone, no

s t r 1N o n e link will be used.

default: "/logout"

visible IfFalse, component will be hidden.

bool

default: True

interactive IfFalse, the Button will be in a disabled state.

bool

default: True

elem_id An optional string that is assigned as the id of this

s t r 1N o n e component in the H T M L DOM. Can be used for

default: None targeting CSS styles.

elem_classes An optional list of strings that are assigned as the

list[str] 1s t r 1N o n e classes of this component in the H T M L DOM. Can

default: None be used for targeting CSS styles.


Parameter Description

render IfFalse, component will not render be rendered in

bool the Blocks context. Should be used ifthe intention

default: True is to assign event listeners n o w but render the

component later.

scale relative size compared to adjacent Components.

in t |N o n e For example ifComponents A and B are in a Row,

default: 0 and A has scale=2, and B has scale=1, A will be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

min_width minimum pixel width, will wrap ifnot sufficient

in t 1N o n e screen space to satisfy this value. Ifa certain scale

default: None value results in this Component being narrower

than min_width, the min_width parameter will be

respected first.

Shortcuts
Interface String
Class Initialization
Shortcut

gradio.Dataframe "logoutbutton" Uses default values

Event Listeners

Description
E ven t lis te n e rs a llo w y o u to c a p tu re an d re sp o n d to u ser in te ra c tio n s w ith

th e UI c o m p o n e n ts y o u 'v e d e fin e d in a G ra d io B lo c k s app. W hen a u ser


in te ra c ts w ith an e le m e n t, su ch as c h a n g in g a s lid e r v a lu e o r u p lo a d in g an

im age, a fu n c tio n is c a lle d .


Supported Event Listeners
T he L o g o u t B u t t o n c o m p o n e n t s u p p o rts th e fo llo w in g e v e n t listen e rs.

Each e v e n t lis te n e r ta k e s th e sa m e p a ra m e te rs, w h ic h are listed in th e

Event Arguments ta b le below .

Listener Description

gradio.Dataframe.change Triggered when the Button is clicked.

(fn, •••)

Event Arguments
Parameter Description

fn the function to call when this event is

C a lla b le |N o n e | triggered. Often a machine learning model's

L ite r a l['d e c o r a to r'] prediction function. Each parameter of the

default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tuple of values, with each

element in the tuple corresponding to one

output component.

inputs List of gradio.components to use as inputs. If

Com ponent |lis t[ C o m p o n e n t] | the function takes no inputs, this should be an

s e t[C o m p o n e n t] |N o n e empty list.

default: None

outputs List of gradio.components to use as outputs. If

C o m p o n e n t |lis t[ C o m p o n e n t] | the function returns no outputs, this should be

None an empty list.

default: None
Parameter Description

api_nam e defines how the endpoint appears in the API

str |None |Literal[False] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

s c r o ll_ t o _ o u t p u t If True, w ill scroll to output com ponent on

bool completion

default: False

sh o w _ p ro g re ss If True, w ill show progress animation while

Literal[(’fu ll’, ’m inim al’, pending

’hidden’)]

default: "fu ll"

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

b atch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). The function is

then required to return a tuple of lists (even if


Parameter Description

there is only 1 output component), with each

list in the tupie corresponding to one output

component.

max_batch_size Máximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this


dict[str, Any] | list[dict[str, listener is triggered. For example, setting

Any]] 1None cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

float 1None while the client connection is open.

default: None Interpreted in seconds.


Parameter Description

trigger_mode If "once" (default for all events except

L iteral[('o n ce', '


m ú lt ip le ' .c h a n g e ( ) ) would not allow any submissions

’a l w a y s j a s t ’)] |N o n e while an event is pending. If set to "múltiple",

default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before

s t r 1N o n e running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

concurrency_limit If set, this is the maximum number of this

in t 1N o n e |L ite ra l['d e fa u lt'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.

s t r 1N o n e Events with the same concurrency_id w ill be

default: None limited by the lowest set concurrency_limit.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting


Parameter Description

api_name to False, setting show_api to False

will still allow downstream apps to use this

event. Iffn is None, show_api will

automatically be set to False.

L o g in B u tto n M a rk d o w n

^ gradio Status J C
Custom Com ponents G alleryNEW E x p lo r e

$ gradio

N e w to Gradio? Start here: Getting Started See the Release History

P ro g re ss load

make waveform

gradio.make_waveform(audio, •••)

Description

G e n e ra te s a w a v e fo rm v id e o fro m an a u d io file. U se fu l fo r c re a tin g an easy to

sh a re a u d io v is u a liz a tio n . T he o u tp u t s h o u ld be p assed in to a g r . V id e o

c o m p o n e n t.

InitiaMzation a¡>

Parameter Description

audio Audio file path or tuple of (sample_rate,

str | tuple[int, np.ndarray] audio_data)

required
Parameter Description

b g _ c o lo r Background color of waveform (ignored if

str bg_image is provided)

default: "#f3f4f6"

bg_image Background image of waveform

str |None

default: None

fg _ a lp h a Opacity of foreground waveform

float

default: 0.75

b a r s _ c o lo r Color of waveform bars. Can be a single color or a

str 1tuple[str, str] tuple of (start_color, end_color) of gradient

default: ('#fbbf24', '#ea580c')

b a r_ co u n t Number of bars in waveform

int

default: 50

b ar_w id th Width of bars in waveform. 1 represents full width,

float 0.5 represents half width, etc.

default: 0.6

aním ate If true, the audio waveform overlay w ill be

bool animated, if false, it w ill be static.

default: False

^ Progress load
Status

$ gradio O
Custom Com ponents G alleryNEW E x p lo r e

^ gradio =

N e w to Gradio? Start here: Getting Started See the Release History

^ LogoutButton Model3D

Markdown

gradio.Markdown(•••)

Loading...

g r a d io / m a r k d o w n _ c o m p o n e n t b u ilt w ith G r a d io . H o s te d o n Efi S p a c e s

Description
Used to render arbitrary Markdown output. Can also render latex enclosed by

dollar signs. As this com ponent does not accept user input, it is rarely used as an

input component.

Behavior
As input com ponent: Passes the s t r of Markdown corresponding to the

displayed value.

Your function should accept one of these types:

d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]


)

. . . d e f p r e d ic t (

v a lu e : s t r | None

As output com ponent: Exp ects a v a lid s t r th a t can be re n d e re d as M a rk d o w n .

Your function should return one of these types:

d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( " 0 -> s t r | None

re t u r n v a lu e

InitiaMzation
Parameter Description

value Value to show in Markdown component. If callable,

str |C a lla b le |N o n e the function w ill be called whenever the app loads

default: None to set the initial value of the component.

lab e l The label for this component. Is used as the header

s t r |N o n e if there are a table of examples for this component.

default: None If None and used in a g r . I n t e r f a c e , the label

w ill be the name of the parameter this com ponent

is assigned to.

every If v a lu e is a callable, run the function 'every'

flo a t I N o n e number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.
Parameter Description

s h o w _ la b e l This parameter has no effect.

bool |N o n e

default: None

rtl If True, sets the direction of the rendered text to

bool right-to-left. Default is False, which renders text

default: False left-to-right.

la t e x _ d e lim it e r s A list of dicts of the form " l e f t " : open

list[dict[str, s t r |b o o l]] |N o n e d e lim it e r ( s t r ) , " r ig h t " : c lo s e

default: None d e lim it e r ( s t r ) , " d i s p l a y " : w h e th e r t o

d is p la y in n e w lin e ( b o o l) that w ill be used

to render LaTeX expressions. If not provided,

l a t e x _ d e l im i t e r s is set to [ " l e f t " : "$ $ ",

" r ig h t " : "$ $ ", " d is p la y " : T ru e ] , so only

expressions enclosed in $$ delim iters w ill be

rendered as LaTeX, and in a new line. Pass in an

empty list to disable LaTeX rendering. For more

information, see the [KaTeX documentation]

(https://katex.org/docs/autorender.html).

v is ib le If False, com ponent w ill be hidden.

bool

default: True

e le m _ id An optional string that is assigned as the id of this

s t r IN o n e com ponent in the HTML DOM. Can be used for

default: None targeting CSS styles.

e le m _ c la s s e s An optional list of strings that are assigned as the

list[str] Is t r I N o n e classes of this com ponent in the HTML DOM. Can


Parameter Description

default: None be used for targeting CSS styles.

render IfFalse, component will not render be rendered in

bool the Blocks context. Should be used ifthe intention

default: True is to assign event listeners n o w but render the

component later.

sanitize_html IfFalse, will disable H T M L sanitization when

bool converted from markdown. This is not

default: True recommended, as itcan lead to security

vulnerabilities.

line_breaks IfTrue, will enable Github-flavored Markdown line

bool breaks in chatbot messages. IfFalse (default),

default: False single new lines will be ignored.

header_links IfTrue, will automatically create anchors for

bool headings, displaying a link icon on hover.

default: False

Shortcuts
Interface String
Class Initialization
Shortcut

gradio.Dataframe "markdown" Uses default values

Demos

blocks_hello b lo c k s _ k in e m a tic s


import gradio as gr

I
def welcome(name):

return f'Welcome to Gradio, {name}!"

with gr.Blocks() as demo:

gr.Markdown(

# Helio World!

Start typing below to see the output.

.. )

<*>

Loading...

g r a d i o / b l o c k s _ h e l l o b u ilt w ith G r a d io . H o s te d o n BB S p a c e s

Event Listeners

Description
E ven t lis te n e rs a llo w y o u to c a p tu re an d re sp o n d to u ser in te ra c tio n s w ith

th e UI c o m p o n e n ts y o u 'v e d e fin e d in a G ra d io B lo c k s app. W hen a u ser


in te ra c ts w ith an e le m e n t, su ch as c h a n g in g a s lid e r v a lu e o r u p lo a d in g an

im age, a fu n c tio n is c a lle d .

Supported Event Listeners


T he M a r k d o w n c o m p o n e n t s u p p o rts th e fo llo w in g e v e n t listen e rs. Each

e v e n t lis te n e r ta k e s th e s a m e p a ra m e te rs, w h ic h are listed in th e Event

Arguments ta b le b elow .
Listener Description

gradio.Dataframe.change Triggered when the value of the Markdown

(fn, •••) changes either because of user input (e.g. a


user types in a textbox) OR because of a
function update (e.g. an image receives a value
from the output of an event trigger). See
. in p u t ( ) for a listener that is only triggered
by user input.

Event Arguments
Parameter Description

fn the function to call when this event is

C a lla b le |N o n e | triggered. Often a machine learning model's

L ite r a l['d e c o r a to r'] prediction function. Each parameter of the

default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tuple of values, with each

element in the tuple corresponding to one

output component.

inputs List of gradio.components to use as inputs. If

Com ponent |lis t[ C o m p o n e n t] | the function takes no inputs, this should be an

s e t[C o m p o n e n t] |N o n e empty list.

default: None

outputs List of gradio.components to use as outputs. If

C o m p o n e n t |lis t[ C o m p o n e n t] | the function returns no outputs, this should be

None an empty list.

default: None

api_name defines how the endpoint appears in the API

s t r |N o n e |L ite ra l[F a ls e ] docs. Can be a string, None, or False. If set to a


Parameter Description

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

s c r o ll_ t o _ o u t p u t If True, w ill scroll to output com ponent on

bool completion

default: False

sh o w _ p ro g re ss If True, w ill show progress animation while

Literal[('fuW, ’m inim al’, pending

’hidden’)]

default: "fu ll"

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

b atch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). The function is

then required to return a tuple of lists (even if

there is only 1 output component), with each


Parameter Description

list in the tupie corresponding to one output

component.

max_batch_size Máximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this


dict[str, Any] | list[dict[str, listener is triggered. For example, setting

Any]] 1None cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

float 1None while the client connection is open.

default: None Interpreted in seconds.


Parameter Description

trigger_mode If "once" (default for all events except

L iteral[('o n ce', '


m ú lt ip le ' .c h a n g e ( ) ) would not allow any submissions

’a l w a y s j a s t ’)] |N o n e while an event is pending. If set to "múltiple",

default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before

s t r 1N o n e running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

concurrency_limit If set, this is the maximum number of this

in t 1N o n e |L ite ra l['d e fa u lt'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.

s t r 1N o n e Events with the same concurrency_id w ill be

default: None limited by the lowest set concurrency_limit.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting


Parameter Description

api_name to False, setting show_api to False

will still allow downstream apps to use this

event. Iffn is None, show_api will

automatically be set to False.

Guides

Key Features

LogoutButton Model3D ^

^ gradio Status J C
Custom Com ponents G alleryNEW E x p lo r e

^ gradio =

N e w to Gradio? Start here: Getting Started See the Release History

^ Markdown MultimodalTextbox

Model3D

gradio.Model3D(•••)

Loading...

g r a d io / m o d e l3 d _ c o m p o n e n t b u ilt w ith G r a d io . H o s te d o n B S p a c e s

Description &
Creates a com ponent allows users to upload or view 3D Model files (.obj, .glb, .stl,

.gltf, .splat, or .ply).

Behavior
As input com ponent: Passes the uploaded file as a s t r filepath to the function.

Your function should accept one of these types:

d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (
v a lu e : s t r | None

As output com ponent: Exp ects fu n c tio n to return a s t r o r p a t h lib . P a t h file p a th

o f ty p e (.obj, .glb, .stl, o r .gltf)

Your function should return one of these types:

d e f p r e d ic t ( " 0 -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( " 0 -> s t r | Pa th | None

re t u r n v a lu e

Imtiaíization
Param eter Description

v a lu e path to (.obj, .glb, .stl, .gltf, .splat, or .ply) file to

s t r |C a lla b le |N o n e show in model3D viewer. If callable, the function

default: None w ill be called whenever the app loads to set the

initial value of the component.

c le a r _ c o lo r background color of scene, should be a tuple of 4

tu p le [flo a t, flo a t, flo a t, flo a t] | floats between 0 and 1 representing RGBA values.

None

default: None

c a m e r a _ p o s it io n initial camera position of scene, provided as a

tu p le [in t I flo a t |N o n e , in t |flo a t | tuple of ( a lp h a , b e ta , r a d iu s ) . Each value is

N o n e , in t |flo a t |N o n e ] optional. If provided, a lp h a and b e ta should be in

default: (None, None, None) degrees reflecting the angular position along the

longitudinal and latitudinal axes, respectively.


Parameter Description

Radius corresponds to the distance from the center

of the object to the camera.

zo o m _ sp e e d the speed of zooming in and out of the scene when

float the cursor wheel is rotated or when screen is

default: 1 pinched on a mobile device. Should be a positive

float, increase this value to make zoom ing faster,

decrease to make it slower. Affects the

wheelPrecision property of the camera.

p an_speed the speed of panning the scene when the cursor is

float dragged or when the screen is dragged on a mobile

default: 1 device. Should be a positive float, increase this

value to make panning faster, decrease to make it

slower. Affects the panSensibility property of the

camera.

h e ig h t The height of the model3D component, specified

int |str | None in pixels if a number is passed, or in CSS units if a

default: None string is passed.

la b e l The label for this component. Appears above the

str |None com ponent and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r . I n t e r f a c e , the label w ill be the

name of the parameter this com ponent is assigned

to.

s h o w _ la b e l if True, w ill display label.

bool 1None

default: None
Parameter Description

e v e ry If v a lu e is a callable, run the function 'every'

float |None number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

c o n t a in e r If True, w ill place the com ponent in a container -

bool providing some extra padding around the border.

default: True

s c a le relative size compared to adjacent Components.

int 1None For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A w ill be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

m in _ w id t h minimum pixel width, w ill wrap if not sufficient

int screen space to satisfy this value. If a certain scale

default: 160 value results in this Com ponent being narrower

than min_width, the min_width parameter w ill be

respected first.

in t e r a c t iv e if True, w ill allow users to upload a file; if False, can

bool | None only be used to display files. If not provided, this is

default: None inferred based on whether the com ponent is used

as an input or output.

v is ib le If False, com ponent w ill be hidden.

bool
Parameter Description

default: True

elem_id An optional string that is assigned as the id of this

str |N o n e component in the H T M L DOM. Can be used for

default: None targeting CSS styles.

elem_classes An optional list of strings that are assigned as the

list[str] 1s t r 1N o n e classes of this component in the H T M L DOM. Can

default: None be used for targeting CSS styles.

render IfFalse, component will not render be rendered in

bool the Blocks context. Should be used ifthe intention

default: True is to assign event listeners n o w but render the

component later.

Shortcuts
Interface String
Class Initialization
Shortcut

gradio.Dataframe "model3d" Uses default values

Event Listeners

Description
E ven t lis te n e rs a llo w y o u to c a p tu re an d re sp o n d to u ser in te ra c tio n s w ith

th e UI c o m p o n e n ts y o u 'v e d e fin e d in a G ra d io B lo c k s app. W hen a u ser


in te ra c ts w ith an e le m e n t, su ch as c h a n g in g a s lid e r v a lu e o r u p lo a d in g an

im age, a fu n c tio n is c a lle d .

Supported Event Listeners


T he M o d e l3 D c o m p o n e n t s u p p o rts th e fo llo w in g e v e n t liste n e rs. Each

e v e n t lis te n e r ta k e s th e s a m e p a ra m e te rs, w h ic h are listed in th e Event


Arguments ta b le b elow .

Listener Description

gradio.Dataframe.change Triggered when the value of the Model3D

(fn, •••) changes either because of user input (e.g. a


user types in a textbox) OR because of a
function update (e.g. an image receives a value
from the output of an event trigger). See
. in p u t ( ) for a listener that is only triggered
by user input.

gradio.Model3D.upload(f This listener is triggered when the user


n, •••) uploads a file into the Model3D.

gradio.Model3D.edit(fn, This listener is triggered when the user edits


•••) the Model3D (e.g. image) using the built-in
editor.

gradio.Model3D.clear(fn This listener is triggered when the user clears


, •••) the Model3D using the X button for the
component.

Event Arguments
Parameter Description

fn the function to call when this event is

Callable |None | triggered. Often a machine learning model's

Litem l[’decom tor’] prediction function. Each parameter of the

default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tuple of values, with each

element in the tuple corresponding to one

output component.

inputs List of gradio.components to use as inputs. If

the function takes no inputs, this should be an


Parameter Description

C o m p o n e n t |lis t[ C o m p o n e n t] | empty list.

s e t[C o m p o n e n t] |N o n e

default: None

o u tp u ts List of gradio.components to use as outputs. If

Com ponent |lis t[ C o m p o n e n t] | the function returns no outputs, this should be


None an empty list.

default: None

api_nam e defines how the endpoint appears in the API

s t r |N o n e |L ite ra l[F a ls e ] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

s c r o ll_ t o _ o u t p u t If True, w ill scroll to output com ponent on

bool completion

default: False

sh o w _ p ro g re ss If True, w ill show progress animation while

L ite ra l[(’f u ll’, ’m in im a l’, pending

’h id d e n ’)]

default: "fu ll"

queue If True, w ill place the request on the queue, if

b o o l |N o n e the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue
Parameter Description

has been enabled. If None, w ill use the queue

setting of the gradio app.

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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 Maximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this


dict[str, Any] | list[dict[str, listener is triggered. For example, setting

Any]] 1None cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.


Parameter Description

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

flo a t |N o n e while the client connection is open.

default: None Interpreted in seconds.

trigger_mode If "once" (default for all events except

L iteral[('o n ce', '


m ú lt ip le ' .c h a n g e ( ) ) would not allow any submissions

’a l w a y s j a s t ’)] |N o n e while an event is pending. If set to "multiple",


default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before


s t r 1N o n e running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

concurrency_limit If set, this is the maximum number of this

in t 1N o n e |L ite ra l['d e fa u lt'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the


Parameter Description

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.


str |N o n e Events with the same concurrency_id w ill be

default: None limited by the lowest set co ncurrencyjim it.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"


default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

autom atically be set to False.

Guides

How To Use 3D Model Component

M a rk d o w n M u ltim o d a lT e x tb o x

^ gradio Status J C
Custom Com ponents G alleryNEW E x p lo r e

$ gradio

N e w to Gradio? Start here: Getting Started See the Release History

Request Flagging ^

mount_gradio_app

gradio.mount_gradio_app(app, blocks, path, •••)

Description

Mount a gradio.Blocks to an existing FastAPI application.

Exampíe 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:80

00/gradio.

InitiaMzation

Parameter Description

app The parent FastAPI application.

fastapi.FastAPI

required

b lo c k s The blocks object we want to mount to the parent

gradio.Blocks app.

required

p a th The path at which the gradio application w ill be

str mounted.

required

a p p _ k w a rg s Additional keyword arguments to pass to the

dict[str, Any] | None underlying FastAPI app as a dictionary of

default: None parameter keys and argument values. For example,

" d o c s _ u r l" : "/d o cs"

a u th If provided, username and password (or list of

Callable | tuple[str, str] | username-password tuples) required to access the

list[tuple[str, str]] | None gradio app. Can also provide function that takes

default: None username and password and returns True if va lid

login.
Parameter Description

a u th _ m e s s a g e If provided, HTML message provided on login page

str |None for this gradio app.

default: None

a u th _ d e p e n d e n c y A function that takes a FastAPI request and returns

Callable[[fastapi.Request], str | a string user ID or None. If the function returns

None] | None None for a specific request, that user is not

default: None authorized to access the gradio app (they w ill see a

401 Unauthorized response). To be used with

external authentication systems like OAuth.

Cannot be used with a u th .

ro o t_ p a th The subpath corresponding to the public

str |None deploym ent of this FastAPI application. For

default: None example, if the application is served at

"https://example.com/myapp", the r o o t_ p a th

should be set to "/myapp". A full URL beginning

with http:// or https:// can be provided, which will

be used in its entirety. Normally, this does not

need to provided (even if you are using a custom

p a th ). However, if you are serving the FastAPI app

behind a proxy, the proxy may not provide the full

path to the Gradio app in the request headers. In

which case, you can provide the root path here.

a llo w e d _ p a t h s List of complete filepaths or parent directories that

list[str] |None this gradio app is allowed to serve. Must be

default: None absolute paths. Warning: if you provide directories,

any files in these directories or their subdirectories

are accessible to all users of your app.


Parameter Description

b lo c k e d _ p a th s List of complete filepaths or parent directories that

list[str] |N o n e this gradio app is not allowed to serve (i.e. users of

default: None your app are not allowed to access). Must be

absolute paths. Warning: takes precedence over

allowed_paths and all other directories exposed

by Gradio by default.

fa v ic o n _ p a th Ifa path to a file (.png, .gif, or .ico) is provided, it

s t r 1N o n e will be used as the favicon for this gradio app's

default: None page.

sh o w _ erro r IfTrue, any errors in the gradio app will be

bool displayed in an alert modal and printed in the

default: True browser console log. Otherwise, errors will only be

visible in the terminal session running the Gradio

app.

m a x _ f ile _ s iz e The m a x i m u m file size in bytes that can be

s t r 1in t 1N o n e uploaded. Can be a string of the form "<value>

default: None <unit>", where value is any positive integer and

unit is one of "b", "kb", "mb", "gb", "tb". IfNone, no

limit is set.

^ Request Flagging ^

Status

$$ gradio X o
Custom Com ponents G alleryNEW E x p lo r e

^ gradio

N e w to Gradio? Start here: Getting Started See the Release History

^ Model3D Number

MultimodalTextbox

gradio.MultimodalTextbox(•••)

Loading...

g r a d io / m u lt im o d a lt e x t b o x _ c o m p o n e n t b u ilt w ith G r a d io . H o s te d o n Efi S p a c e s

Description &
Creates a textarea for users to enter string input or display string output and also

allows for the uploading of multimedia files.

Behavior
As input com ponent: Passes text value and list of file(s) as a d ic t into the

function.

Your function should accept one of these types:

d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

)
. . . d e f p r e d ic t (

v a l u e : M u ltim o d a lV a lu e | None

As output com ponent: Exp ects a d i c t w ith "text" and "files", b oth o p tio n a l. The

file s array is a lis t o f file p a th s o r URLs.

Your function should return one of these types:

d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( ^ " ) -> M u ltim o d a lV a lu e | None

re t u r n v a lu e

InitiaMzation
Parameter Description

v a lu e Default value to show in MultimodalTextbox. A

dict[str, str | list] | Callable | None dictionary of the form " t e x t " : "sa m p le

default: None te x t", " f ile s " : [ { p a th :

" f ile s / f ile . j p g " , o rig _ n a m e :

" f ile . j p g " , u r l:

" h t t p : / / im a g e _ u r l. j p g " , s iz e : 100]}. If

callable, the function w ill be called whenever the

app loads to set the initial value of the component.

f ile _ t y p e s List of file extensions or types of files to be

list[str] |None uploaded (e.g. ['image', '.json', '.mp4']). "file"

default: None 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


Parameter Description

video files to be uploaded, "text" allows only text

files to be uploaded.

lin e s mínimum number of line rows to provide in

in t textarea.

default: 1

max_lines máximum number of line rows to provide in

in t textarea.

default: 20

placeholder placeholder hint to provide behind textarea.

str |N o n e

default: None

lab e l The label for this component. Appears above the

s t r |N o n e com ponent and is also used as the header if there

default: None is a table of examples for this component. If None

and used in a g r . I n t e r f a c e , the label w ill be the

name of the parameter this com ponent is assigned

to.

info additional com ponent description.

s t r |N o n e

default: None

every If v a lu e is a callable, run the function 'every'

flo a t I N o n e number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.
Parameter Description

show_label ifTrue, will display label.

bool |N o n e

default: None

container IfTrue, will place the component in a container -

bool providing some extra padding around the border.

default: True

scale relative size compared to adjacent Components.

in t 1N o n e For example ifComponents A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A will be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

min_width minimum pixel width, will wrap ifnot sufficient

in t screen space to satisfy this value. Ifa certain scale

default: 160 value results in this Component being narrower

than min_width, the min_width parameter will be

respected first.

interactive ifTrue, will be rendered as an editable textbox; if

b o o l |N o n e False, editing will be disabled. Ifnot provided, this

default: None is inferred based on whether the component is

used as an input or output.

visible IfFalse, component will be hidden.

bool

default: True
Parameter Description

e le m _ id An optional string that is assigned as the id of this

str |None com ponent in the HTML DOM. Can be used for

default: None targeting CSS styles.

a u to fo c u s If True, w ill focus on the textbox when the page

bool loads. Use this carefully, as it can cause usability

default: False issues for sighted and non-sighted users.

a u t o s c r o ll If True, w ill autom atically scroll to the bottom of

bool the textbox when the value changes, unless the

default: True user scrolls up. If False, w ill not scroll to the

bottom of the textbox when the value changes.

e le m _ c la s s e s An optional list of strings that are assigned as the

list[str] 1str 1None classes of this com ponent in the HTML DOM. Can

default: None be used for targeting CSS styles.

re n d e r If False, com ponent w ill not render be rendered in

bool the Blocks context. Should be used if the intention

default: True is to assign event listeners now but render the

com ponent later.

t e x t _ a lig n How to align the text in the textbox, can be: "left",

Literal[('left', 'right')] | None "right", or None (default). If None, the alignment is

default: None left if r t l is False, or right if r t l is True. Can only

be changed if t y p e is "text".

rtl If True and t y p e is "text", sets the direction of the

bool text to right-to-left (cursor appears on the left of

default: False
Parameter Description

the text). Default is False, which renders cursor on

the right.

s u b m it _ b t n If False, w ill not show a subm it button. If a string,

str |L ite ra l[F a ls e ] |N o n e w ill use that string as the subm it button text. Only

default: None applies if i n t e r a c t i v e is True.

Shortcuts
Interface String
Class Initialization
Shortcut

gradio.Dataframe "multimodaltextbox" Uses default values

Demos

chatbot_m ultim odal


import gradio as gr

import os

import time

# Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, i
I
mage, audio, & video). Plus shows support for streaming text.

def print_like_dislike(x : gr.LikeData):

print(x .index, x .value, x .liked)


Loading...

g r a d i o / c h a t b o t _ m u l t i m o d a l b u ilt w ith G ra d io . H o s te d o n Efi S p a c e s

Event Listeners

Description
E ven t lis te n e rs a llo w y o u to c a p tu re an d re sp o n d to u ser in te ra c tio n s w ith

th e UI c o m p o n e n ts y o u 'v e d e fin e d in a G ra d io B lo c k s app. W hen a u ser


in te ra c ts w ith an e le m e n t, su ch as c h a n g in g a s lid e r v a lu e o r u p lo a d in g an

im age, a fu n c tio n is c a lle d .

Supported Event Listeners


T he M u l t i m o d a l T e x t b o x c o m p o n e n t s u p p o rts th e fo llo w in g e v e n t

listen e rs. Each e v e n t lis te n e r ta k e s th e s a m e p a ra m e te rs, w h ic h are listed

in th e Event Arguments ta b le below .

Listener Description

gradio.Dataframe.change Triggered when the value of the


MultimodalTextbox changes either because of
(fn, •••)
user input (e.g. a user types in a textbox) OR
because of a function update (e.g. an image
receives a value from the output of an event
trigger). See . in p u t ( ) for a listener that is
only triggered by user input.

g r a d io .M u lt im o d a lT e x t b o This listener is triggered when the user


x . in p u t ( f n , •••) changes the value of the MultimodalTextbox.

g r a d io .M u lt im o d a lT e x t b o Event listener for when the user selects or


x . s e le c t ( f n , •••) deselects the MultimodalTextbox. Uses event
data gradio.SelectData to carry v a lu e
referring to the label of the
Listener Description

MultimodalTextbox, and s e le c t e d to refer to


state of the MultimodalTextbox. See EventData
documentation on how to use this event data

g r a d io .M u lt im o d a lT e x t b o This listener is triggered when the user presses


x . s u b m it ( f n , •••) the Enter key while the MultimodalTextbox is
focused.

g r a d io .M u lt im o d a lT e x t b o This listener is triggered when the


x .fo c u s (fn , •••) MultimodalTextbox is focused.

g r a d io .M u lt im o d a lT e x t b o This listener is triggered when the


x . b lu r ( f n , •••) MultimodalTextbox is unfocused/blurred.

Event Arguments
Parameter Description

fn the function to call when this event is

C a lla b le |N o n e | triggered. Often a machine learning model's

L ite r a l['d e c o r a to r'] prediction function. Each parameter of the

default: "decorator" 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.

in p u t s List of gradio.components to use as inputs. If

Com ponent |lis t[ C o m p o n e n t] | the function takes no inputs, this should be an

s e t[C o m p o n e n t] |N o n e empty list.

default: None

o u tp u ts List of gradio.components to use as outputs. If

the function returns no outputs, this should be


Parameter Description

Com ponent | lis t[ C o m p o n e n t] | an empty list.

None

default: None

api_name defines how the endpoint appears in the API

s t r IN o n e |L ite ra l[F a ls e ] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

scroll_to_output If True, w ill scroll to output com ponent on

bool completion

default: False

show_progress If True, w ill show progress animation while

L ite ra l[(’f u ll’, ’m in im a l’, pending

’h id d e n ’)]

default: "fu ll"

queue If True, w ill place the request on the queue, if

b o o l |N o n e the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept


Parameter Description

default: False a list of input valúes for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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 Maximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this


dict[str, Any] | list[dict[str, listener is triggered. For example, setting

Any]] 1None cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.
Parameter Description

every Run this event 'every' number of seconds

flo a t |N o n e while the client connection is open.

default: None Interpreted in seconds.

trigger_mode If "once" (default for all events except

L iteral[('o n ce', '


m ú lt ip le ' .c h a n g e ( ) ) would not allow any submissions

’a l w a y s j a s t ’)] |N o n e while an event is pending. If set to "multiple",

default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before

s t r 1N o n e running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

concurrency_limit If set, this is the maximum number of this

in t 1N o n e |L ite ra l['d e fa u lt'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.

s t r 1N o n e Events with the same concurrency_id w ill be

default: None limited by the lowest set concurrency_limit.


Parameter Description

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

will still allow downstream apps to use this

event. Iffn is None, show_api will

automatically be set to False.

^ Model3D Number

^ gradio Status J C
Custom Com ponents G alleryNEW E xp lore

$ gradio

N e w to Gradio? Start here: Getting Started See the Release History

^ Themes

NO RELOAD

if gr.NO_RELOAD:

Description &

Any code in a 'if gr.NO_RELOAD' code-block will not be re-evaluated when the

source file is reloaded. This is helpful for importing modules that do not like to be

reloaded (tiktoken, numpy) as well as database connections and long running set

up code.

Exampíe Usage

import gradio as gr

if gr.NO_RELOAD:

from transformers import pipeline

pipe = pipeline("text-classification", model="cardiffnlp/twitter-roberta-base-

sentiment-latest")
gr.Interface.from_pipeline(pipe).launch()

th e m e s

Status

$ gradio o
Custom Com ponents G alleryNEW E xp lore

$ gradio

N e w to Gradio? Start here: Getting Started See the Release History

^ MultimodalTextbox ParamViewer

Number

gradio.Number(•••)

<*>

Loading...

g r a d io / n u m b e r_ c o m p o n e n t b u ilt w ith G ra d io . H o s te d o n Spaces

Description

Creates a numeric field for user to enter numbers as input or display numeric

output.
Behavior

As input com ponent: P asses fie ld v a lu e as a f l o a t o r i n t in to th e fu n c tio n ,

d e p e n d in g on p r e c i s i ó n .

Your function should accept one of these types:

d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (

v a lu e : f lo a t | in t | None

As output com ponent: Exp ects an i n t o r f l o a t re tu rn e d fro m th e fu n c tio n and

sets fie ld v a lu e to it.

Your function should return one of these types:

d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( ^ " ) -> f l o a t | in t | None

re t u r n v a lu e

InitiaMzation

Param eter Description

value default value. Ifcallable, the function will be called

flo a t |C a lla b le |N o n e whenever the app loads to set the initial value of

default: None the component.


Parameter Description

lab e l The label for this component. Appears above the

str |None com ponent and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r . I n t e r f a c e , the label w ill be the

name of the parameter this com ponent is assigned

to.

info additional com ponent description.

str 1None

default: None

every If v a lu e is a callable, run the function 'every'

float 1None number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

show_label if True, w ill display label.

bool 1None

default: None

container If True, w ill place the com ponent in a container -

bool providing some extra padding around the border.

default: True

scale relative size compared to adjacent Components.

int 1None For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A w ill be

twice as wide as B. Should be an integer. scale


Parameter Description

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

min_width mínimum pixel width, will wrap ifnot sufficient

in t screen space to satisfy this value. Ifa certain scale

default: 160 value results in this Component being narrower

than min_width, the min_width parameter will be

respected first.

interactive ifTrue, will be editable; ifFalse, editing will be

bool |N o n e disabled. Ifnot provided, this is inferred based on

default: None whether the component is used as an input or

output.

visible IfFalse, component will be hidden.

bool

default: True

elem_id An optional string that is assigned as the id of this

s t r IN o n e component in the H T M L DOM. Can be used for

default: None targeting CSS styles.

elem_classes An optional list of strings that are assigned as the

list[str] Is t r I N o n e classes of this component in the H T M L DOM. Can

default: None be used for targeting CSS styles.

render IfFalse, component will not render be rendered in

bool the Blocks context. Should be used ifthe intention

default: True is to assign event listeners n o w but render the

component later.
Parameter Description

p r e c is ió n Precisión to round input/output to. If set to 0, will

int | None round to nearest integer and convert type to int. If

default: None None, no rounding happens.

m ínim um Mínimum value. Only applied when com ponent is

float 1None used as an input. If a user provides a sm aller value,

default: None a gr.Error exception is raised by the backend.

máximum Maximum value. Only applied when com ponent is

float 1None used as an input. If a user provides a larger value, a

default: None gr.Error exception is raised by the backend.

s te p The interval between allowed numbers in the

float component. Can be used along with optional

default: 1 parameters mínimum and maximum to create a

range of legal values starting from mínimum and

incrementing according to this parameter.

Shortcuts

Interface String
Class Initialization
Shortcut

g r a d io . Dataframe "number" Uses default values

Demos
tax_calculator b lo c k s _ s im p le _ s q u a re s


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"])
i
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

Loading...

g r a d i o / t a x _ c a l c u l a t o r b u ilt w ith G ra d io . H o s te d o n Spaces

Event Listeners

Description
E ven t lis te n e rs a llo w y o u to c a p tu re an d re sp o n d to u ser in te ra c tio n s w ith

th e UI c o m p o n e n ts y o u 'v e d e fin e d in a G ra d io B lo c k s app. W hen a u ser


in te ra c ts w ith an e le m e n t, su ch as c h a n g in g a s lid e r v a lu e o r u p lo a d in g an

im age, a fu n c tio n is c a lle d .

Supported Event Listeners


T he N u m b e r c o m p o n e n t s u p p o rts th e fo llo w in g e v e n t listen e rs. Each

e v e n t lis te n e r ta k e s th e s a m e p a ra m e te rs, w h ic h are listed in th e Event

Arguments ta b le b elow .

Listener Description

gradio.Dataframe.change Triggered when the value of the Number

(fn, •••) changes either because of user input (e.g. a


user types in a textbox) OR because of a
function update (e.g. an image receives a value
from the output of an event trigger). See
. in p u t ( ) for a listener that is only triggered
by user input.

g r a d io .N u m b e r .in p u t ( f n , This listener is triggered when the user


•••) changes the value of the Number.

g ra d io .N u m b e r. s u b m it( fn This listener is triggered when the user presses


, •••) the Enter key while the Number is focused.

g r a d io .N u m b e r .fo c u s ( fn , This listener is triggered when the Number is


•••) focused.

Event Arguments
Parameter Description

fn the function to call when this event is

Callable |None | triggered. Often a machine learning model's

Litem l[’decom tor’] prediction function. Each parameter of the

default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tuple of values, with each


Parameter Description

element in the tupie corresponding to one

output component.

inputs List of gradio.components to use as inputs. If

C o m p o n e n t |lis t[ C o m p o n e n t] | the function takes no inputs, this should be an

s e t[C o m p o n e n t] |N o n e empty list.

default: None

outputs List of gradio.components to use as outputs. If

Com ponent |lis t[ C o m p o n e n t] | the function returns no outputs, this should be

None an empty list.

default: None

api_name defines how the endpoint appears in the API

s t r |N o n e |L ite ra l[F a ls e ] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

scroll_to_output If True, w ill scroll to output com ponent on

bool completion

default: False

show_progress If True, w ill show progress animation while

L ite ra l[(’f u ll’, ’m in im a l’, pending

’h id d e n ’)]

default: "fu ll
Parameter Description

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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 Maximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this

listener is triggered. For example, setting


Parameter Description

dict[str, A n y ] |list[dict[str, cancels=[click_event] w ill cancel the

A ny]] 1N o n e click_event, where click_event is the return

default: None value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

flo a t 1N o n e while the client connection is open.

default: None Interpreted in seconds.

trigger_mode If "once" (default for all events except

L ite ra l[(’o n c e ’, 'm ú lt ip le , .c h a n g e ( ) ) would not allow any submissions

’a l w a y s j a s t ’)] |N o n e while an event is pending. If set to "multiple",


default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before

s t r |N o n e running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

concurrency_limit If set, this is the maximum number of this

in t 1N o n e |L ite ra l['d e fa u lt'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the


Parameter Description

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

c o n c u rre n c y _ id If set, this is the id of the concurrency group.


str |None Events with the same concurrency_id w ill be

default: None limited by the lowest set co ncurrencyjim it.

show _api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"


default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

autom atically be set to False.

M u ltim o d a lT e x tb o x P a ra m V ie w e r

Status

$ gradio O
Custom Com ponents G alleryNEW E xp lore

$ gradio

N e w to Gradio? Start here: Getting Started See the Release History

Number Plot ^

ParamViewer

gradio.ParamViewer(•••)

Loading...

g r a d io / p a r a m v ie w e r _ c o m p o n e n t b u ilt w ith G ra d io . H o s te d o n Spaces

Description

Displays an interactive table of parameters and their descriptions and default


values with syntax highlighting. For each parameter, the user should provide a

type (e.g. a s t r ), a human-readable description, and a default value. As this


c o m p o n e n t d o e s n o t a c c e p t u se r in p u t, it is ra re ly used as an in p u t

c o m p o n e n t.In te rn a lly , th is c o m p o n e n t is used to d is p la y th e p a ra m e te rs o f

c o m p o n e n ts in th e C u sto m C o m p o n e n t G a lle ry
(h ttp s ://w w w .g ra d io .a p p /c u s to m -c o m p o n e n ts /g a lle ry ).

Behavior

As input com ponent: (R arely used) p a sse s v a lu e as a d i c t [ s t r , d i c t ] . T he key

in th e o u te r d ic tio n a ry is th e p a ra m e te r n am e, w h ile th e in n e r d ic tio n a ry has keys

"type", "d e sc rip tio n ", an d (o p tio n a lly ) "d e fa u lt" fo r each p aram eter.

Your function should accept one of these types:

d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (

v a l u e : d i c t [ s t r , P a ra m e te r]

As output com ponent: Exp ects v a lu e as a d i c t [ s t r , d i c t ] . T he key in th e o u te r

d ic tio n a ry is th e p a ra m e te r n am e , w h ile th e in n e r d ic tio n a ry has keys "type",


"d e sc rip tio n ", and (o p tio n a lly ) "d e fa u lt" fo r each p aram eter.

Your function should return one of these types:

d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( ^ " ) -> d i c t [ s t r , P a ra m e te r]

re t u r n v a lu e

InitiaMzation
Parameter Description

value A list of dictionaries with keys "type", "description",

dict[str, P a ra m e te r ] |N o n e and "default" for each parameter.

default: None

language The language to display the code in. One of

L ite r a l[( 'p y th o n , ’t y p e s c r ip t ’)] "python" or "typescript".

default: "python"

linkify A list of strings to linkify. If any of these strings is

list[str] 1N o n e found in the description, it w ill be rendered as a

default: None link.

every If v a lu e is a callable, run the function 'every'

flo a t 1N o n e number of seconds while the client connection is

default: None 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.

render If False, com ponent w ill not render be rendered in

bool the Blocks context. Should be used if the intention

default: True is to assign event listeners now but render the

com ponent later.

Shortcuts

Interface String
Class Initialization
Shortcut

g r a d io . Dataframe "paramviewer" Uses default values


Event Listeners

Description
E ven t lis te n e rs a llo w y o u to c a p tu re an d re sp o n d to u ser in te ra c tio n s w ith

th e UI c o m p o n e n ts y o u 'v e d e fin e d in a G ra d io B lo c k s app. W hen a u ser


in te ra c ts w ith an e le m e n t, su ch as c h a n g in g a s lid e r v a lu e o r u p lo a d in g an

im age, a fu n c tio n is c a lle d .

Supported Event Listeners


T he P a r a m V ie w e r c o m p o n e n t s u p p o rts th e fo llo w in g e v e n t listen e rs.

Each e v e n t lis te n e r ta k e s th e sa m e p a ra m e te rs, w h ic h are listed in th e

Event Arguments ta b le below .

Listener Description

gradio.Dataframe.change Triggered when the value of the ParamViewer

(fn, •••) changes either because of user input (e.g. a


user types in a textbox) OR because of a
function update (e.g. an image receives a value
from the output of an event trigger). See
. in p u t ( ) for a listener that is only triggered
by user input.

gradio.ParamViewer.uplo This listener is triggered when the user


ad(fn, •••) uploads a file into the ParamViewer.

Event Arguments
Parameter Description

fn the function to call when this event is

Callable |None | triggered. Often a machine learning model's

Litem l[’decom tor’] prediction function. Each parameter of the


Parameter Description

default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tupie of valúes, with each

element in the tupie corresponding to one

output component.

in p u t s List of gradio.components to use as inputs. If

C o m p o n e n t |lis t[ C o m p o n e n t] | the function takes no inputs, this should be an

s e t[C o m p o n e n t] |N o n e empty list.

default: None

o u tp u ts List of gradio.components to use as outputs. If

Com ponent |lis t[ C o m p o n e n t] | the function returns no outputs, this should be

None an empty list.

default: None

api_nam e defines how the endpoint appears in the API

s t r |N o n e |L ite ra l[F a ls e ] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

s c r o ll_ t o _ o u t p u t If True, w ill scroll to output com ponent on

bool completion

default: False
Parameter Description

show_progress If True, w ill show progress animation while

Literal[('fuW, ’m inim al’, pending

’hidden’)]

default: "fu ll"

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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 Maximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).


Parameter Description

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this

dict[str, A n y ] |list[dict[str, listener is triggered. For example, setting

A ny]] 1N o n e cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

flo a t 1N o n e while the client connection is open.

default: None Interpreted in seconds.

trigger_mode If "once" (default for all events except

L ite ra l[(’o n c e ’, 'm ú lt ip le , .c h a n g e ( ) ) would not allow any submissions

’a l w a y s j a s t ’)] |N o n e while an event is pending. If set to "multiple",

default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before

s t r 1N o n e running 'fn'. Input arguments for js method are

default: None
Parameter Description

valúes of 'inputs' and 'outputs', return should

be a list of valúes for output components.

concurrency_limit If set, this is the maximum number of this

int | None | Literal['default'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.


str 1None Events with the same concurrency_id w ill be

default: None limited by the lowest set co ncurrencyjim it.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"


default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

autom atically be set to False.

Num ber P lo t
Status

$ gradio O
Custom Com ponents G alleryNEW Exp lore

$ gradio

New to Gradio? Start here: Getting Started See the Release History

^ ParamViewer Radio

Plot

gradio.Plot(•••)

12 Plot

g r a d i o / p l o t _ c o m p o n e n t b u ilt w i t h G r a d i o . H o s te d on Spaces

Description <sP

Creates a plot component to display various kinds of plots (matplotlib, plotly,

altair, or bokeh plots are supported). As this component does not accept user

input, it is rarely used as an input component.

Behavior

As input com ponent: (Rarely used) passes the data displayed in the plot as an

PlotData dataclass, which includes the plot information as a JSON string, as well

as the type of chart and the plotting library.


Your function should accept one of these types:

d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (

v a l u e : P lo tD a ta | None

As output com ponent: Exp ects p lo t data in o n e o f th e se form ats: a

m a tp lo tlib .F ig u re , b o k e h .M o d e l, p lo tly .F ig u re , o r a lta ir.C h a rt o b je ct.

Your function should return one of these types:

d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( ^ " ) -> Any

re t u r n v a lu e

InitiaMzation

Parameter Description

value Optionally, supply a default plot object to display,

Any |N o n e must be a matplotlib, plotly, altair, or bokeh figure,

default: None or a callable. Ifcallable, the function will be called

whenever the app loads to set the initial value of

the component.

format File format in which to send matplotlib plots to the

str front end, such as 'jpg' or 'png'.

default: "w ebp"


Parameter Description

la b e l The label for this component. Appears above the

str |None com ponent and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r . I n t e r f a c e , the label w ill be the

name of the parameter this com ponent is assigned

to.

e v e ry If v a lu e is a callable, run the function 'every'

float 1None number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

s h o w _ la b e l if True, w ill display label.

bool 1None

default: None

c o n t a in e r If True, w ill place the com ponent in a container -

bool providing some extra padding around the border.

default: True

s c a le relative size compared to adjacent Components.

int 1None For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A w ill be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.


Parameter Description

min_width mínimum pixel width, will wrap ifnot sufficient

in t screen space to satisfy this value. Ifa certain scale

default: 160 value results in this Component being narrower

than min_width, the min_width parameter will be

respected first.

visible IfFalse, component will be hidden.

bool

default: True

elem_id An optional string that is assigned as the id of this

str |N o n e component in the H T M L DOM. Can be used for

default: None targeting CSS styles.

elem_classes An optional list of strings that are assigned as the

list[str] Is t r I N o n e classes of this component in the H T M L DOM. Can

default: None be used for targeting CSS styles.

render IfFalse, component will not render be rendered in

bool the Blocks context. Should be used ifthe intention

default: True is to assign event listeners n o w but render the

component later.

Shortcuts

Interface String
Class Initialization
Shortcut

gradio.Dataframe "plot" Uses default values


Demos

blocks_kinem atics s to c k _ fo re c a st


import pandas as pd

import numpy as np

import gradio as gr
I
def plot(v, a):

g = 9.81

theta = a / 180 * 3.14

tmax = ((2 * v) * np.sin(theta)) / g

timemat = tmax * np.linspace(0, 1, 40)

Loading...

g r a d i o / b l o c k s _ k i n e m a t i c s b u ilt w ith G ra d io . H o s te d o n Spaces

Event Listeners
Description
E ven t lis te n e rs a llo w y o u to c a p tu re an d re sp o n d to u ser in te ra c tio n s w ith

th e UI c o m p o n e n ts y o u 'v e d e fin e d in a G ra d io B lo c k s app. W hen a u ser


in te ra c ts w ith an e le m e n t, su ch as c h a n g in g a s lid e r v a lu e o r u p lo a d in g an

im age, a fu n c tio n is c a lle d .

Supported Event Listeners


T he P l o t c o m p o n e n t s u p p o rts th e fo llo w in g e v e n t listen e rs. Each e v e n t

lis te n e r ta k e s th e sa m e p a ra m e te rs, w h ic h are listed in th e Event Arguments

ta b le below .

Listener Description

gradio.Dataframe.change Triggered when the value of the Plot changes

(fn, •••) either because of user input (e.g. a user types


in a textbox) OR because of a function update
(e.g. an image receives a value from the output
of an event trigger). See . in p u t ( ) for a
listener that is only triggered by user input.

gradio.Plot.clear(fn, This listener is triggered when the user clears


•••) the Plot using the X button for the component.

Event Arguments
Parameter Description

fn the function to call when this event is

Callable |None | triggered. Often a machine learning model's

Litem l[’decom tor’] prediction function. Each parameter of the

default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tuple of values, with each


Parameter Description

element in the tupie corresponding to one

output component.

inputs List of gradio.components to use as inputs. If

C o m p o n e n t |lis t[ C o m p o n e n t] | the function takes no inputs, this should be an

s e t[C o m p o n e n t] |N o n e empty list.

default: None

outputs List of gradio.components to use as outputs. If

Com ponent |lis t[ C o m p o n e n t] | the function returns no outputs, this should be

None an empty list.

default: None

api_name defines how the endpoint appears in the API

s t r |N o n e |L ite ra l[F a ls e ] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

scroll_to_output If True, w ill scroll to output com ponent on

bool completion

default: False

show_progress If True, w ill show progress animation while

L ite ra l[(’f u ll’, ’m in im a l’, pending

’h id d e n ’)]

default: "fu ll
Parameter Description

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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 Maximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this

listener is triggered. For example, setting


Parameter Description

dict[str, A n y ] |list[dict[str, cancels=[click_event] w ill cancel the

A ny]] 1N o n e click_event, where click_event is the return

default: None value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

flo a t 1N o n e while the client connection is open.

default: None Interpreted in seconds.

trigger_mode If "once" (default for all events except

L ite ra l[(’o n c e ’, 'm ú lt ip le , .c h a n g e ( ) ) would not allow any submissions

’a l w a y s j a s t ’)] |N o n e while an event is pending. If set to "multiple",


default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before

s t r |N o n e running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

concurrency_limit If set, this is the maximum number of this

in t 1N o n e |L ite ra l['d e fa u lt'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the


Parameter Description

default concurrency limit (defined by the

d e fa u lt_ co n cu rre n cy _ lim it parameter in

B lo ck s.q u e u e (), which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.


str |None Events with the same concurrency_id will be

default: None limited by the lowest set concurrencyjimit.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"


default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

will still allow downstream apps to use this

event. If fn is None, show_api will

automatically be set to False.

Guides

Plot Component For Maps

^ ParamViewer Radio

Status

$ gradio X o
Custom Com ponents G alleryNEW E xp lore

$ gradio

N e w to Gradio? Start here: Getting Started See the Release History

E xa m p le s m a k e _ w a v e fo rm

Progress

gradio.Progress(•••)

Description

T he P ro g re ss cla s s p ro v id e s a c u sto m p ro g re ss tra c k e r th a t is u sed in a fu n c tio n


sig n a tu re . To attach a P ro g re ss tra c k e r to a fu n c tio n , s im p ly ad d a p a ra m e te r

rig h t a fte r th e in p u t p a ra m e te rs th a t has a d e fa u lt v a lu e se t to a

g r a d io . P r o g r e s s ( ) in stan ce. T he P ro g re ss tra c k e r can th e n be u p d a te d in th e

fu n c tio n by c a llin g th e P ro g re ss o b je c t o r u sin g th e tqdm m e th o d on an Iterable.

T he P ro g re ss tra c k e r is c u rre n tly o n ly a v a ila b le w ith q u e u e ( ) .

Exampíe Usage &

import gradio as gr

import time

def my_function(x , progress=gr.Progress()):

progress(0, desc= "Starting...")


time.sleep(1)

for i in progress.tqdm(range(100)):

time.sleep(0.1)

return x

gr.Interface(my_function, gr.Textbox(), gr.Textbox()).queue() .launch()

InitiaMzation

Parameter Description

track_tqdm IfTrue, the Progress object will track any

bool tqdm.tqdm iterations with the tqdm library in the

default: False function.

Methods

cali

gradio.Progress.__call__(progress, •••)

Description

U p d a te s p ro g re ss tra c k e r w ith p ro g re ss an d m e ssag e text.


Agruments

Parameter Description

progress Iffloat, should be between 0 and 1

flo a t |tu p le [in t, in t |N o n e ] | representing completion. IfTupie, first number

None represents steps completed, and second value

required represents total steps or None ifunknown. If

None, hides progress bar.

desc description to display.

s t r 1N o n e

default: None

total estimated total number of steps.

in t 1N o n e

default: None

unit unit of iterations.

str

default: "steps"

tqdm

gradio.Progress.tqdm(iterableJ •••)
Descri ption

A tta c h e s p ro g re ss tra c k e r to ite ra b le , lik e tq d m .

Agruments

Parameter Description

iterable iterable to attach progress tracker to.

Ite ra b le |N o n e

required

desc description to display.

s t r 1N o n e

default: None

total estimated total number of steps.

in t 1N o n e

default: None

unit unit of iterations.

str

default: "steps"

E xa m p le s m a k e _ w a v e fo rm
Status

$ gradio O
Custom Com ponents G alleryNEW E xp lore

$ gradio

N e w to Gradio? Start here: Getting Started See the Release History

P lo t S c a tte rP lo t

Radio

gradio.Radio(•••)

Loading...

g r a d io / r a d i o _ c o m p o n e n t b u ilt w ith G ra d io . H o s te d o n Spaces

Description

C reate s a se t o f (strin g o r n u m e ric type) ra d io b u tto n s o f w h ic h o n ly o n e can be

se le cte d .
Behavior

As input com ponent: P asses th e v a lu e o f th e se le cte d ra d io b u tto n as a s t r |

in t | f l o a t , o r its in d e x as an i n t in to th e fu n c tio n , d e p e n d in g on t y p e .

Your function should accept one of these types:

d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (

v a lu e : s t r | in t | flo a t | None

As output com ponent: Exp ects a s t r | in t | f l o a t c o rre s p o n d in g to th e v a lu e

o f th e ra d io b u tto n to be se le cte d

Your function should return one of these types:

d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( " 0 -> s t r | in t | flo a t | None

re t u r n v a lu e

InitiaMzation
Parameter Description

c h o ic e s A list of string or numeric options to select from. An

list[str |in t |flo a t |tuple[str, s t r | option can also be a tupie of the form (name,

in t |flo a t]] |N o n e value), where name is the displayed name of the

default: None radio button and value is the value to be passed to

the function, or returned by the function.

v a lu e The option selected by default. If None, no option

s t r |in t |flo a t |C a lla b le |N o n e is selected by default. If callable, the function will

default: None be called whenever the app loads to set the initial

value of the component.

ty p e Type of value to be returned by component.

str "value" returns the string of the choice selected,

default: "value" "index" returns the index of the choice selected.

la b e l The label for this component. Appears above the

s t r |N o n e com ponent and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r . I n t e r f a c e , the label w ill be the

name of the parameter this com ponent is assigned

to.

in f o Additional com ponent description.

s t r |N o n e

default: None

e v e ry If v a lu e is a callable, run the function 'every'

flo a t |N o n e number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be


Parameter Description

accessed (e.g. to cancel it) via this component's

.load_event attribute.

show_label ifTrue, will display label.

bool |N o n e

default: None

container IfTrue, will place the component in a container -

bool providing some extra padding around the border.

default: True

scale Relative width compared to adjacent Components

in t 1N o n e in a Row. For example, ifComponent A has scale=2,

default: None and Component B has scale=1, A will be twice as

wide as B. Should be an integer.

min_width Minimum pixel width, will wrap ifnot sufficient

in t screen space to satisfy this value. Ifa certain scale

default: 160 value results in this Component being narrower

than min_width, the min_width parameter will be

respected first.

interactive IfTrue, choices in this radio group will be

b o o l |N o n e selectable; if False, selection will be disabled. Ifnot

default: None provided, this is inferred based on whether the

component is used as an input or output.

visible IfFalse, component will be hidden.

bool

default: True
Parameter Description

elem_id An optional string that is assigned as the id of this

str |N o n e component in the H T M L DOM. Can be used for

default: None targeting CSS styles.

elem_classes An optional list of strings that are assigned as the

list[str] Is t r I N o n e classes of this component in the H T M L DOM. Can

default: None be used for targeting CSS styles.

render IfFalse, component will not render be rendered in

bool the Blocks context. Should be used ifthe intention

default: True is to assign event listeners n o w but render the

component later.

Shortcuts

Interface String
Class Initialization
Shortcut

gradio.Dataframe "radio" Uses default values

Demos

sentence_builder b lo c k s_ e s sa y

I
import gradio as gr

def sentence_builder(quantity, animal, countries, place, activity_list, mor



ning):

return f .. The {quantity} {animal}s from {" and ".join(countries)} went

to the {place} where they {" and ".join(activity_list)} until the {"mornin

g" if morning else "night"}..


I
demo = gr.Interface(

Loading...

g r a d i o / s e n t e n c e _ b u i l d e r b u ilt w ith G ra d io . H o s te d o n Spaces

Event Listeners

Description
E ven t lis te n e rs a llo w y o u to c a p tu re an d re sp o n d to u ser in te ra c tio n s w ith

th e UI c o m p o n e n ts y o u 'v e d e fin e d in a G ra d io B lo c k s app. W hen a u ser


in te ra c ts w ith an e le m e n t, su ch as c h a n g in g a s lid e r v a lu e o r u p lo a d in g an

im age, a fu n c tio n is c a lle d .

Supported Event Listeners


T he R a d i o c o m p o n e n t s u p p o rts th e fo llo w in g e v e n t liste n e rs. Each e v e n t

lis te n e r ta k e s th e sa m e p a ra m e te rs, w h ic h are liste d in th e Event Arguments

ta b le below .
Listener Description

gradio.Dataframe.change Event listener for when the user selects or

(fn, •••) deselects the Radio. Uses event data


gradio.SelectData to carry v a lu e referring to
the label of the Radio, and s e le c t e d to refer
to state of the Radio. See EventData
documentation on how to use this event data

gradio.Radio.change(fn, Triggered when the value of the Radio changes


•••) either because of user input (e.g. a user types
in a textbox) OR because of a function update
(e.g. an image receives a value from the output
of an event trigger). See . in p u t ( ) for a
listener that is only triggered by user input.

gradio.Radio.input(fn, This listener is triggered when the user


•••) changes the value of the Radio.

Event Arguments
Parameter Description

fn the function to call when this event is

Callable |None | triggered. Often a machine learning model's

Litem l[’decom tor’] prediction function. Each parameter of the

default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tuple of values, with each

element in the tuple corresponding to one

output component.

inputs List of gradio.components to use as inputs. If

Component | list[Component] | the function takes no inputs, this should be an

set[Component] | None empty list.

default: None
Parameter Description

o u tp u ts List of gradio.components to use as outputs. If

Com ponent |lis t[ C o m p o n e n t] | the function returns no outputs, this should be

None an empty list.

default: None

api_nam e defines how the endpoint appears in the API

s t r 1N o n e |L ite ra l[F a ls e ] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

s c r o ll_ t o _ o u t p u t If True, w ill scroll to output com ponent on

bool completion

default: False

sh o w _ p ro g re ss If True, w ill show progress animation while

L ite ra l[(’f u ll’, ’m in im a l’, pending


’h id d e n ’)]

default: "fu ll"

queue If True, w ill place the request on the queue, if

b o o l |N o n e the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.


Parameter Description

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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 Maximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this

dict[str, Any] | list[dict[str, listener is triggered. For example, setting

Any]] 1None cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but


Parameter Description

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

flo a t |N o n e while the client connection is open.

default: None Interpreted in seconds.

trigger_mode If "once" (default for all events except

L iteral[('o n ce', '


m ú lt ip le ' .c h a n g e ( ) ) would not allow any submissions

’a l w a y s j a s t ’)] |N o n e while an event is pending. If set to "multiple",


default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before


s t r 1N o n e running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

concurrency_limit If set, this is the maximum number of this

in t 1N o n e |L ite ra l['d e fa u lt'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).


Parameter Description

concurrency_id Ifset, this is the id of the concurrency group.

str |N o n e Events with the same concurrency_id will be

default: None limited by the lowest set concurrencyjimit.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

will still allow downstream apps to use this

event. Iffn is None, show_api will

automatically be set to False.

Plot ScatterPlot

Status

$ gradio O
Custom Com ponents G alleryNEW E xp lore

$ gradio

N e w to Gradio? Start here: Getting Started See the Release History

Info m o u n t_ g ra d io _ a p p

Request

gradio.Request(•••)

Description

A G ra d io re q u e st o b je c t th a t can be u sed to access th e re q u e st h ead e rs, c o o k ie s,

q u e ry p a ra m e te rs an d o th e r in fo rm a tio n a b o u t th e re q u e st fro m w ith in th e

p re d ic tio n fu n c tio n . T h e c la s s is a th in w ra p p e r a ro u n d th e fa sta p i.R e q u e s t class.

A ttrib u te s o f th is c la s s in clu d e : h e a d e r , c l i e n t , q u e ry _ p a ra m s, s e s s io n _ h a s ,

and p a th _ p a ra m s. If au th is e n a b le d , th e username a ttrib u te can be u sed to get

th e log ged in user.

Exampíe Usage &

import gradio as gr

def echo(text, request: gr.Request):

if request:

print("Request headers dictionary:", request.headers)


print("IP address:", request.client.host)

print("Query parameters:", dict(request.query_params))

print("Session hash:", request.session_hash)

return text

io = gr.Interface(echo, "textbox", "textbox").launch()

InitiaMzation

Parameter Description

request A fastapi.Request

fa s t a p i.R e q u e s t |N o n e

default: None

username The username of the logged in user (ifauth is

s t r IN o n e enabled)

default: None

session hash The session hash of the current session. It is

s t r |N o n e unique for each page load.

default: None

Demos

request_ip_headers

import gradio as gr

def predict(text, request: gr.Request):


headers = request.headers

host = request.client.host

user_agent = request.headers["user-agent"]

return {

"ip": host,

"user_agent": user_agent,

"headers": headers,

Loading...

g r a d i o / r e q u e s t _ i p _ h e a d e r s b u ilt w ith G ra d io . H o s te d o n Spaces

Info m o u n t_ g ra d io _ a p p

Status

O
Custom Com ponents G a lle ry NEW Explore

gradio =

New to Gradio? Start here: G etting Started See the Release History

^ B lo c k s C o lu m n

Row

with gradio.Row():

Description
R o w is a la y o u t e le m e n t w ith in B lo c k s th a t re n d e rs a ll c h ild re n h o riz o n ta lly .

Exampíe Usage

with gr.Blocks() as demo:

with gr.Row():

g r .Image("lion.jpg", scale=2)

g r .Image("tiger.jpg", scale=1)

demo.launch()

Initiaíization
Param eter D escription

v a r ia n t row type, 'default' (no background), 'panel' (gray

Literal[('default', 'panel', background color and rounded corners), or

'compact')] 'com pact' (rounded corners and no internal gap).

default: "d efault"

v is ib le If False, row w ill be hidden.

bool
Param eter D escription

default: True

e le m _ id An optional string that is assigned as the id of this

str | None com ponent in the HTML DOM. Can be used for

default: None targeting CSS styles.

e l e m _ c la s s e s An optional string or list of strings that are

list[str] 1str 1None assigned as the class of this com ponent in the

default: None HTML DOM. Can be used for targeting CSS styles.

re n d e r If False, this layout w ill not be rendered in the

bool Blocks context. Should be used if the intention is to

default: True assign event listeners now but render the

com ponent later.

e q u a l_ h e ig h t If True, makes every child elem ent have equal

bool height

default: True

Guides

Controlling Layout

^ B lo c k s C o lu m n

0 gradio Status X O
Custom Com ponents G alleryNEW E xp lore

$ gradio

N e w to Gradio? Start here: Getting Started See the Release History

^ Radio Simplelmage

ScatterPlot

gradio.ScatterPlot(•••)

g r a d i o / s c a t t e r p l o t _ c o m p o n e n t b u ilt w ith G ra d io . H o s te d o n Spaces

Description &

Creates a scatter plot c o m p o n e n t to display data from a pandas DataFrame (as

output). As this c o m p o n e n t does not accept user input, it is rarely used as an


in p u t c o m p o n e n t.

Behavior

As input com ponent: (R arely used) p a sse s th e data d is p la y e d in th e s c a tte r p lo t

as an A lta irP lo tD a ta d a ta c la s s, w h ic h in c lu d e s th e p lo t in fo rm a tio n as a JS O N

strin g , as w e ll as th e ty p e o f p lo t (in th is case, "scatter").

Your function should accept one of these types:

d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (

v a l u e : A l t a ir P lo t D a t a | None

As output com ponent: Exp ects a p a n d a s D ataFram e c o n ta in in g th e data to

d is p la y in th e s c a tte r p lo t. T h e D ataFram e sh o u ld c o n ta in a t le a st tw o co lu m n s ,

o n e fo r th e x-axis (c o rre s p o n d in g to th is c o m p o n e n t's x a rg u m e n t) an d o n e fo r

th e y-axis (c o rre s p o n d in g to y ).

Your function should return one of these types:

d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( " 0 -> pd. DataFrame | d ic t | None

re t u r n v a lu e

InitiaMzation
Parameter Description

value The pandas dataframe containing the data to

p d .D a t a F r a m e |C a lla b le |N o n e display in a scatter plot, or a callable. Ifcallable,

default: None the function will be called whenever the app loads

to set the initial value of the component.

x Column corresponding to the x axis.

s t r 1N o n e

default: None

y Column corresponding to the y axis.

s t r 1N o n e

default: None

color The column to determine the point color. Ifthe

s t r |N o n e column contains numeric data, gradio will

default: None interpolate the column data so that small values

correspond to light colors and large values

correspond to dark values.

si z e The column used to determine the point size.

s t r 1N o n e Should contain numeric data so that gradio can

default: None m a p the data to the point size.

shape The column used to determine the point shape.

s t r 1N o n e Should contain categorical data. Gradio will m a p

default: None each unique value to a different shape.

title The title to display on top of the chart.

s t r 1N o n e

default: None
Parameter Description

tooltip The column (or list of columns) to display on the

list[str] |s t r |N o n e tooltip when a user hovers a point on the plot.

default: None

x_title The title given to the x-axis. By default, uses the

s t r 1N o n e value of the x parameter.

default: None

y_title The title given to the y-axis. By default, uses the

s t r 1N o n e value of the y parameter.

default: None

x_label_angle The angle for the x axis labels rotation. Positive

flo a t 1N o n e values are clockwise, and negative values are

default: None counter-clockwise.

y_label_angle The angle for the y axis labels rotation. Positive

flo a t 1N o n e values are clockwise, and negative values are

default: None counter-clockwise.

color_legend_title The title given to the color legend. By default, uses

s t r 1N o n e the value of color parameter.

default: None

size_legend_title The title given to the size legend. By default, uses

s t r 1N o n e the value of the size parameter.

default: None

shape_legend_title The title given to the shape legend. By default,

s t r 1N o n e uses the value of the shape parameter.

default: None
Parameter Description

color_legend_position The position of the color legend. Ifthe string value

L ite ra l[(’le ft, 'right', ’t o p ’, 'none' is passed, this legend is omitted. For other

’b o tto m ', ’to p -le ft, 't o p - r ig h t , valid position values see:

’b o tto m -le ft, ’b o tt o m - r ig h t, https://vega.github.io/vega/docs/legends/#orienta

'n o n e')] |N o n e tion.

default: None

size_legend_position The position of the size legend. Ifthe string value

L ite ra l[(1 e ft, 'rig h t, 'to p , 'none' is passed, this legend is omitted. For other

'b o tt o m , ’to p -le ft, 'to p -rig h t, valid position values see:

’b o tto m -le ft, ’b o t t o m - r ig h t , https://vega.github.io/vega/docs/legends/#orienta

'n o n e ')] |N o n e tion.

default: None

shape_legend_position The position of the shape legend. Ifthe string value

L ite ra l[(’le ft, 'r ig h t , ’to p , 'none' is passed, this legend is omitted. For other

'b o tt o m , ’to p -le ft, 'to p -rig h t, valid position values see:

’b o tto m -le ft, ’b o t t o m - r ig h t , https://vega.github.io/vega/docs/legends/#orienta

'n o n e ')] |N o n e tion.

default: None

height The height of the plot, specified in pixels ifa

in t 1s t r 1N o n e number is passed, or in CSS units ifa string is

default: None passed.

width The width of the plot, specified in pixels ifa

in t 1s t r 1N o n e number is passed, or in CSS units ifa string is

default: None passed.


Parameter Description

x _ lim A tupie or list containing the limits for the x-axis,

list[in t |flo a t] |N o n e specified as [x_min, x_max].

default: None

y _ lim A tuple of list containing the limits for the y-axis,

list[in t 1flo a t] 1N o n e specified as [y_min, y_max].

default: None

c a p t io n The (optional) caption to display below the plot.

s t r 1N o n e

default: None

in t e r a c t iv e Whether users should be able to interact with the

b o o l 1N o n e plot by panning or zooming with their mouse or

default: True trackpad.

la b e l The (optional) label to display on the top left

s t r 1N o n e corner of the plot.

default: None

e v e ry If v a lu e is a callable, run the function 'every'

flo a t |N o n e number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

s h o w _ la b e l Whether the label should be displayed.

b o o l 1N o n e

default: None

c o n t a in e r
Parameter Description

bool

default: True

scale

in t |N o n e

default: None

min_width

in t

default: 160

visible Whether the plot should be visible.

bool

default: True

elem_id An optional string that is assigned as the id of this

s t r IN o n e component in the H T M L DOM. Can be used for

default: None targeting CSS styles.

elem_classes An optional list of strings that are assigned as the

list[str] Is t r I N o n e classes of this component in the H T M L DOM. Can

default: None be used for targeting CSS styles.

render IfFalse, component will not render be rendered in

bool the Blocks context. Should be used ifthe intention

default: True is to assign event listeners n o w but render the

component later.

s h o w _actions_ b u t t o n Whether to show the actions button on the top

bool right corner of the plot.

default: False
Shortcuts

Interface String
Class Initialization
Shortcut

g r a d io . Dataframe "scatterplot" Uses default values

Event Listeners

Description
Event listeners allow you to capture and respond to user interactions with

the UI c o m p o n e n t s you've defined in a Gradio Blocks app. W h e n a user


interacts with an element, such as changing a slider value or uploading an

image, a function is called.

Supported Event Listeners


T h e S c a t t e r P l o t c o m p o n e n t supports the following event listeners.

Each event listener takes the s a m e parameters, which are listed in the

Event Arguments table below.

Listener Description

gradio.Dataframe.change Triggered when the value of the Plot changes

(fn, •••) either because of user input (e.g. a user types


in a textbox) OR because of a function update
(e.g. an image receives a value from the output
of an event trigger). See . in p u t ( ) for a
listener that is only triggered by user input.

gradio.ScatterPlot.clea This listener is triggered when the user clears


r(fn, ■■■) the Plot using the X button for the component.
Event Arguments
Parameter Description

fn the function to call when this event is

C a lla b le |N o n e | triggered. Often a machine learning model's

L it e m l[ ’d e c o m t o r ’] prediction function. Each parameter of the

default: "decorator" 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.

in p u t s List of gradio.components to use as inputs. If

Com ponent |lis t[ C o m p o n e n t] | the function takes no inputs, this should be an

s e t[C o m p o n e n t] |N o n e empty list.

default: None

o u tp u ts List of gradio.components to use as outputs. If

C o m p o n e n t |lis t[ C o m p o n e n t] | the function returns no outputs, this should be

None an empty list.

default: None

api_nam e defines how the endpoint appears in the API

s t r |N o n e |L ite ra l[F a ls e ] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.


Parameter Description

scroll_to_output If True, w ill scroll to output com ponent on

bool completion

default: False

show_progress If True, w ill show progress animation while

Literal[('fuW, ’m inim al’, pending

’hidden’)]

default: "fu ll"

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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 Maximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.


Parameter Description

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this


dict[str, A n y ] |list[dict[str, listener is triggered. For example, setting

A ny]] 1N o n e cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

flo a t 1N o n e while the client connection is open.

default: None Interpreted in seconds.

trigger_mode If "once" (default for all events except

L ite ra l[(’o n c e ’, 'm ú lt ip le , .c h a n g e ( ) ) would not allow any submissions

’a l w a y s j a s t ’)] |N o n e while an event is pending. If set to "multiple",


default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.
Parameter Description

js Optional frontend js method to run before

str |None running 'fn'. Input arguments for js method are

default: None valúes of 'inputs' and 'outputs', return should

be a list of valúes for output components.

concurrency_limit If set, this is the maximum number of this

int 1None | Literal['default'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.

str 1None Events with the same concurrency_id w ill be

default: None limited by the lowest set concurrency_limit.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

autom atically be set to False.


Guides

Creating A Dashboard From Bigquery Data

Radio Simplelmage

Status

^ gradio o
Custom Com ponents G alleryNEW E xp lore

$ gradio

N e w to Gradio? Start here: Getting Started See the Release History

Video EventData

set_static_paths

gradio.set_static_paths(paths, •••)

Description

Set the static paths to be served by the gradio app.

Static files are not m o v e d to the gradio cache and are served directly from the file

system. This function is useful w h e n you w a n t to serve files that you k n o w will

not be modified during the lifetime of the gradio a p p (like files used in

gr.Examples). By setting static paths, your a p p will launch faster and it will

c o n s u m e less disk space. Calling this function will set the static paths for all

gradio applications defined in the s a m e interpreter session until it is called again

or the session ends. To clear out the static paths, call this function with an e m p t y

list.

Exampíe Usage &


import gradio as gr

# Paths can be a list of strings or pathlib.Path objects

# corresponding to filenames or directories.

gr.set_static_paths(paths= ["test/test_files/"])

# The example files and the default value of the input

# will not be copied to the gradio cache and will be served directly.

demo = gr.Interface(

lambda s : s .rotate(45),

gr.Image(value="test/test_files/cheetah1.jpg", type="pil"),

gr.Image(),

examples= ["test/test_files/bus.png"],

demo.launch()

Imtiaíization

Parameter Description

paths List of filepaths or directory names to be served by

list[str |P a th ] the gradio app. Ifit is a directory name, ALL files

r e q u ir e d located within that directory will be considered

static and not moved to the gradio cache. This also

means that ALL files in that directory will be

accessible over the network.

Video EventData
Status

$ gradio O
Custom Com ponents G alleryNEW E xp lore

$ gradio

N e w to Gradio? Start here: Getting Started See the Release History

ScatterPlot Slider

Simplelmage

gradio.SimpleImage(•••)

Loading...

g r a d io / s im p le im a g e _ c o m p o n e n t b u ilt w ith G ra d io . H o s te d o n Spaces

Description

Creates an image c o m p o n e n t that can be used to upload images (as an input) or

display images (as an output).


Behavior

As input com ponent: A s t r c o n ta in in g th e path to th e im age.

Your function should accept one of these types:

d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (

v a lu e : s t r | None

As output com ponent: Exp ects a s t r o r p a t h lib . P a t h o b je c t c o n ta in in g th e path

to th e im age.

Your function should return one of these types:

d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( " 0 -> s t r | Pa th | None

re t u r n v a lu e

InitiaMzation

Parameter Description

value A path or URL for the default value that

str |N o n e SimpleImage component is going to take. If

default: None callable, the function will be called whenever the

app loads to set the initial value of the component.


Parameter Description

lab e l The label for this component. Appears above the

str |N o n e com ponent and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r . I n t e r f a c e , the label w ill be the

name of the parameter this com ponent is assigned

to.

every If v a lu e is a callable, run the function 'every'

flo a t I N o n e number of seconds while the client connection is

default: None 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 if True, w ill display label.

b o o l IN o n e

default: None

show_download b u tto n If True, w ill display button to download image.

bool

default: True

container If True, w ill place the com ponent in a container -

bool providing some extra padding around the border.

default: True

scale relative size compared to adjacent Components.

in t I N o n e For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A w ill be

twice as wide as B. Should be an integer. scale


Parameter Description

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

min_width mínimum pixel width, will wrap ifnot sufficient

in t screen space to satisfy this value. Ifa certain scale

default: 160 value results in this Component being narrower

than min_width, the min_width parameter will be

respected first.

interactive ifTrue, will allow users to upload and edit an

bool |N o n e image; if False, can only be used to display images.

default: None Ifnot provided, this is inferred based on whether

the component is used as an input or output.

visible IfFalse, component will be hidden.

bool

default: True

elem_id An optional string that is assigned as the id of this

s t r IN o n e component in the H T M L DOM. Can be used for

default: None targeting CSS styles.

elem_classes An optional list of strings that are assigned as the

list[str] Is t r I N o n e classes of this component in the H T M L DOM. Can

default: None be used for targeting CSS styles.

render IfFalse, component will not render be rendered in

bool the Blocks context. Should be used ifthe intention

default: True is to assign event listeners n o w but render the

component later.
Shortcuts

Interface String
Class Initialization
Shortcut

gradio.Dataframe "simpleimage" Uses default values

Event Listeners

Description
Event listeners allow you to capture and respond to user interactions with

the UI c o m p o n e n t s you've defined in a Gradio Blocks app. W h e n a user


interacts with an element, such as changing a slider value or uploading an

image, a function is called.

Supported Event Listeners


T h e S i m p l e l m a g e c o m p o n e n t supports the following event listeners.

Each event listener takes the s a m e parameters, which are listed in the

Event Arguments table below.

Listener Description

gradio.Dataframe.change This listener is triggered when the user clears

(fn, •••) the SimpleImage using the X button for the


component.

gradio.Simplelmage.chan Triggered when the value of the SimpleImage


ge(fn, •••) changes either because of user input (e.g. a
user types in a textbox) O R because of a
function update (e.g. an image receives a value
from the output of an event trigger). See
Listener Description

. in p u t ( ) for a listener that is only triggered


by user input.

g r a d io .S im p le lm a g e .u p lo This listener is triggered when the user


a d (fn , •••) uploads a file into the Simplelmage.

Event Arguments
Parameter Description

fn the function to call when this event is

C a lla b le |N o n e | triggered. Often a machine learning model's

L ite r a l['d e c o r a to r'] prediction function. Each parameter of the

default: "decorator" 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.

in p u t s List of gradio.components to use as inputs. If

Com ponent |lis t[ C o m p o n e n t] | the function takes no inputs, this should be an

s e t[C o m p o n e n t] |N o n e empty list.

default: None

o u tp u ts List of gradio.components to use as outputs. If

C o m p o n e n t |lis t[ C o m p o n e n t] | the function returns no outputs, this should be

None an empty list.

default: None

api_nam e defines how the endpoint appears in the API

s t r |N o n e |L ite ra l[F a ls e ] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),


Parameter Description

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

scroll_to_output If True, w ill scroll to output com ponent on

bool completion

default: False

show_progress If True, w ill show progress animation while

Literal[('fuW , ’m in im a l’, pending

’h id d e n ’)]

default: "fu ll"

queue If True, w ill place the request on the queue, if

bool |N o n e the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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.
Parameter Description

max_batch_size Máximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this

dict[str, Any] | list[dict[str, listener is triggered. For example, setting

Any]] 1None cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

float 1None while the client connection is open.

default: None Interpreted in seconds.


Parameter Description

trigger_mode If "once" (default for all events except

L iteral[('o n ce', '


m ú lt ip le ' .c h a n g e ( ) ) would not allow any submissions

’a l w a y s j a s t ’)] |N o n e while an event is pending. If set to "múltiple",

default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before

s t r 1N o n e running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

concurrency_limit If set, this is the maximum number of this

in t 1N o n e |L ite ra l['d e fa u lt'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.

s t r 1N o n e Events with the same concurrency_id w ill be

default: None limited by the lowest set concurrency_limit.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting


Parameter Description

api_name to False, setting show_api to False

will still allow downstream apps to use this

event. Iffn is None, show_api will

automatically be set to False.

ScatterPlot Slider

Status

^ gradio o
Custom Components GalleryNEW Explore

$ gradio

New to Gradio? Start here: Getting Started See the Release History

^ S im p le lm a g e State

Slider

gradio.Slider(•••)

Loading...

g r a d i o / s l i d e r _ c o m p o n e n t b u ilt w ith G r a d io . Hoste d on S p a ce s

Description ¿P

Creates a slid e r th a t ranges from minimum to máximum w ith a step size o f s te p .

Behavior
As input component: Passes slid e r value as a f l o a t into the function.

Your function should accept one of these types:

def p r e d ic t (

v a lu e : pd. DataFrame | np. ndarray | p l . DataFrame | l i s t [ l i s t ]

. . . d ef p r e d ic t (

v a lu e : f l o a t

As output component: Expects an i n t o r f l o a t returned from fu n ction and sets s lid e r value to

as long as it is w ith in range (otherw ise, sets to m in im u m value).

Your function should return one of these types:

def p r e d ic t ( ---) -> pd. DataFrame | S t y le r | np. ndarray | p l . DataFrame | l i s t | lis t[lis t] | d ic t | str | None

re tu rn v a lu e def p r e d ic t ( ---) -> f l o a t | None

re tu rn va lu e

Initialization

Parameter Description

minimum minimum value for slider.

float

default: 0

máximum maximum value for slider.

float

default: 100

value default value. If callable, the function will be called whenever

float | Callable | None the app loads to set the initial value of the component.
Parameter Description

default: None Ignored if randomized=True.

step increment between slider valúes.

float | None

default: None

label The label for this component. Appears above the component

str 1None and is also used as the header if there are a table of examples

default: None for this component. If None and used in a g r . I n t e r f a c e ,

the label will be the name of the parameter this component is

assigned to.

info additional component description.

str 1None

default: None

every If v a lu e is a callable, run the function 'every' number of

float 1None seconds while the client connection is open. Has no effect

default: None otherwise. The event can be accessed (e.g. to cancel it) via

this component's .load_event attribute.

show_label if True, will display label.

bool 1None

default: None

container If True, will place the component in a container - providing

bool some extra padding around the border.

default: True

scale relative size compared to adjacent Components. For example

int 1None if Components A and B are in a Row, and A has scale=2, and B

default: None has scale=1, A will be twice as wide as B. Should be an


Parameter Description

integer. scale applies in Rows, and to top-level Components

in Blocks where fill_height=True.

min_width mínimum pixel width, will wrap if not sufficient screen space

int to satisfy this value. If a certain scale value results in this

default: 160 Component being narrower than min_width, the min_width

parameter will be respected first.

interactive if True, slider will be adjustable; if False, adjusting will be

bool | None disabled. If not provided, this is inferred based on whether

default: None the component is used as an input or output.

visible If False, component will be hidden.

bool

default: True

elem_id An optional string that is assigned as the id of this componen

str I None in the HTML DOM. Can be used for targeting CSS styles.

default: None

elem_classes An optional list of strings that are assigned as the classes of

list[str] Istr I None this component in the HTML DOM. Can be used for targeting

default: None CSS styles.

render If False, component will not render be rendered in the Blocks

bool context. Should be used if the intention is to assign event

default: True listeners now but render the component later.

randomize If True, the value of the slider when the app loads is taken

bool uniformly at random from the range given by the minimum

default: False and maximum.


Shortcuts

Class Interface String Shortcut Initialization

gradio.Dataframe "slider" Uses default valúes

Demos

sentence_builder slider_release in te rfa ce _ ra n d o m _ slid e r b lo ck s_ ra n d o m _ slid e r

import gradio as gr

def sentence_builder(quantity, animal, countries, place, activity_list, morning):

return f.. The {quantity} {animal}s from {" and ".join(countries)} went to the {place}

where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}..

demo = gr.Interface(

sentence_builder,

Loading...

g r a d i o / s e n t e n c e _ b u i l d e r b u ilt w ith G r a d io . Hosted on S p a ce s


Event Listeners

Description
Event listeners a llo w you to cap ture and respond to user in te ra ctio n s w ith the UI
co m p o n e n ts you 've defin ed in a G radio B locks app. W hen a user interacts w ith an
elem ent, such as ch ang ing a slid e r value o r u p lo a d in g an im age, a fu n ction is called.

Supported Event Listeners


The S l i d e r co m p o n e n t su p p o rts th e fo llo w in g even t listeners. Each even t listener take
th e sam e param eters, w h ich are listed in th e Event Arguments ta b le below.

Listener Description

gradio.Dataframe.c h a n g e f n , •• Triggered when the value of the Slider changes either

•)
because of user input (e.g. a user types in a textbox) OR
because of a function update (e.g. an image receives a
value from the output of an event trigger). See . in p u t ( )
for a listener that is only triggered by user input.

gradio.Slider.input(fn, ■■■) This listener is triggered when the user changes the value
of the Slider.

gradio.Slider.release(fn, This listener is triggered when the user releases the


■■■) mouse on this Slider.

Event Arguments
Parameter Description

fn the function to call when this event is triggered. Often a


Callable | None | Literal['decorator'] machine learning model's prediction function. Each
default: "decorator" parameter of the function corresponds to one input

component, and the function should return a single


Parameter Description

value or a tupie of valúes, with each element in the tupie

corresponding to one output component.

inputs List of gradio.components to use as inputs. If the


Component | list[Component] | function takes no inputs, this should be an empty list.
set[Component] |None

default: None

outputs List of gradio.components to use as outputs. If the


Component | list[Component] | None function returns no outputs, this should be an empty list.
default: None

api_name defines how the endpoint appears in the API docs. Can

str | None | Literal[False] be a string, None, or False. If set to a string, the endpoint
default: None will be exposed in the API docs with the given name. If

None (default), the name of the function will be used as

the API endpoint. If False, the endpoint will not be

exposed in the API docs and downstream apps (including

those that g r . lo a d this app) will not be able to use this

event.

s c r o ll_ t o _ o u t p u t If True, will scroll to output component on completion


bool

default: False

show _progress If True, will show progress animation while pending

Literal[('full', 'minimal', 'hidden')]

default: "full"

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

bo° | None has been enabled. If False, will not put this event on the

default: None queue, even if the queue has been enabled. If None, will

use the queue setting of the gradio app.


Parameter Description

batch If True, then the function should process a batch of


bool inputs, meaning that it should accept a list of input
default: False valúes 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.

m ax_batch_size Maximum number of inputs to batch together if this is

int called from the queue (only relevant if batch=True)


default: 4

p re p ro ce ss If False, will not run preprocessing of component data


bool before running 'fn' (e.g. leaving it as a base64 string if thi:

default: True method is called with the Image component).

p o stp ro c e ss If False, will not run postprocessing of component data


bool before returning 'fn' output to the browser.

default: True

c a n c e ls A list of other events to cancel when this listener is


dict[str, Any] | list[dict[str, Any]] |None triggered. For example, setting cancels=[click_event] will
default: None cancel the click_event, where click_event is the return

value of another components .click method. Functions

that have not yet run (or generators that are iterating)

will be cancelled, but functions that are currently

running will be allowed to finish.

ev ery Run this event 'every' number of seconds while the client
float 1None connection is open. Interpreted in seconds.
default: None
Parameter Description

trigger_mode If "once" (default for all events except .c h a n g e ())


Literal[('once, 'múltiple, would not allow any submissions while an event is
'alwaysjast')] | None pending. If set to "multiple", unlimited submissions are
default: None allowed while pending, and "alw aysjast" (default for

.ch a n g e () and .ke y _ u p () events) would allow a

second submission after the pending event is complete.

js Optional frontend js method to run before running 'fn'.


str 1None Input arguments for js method are values of 'inputs' and
default: None 'outputs', return should be a list of values for output

components.

concurrency_limit If set, this is the maximum number of this event that can
int 1None | Literal['default'] be running simultaneously. Can be set to None to mean
default: "default" no concurrency_limit (any number of this event can be

running simultaneously). Set to "default" to use the

default concurrency limit (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s .q u e u e ( ) , which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group. Events with


str 1None the same concurrency_id will be limited by the lowest sei
default: None concurrency_limit.

show_api whether to show this event in the "view API" page of the
bool Gradio app, or in the ".view_api()" method of the Gradio
default: True clients. Unlike setting api_name to False, setting

show_api to False will still allow downstream apps to use

this event. If fn is None, show_api will automatically be

set to False.
Guides

Create Your Own Friends With A Gan

^ S im p le lm a g e State

Status

$ gradio O
Custom Com ponents G alleryNEW E xp lore

$ gradio

N e w to Gradio? Start here: Getting Started See the Release History

^ Slider Textbox

State

gradio.State(•••)

Description

A base class for defining m e t h o d s that all input/output c o m p o n e n t s should have.

Behavior

As input com ponent: Passes a value of arbitrary type through.

Your function should accept one of these types:

d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (

v a l u e : Any
)

As output com ponent: Expects a value of arbitrary type, as long as it can be

deepcopied.

Your function should return one of these types:

d e f p r e d ic t ( " 0 -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( " 0 -> Any

re t u r n v a lu e

InitiaMzation

Parameter Description

value the initial value (of arbitrary type) of the state. The

Any provided argument is deepcopied. Ifa callable is

default: None provided, the function will be called whenever the

app loads to set the initial value of the state.

render has no effect, but is included for consistency with

bool other components.

default: True

t i m e to live The number of seconds the state should be stored

in t |flo a t |N o n e for after it is created or updated. IfNone, the state

default: None will be stored indefinitely. Gradio automatically

deletes state variables after a user closes the

browser tab or refreshes the page, so this is useful


Parameter Description

for clearing state for potentially long running

sessions.

delete_callback A function that is called when the state is deleted.

C a lla b le [[A n y ], N o n e ] |N o n e The function should take the state value as an

default: None argument.

^ S lid e r T extbox

Status

$ gradio X o
Custom Com ponents G allery NEW Explore

0 , gradio
New to Gradio? Start here: G etting Started See the Release History

C o lu m n G ro u p

Tab

with gradio.Tab():

Description
Tab (or its a lia s T abItem ) is a la y o u t e le m e n t. C o m p o n e n ts d e fin e d w ith in th e Tab

w ill be v is ib le w h e n th is ta b is s e le c te d tab .

Exampíe Usage

with gr.Blocks() as demo: cP

with gr.Tab("Lion"):

gr.Image("lion.jpg")

gr.Button("New Lion")

with gr.Tab("Tiger"):

gr.Image("tiger.jpg")

gr.Button("New Tiger")

Initiaíization
Param eter D escription

la b e l The visual label for the tab

str | None

default: None
Param eter D escription

v is ib le If False, Tab w ill be hidden.

bool

default: True

in t e r a c t iv e If False, Tab w ill not be clickable.

bool

default: True

id An optional identifier for the tab, required if you

int |str | None wish to control the selected tab from a predict

default: None function.

e le m _ id An optional string that is assigned as the id of the

str 1None <div> containing the contents of the Tab layout.

default: None The same string follow ed by "-button" is attached

to the Tab button. Can be used for targeting CSS

styles.

e l e m _ c la s s e s An optional string or list of strings that are

list[str] 1str 1None assigned as the class of this com ponent in the

default: None HTML DOM. Can be used for targeting CSS styles.

re n d e r If False, this layout w ill not be rendered in the

bool Blocks context. Should be used if the intention is to

default: True assign event listeners now but render the

com ponent later.

Methods
select

gradio.Tab.select(•••)

Description
E v e n t lis te n e r fo r w h e n th e u se r s e le c ts o r d e s e le c ts th e Tab. U se s e v e n t

d a ta g ra d io .S e le c tD a ta to c a rry v a lu e re fe rrin g to th e la b e l o f th e Tab, an d

s e le c t e d to refer to sta te o f th e Tab. S e e E v e n tD a ta d o c u m e n ta tio n on

h o w to use th is e v e n t d ata

Agruments
Param eter D escription

fn the function to call when this event is

Callable | None | triggered. Often a machine learning m odel's

Literal['decorator'] prediction function. Each parameter of the

default: "decorator" function corresponds to one input

com ponent, and the function should return a

single value or a tuple of values, with each

elem ent in the tuple corresponding to one

output component.

in p u t s List of gradio.com ponents to use as inputs. If

Component | list[Component] | the function takes no inputs, this should be an

set[Component] | None em pty list.

default: None

o u tp u ts List of gradio.com ponents to use as outputs. If

Component | list[Component] | the function returns no outputs, this should be

None an empty list.

default: None
Param eter D escription

a p i_ n a m e defines how the endpoint appears in the API

str | None | Literal[False] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . l o a d this app) w ill

not be able to use this event.

s c r o ll_ t o _ o u t p u t If True, w ill scroll to output com ponent on

bool com pletion

default: False

sh o w _ p ro g re ss If True, w ill show progress anim ation w hile

L¡teral[('full', 'minimal', pending

'hidden')]

default: "fu ll"

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

b a tc h If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). The function is


Param eter D escription

then required to return a tupie of lists (even if

there is only 1 output component), with each

list in the tupie corresponding to one output

component.

m a x _ b a t c h _ s iz e Maximum num ber of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

p re p ro ce ss If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

p o s tp ro c e s s If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

c a n c e ls A list of other events to cancel when this

dict[str, Any] | list[dict[str, listener is triggered. For example, setting

Any]] 1None cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another com ponents .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running w ill be

allowed to finish.

e v e ry Run this event 'every' num ber of seconds

float 1None w hile the client connection is open.


Param eter D escription

default: None Interpreted in seconds.

t r ig g e r _ m o d e If "once" (default for all events except

L¡teral[('once', 'múltiple', . c h a n g e ( ) ) would not allow any subm issions

'a lw a y sjast')] | None w hile an event is pending. If set to "multiple",

default: None unlim ited subm issions are allowed while

pending, and "always_last" (default for

.c h a n g e ( ) and .k e y _ u p ( ) events) would

allow a second subm ission after the pending

event is complete.

js Optional frontend js method to run before

str 1None running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

c o n c u r r e n c y _ lim it If set, this is the maximum num ber of this

int 1None | Literal['default'] event that can be running simultaneously. Can

default: "d efault" be set to None to mean no concurrency_lim it

(any num ber of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

c o n c u r r e n c y _ id If set, this is the id of the concurrency group.

str 1None Events with the same concurrency_id w ill be

default: None lim ited by the lowest set concurrency_lim it.


Param eter D escription

show _api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting

api_nam e to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api w ill

autom atically be set to False.

Guides

Controlling Layout

^ C o lu m n G ro u p

^ gradio Status O
Custom Com ponents G a lle ry NEW Explore

gradio =

New to Gradio? Start here: G etting Started See the Release History

^ C h a tIn te rfa c e B lo c k s

TabbedInterface

gradio.TabbedInterface(interface_list, •••)

Description
A T a b b e d In te rfa c e is cre a te d b y p ro v id in g a lis t o f In terface s o r B lo c k s , each o f

w h ic h gets re n d e re d in a se p a ra te tab . O n ly th e c o m p o n e n ts fro m th e

In te rfa c e /B lo c k s w ill be re n d e re d in th e tab . C e rta in h ig h -le v e l a ttrib u te s o f th e

B lo c k s (e.g. c u s to m c s s , j s , a n d head a ttrib u te s) w ill n o t be lo a d e d .

Initialization
Param eter D escription

in t e r f a c e _ lis t A list of Interfaces (or Blocks) to be rendered in the

list[Interface] tabs.

required

ta b _ n a m e s A list of tab names. If None, the tab names w ill be

list[str] | None "Tab 1", "Tab 2", etc.

default: None

t it le The tab title to display when this dem o is opened

str I None in a browser window.

default: None
Param eter D escription

theme A Theme object or a string representing a theme. If

Theme |str | None a string, w ill look for a built-in theme with that

default: None name (e.g. "soft" or "default"), or w ill attempt to

load a theme from the Hugging Face Hub (e.g.

"gradio/m onochrom e"). If None, w ill use the

Default theme.

analytics_enabled W hether to allow basic telemetry. If None, w ill use

bool I None GRADIO_ANALYTICS_ENABLED environm ent

default: None variable or default to True.

css Custom css as a string or path to a css file. This css

str I None w ill be included in the demo webpage.

default: None

js Custom js as a string or path to a js file. The custom

str I None js should in the form of a single js function. This

default: None function w ill autom atically be executed when the

page loads. For more flexibility, use the head

parameter to insert js inside <script> tags.

head Custom html to insert into the head of the demo

str I None webpage. This can be used to add custom meta

default: None tags, m ultiple scripts, stylesheets, etc. to the page.

Demos

tabbed_interface_lite
import gradio as gr

hello_world = gr.Interface(lambda name: "Helio " + name, "text", "text")

bye_world = gr.Interface(lambda name: ''Bye " + name, "text", "text")

demo = gr.TabbedInterface([hello_world, bye_world], ["Hello World", "Bye Worl

d"])

if __name__ == "__main

demo.launch()

Loading...

g r a d io / t a b b e d _ in t e r fa c e _ lit e built with Gradio. Hosted on EE Spaces

C h a tIn te rfa ce B lo c k s

<§, gradio Status JC


Custom Com ponents G alleryNEW E xp lore

$ gradio

N e w to Gradio? Start here: Getting Started See the Release History

State UploadButton

Textbox

gradio.Textbox(•••)

Loading...

g r a d io / t e x t b o x _ c o m p o n e n t b u ilt w ith G ra d io . H o s te d o n Spaces

Description &

Creates a textarea for user to enter string input or display string output.
Behavior

As input com ponent: P asses te x t v a lu e as a s t r in to th e fu n c tio n .

Your function should accept one of these types:

d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (

v a lu e : s t r | None

As output com ponent: Exp ects a s t r re tu rn e d fro m fu n c tio n and se ts textarea

v a lu e to it.

Your function should return one of these types:

d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( ^ " ) -> s t r | None

re t u r n v a lu e

InitiaMzation

Parameter Description

value default text to provide in textarea. Ifcallable, the

str |C a lla b le |N o n e function will be called whenever the app loads to

default: None set the initial value of the component.


Parameter Description

lin e s mínimum number of line rows to provide in

int textarea.

default: 1

m a x _ lin e s máximum number of line rows to provide in

int textarea.

default: 20

p la c e h o ld e r placeholder hint to provide behind textarea.

str |None

default: None

la b e l The label for this component. Appears above the

str |None com ponent and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r . I n t e r f a c e , the label w ill be the

name of the parameter this com ponent is assigned

to.

in f o additional com ponent description.

str 1None

default: None

e v e ry If v a lu e is a callable, run the function 'every'

float 1None number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.
Parameter Description

show_label ifTrue, will display label. IfFalse, the copy button

bool |N o n e is hidden as well as well as the label.

default: None

container IfTrue, will place the component in a container -

bool providing some extra padding around the border.

default: True

scale relative size compared to adjacent Components.

in t 1N o n e For example ifComponents A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A will be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

min_width minimum pixel width, will wrap ifnot sufficient

in t screen space to satisfy this value. Ifa certain scale

default: 160 value results in this Component being narrower

than min_width, the min_width parameter will be

respected first.

interactive ifTrue, will be rendered as an editable textbox; if

b o o l |N o n e False, editing will be disabled. Ifnot provided, this

default: None is inferred based on whether the component is

used as an input or output.

visible IfFalse, component will be hidden.

bool

default: True
Parameter Description

elem_id An optional string that is assigned as the id of this

str |N o n e component in the H T M L DOM. Can be used for

default: None targeting CSS styles.

autofocus IfTrue, will focus on the textbox when the page

bool loads. Use this carefully, as itcan cause usability

default: False issues for sighted and non-sighted users.

autoscroll IfTrue, will automatically scroll to the bottom of

bool the textbox when the value changes, unless the

default: True user scrolls up. IfFalse, will not scroll to the

bottom of the textbox when the value changes.

elem_classes An optional list of strings that are assigned as the

list[str] 1s t r 1N o n e classes of this component in the H T M L DOM. Can

default: None be used for targeting CSS styles.

render IfFalse, component will not render be rendered in

bool the Blocks context. Should be used ifthe intention

default: True is to assign event listeners n o w but render the

component later.

type The type of textbox. One of: 'text', 'password',

L ite ra l[(’t e x t’, ’p a s s w o r d ’, 'email', Default is 'text'.

'em a il')]

default: "text"

text_align H o w to align the text in the textbox, can be: "left",

L ite ra l[('le ft, 'righ t')] |N o n e "right", or None (default). If None, the alignment is

default: None
Parameter Description

left if r t l is False, or right if r t l is True. Can only

be changed if t y p e is "text".

rtl If True and t y p e is "text", sets the direction of the

bool text to right-to-left (cursor appears on the left of

default: False the text). Default is False, which renders cursor on

the right.

show_copy_button If True, includes a copy button to copy the text in

bool the textbox. Only applies if show_label is True.

default: False

Shortcuts

Interface String
Class Initialization
Shortcut

gradio.Textbox "textbox" Uses default values

gradio.TextArea "textarea" Uses lines=7

Demos

hello_world d¡ff_texts sentence_builder

import gradio as gr

def greet(name):

return "Helio " + name + "!


demo = gr.Interface(fn=greet, inputs="textbox", outputs="textbox")

if name == " main

demo.launch()

Loading...

g r a d i o / h e l l o _ w o r l d b u ilt w ith G ra d io . H o s te d o n Spaces

Event Listeners

Description
Event listeners allow you to capture and respond to user interactions with

the UI c o m p o n e n t s you've defined in a Gradio Blocks app. W h e n a user


interacts with an element, such as changing a slider value or uploading an

image, a function is called.

Supported Event Listeners


T h e T e x t b o x c o m p o n e n t supports the following event listeners. Each

event listener takes the s a m e parameters, which are listed in the Event

Arguments table below.


Listener Description

gradio.Textbox.change(f Triggered when the value of the Textbox


n, •••) changes either because of user input (e.g. a
user types in a textbox) OR because of a
function update (e.g. an image receives a value
from the output of an event trigger). See
. in p u t ( ) for a listener that is only triggered
by user input.

gradio.Textbox.input(fn This listener is triggered when the user


, •••) changes the value of the Textbox.

gradio.Textbox.select(f Event listener for when the user selects or


n, •••) deselects the Textbox. Uses event data
gradio.SelectData to carry v a lu e referring to
the label of the Textbox, and s e le c t e d to
refer to state of the Textbox. See EventData
documentation on how to use this event data

gradio.Textbox.submit(f This listener is triggered when the user presses


n, •••) the Enter key while the Textbox is focused.

gradio.Textbox.focus(fn This listener is triggered when the Textbox is


, •••) focused.

gradio.Textbox.blur(fn, This listener is triggered when the Textbox is


•••) unfocused/blurred.

Event Arguments
Parameter Description

fn the function to call when this event is

Callable |None | triggered. Often a machine learning model's

Litem l[’decom tor’] prediction function. Each parameter of the

default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tuple of values, with each


Parameter Description

element in the tupie corresponding to one

output component.

inputs List of gradio.components to use as inputs. If

C o m p o n e n t |lis t[ C o m p o n e n t] | the function takes no inputs, this should be an

s e t[C o m p o n e n t] |N o n e empty list.

default: None

outputs List of gradio.components to use as outputs. If

Com ponent |lis t[ C o m p o n e n t] | the function returns no outputs, this should be

None an empty list.

default: None

api_name defines how the endpoint appears in the API

s t r |N o n e |L ite ra l[F a ls e ] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

scroll_to_output If True, w ill scroll to output com ponent on

bool completion

default: False

show_progress If True, w ill show progress animation while

L ite ra l[(’f u ll’, ’m in im a l’, pending

’h id d e n ’)]

default: "fu ll
Parameter Description

queue If True, w ill place the request on the queue, if

bool | None the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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 Maximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this

listener is triggered. For example, setting


Parameter Description

dict[str, A n y ] |list[dict[str, cancels=[click_event] w ill cancel the

A ny]] 1N o n e click_event, where click_event is the return

default: None value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

flo a t 1N o n e while the client connection is open.

default: None Interpreted in seconds.

trigger_mode If "once" (default for all events except

L ite ra l[(’o n c e ’, 'm ú lt ip le , .c h a n g e ( ) ) would not allow any submissions

’a l w a y s j a s t ’)] |N o n e while an event is pending. If set to "multiple",


default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before

s t r |N o n e running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

concurrency_limit If set, this is the maximum number of this

in t 1N o n e |L ite ra l['d e fa u lt'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the


Parameter Description

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.


str |N o n e Events with the same concurrency_id w ill be

default: None limited by the lowest set co ncurrencyjim it.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"


default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

w ill still allow downstream apps to use this

event. If fn is None, show_api will

autom atically be set to False.

Guides

Real Time Speech Recognition

State UploadButton

Status

$ gradio xO
Custom Com ponents G alleryNEW E xp lore

0 gradio

New to Gradio? Start here: Getting Started See the Release History

^ F la g g in g NO RELO AD ^

Themes

Description

C u sto m iz e th e lo o k o f y o u r a p p by w ritin g y o u r o w n cu sto m th e m e

Base

gradio.Base(•••)

InitiaMzation
Parameter Description

primary_hue The primary hue of the theme. Load a preset, like

c o lo r s .C o lo r |s t r gradio.themes.colors.green (or just the string

default: Color() "green"), or pass your own

gradio.themes.utils.Color object.

secondary_hue The secondary hue of the theme. Load a preset,

c o lo r s .C o lo r |s t r like gradio.themes.colors.green (or just the string

default: Color() "green"), or pass your own

gradio.themes.utils.Color object.

neutral_hue The neutral hue of the theme, used .Load a preset,

c o lo r s .C o lo r |s t r like gradio.themes.colors.green (or just the string

default: Color() "green"), or pass your own

gradio.themes.utils.Color object.

text_size The size of the text. Load a preset, like

s iz e s.S iz e |s t r gradio.themes.sizes.text_sm (or just the string

default: Size() "sm"), or pass your o w n gradio.themes.utils.Size

object.

spacing_size The size of the spacing. Load a preset, like

s iz e s.S iz e |s t r gradio.themes.sizes.spacing_sm (orjust the string

default: Size() "sm"), or pass your o w n gradio.themes.utils.Size

object.

radius_size The radius size of corners. Load a preset, like

s iz e s.S iz e |s t r gradio.themes.sizes.radius_sm (orjust the string

default: Size() "sm"), or pass your o w n gradio.themes.utils.Size

object.
Parameter Description

font The primary font to use for the theme. Pass a string

fo n ts .F o n t |s t r | for a system font, or a

Ite ra b le [fo n ts .F o n t |str] gradio.themes.font.GoogleFont object to load a

default: font from Google Fonts. Pass a list of fonts for

(<gradio.themes.utils.fonts.Goo fallbacks.

gleFont (name='Source Sans

Pro', weights=(400, 600))>, 'ui-

sans-serif', 'system-ui', 'sans-

serif')

font_mono The monospace font to use for the theme, applies

fo n ts .F o n t 1s t r | to code. Pass a string for a system font, or a

Ite ra b le [fo n ts .F o n t |str] gradio.themes.font.GoogleFont object to load a

default: font from Google Fonts. Pass a list of fonts for

(<gradio.themes.utils.fonts.Goo fallbacks.

gleFont (name='IBM Plex

Mono', weights=(400, 600))>,

'ui-monospace', 'Consolas',

'm onospace')

Methods

Methods

push_to_hub
gradio.Base.push_to_hub(repo_name, •••)

Description

Upload a t h e m e to the HuggingFace hub. <br> This requires a HuggingFace

account. <br>

Agruments

Parameter Description

repo_name The na m e of the repository to store the theme

str assets, e.g. 'my_theme' or 'sunset'.

required

org_name The na m e of the org to save the space in. If

str |N o n e None (the default), the username

default: None corresponding to the logged in user, or

h/_token is used.

versión A semantic version tag for theme. Bumping

s t r |N o n e the version tag lets you publish updates to a

default: None theme without changing the look of

applications that already loaded your theme.

hf_token API token for your HuggingFace account

s t r 1N o n e

default: None
Parameter Description

theme_name N a m e for the name. IfNone, defaults to

str |N o n e repo_name

default: None

description A long form description to your theme.

s t r 1N o n e

default: None

prívate

bool

default: False

from hub

gradio.Base.from_hub(repo_name, •••)

Description

Load a t h e m e from the hub. <br> This D O E S N O T require a HuggingFace

account for downloading publicly available themes. <br>

Agruments
Parameter Description

repo_name string of the form <author>/<theme-

str name>@<semantic-version-expression>. Ifa

r e q u ir e d semantic versión expression is omitted, the

latest versión will be fetched.

hf_token HuggingFace Token. Only needed to download

str |N o n e private themes.

default: None

load

gradio.Base.load(path, •••)

Description

Load a t h e m e from a json file. <br>

Agruments

Parameter Description

path The filepath to read

str

r e q u ir e d
dump

gradio.Base.dumpfilename, •••)

Description

Write the t h e m e to a json file. <br>

Agruments

Parameter Description

filename The path to write the theme too

str

r e q u ir e d

from dict

gradio.Base.from_dict(theme, •••)

Description
Create a t h e m e instance from a dictionary representation. <br>

Agruments

Param eter Description

theme The dictionary representation of the theme.

dict[str, dict[str, str]]

r e q u ir e d

to dict

gradio.Base.to_dict(•••)

Description

Convert the t h e m e into a python dictionary.

Flagging N O RELOAD ^

Status

$ gradio X o
Custom Com ponents G alleryNEW E xp lore

$ gradio

N e w to Gradio? Start here: Getting Started See the Release History

^ Textbox Video

UploadButton

gradio.UploadButton(•••)

Loading...

g r a d io / u p l o a d b u t t o n _ c o m p o n e n t b u ilt w ith G ra d io . H o s te d o n Spaces

Description &

Used to create an upload button, w h e n clicked allows a user to upload files that

satisfy the specified file type or generic files (if file_type not set).
Behavior

As input c o m p o n e n t : P asses th e file as a s t r o r b y te s o b je ct, o r a lis t o f s t r o r list

o f b y te s o b je cts, d e p e n d in g on ty p e an d f i l e _ c o u n t .

Your function should accept one of these types:

d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (

v a l u e : b yte s | str | l i s t [ b y te s] | lis t [str] | None

As output c o m p o n e n t : Exp ects a s t r file p a th o r URL, o r a l i s t [ s t r ] o f

file p a th s /U R L s.

Your function should return one of these types:

d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( ^ " ) -> s t r | lis t [s tr] | None

re t u r n v a lu e

InitiaMzation

Parameter Description

label Text to display on the button. Defaults to "Upload a

str File".

default: "Upload a File M


Parameter Description

v a lu e File or list of files to upload by default.

s t r |list[str] |C a lla b le |N o n e

default: None

e v e ry If v a lu e is a callable, run the function 'every'

flo a t 1N o n e number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

v a r ia n t 'primary' for main call-to-action, 'secondary' for a

L ite ra l[( ’p r im a r y ’, ’s e c o n d a r y ’, more subdued style, 'stop' for a stop button.

'stop')]

default: "secondary"

v is ib le If False, com ponent w ill be hidden.

bool

default: True

s iz e Size of the button. Can be "sm" or "lg".

L ite ra l[('s m , 'lg')] |N o n e

default: None

ic o n URL or path to the icon file to display within the

s t r |N o n e button. If None, no icon w ill be displayed.

default: None

s c a le relative size compared to adjacent Components.

in t |N o n e For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A w ill be

twice as wide as B. Should be an integer. scale


Parameter Description

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

min_width mínimum pixel width, will wrap ifnot sufficient

in t |N o n e screen space to satisfy this value. Ifa certain scale

default: None value results in this Component being narrower

than min_width, the min_width parameter will be

respected first.

interactive IfFalse, the UploadButton will be in a disabled

bool state.

default: True

elem_id An optional string that is assigned as the id of this

s t r IN o n e component in the H T M L DOM. Can be used for

default: None targeting CSS styles.

elem_classes An optional list of strings that are assigned as the

list[str] Is t r I N o n e classes of this component in the H T M L DOM. Can

default: None be used for targeting CSS styles.

render IfFalse, component will not render be rendered in

bool the Blocks context. Should be used ifthe intention

default: True is to assign event listeners n o w but render the

component later.

type Type of value to be returned by component. "file"

L ite ra l[('fíle p a th ', ’b ytes')] returns a temporary file object with the same base

default: "filepath" n a m e as the uploaded file, whose full path can be

retrieved by file_obj.name, "binary" returns an

bytes object.
Parameter Description

file_count ifsingle, allows user to upload one file. If

L ite ra l[('sin g le ', 'm ú lt ip le 1


, "múltiple", user uploads múltiple files. If

’d ir e c t o r y ’)] "directory", user uploads all files in selected

default: "single" directory. Return type will be listfor each file in

case of "multiple" or "directory".

file_types List of type of files to be uploaded. "file" allows any

list[str] |N o n e file to be uploaded, "image" allows only image

default: None 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.

Shortcuts

Interface String
Class Initialization
Shortcut

gradio.UploadButton "uploadbutton" Uses default values

Demos

upload_and_download upload_button

from pathlib import Path

import gradio as gr

def upload_file(filepath):
name = Path(filepath).name

return [gr.UploadButton(visible=False), gr.DownloadButton(label=f"Downl

oad {name}", value=filepath, visible=True)]

def download_file():

return [gr.UploadButton(visible=T rue), gr.DownloadButton(visible=Fals

e)]

<6

Loading...

g r a d io / u p lo a d _ a n d _ d o w n lo a d b u ilt w ith G ra d io . H o s te d o n Spaces

Event Listeners

Description
Event listeners allow you to capture and respond to user interactions with

the UI c o m p o n e n t s you've defined in a Gradio Blocks app. W h e n a user


interacts with an element, such as changing a slider value or uploading an

image, a function is called.

Supported Event Listeners


T h e U p l o a d B u t t o n c o m p o n e n t supports the following event listeners.

Each event listener takes the s a m e parameters, which are listed in the

Event Arguments table below.


Listener Description

gradio.UploadButton.cli Triggered when the UploadButton is clicked.


ck(fn, •••)

gradio.UploadButton.upl This listener is triggered when the user


oad(fn, •••) uploads a file into the UploadButton.

Event Arguments
Parameter Description

fn the function to call when this event is

C a lla b le |N o n e | triggered. Often a machine learning model's

L ite r a l['d e c o r a to r'] prediction function. Each parameter of the

default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tuple of values, with each

element in the tuple corresponding to one

output component.

inputs List of gradio.components to use as inputs. If

Com ponent |lis t[ C o m p o n e n t] | the function takes no inputs, this should be an

s e t[C o m p o n e n t] |N o n e empty list.

default: None

outputs List of gradio.components to use as outputs. If

C o m p o n e n t |lis t[ C o m p o n e n t] | the function returns no outputs, this should be

None an empty list.

default: None

api_name defines h o w the endpoint appears in the API

s t r |N o n e |L ite ra l[F a ls e ] docs. Can be a string, None, or False. Ifset to a

default: None string, the endpoint will be exposed in the API


Parameter Description

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

scroll_to_output If True, w ill scroll to output com ponent on

bool completion

default: False

show_progress If True, w ill show progress animation while

Literal[('fuW , ’m in im a l’, pending

’h id d e n ’)]

default: "fu ll"

queue If True, w ill place the request on the queue, if

bool |N o n e the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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.
Parameter Description

max_batch_size Máximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this

dict[str, Any] | list[dict[str, listener is triggered. For example, setting

Any]] 1None cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

float 1None while the client connection is open.

default: None Interpreted in seconds.


Parameter Description

trigger_mode If "once" (default for all events except

L iteral[('o n ce', '


m ú lt ip le ' .c h a n g e ( ) ) would not allow any submissions

’a l w a y s j a s t ’)] |N o n e while an event is pending. If set to "múltiple",

default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before

s t r 1N o n e running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

concurrency_limit If set, this is the maximum number of this

in t 1N o n e |L ite ra l['d e fa u lt'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).

concurrency_id If set, this is the id of the concurrency group.

s t r 1N o n e Events with the same concurrency_id w ill be

default: None limited by the lowest set concurrency_limit.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting


Parameter Description

api_name to False, setting show_api to False

will still allow downstream apps to use this

event. Iffn is None, show_api will

automatically be set to False.

Textbox Video

Status

^ gradio o
Custom Com ponents G alleryNEW E xp lore

$ gradio

N e w to Gradio? Start here: Getting Started See the Release History

UploadButton load

Video

gradio.Video(•••)

Loading...

g r a d io / v id e o _ c o m p o n e n t b u ilt w ith G ra d io . H o s te d o n Spaces

Description &

Creates a video c o m p o n e n t 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 m u s t have a compatible container and codec combination. Allowed

combinations are . m p 4 with h264 codec, .ogg with theora codec, and . w e b m with
vp 9 co d e c. If th e c o m p o n e n t d e te cts th a t th e o u tp u t v id e o w o u ld n o t be p la y a b le

in th e b ro w s e r it w ill a tte m p t to c o n v e rt it to a p la y a b le m p 4 v id e o . If th e

c o n v e rs io n fails, th e o rig in a l v id e o is retu rn e d .

Behavior

As input c o m p o n e n t : P asses th e u p lo a d e d v id e o as a s t r file p a th o r U R L w h o se

e xte n sio n can be m o d ifie d by f o r m a t .

Your function should accept one of these types:

d e f p r e d ic t (

v a l u e : pd. DataFrame | np. n d a rra y | p l . DataFrame | lis t [lis t ]

. . . d e f p r e d ic t (

v a lu e : s t r | None

As output c o m p o n e n t : Exp ects a s t r o r p a t h lib . P a t h file p a th to a v id e o w h ic h is

d is p la y e d , o r a T u p le [ s t r | p a t h l ib . P a t h , s tr | p a t h lib . P a t h | None]

w h e re th e firs t e le m e n t is a file p a th to a v id e o and th e se co n d e le m e n t is an

o p tio n a l file p a th to a s u b title file.

Your function should return one of these types:

d e f p r e d ic t ( ^ " ) -> pd. DataFrame | S t y le r | np. n d a rra y | p l . DataFrame | lis t | lis t [lis t ] |

d ic t | s tr | None

re t u r n v a lu e d e f p r e d ic t ( " 0 -> s t r | Pa th | tu p le [ s t r | P a th , s t r | Pa th | None] | None

re t u r n v a lu e

InitiaMzation
Parameter Description

value A path or URL for the default value that Video

s t r |P a th |tu p le [s tr |P a th , s t r | com ponent is going to take. Can also be a tupie

P a th |N o n e ] |C a lla b le |N o n e consisting of (video filepath, subtitle filepath). If a

default: None subtitle file is provided, it should be of type .srt or

.vtt. Or can be callable, in which case the function

w ill be called whenever the app loads to set the

initial value of the component.

format Format of video format to be returned by

s t r |N o n e component, such as 'avi' or 'mp4'. Use 'mp4' to

default: None ensure browser playability. If set to None, video

w ill keep uploaded format.

sources A list of sources permitted for video. "upload"

list[L ite ra l[(’u p lo a d ’, ’w e b c a m ’)]] creates a box where user can drop an video file,

|N o n e "webcam" allows user to record a video from their

default: None webcam. If None, defaults to ["upload, "webcam"].

height The height of the displayed video, specified in

in t |s t r |N o n e pixels if a number is passed, or in CSS units if a

default: None string is passed.

width The width of the displayed video, specified in

in t |s t r |N o n e pixels if a number is passed, or in CSS units if a

default: None string is passed.

lab e l The label for this component. Appears above the

s t r |N o n e com ponent and is also used as the header if there

default: None are a table of examples for this component. If None

and used in a g r . I n t e r f a c e , the label w ill be the


Parameter Description

name of the parameter this com ponent is assigned

to.

e v e ry If v a lu e is a callable, run the function 'every'

float |None number of seconds while the client connection is

default: None open. Has no effect otherwise. The event can be

accessed (e.g. to cancel it) via this component's

.load_event attribute.

s h o w _ la b e l if True, w ill display label.

bool 1None

default: None

c o n t a in e r If True, w ill place the com ponent in a container -

bool providing some extra padding around the border.

default: True

s c a le relative size compared to adjacent Components.

int 1None For example if Components A and B are in a Row,

default: None and A has scale=2, and B has scale=1, A w ill be

twice as wide as B. Should be an integer. scale

applies in Rows, and to top-level Components in

Blocks where fill_height=True.

m in _ w id t h minimum pixel width, w ill wrap if not sufficient

int screen space to satisfy this value. If a certain scale

default: 160 value results in this Com ponent being narrower

than min_width, the min_width parameter w ill be

respected first.
Parameter Description

interactive ifTrue, will allow users to upload a video; ifFalse,

bool |N o n e can only be used to display videos. Ifnot provided,

default: None this is inferred based on whether the component is

used as an input or output.

visible IfFalse, component will be hidden.

bool

default: True

elem_id An optional string that is assigned as the id of this

s t r 1N o n e component in the H T M L DOM. Can be used for

default: None targeting CSS styles.

elem_classes An optional list of strings that are assigned as the

list[str] 1s t r 1N o n e classes of this component in the H T M L DOM. Can

default: None be used for targeting CSS styles.

render IfFalse, component will not render be rendered in

bool the Blocks context. Should be used ifthe intention

default: True is to assign event listeners n o w but render the

component later.

mirror_webcam IfTrue w e b c a m will be mirrored. Default is True.

bool

default: True

include_audio Whether the component should record/retain the

b o o l |N o n e audio track for a video. By default, audio is

default: None excluded for w e b c a m videos and included for

uploaded videos.
Parameter Description

autoplay Whether to automatically play the video when the

bool component is used as an output. Note: browsers

default: False will not autoplay video files ifthe user has not

interacted with the page yet.

show_share_button IfTrue, will show a share icon in the corner of the

bool |N o n e component that allows user to share outputs to

default: None Hugging Face Spaces Discussions. If False, icon

does not appear. Ifset to None (default behavior),

then the icon appears ifthis Gradio app is

launched on Spaces, but not otherwise.

show_download_button IfTrue, will show a download icon in the corner of

b o o l |N o n e the component that allows user to download the

default: None output. IfFalse, icon does not appear. By default, it

will be True for output components and False for

input components.

min_length The minimum length of video (in seconds) that the

in t 1N o n e user can pass into the prediction function. If None,

default: None there is no minimum length.

max_length The m a x i m u m length of video (in seconds) that the

in t 1N o n e user can pass into the prediction function. If None,

default: None there is no m a x i m u m length.

Shortcuts
Interface String
Class Initialization
Shortcut

gradio.Video "video" Uses default values

g r a d i o .P l a y a b l e V i d e o "playablevideo" Uses format="mp4"

Demos

video_identity_2

import gradio as gr

def video_identity(video) :

return video

demo = gr.Interface(video_identity,

gr.Video(),

"playable_video",

Loading...

g r a d i o / v i d e o _ i d e n t i t y _ 2 b u ilt w ith G ra d io . H o s te d o n Spaces


Event Listeners

Description
Event listeners allow you to capture and respond to user interactions with

the UI c o m p o n e n t s you've defined in a Gradio Blocks app. W h e n a user


interacts with an element, such as changing a slider value or uploading an

image, a function is called.

Supported Event Listeners


T h e V i d e o c o m p o n e n t supports the following event listeners. Each event

listener takes the s a m e parameters, which are listed in the Event Arguments

table below.

Listener Description

g r a d io . V id e o . c h a n g e ( f n , Triggered when the value of the Video changes


•••) either because of user input (e.g. a user types
in a textbox) O R because of a function update
(e.g. an image receives a value from the output
of an event trigger). See . in p u t ( ) for a
listener that is only triggered by user input.

g r a d io . V id e o . c le a r ( f n , This listener is triggered when the user clears


•••) the Video using the X button for the
component.

g r a d io . V id e o . s t a r t _ r e c o This listener is triggered when the user starts


r d in g ( f n , •••) recording with the Video.

g r a d io . V id e o . s t o p _ r e c o r This listener is triggered when the user stops


d in g ( f n , •••) recording with the Video.

g r a d io . V id e o . s t o p ( f n , This listener is triggered when the user


•••) reaches the end of the media playing in the
Video.
Listener Description

gradio.Video.play(fn, This listener is triggered when the user plays


•••) the media in the Video.

gradio.Video.pause(fn, This listener is triggered when the media in the


•••) Video stops for any reason.

gradio.Video.end(fn, This listener is triggered when the user


•••) reaches the end of the media playing in the
Video.

gradio.Video.upload(fn, This listener is triggered when the user


•••) uploads a file into the Video.

Event Arguments
Parameter Description

fn the function to call when this event is

C a lla b le |N o n e | triggered. Often a machine learning model's

L it e m l[ ’d e c o m t o r ’] prediction function. Each parameter of the

default: "decorator" function corresponds to one input

component, and the function should return a

single value or a tuple of values, with each

element in the tuple corresponding to one

output component.

inputs List of gradio.components to use as inputs. If

Com ponent |lis t[ C o m p o n e n t] | the function takes no inputs, this should be an

s e t[C o m p o n e n t] |N o n e empty list.

default: None
Parameter Description

o u tp u ts List of gradio.components to use as outputs. If

Com ponent |lis t[ C o m p o n e n t] | the function returns no outputs, this should be

None an empty list.

default: None

api_nam e defines how the endpoint appears in the API

s t r 1N o n e |L ite ra l[F a ls e ] docs. Can be a string, None, or False. If set to a

default: None string, the endpoint w ill be exposed in the API

docs with the given name. If None (default),

the name of the function w ill be used as the

API endpoint. If False, the endpoint w ill not be

exposed in the API docs and downstream apps

(including those that g r . lo a d this app) will

not be able to use this event.

s c r o ll_ t o _ o u t p u t If True, w ill scroll to output com ponent on

bool completion

default: False

sh o w _ p ro g re ss If True, w ill show progress animation while

L ite ra l[(’f u ll’, ’m in im a l’, pending


’h id d e n ’)]

default: "fu ll"

queue If True, w ill place the request on the queue, if

b o o l |N o n e the queue has been enabled. If False, w ill not

default: None put this event on the queue, even if the queue

has been enabled. If None, w ill use the queue

setting of the gradio app.


Parameter Description

batch If True, then the function should process a

bool batch of inputs, meaning that it should accept

default: False a list of input values for each parameter. The

lists should be of equal length (and be up to

length m a x _ b a tc h _ s iz e ). 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 Maximum number of inputs to batch together

int if this is called from the queue (only relevant if

default: 4 batch=True)

preprocess If False, w ill not run preprocessing of

bool com ponent data before running 'fn' (e.g.

default: True leaving it as a base64 string if this method is

called with the Image component).

postprocess If False, w ill not run postprocessing of

bool com ponent data before returning 'fn' output

default: True to the browser.

cancels A list of other events to cancel when this

dict[str, Any] | list[dict[str, listener is triggered. For example, setting

Any]] 1None cancels=[click_event] w ill cancel the

default: None click_event, where click_event is the return

value of another components .click method.

Functions that have not yet run (or generators

that are iterating) w ill be cancelled, but


Parameter Description

functions that are currently running will be

allowed to finish.

every Run this event 'every' number of seconds

flo a t |N o n e while the client connection is open.

default: None Interpreted in seconds.

trigger_mode If "once" (default for all events except

L iteral[('o n ce', '


m ú lt ip le ' .c h a n g e ( ) ) would not allow any submissions

’a l w a y s j a s t ’)] |N o n e while an event is pending. If set to "multiple",


default: None unlimited submissions are allowed while

pending, and "always_last" (default for

.c h a n g e () and .k e y _ u p ( ) events) would

allow a second submission after the pending

event is complete.

js Optional frontend js method to run before


s t r 1N o n e running 'fn'. Input arguments for js method are

default: None values of 'inputs' and 'outputs', return should

be a list of values for output components.

concurrency_limit If set, this is the maximum number of this

in t 1N o n e |L ite ra l['d e fa u lt'] event that can be running simultaneously. Can

default: "default" be set to None to mean no concurrency_limit

(any number of this event can be running

simultaneously). Set to "default" to use the

default concurrency lim it (defined by the

d e f a u lt _ c o n c u r r e n c y _ lim it parameter in

B lo c k s . q u e u e ( ) , which itself is 1 by default).


Parameter Description

concurrency_id Ifset, this is the id of the concurrency group.

str |N o n e Events with the same concurrency_id will be

default: None limited by the lowest set concurrencyjimit.

show_api whether to show this event in the "view API"

bool page of the Gradio app, or in the ".view_apiO"

default: True method of the Gradio clients. Unlike setting

api_name to False, setting show_api to False

will still allow downstream apps to use this

event. Iffn is None, show_api will

automatically be set to False.

UploadButton load

Status

$ gradio O
Custom Com ponents G alleryNEW E xp lore

$ gradio

N e w to Gradio? Start here: Getting Started See the Release History

E rro r Info

Warning

gradio.Warning(•••)

Description

T h is fu n c tio n a llo w s you to p ass cu sto m w a rn in g m essa g e s to th e user. You can

d o so s im p ly by w ritin g g r.W a rn in g ( 'm e s s a g e h e r e ' ) in y o u r fu n c tio n , and

w h e n th a t lin e is exe cu te d th e cu sto m m e ssa g e w ill a p p e a r in a m o d a l on th e

d e m o . T he m o d a l is y e llo w by d e fa u lt an d has th e headin g: "W arning." Q u eu e

m u st be e n a b le d fo r th is b e h a v io r; o th e rw is e , th e w a rn in g w ill be p rin te d to th e

c o n s o le u sin g th e w a rn in g s lib ra ry.

Exampíe Usage &

import gradio as gr

def hello_world():

gr.Warning('This is a warning message.')

return "helio world


with gr.Blocks() as demo:

md = gr.Markdown()

demo.load(hello_world, inputs=None, outputs= [md])

demo.queue().launch()

InitiaMzation

Param eter Description

message The warning message to be displayed to the user.

str

default: "W arning issued."

Demos

blocks_chained_events


import gradio as gr

import time

I
def failure():

raise gr.Error("This should fail!")

def exception():

raise ValueError("Something went wrong")

def success():
Loading...

g r a d i o / b l o c k s _ c h a i n e d _ e v e n t s b u ilt w ith G ra d io . H o s te d o n Spaces

Error Info

Status

^ gradio o

You might also like