Gradio logo

New to Gradio? Start here: Getting Started

See the Release History

Blocks

with gradio.Blocks():

Description

Blocks is Gradio's low-level API that allows you to create more custom web applications and demos than Interfaces (yet still entirely in Python).

Compared to the Interface class, Blocks offers more flexibility and control over: (1) the layout of components (2) the events that trigger the execution of functions (3) data flows (e.g. inputs can trigger outputs, which can trigger the next level of outputs). Blocks also offers ways to group together related demos such as with tabs.

The basic usage of Blocks is as follows: create a Blocks object, then use it as a context (with the "with" statement), and then define layouts, components, or events within the Blocks context. Finally, call the launch() method to launch the demo.

Example Usage

import gradio as gr
def update(name):
    return f"Welcome to Gradio, {name}!"

with gr.Blocks() as demo:
    gr.Markdown("Start typing below and then click **Run** to see the output.")
    with gr.Row():
        inp = gr.Textbox(placeholder="What is your name?")
        out = gr.Textbox()
    btn = gr.Button("Run")
    btn.click(fn=update, inputs=inp, outputs=out)

demo.launch()

Initialization

Parameter Description
theme

Theme | str | None

default: None

a Theme object or a string representing a theme. If a string, will look for a built-in theme with that name (e.g. "soft" or "default"), or will attempt to load a theme from the HF Hub (e.g. "gradio/monochrome"). If None, will use the Default theme.

analytics_enabled

bool | None

default: None

whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable or default to True.

mode

str

default: "blocks"

a human-friendly name for the kind of Blocks or Interface being created.

title

str

default: "Gradio"

The tab title to display when this is opened in a browser window.

css

str | None

default: None

custom css or path to custom css file to apply to entire Blocks

Demos

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()

Methods

launch

gradio.Blocks.launch(ยทยทยท)

Description

Launches a simple web server that serves the demo. Can also be used to create a public link used by anyone to access the demo from their browser by setting share=True.

Example Usage

import gradio as gr
def reverse(text):
    return text[::-1]
with gr.Blocks() as demo:
    button = gr.Button(value="Reverse")
    button.click(reverse, gr.Textbox(), gr.Textbox())
demo.launch(share=True, auth=("username", "password"))

Agruments

Parameter Description
inline

bool | None

default: None

whether to display in the interface inline in an iframe. Defaults to True in python notebooks; False otherwise.

inbrowser

bool

default: False

whether to automatically launch the interface in a new tab on the default browser.

share

bool | None

default: None

whether to create a publicly shareable link for the interface. Creates an SSH tunnel to make your UI accessible from anywhere. If not provided, it is set to False by default every time, except when running in Google Colab. When localhost is not accessible (e.g. Google Colab), setting share=False is not supported.

debug

bool

default: False

if True, blocks the main thread from running. If running in Google Colab, this is needed to print the errors in the cell output.

enable_queue

bool | None

default: None

DEPRECATED (use .queue() method instead.) if True, inference requests will be served through a queue instead of with parallel threads. Required for longer inference times (> 1min) to prevent timeout. The default option in HuggingFace Spaces is True. The default option elsewhere is False.

max_threads

int

default: 40

the maximum number of total threads that the Gradio app can generate in parallel. The default is inherited from the starlette library (currently 40). Applies whether the queue is enabled or not. But if queuing is enabled, this parameter is increaseed to be at least the concurrency_count of the queue.

auth

Callable | tuple[str, str] | list[tuple[str, str]] | None

default: None

If provided, username and password (or list of username-password tuples) required to access interface. Can also provide function that takes username and password and returns True if valid login.

auth_message

str | None

default: None

If provided, HTML message provided on login page.

prevent_thread_lock

bool

default: False

If True, the interface will block the main thread while the server is running.

show_error

bool

default: False

If True, any errors in the interface will be displayed in an alert modal and printed in the browser console log

server_name

str | None

default: None

to make app accessible on local network, set this to "0.0.0.0". Can be set by environment variable GRADIO_SERVER_NAME. If None, will use "127.0.0.1".

server_port

int | None

default: None

will start gradio app on this port (if available). Can be set by environment variable GRADIO_SERVER_PORT. If None, will search for an available port starting at 7860.

show_tips

bool

default: False

if True, will occasionally show tips about new Gradio features

height

int

default: 500

The height in pixels of the iframe element containing the interface (used if inline=True)

width

int | str

default: "100%"

The width in pixels of the iframe element containing the interface (used if inline=True)

encrypt

bool | None

default: None

DEPRECATED. Has no effect.

favicon_path

str | None

default: None

If a path to a file (.png, .gif, or .ico) is provided, it will be used as the favicon for the web page.

ssl_keyfile

str | None

default: None

If a path to a file is provided, will use this as the private key file to create a local server running on https.

ssl_certfile

str | None

default: None

If a path to a file is provided, will use this as the signed certificate for https. Needs to be provided if ssl_keyfile is provided.

ssl_keyfile_password

str | None

default: None

If a password is provided, will use this with the ssl certificate for https.

ssl_verify

bool

default: True

If False, skips certificate validation which allows self-signed certificates to be used.

quiet

bool

default: False

If True, suppresses most print statements.

show_api

bool

default: True

If True, shows the api docs in the footer of the app. Default True. If the queue is enabled, then api_open parameter of .queue() will determine if the api docs are shown, independent of the value of show_api.

file_directories

list[str] | None

default: None

This parameter has been renamed to `allowed_paths`. It will be removed in a future version.

allowed_paths

list[str] | None

default: None

List of complete filepaths or parent directories that gradio is allowed to serve (in addition to the directory containing the gradio python file). Must be absolute paths. Warning: if you provide directories, any files in these directories or their subdirectories are accessible to all users of your app.

blocked_paths

list[str] | None

default: None

List of complete filepaths or parent directories that gradio is not allowed to serve (i.e. users of your app are not allowed to access). Must be absolute paths. Warning: takes precedence over `allowed_paths` and all other directories exposed by Gradio by default.

root_path

str

default: ""

The root path (or "mount point") of the application, if it's not served from the root ("/") of the domain. Often used when the application is behind a reverse proxy that forwards requests to the application. For example, if the application is served at "https://example.com/myapp", the `root_path` should be set to "/myapp".

app_kwargs

dict[str, Any] | None

default: None

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

queue

gradio.Blocks.queue(ยทยทยท)

Description

You can control the rate of processed requests by creating a queue. This will allow you to set the number of requests to be processed at one time, and will let users know their position in the queue.

Example Usage

with gr.Blocks() as demo:
    button = gr.Button(label="Generate Image")
    button.click(fn=image_generator, inputs=gr.Textbox(), outputs=gr.Image())
demo.queue(concurrency_count=3)
demo.launch()

Agruments

Parameter Description
concurrency_count

int

default: 1

Number of worker threads that will be processing requests from the queue concurrently. Increasing this number will increase the rate at which requests are processed, but will also increase the memory usage of the queue.

status_update_rate

float | Literal['auto']

default: "auto"

If "auto", Queue will send status estimations to all clients whenever a job is finished. Otherwise Queue will send status at regular intervals set by this parameter as the number of seconds.

client_position_to_load_data

int | None

default: None

DEPRECATED. This parameter is deprecated and has no effect.

default_enabled

bool | None

default: None

Deprecated and has no effect.

api_open

bool

default: True

If True, the REST routes of the backend will be open, allowing requests made directly to those endpoints to skip the queue.

max_size

int | None

default: None

The maximum number of events the queue will store at any given moment. If the queue is full, new events will not be added and a user will receive a message saying that the queue is full. If None, the queue size will be unlimited.

integrate

gradio.Blocks.integrate(ยทยทยท)

Description

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

Agruments

Parameter Description
comet_ml

<class 'inspect._empty'>

default: None

If a comet_ml Experiment object is provided, will integrate with the experiment and appear on Comet dashboard

wandb

ModuleType | None

default: None

If the wandb module is provided, will integrate with it and appear on WandB dashboard

mlflow

ModuleType | None

default: None

If the mlflow module is provided, will integrate with the experiment and appear on ML Flow dashboard

load

gradio.Blocks.load(ยทยทยท)

Description

For reverse compatibility reasons, this is both a class method and an instance method, the two of which, confusingly, do two completely different things.

Class method: loads a demo from a Hugging Face Spaces repo and creates it locally and returns a block instance. Warning: this method will be deprecated. Use the equivalent `gradio.load()` instead.

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

Example Usage

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

Agruments

Parameter Description
fn

Callable | None

default: None

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

inputs

list[Component] | None

default: None

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

outputs

list[Component] | None

default: None

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

api_name

str | None | Literal[False]

default: None

Instance Method - Defines how the endpoint appears in the API docs. Can be a string, None, or False. If False, the endpoint will not be exposed in the api docs. If set to None, the endpoint will be exposed in the api docs as an unnamed endpoint, although this behavior will be changed in Gradio 4.0. If set to a string, the endpoint will be exposed in the api docs with the given name.

scroll_to_output

bool

default: False

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

show_progress

str

default: "full"

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

queue

<class 'inspect._empty'>

default: None

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

batch

bool

default: False

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

max_batch_size

int

default: 4

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

preprocess

bool

default: True

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

postprocess

bool

default: True

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

every

float | None

default: None

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

name

str | None

default: None

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

src

str | None

default: None

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

api_key

str | None

default: None

Class Method - optional access token for loading private Hugging Face Hub models or spaces. Find your token here: https://huggingface.co/settings/tokens. Warning: only provide this if you are loading a trusted private Space as it can be read by the Space you are loading.

alias

str | None

default: None

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