Introducing Gradio Clients
WatchIntroducing Gradio Clients
WatchNew to Gradio? Start here: Getting Started
See the Release History
with gradio.Blocks():
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()
theme: Theme | str | None
= None
A Theme object or a string representing a theme. If a string, will look for a built-in theme with that name (e.g. "soft" or "default"), or will attempt to load a theme from the Hugging Face Hub (e.g. "gradio/monochrome"). If None, will use the Default theme.
analytics_enabled: bool | None
= None
Whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable or default to True.
mode: str
= "blocks"
A human-friendly name for the kind of Blocks or Interface being created. Used internally for analytics.
title: str
= "Gradio"
The tab title to display when this is opened in a browser window.
css: str | Path | None
= None
Custom css as a code string or pathlib.Path to a css file. This css will be included in the demo webpage.
js: str | Path | None
= None
Custom js as a code string or pathlib.Path to a js file. The custom js should be in the form of a single js function. This function will automatically be executed when the page loads. For more flexibility, use the head parameter to insert js inside <script> tags.
head: str | Path | None
= None
Custom html to insert into the head of the demo webpage, either as a code string or a pathlib.Path to an html file. This can be used to add custom meta tags, multiple scripts, stylesheets, etc. to the page.
fill_height: bool
= False
Whether to vertically expand top-level child components to the height of the window. If True, expansion occurs when the scale value of the child components >= 1.
fill_width: bool
= False
Whether to horizontally expand to fill container fully. If False, centers and constrains app to a maximum width. Only applies if this is the outermost `Blocks` in your Gradio app.
delete_cache: tuple[int, int] | None
= None
A tuple corresponding [frequency, age] both expressed in number of seconds. Every `frequency` seconds, the temporary files created by this Blocks instance will be deleted if more than `age` seconds have passed since the file was created. For example, setting this to (86400, 86400) will delete temporary files every day. The cache will be deleted entirely when the server restarts. If None, no cache deletion will occur.
import gradio as gr
def welcome(name):
return f"Welcome to Gradio, {name}!"
with gr.Blocks() as demo:
gr.Markdown(
"""
# Hello World!
Start typing below to see the output.
""")
inp = gr.Textbox(placeholder="What is your name?")
out = gr.Textbox()
inp.change(welcome, inp, out)
if __name__ == "__main__":
demo.launch()
gradio.Blocks.launch(ยทยทยท)
Launches a simple web server that serves the demo. Can also be used to create a public link used by anyone to access the demo from their browser by setting share=True.
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"))
inline: bool | None
= None
whether to display in the gradio app inline in an iframe. Defaults to True in python notebooks; False otherwise.
inbrowser: bool
= False
whether to automatically launch the gradio app in a new tab on the default browser.
share: bool | None
= None
whether to create a publicly shareable link for the gradio app. Creates an SSH tunnel to make your UI accessible from anywhere. If not provided, it is set to False by default every time, except when running in Google Colab. When localhost is not accessible (e.g. Google Colab), setting share=False is not supported. Can be set by environment variable GRADIO_SHARE=True.
debug: bool
= False
if True, blocks the main thread from running. If running in Google Colab, this is needed to print the errors in the cell output.
max_threads: int
= 40
the maximum number of total threads that the Gradio app can generate in parallel. The default is inherited from the starlette library (currently 40).
auth: Callable[[str, str], bool] | tuple[str, str] | list[tuple[str, str]] | None
= None
If provided, username and password (or list of username-password tuples) required to access app. Can also provide function that takes username and password and returns True if valid login.
auth_message: str | None
= None
If provided, HTML message provided on login page.
prevent_thread_lock: bool
= False
By default, the gradio app blocks the main thread while the server is running. If set to True, the gradio app will not block and the gradio server will terminate as soon as the script finishes.
show_error: bool
= False
If True, any errors in the gradio app will be displayed in an alert modal and printed in the browser console log
server_name: str | None
= None
to make app accessible on local network, set this to "0.0.0.0". Can be set by environment variable GRADIO_SERVER_NAME. If None, will use "127.0.0.1".
server_port: int | None
= None
will start gradio app on this port (if available). Can be set by environment variable GRADIO_SERVER_PORT. If None, will search for an available port starting at 7860.
height: int
= 500
The height in pixels of the iframe element containing the gradio app (used if inline=True)
width: int | str
= "100%"
The width in pixels of the iframe element containing the gradio app (used if inline=True)
favicon_path: str | None
= None
If a path to a file (.png, .gif, or .ico) is provided, it will be used as the favicon for the web page.
ssl_keyfile: str | None
= None
If a path to a file is provided, will use this as the private key file to create a local server running on https.
ssl_certfile: str | None
= None
If a path to a file is provided, will use this as the signed certificate for https. Needs to be provided if ssl_keyfile is provided.
ssl_keyfile_password: str | None
= None
If a password is provided, will use this with the ssl certificate for https.
ssl_verify: bool
= True
If False, skips certificate validation which allows self-signed certificates to be used.
quiet: bool
= False
If True, suppresses most print statements.
show_api: bool
= True
If True, shows the api docs in the footer of the app. Default True.
allowed_paths: list[str] | None
= None
List of complete filepaths or parent directories that gradio is allowed to serve. Must be absolute paths. Warning: if you provide directories, any files in these directories or their subdirectories are accessible to all users of your app. Can be set by comma separated environment variable GRADIO_ALLOWED_PATHS. These files are generally assumed to be secure and will be displayed in the browser when possible.
blocked_paths: list[str] | None
= None
List of complete filepaths or parent directories that gradio is not allowed to serve (i.e. users of your app are not allowed to access). Must be absolute paths. Warning: takes precedence over `allowed_paths` and all other directories exposed by Gradio by default. Can be set by comma separated environment variable GRADIO_BLOCKED_PATHS.
root_path: str | None
= None
The root path (or "mount point") of the application, if it's not served from the root ("/") of the domain. Often used when the application is behind a reverse proxy that forwards requests to the application. For example, if the application is served at "https://example.com/myapp", the `root_path` should be set to "/myapp". A full URL beginning with http:// or https:// can be provided, which will be used as the root path in its entirety. Can be set by environment variable GRADIO_ROOT_PATH. Defaults to "".
app_kwargs: dict[str, Any] | None
= None
Additional keyword arguments to pass to the underlying FastAPI app as a dictionary of parameter keys and argument values. For example, `{"docs_url": "/docs"}`
state_session_capacity: int
= 10000
The maximum number of sessions whose information to store in memory. If the number of sessions exceeds this number, the oldest sessions will be removed. Reduce capacity to reduce memory usage when using gradio.State or returning updated components from functions. Defaults to 10000.
share_server_address: str | None
= None
Use this to specify a custom FRP server and port for sharing Gradio apps (only applies if share=True). If not provided, will use the default FRP server at https://gradio.live. See https://github.com/huggingface/frp for more information.
share_server_protocol: Literal['http', 'https'] | None
= None
Use this to specify the protocol to use for the share links. Defaults to "https", unless a custom share_server_address is provided, in 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".
auth_dependency: Callable[[fastapi.Request], str | None] | None
= None
A function that takes a FastAPI request and returns a string user ID or None. If the function returns None for a specific request, that user is not authorized to access the app (they will see a 401 Unauthorized response). To be used with external authentication systems like OAuth. Cannot be used with `auth`.
max_file_size: str | int | None
= None
The maximum file size in bytes that can be uploaded. Can be a string of the form "<value><unit>", where value is any positive integer and unit is one of "b", "kb", "mb", "gb", "tb". If None, no limit is set.
enable_monitoring: bool | None
= None
Enables traffic monitoring of the app through the /monitoring endpoint. By default is None, which enables this endpoint. If explicitly True, will also print the monitoring URL to the console. If False, will disable monitoring altogether.
strict_cors: bool
= True
If True, prevents external domains from making requests to a Gradio server running on localhost. If False, allows requests to localhost that originate from localhost but also, crucially, from "null". This parameter should normally be True to prevent CSRF attacks but may need to be False when embedding a *locally-running Gradio app* using web components.
node_server_name: str | None
= None
node_port: int | None
= None
ssr_mode: bool | None
= None
If True, the Gradio app will be rendered using server-side rendering mode, which is typically more performant and provides better SEO, but this requires Node 18+ to be installed on the system. If False, the app will be rendered using client-side rendering mode. If None, will use GRADIO_SSR_MODE environment variable or default to False.
gradio.Blocks.queue(ยทยทยท)
By enabling the queue you can control when users know their position in the queue, and set a limit on maximum number of events allowed.
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()
status_update_rate: float | Literal['auto']
= "auto"
If "auto", Queue will send status estimations to all clients whenever a job is finished. Otherwise Queue will send status at regular intervals set by this parameter as the number of seconds.
api_open: bool | None
= None
If True, the REST routes of the backend will be open, allowing requests made directly to those endpoints to skip the queue.
max_size: int | None
= None
The maximum number of events the queue will store at any given moment. If the queue is full, new events will not be added and a user will receive a message saying that the queue is full. If None, the queue size will be unlimited.
default_concurrency_limit: int | None | Literal['not_set']
= "not_set"
The default value of `concurrency_limit` to use for event listeners that don't specify a value. Can be set by environment variable GRADIO_DEFAULT_CONCURRENCY_LIMIT. Defaults to 1 if not set otherwise.
gradio.Blocks.integrate(ยทยทยท)
A catch-all method for integrating with other libraries. This method should be run after launch()
comet_ml: <class 'inspect._empty'>
= None
If a comet_ml Experiment object is provided, will integrate with the experiment and appear on Comet dashboard
wandb: ModuleType | None
= None
If the wandb module is provided, will integrate with it and appear on WandB dashboard
mlflow: ModuleType | None
= None
If the mlflow module is provided, will integrate with the experiment and appear on ML Flow dashboard
gradio.Blocks.load(block, ยทยทยท)
This listener is triggered when the Blocks initially loads in the browser.
block: Block | None
fn: Callable | None | Literal['decorator']
= "decorator"
the function to call when this event is triggered. Often a machine learning model's prediction function. Each parameter of the function corresponds to one input component, and the function should return a single value or a tuple of values, with each element in the tuple corresponding to one output component.
inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
= None
List of gradio.components to use as inputs. If the function takes no inputs, this should be an empty list.
outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
= None
List of gradio.components to use as outputs. If the function returns no outputs, this should be an empty list.
api_name: str | None | Literal[False]
= None
defines how the endpoint appears in the API docs. Can be a string, None, or False. If set to a 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 `gr.load` this app) will not be able to use this event.
scroll_to_output: bool
= False
If True, will scroll to output component on completion
show_progress: Literal['full', 'minimal', 'hidden']
= "full"
how to show the progress animation while event is running: "full" shows a spinner which covers the output component area as well as a runtime display in the upper right corner, "minimal" only shows the runtime display, "hidden" shows no progress animation at all
queue: bool
= True
If True, will place the request on the queue, if the queue has been enabled. If False, will not put this event on the queue, even if the queue has been enabled. If None, will use the queue setting of the gradio app.
batch: bool
= False
If True, then the function should process a batch of inputs, meaning that it should accept a list of input values for each parameter. The lists should be of equal length (and be up to length `max_batch_size`). The function is then *required* to return a tuple of lists (even if there is only 1 output component), with each list in the tuple corresponding to one output component.
max_batch_size: int
= 4
Maximum number of inputs to batch together if this is called from the queue (only relevant if batch=True)
preprocess: bool
= True
If False, will not run preprocessing of component data before running 'fn' (e.g. leaving it as a base64 string if this method is called with the `Image` component).
postprocess: bool
= True
If False, will not run postprocessing of component data before returning 'fn' output to the browser.
cancels: dict[str, Any] | list[dict[str, Any]] | None
= None
A list of other events to cancel when this listener is triggered. For example, setting cancels=[click_event] will cancel the click_event, where click_event is the return value of another components .click method. Functions that have not yet run (or generators that are iterating) will be cancelled, but functions that are currently running will be allowed to finish.
trigger_mode: Literal['once', 'multiple', 'always_last'] | None
= None
If "once" (default for all events except `.change()`) would not allow any submissions while an event is pending. If set to "multiple", 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: str | None
= None
Optional frontend js method to run before running 'fn'. Input arguments for js method are values of 'inputs' and 'outputs', return should be a list of values for output components.
concurrency_limit: int | None | Literal['default']
= "default"
If set, this is the maximum number of this event that can be running simultaneously. Can 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_limit` parameter in `Blocks.queue()`, which itself is 1 by default).
concurrency_id: str | None
= None
If set, this is the id of the concurrency group. Events with the same concurrency_id will be limited by the lowest set concurrency_limit.
show_api: bool
= True
whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False.
time_limit: int | None
= None
stream_every: float
= 0.5
like_user_message: bool
= False
gradio.Blocks.unload(fn, ยทยทยท)
This listener is triggered when the user closes or refreshes the tab, ending the user session. It is useful for cleaning up resources when the app is closed.
import gradio as gr
with gr.Blocks() as demo:
gr.Markdown("# When you close the tab, hello will be printed to the console")
demo.unload(lambda: print("hello"))
demo.launch()
fn: Callable[..., Any]
Callable function to run to clear resources. The function should not take any arguments and the output is not used.