text stringlengths 0 2k | heading1 stringlengths 3 79 | source_page_url stringclasses 190
values | source_page_title stringclasses 190
values |
|---|---|---|---|
Often times, you may want to bind multiple triggers to the same function. For example, you may want to allow a user to click a submit button, or press enter to submit a form. You can do this using the `gr.on` method and passing a list of triggers to the `trigger`.
$code_on_listener_basic
$demo_on_listener_basic
You c... | Binding Multiple Triggers to a Function | https://gradio.app/guides/blocks-and-event-listeners | Building With Blocks - Blocks And Event Listeners Guide |
If you want to set a Component's value to always be a function of the value of other Components, you can use the following shorthand:
```python
with gr.Blocks() as demo:
num1 = gr.Number()
num2 = gr.Number()
product = gr.Number(lambda a, b: a * b, inputs=[num1, num2])
```
This functionally the same as:
```pytho... | Binding a Component Value Directly to a Function of Other Components | https://gradio.app/guides/blocks-and-event-listeners | Building With Blocks - Blocks And Event Listeners Guide |
Global state in Gradio apps is very simple: any variable created outside of a function is shared globally between all users.
This makes managing global state very simple and without the need for external services. For example, in this application, the `visitor_count` variable is shared between all users
```py
import ... | Global State | https://gradio.app/guides/state-in-blocks | Building With Blocks - State In Blocks Guide |
Gradio supports session state, where data persists across multiple submits within a page session. To reiterate, session data is _not_ shared between different users of your model, and does _not_ persist if a user refreshes the page to reload the Gradio app. To store data in a session state, you need to do three things:... | Session State | https://gradio.app/guides/state-in-blocks | Building With Blocks - State In Blocks Guide |
riggered if the **hash** of the value changes. So if you define a custom class and create a `gr.State` variable that is an instance of that class, make sure that the the class includes a sensible `__hash__` implementation.
The value of a session State variable is cleared when the user refreshes the page. The value is... | Session State | https://gradio.app/guides/state-in-blocks | Building With Blocks - State In Blocks Guide |
return "Error: Session not initialized"
with gr.Blocks() as demo:
output = gr.Textbox(label="Status")
counter = gr.Number(label="Counter Value")
increment_btn = gr.Button("Increment Counter")
increment_btn.click(increment_counter, inputs=None, outputs=counter)
Initialize instance when page ... | Session State | https://gradio.app/guides/state-in-blocks | Building With Blocks - State In Blocks Guide |
Gradio also supports browser state, where data persists in the browser's localStorage even after the page is refreshed or closed. This is useful for storing user preferences, settings, API keys, or other data that should persist across sessions. To use local state:
1. Create a `gr.BrowserState` object. You can optiona... | Browser State | https://gradio.app/guides/state-in-blocks | Building With Blocks - State In Blocks Guide |
You can initialize the `I18n` class with multiple language dictionaries to add custom translations:
```python
import gradio as gr
Create an I18n instance with translations for multiple languages
i18n = gr.I18n(
en={"greeting": "Hello, welcome to my app!", "submit": "Submit"},
es={"greeting": "¡Hola, bienvenid... | Setting Up Translations | https://gradio.app/guides/internationalization | Additional Features - Internationalization Guide |
When you use the `i18n` instance with a translation key, Gradio will show the corresponding translation to users based on their browser's language settings or the language they've selected in your app.
If a translation isn't available for the user's locale, the system will fall back to English (if available) or displa... | How It Works | https://gradio.app/guides/internationalization | Additional Features - Internationalization Guide |
Locale codes should follow the BCP 47 format (e.g., 'en', 'en-US', 'zh-CN'). The `I18n` class will warn you if you use an invalid locale code.
| Valid Locale Codes | https://gradio.app/guides/internationalization | Additional Features - Internationalization Guide |
The following component properties typically support internationalization:
- `description`
- `info`
- `title`
- `placeholder`
- `value`
- `label`
Note that support may vary depending on the component, and some properties might have exceptions where internationalization is not applicable. You can check this by referri... | Supported Component Properties | https://gradio.app/guides/internationalization | Additional Features - Internationalization Guide |
Add `@gr.cache` to any function to automatically cache its results. The decorator hashes inputs by their content — two different numpy arrays with the same pixel values will produce a cache hit. Cache hits bypass the Gradio queue entirely.
```python
import gradio as gr
@gr.cache
def classify(image):
return model.... | Automatic caching with `@gr.cache` | https://gradio.app/guides/caching | Additional Features - Caching Guide |
.
- **`per_session`** — when `True`, each user session gets an isolated cache namespace. Prevents one user's cached results from being served to another, clears that session's entries when the client disconnects, and still applies `max_size` and `max_memory` to the shared cache store across all sessions.
Access the c... | Automatic caching with `@gr.cache` | https://gradio.app/guides/caching | Additional Features - Caching Guide |
For full control over what gets cached and when, use `gr.Cache()` as an injectable parameter (like `gr.Progress`). Gradio injects the same instance on every call, giving you a thread-safe `get`/`set` interface:
```python
def my_function(prompt, c=gr.Cache()):
hit = c.get(prompt)
if hit is not None:
ret... | Manual cache control with `gr.Cache()` | https://gradio.app/guides/caching | Additional Features - Caching Guide |
best_len = len(cached_key)
if best_key:
past_kv = c.get(best_key)["kv"]
output = model.generate(prompt, past_key_values=past_kv)
else:
output = model.generate(prompt)
c.set(prompt, kv=model.past_key_values)
return output.text
```
For a full runnable version, see the [`g... | Manual cache control with `gr.Cache()` | https://gradio.app/guides/caching | Additional Features - Caching Guide |
`@gr.cache` is most useful for **deterministic** functions where the same input always produces the same output: image classification, audio transcription, embedding computation, structured data extraction.
It is less useful for **non-deterministic** functions like text generation or image generation, where users migh... | When to use caching | https://gradio.app/guides/caching | Additional Features - Caching Guide |
Take a look at these complete examples and then build your own Gradio app with caching!
- [`@gr.cache()` function types demo](https://github.com/gradio-app/gradio/blob/main/demo/cache_demo/run.py) - sync, async, generator, and async generator caching
- [`gr.Cache()` manual cache demo](https://github.com/gradio-app/gra... | Next steps | https://gradio.app/guides/caching | Additional Features - Caching Guide |
When a user closes their browser tab, Gradio will automatically delete any `gr.State` variables associated with that user session after 60 minutes. If the user connects again within those 60 minutes, no state will be deleted.
You can control the deletion behavior further with the following two parameters of `gr.State`... | Automatic deletion of `gr.State` | https://gradio.app/guides/resource-cleanup | Additional Features - Resource Cleanup Guide |
Your Gradio application will save uploaded and generated files to a special directory called the cache directory. Gradio uses a hashing scheme to ensure that duplicate files are not saved to the cache but over time the size of the cache will grow (especially if your app goes viral 😉).
Gradio can periodically clean up... | Automatic cache cleanup via `delete_cache` | https://gradio.app/guides/resource-cleanup | Additional Features - Resource Cleanup Guide |
Additionally, Gradio now includes a `Blocks.unload()` event, allowing you to run arbitrary cleanup functions when users disconnect (this does not have a 60 minute delay).
Unlike other gradio events, this event does not accept inputs or outptus.
You can think of the `unload` event as the opposite of the `load` event.
| The `unload` event | https://gradio.app/guides/resource-cleanup | Additional Features - Resource Cleanup Guide |
The following demo uses all of these features. When a user visits the page, a special unique directory is created for that user.
As the user interacts with the app, images are saved to disk in that special directory.
When the user closes the page, the images created in that session are deleted via the `unload` event.
T... | Putting it all together | https://gradio.app/guides/resource-cleanup | Additional Features - Resource Cleanup Guide |
The simplest possible Workflow app:
```python
import gradio as gr
gr.Workflow().launch()
```
Open the app, drag Spaces, models, and datasets from the sidebar onto the canvas, connect their ports, and hit **Run**. As you add, remove, or change nodes and edges, a `workflow.json` file will automatically be created next... | Quickstart | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
Pass your own Python functions via `bind=` and they appear as callable nodes on the canvas. Gradio inspects the function signature to auto-generate input/output ports.
```python
import gradio as gr
def summarize(text: str) -> str:
return text[:200]
gr.Workflow(bind=[summarize]).launch()
```
Use a dict to give n... | Binding Python functions | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
For pipelines you want to ship with a fixed topology, declare edges programmatically:
```python
import gradio as gr
def clean(text: str) -> str:
return text.strip().lower()
def tag(text: str) -> str:
return f"[processed] {text}"
gr.Workflow(
bind=[clean, tag],
edges=[("clean", "tag")],
).launch()
``... | Defining edges in code | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
Pass a `graph=` path to load a saved workflow topology. The canvas reads from the file on each page load and autosaves back to it when you add, remove, or change nodes and edges.
```python
gr.Workflow(graph="workflow.json").launch()
```
If the file doesn't exist yet, it's created on the first authorized edit. `bind=`... | Loading from a JSON file | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
A workflow is a JSON file with three node collections:
```json
{
"schema_version": "2",
"name": "My Pipeline",
"references": [
{
"id": "ref_prompt", "label": "Prompt", "role": "reference",
"asset_type": "text",
"inputs": [{"id": "in", "label": "Text", "type": "text"}],
"outputs": [{"... | Workflow JSON format | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
n the file, and `workflow.json` is never rewritten with it. `height` is measured from the rendered card. `width` is the default every viewer starts from — anyone can resize a card locally, and a writer's resize becomes the new default the next time an edit is saved.
| Collection | Role |
|---|---|
| `references` | Inp... | Workflow JSON format | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
Ports are typed so the canvas can validate connections. Supported types:
`image` · `audio` · `video` · `text` · `number` · `boolean` · `gallery` · `file` · `json` · `model3d` · `any`
`any` is a compatibility fallback that can connect to every port type. `file` and `any` usually come from API schema inference and are ... | Port types | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
One reference can feed multiple operators simultaneously. When you run the workflow in the interactive canvas, operators at the same dependency depth run in parallel:
```python
workflow.json excerpt — one product photo → 4 FLUX Kontext branches
"edges": [
{"from_node_id": "ref_product", ..., "to_node_id": "op_kontex... | Fan-out pipelines | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
A Workflow app is a standard Gradio app — deploy it to Hugging Face Spaces exactly like any other, by uploading the code to a Space, or by simply running in your terminal:
```
gradio deploy
```
Set `hf_oauth: true` [in your Space](https://huggingface.co/docs/hub/en/spaces-oauth) so the owner can authenticate for edit... | Deploying to Spaces | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
Two different things in a Workflow app can spend GPU time, and each is set up its own way:
- **Space, model, and dataset nodes** call out to someone else's hardware. The workflow app itself stays on CPU; what matters is *whose* quota each call is billed to.
- **`kind: "fn"` nodes** run inside the workflow app. If one ... | gr.Workflow on ZeroGPU | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
. | [Sizing `duration`](sizing-duration-on-bound-functions) |
| `ZeroGPU client warning` — "GPU device not used" | The decorated function never touched the GPU — usually the model was moved to `cuda` somewhere the decorator can't see. | [Load models at module scope](load-models-at-module-scope) |
| `RuntimeError: CUDA ... | gr.Workflow on ZeroGPU | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
one edit:
```yaml
README.md of your Space
hf_oauth: true
```
The workflow app itself does not need GPU hardware. It orchestrates calls to other Spaces, so CPU basic is the right choice unless a function you passed to `bind=` does its own GPU work.
Sizing `duration` on bound functions
The number you write in `@space... | gr.Workflow on ZeroGPU | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
t spaces must be imported before anything initializes CUDA
import torch
from diffusers import AutoPipelineForText2Image
pipe = AutoPipelineForText2Image.from_pretrained(
"stabilityai/sdxl-turbo", torch_dtype=torch.float16, variant="fp16"
).to("cuda")
@spaces.GPU(duration=60)
def illustrate(prompt: str) -> dict:
... | gr.Workflow on ZeroGPU | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
as `{"path": ..., "url": ...}`, but one chained from an upstream node arrives as `{"url": "/gradio_api/file=<percent-encoded path>"}` with no `path` key at all. Normalize both before opening the file:
```python
from urllib.parse import unquote
def local_path(value):
if isinstance(value, str):
return valu... | gr.Workflow on ZeroGPU | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
Every Workflow app also renders as an ordinary Gradio app. Each independent pipeline is laid out like a `gr.Interface` — its unconnected inputs and a **Run** button on the left, its outputs on the right — and workflows with more than one pipeline get one tab each. Reference nodes that already hold a value show up as th... | App view | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
Every Workflow app is a Gradio app, meaning that it exposes its connected pipelines through the standard Gradio REST API. Each disconnected pipeline containing one or more output (subject) nodes gets one endpoint. Its name is derived from the first subject's label — for example, a pipeline whose first subject is labell... | API access | https://gradio.app/guides/workflows | Additional Features - Workflows Guide |
- **1. Static files**. You can designate static files or directories using the `gr.set_static_paths` function. Static files are not be copied to the Gradio cache (see below) and will be served directly from your computer. This can help save disk space and reduce the time your app takes to launch but be mindful of poss... | Files Gradio allows users to access | https://gradio.app/guides/file-access | Additional Features - File Access Guide |
First, it's important to understand why Gradio has a cache at all. Gradio copies files to a cache directory before returning them to the frontend. This prevents files from being overwritten by one user while they are still needed by another user of your application. For example, if your prediction function returns a vi... | The Gradio cache | https://gradio.app/guides/file-access | Additional Features - File Access Guide |
d by a user to your Gradio app (e.g. through the `File` or `Image` input components).
Tip: If at any time Gradio blocks a file that you would like it to process, add its path to the `allowed_paths` parameter.
| The Gradio cache | https://gradio.app/guides/file-access | Additional Features - File Access Guide |
While running, Gradio apps will NOT ALLOW users to access:
- **Files that you explicitly block via the `blocked_paths` parameter in `launch()`**. You can pass in a list of additional directories or exact filepaths to the `blocked_paths` parameter in `launch()`. This parameter takes precedence over the files that Gradi... | The files Gradio will not allow others to access | https://gradio.app/guides/file-access | Additional Features - File Access Guide |
Sharing your Gradio application will also allow users to upload files to your computer or server. You can set a maximum file size for uploads to prevent abuse and to preserve disk space. You can do this with the `max_file_size` parameter of `.launch`. For example, the following two code snippets limit file uploads to 5... | Uploading Files | https://gradio.app/guides/file-access | Additional Features - File Access Guide |
* Set a `max_file_size` for your application.
* Do not return arbitrary user input from a function that is connected to a file-based output component (`gr.Image`, `gr.File`, etc.). For example, the following interface would allow anyone to move an arbitrary file in your local directory to the cache: `gr.Interface(lambd... | Best Practices | https://gradio.app/guides/file-access | Additional Features - File Access Guide |
Both `gr.set_static_paths` and the `allowed_paths` parameter in launch expect absolute paths. Below is a minimal example to display a local `.png` image file in an HTML block.
```txt
├── assets
│ └── logo.png
└── app.py
```
For the example directory structure, `logo.png` and any other files in the `assets` folder ca... | Example: Accessing local files | https://gradio.app/guides/file-access | Additional Features - File Access Guide |
By default, Gradio automatically generates a navigation bar for multipage apps that displays all your pages with "Home" as the title for the main page. You can customize the navbar behavior using the `gr.Navbar` component.
Per-Page Navbar Configuration
You can have different navbar configurations for each page of you... | Customizing the Navbar | https://gradio.app/guides/multipage-apps | Additional Features - Multipage Apps Guide |
Let's create a demo where a user can choose a filter to apply to their webcam stream. Users can choose from an edge-detection filter, a cartoon filter, or simply flipping the stream vertically.
$code_streaming_filter
$demo_streaming_filter
You will notice that if you change the filter value it will immediately take e... | A Realistic Image Demo | https://gradio.app/guides/streaming-inputs | Additional Features - Streaming Inputs Guide |
For some image streaming demos, like the one above, we don't need to display separate input and output components. Our app would look cleaner if we could just display the modified output stream.
We can do so by just specifying the input image component as the output of the stream event.
$code_streaming_filter_unified... | Unified Image Demos | https://gradio.app/guides/streaming-inputs | Additional Features - Streaming Inputs Guide |
Your streaming function should be stateless. It should take the current input and return its corresponding output. However, there are cases where you may want to keep track of past inputs or outputs. For example, you may want to keep a buffer of the previous `k` inputs to improve the accuracy of your transcription demo... | Keeping track of past inputs or outputs | https://gradio.app/guides/streaming-inputs | Additional Features - Streaming Inputs Guide |
For an end-to-end example of streaming from the webcam, see the object detection from webcam [guide](/main/guides/object-detection-from-webcam-with-webrtc). | End-to-End Examples | https://gradio.app/guides/streaming-inputs | Additional Features - Streaming Inputs Guide |
**API endpoint names**
When you create a Gradio application, the API endpoint names are automatically generated based on the function names. You can change this by using the `api_name` parameter in `gr.Interface` or `gr.ChatInterface`. If you are using Gradio `Blocks`, you can name each event listener, like this:
```... | Configuring the API Page | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
**Adding API endpoints**
You can also add new API routes to your Gradio application that do not correspond to events in your UI.
For example, in this Gradio application, we add a new route that adds numbers and slices a list:
```py
import gradio as gr
with gr.Blocks() as demo:
with gr.Row():
input = gr... | Configuring the API Page | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
This API page not only lists all of the endpoints that can be used to query the Gradio app, but also shows the usage of both [the Gradio Python client](https://gradio.app/guides/getting-started-with-the-python-client/), and [the Gradio JavaScript client](https://gradio.app/guides/getting-started-with-the-js-client/).
... | The Clients | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
Instead of reading through the view API page, you can also use Gradio's built-in API recorder to generate the relevant code snippet. Simply click on the "API Recorder" button, use your Gradio app via the UI as you would normally, and then the API Recorder will generate the code using the Clients to recreate your all of... | The API Recorder 🪄 | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
Next to the "Use via API" link, the footer has a **Runs** link, which opens a page at `<your-gradio-app-url>/gradio_api/runs` listing the runs made from this browser, grouped by endpoint. Each run shows its inputs, its outputs, how long the function took, and whether it succeeded. Clicking **Load run** puts a saved run... | Run History | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
o want:
```py
demo.launch(footer_links=["api", "gradio", "settings"])
```
To turn the feature off completely, set `run_history=False`. Nothing is recorded, the run history page returns a 404, and any runs this app had already saved are cleared from the browser the next time someone opens it:
```py
demo.launch(run_hi... | Run History | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
The API page also includes instructions on how to use the Gradio app as an Model Context Protocol (MCP) server, which is a standardized way to expose functions as tools so that they can be used by LLMs.

... | MCP Server | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
You can access the complete OpenAPI (formerly Swagger) specification of your Gradio app's API at the endpoint `<your-gradio-app-url>/gradio_api/openapi.json`. The OpenAPI specification is a standardized, language-agnostic interface description for REST APIs that enables both humans and computers to discover and underst... | OpenAPI Specification | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
1. `GRADIO_SERVER_PORT`
- **Description**: Specifies the port on which the Gradio app will run.
- **Default**: `7860`
- **Example**:
```bash
export GRADIO_SERVER_PORT=8000
```
2. `GRADIO_SERVER_NAME`
- **Description**: Defines the host name for the Gradio server. To make Gradio accessible from any IP address, ... | Key Environment Variables | https://gradio.app/guides/environment-variables | Additional Features - Environment Variables Guide |
r the Gradio application. Useful if running Gradio [behind a reverse proxy](/guides/running-gradio-on-your-web-server-with-nginx).
- **Default**: `""`
- **Example**:
```sh
export GRADIO_ROOT_PATH="/myapp"
```
9. `GRADIO_SHARE`
- **Description**: Enables or disables sharing the Gradio app.
- **Default**: `"False... | Key Environment Variables | https://gradio.app/guides/environment-variables | Additional Features - Environment Variables Guide |
the application will trust the `X-Forwarded-For` header from these IP addresses to determine the original IP address of the user making the request. This means that if you use the `gr.Request` [object's](https://www.gradio.app/docs/gradio/request) `client.host` property, it will correctly get the user's IP address ins... | Key Environment Variables | https://gradio.app/guides/environment-variables | Additional Features - Environment Variables Guide |
e()`, `gr.ChatInterface()` or in `gr.Examples()`, Gradio will run your prediction function and save the results to disk. By default, this is in the `.gradio/cached_examples//` subdirectory within your app's working directory. You can customize the location of cached example files created by Gradio by setting the enviro... | Key Environment Variables | https://gradio.app/guides/environment-variables | Additional Features - Environment Variables Guide |
e"`
- **Options**: `"True"`, `"False"`
- **Example**:
```sh
export GRADIO_RESET_EXAMPLES_CACHE="True"
```
20. `GRADIO_CHAT_FLAGGING_MODE`
- **Description**: Controls whether users can flag messages in `gr.ChatInterface` applications. Similar to `GRADIO_FLAGGING_MODE` but specifically for chat interfaces.
- **De... | Key Environment Variables | https://gradio.app/guides/environment-variables | Additional Features - Environment Variables Guide |
*Options**: `"True"`, `"False"`
- **Example**:
```sh
export GRADIO_MCP_SERVER="True"
```
24. `GRADIO_NUM_WORKERS`
- **Description**: Number of multiple workers to launch in the background to offload traffic for file I/O and static assets from the main Gradio server. Only works when SSR mode is set.
- **Default... | Key Environment Variables | https://gradio.app/guides/environment-variables | Additional Features - Environment Variables Guide |
To set environment variables in your terminal, use the `export` command followed by the variable name and its value. For example:
```sh
export GRADIO_SERVER_PORT=8000
```
If you're using a `.env` file to manage your environment variables, you can add them like this:
```sh
GRADIO_SERVER_PORT=8000
GRADIO_SERVER_NAME="... | How to Set Environment Variables | https://gradio.app/guides/environment-variables | Additional Features - Environment Variables Guide |
Gradio can stream audio and video directly from your generator function.
This lets your user hear your audio or see your video nearly as soon as it's `yielded` by your function.
All you have to do is
1. Set `streaming=True` in your `gr.Audio` or `gr.Video` output component.
2. Write a python generator that yields the... | Streaming Media | https://gradio.app/guides/streaming-outputs | Additional Features - Streaming Outputs Guide |
For an end-to-end example of streaming media, see the object detection from video [guide](/main/guides/object-detection-from-video) or the streaming AI-generated audio with [transformers](https://huggingface.co/docs/transformers/index) [guide](/main/guides/streaming-ai-generated-audio). | End-to-End Examples | https://gradio.app/guides/streaming-outputs | Additional Features - Streaming Outputs Guide |
To add custom buttons to a component, pass a list of `gr.Button()` instances to the `buttons` parameter:
```python
import gradio as gr
refresh_btn = gr.Button("Refresh", variant="secondary", size="sm")
clear_btn = gr.Button("Clear", variant="secondary", size="sm")
textbox = gr.Textbox(
value="Sample text",
l... | Basic Usage | https://gradio.app/guides/custom-buttons | Additional Features - Custom Buttons Guide |
Custom buttons work just like regular `gr.Button` components. You can connect them to Python functions or JavaScript functions using the `.click()` method:
Python Functions
```python
def refresh_data():
import random
return f"Refreshed: {random.randint(1000, 9999)}"
refresh_btn.click(refresh_data, outputs=te... | Connecting Button Events | https://gradio.app/guides/custom-buttons | Additional Features - Custom Buttons Guide |
Here's a complete example showing custom buttons with both Python and JavaScript functions:
$code_textbox_custom_buttons
| Complete Example | https://gradio.app/guides/custom-buttons | Additional Features - Custom Buttons Guide |
- Custom buttons appear in the component's toolbar, typically in the top-right corner
- Only the `value` of the Button is used, other attributes like `icon` are not used.
- Buttons are rendered in the order they appear in the `buttons` list
- Built-in buttons (like "copy", "download") can be hidden by omitting them fro... | Notes | https://gradio.app/guides/custom-buttons | Additional Features - Custom Buttons Guide |
By default, each event listener has its own queue, which handles one request at a time. This can be configured via two arguments:
- `concurrency_limit`: This sets the maximum number of concurrent executions for an event listener. By default, the limit is 1 unless configured otherwise in `Blocks.queue()`. You can also ... | Configuring the Queue | https://gradio.app/guides/queuing | Additional Features - Queuing Guide |
identified by `"gpu_queue"`. The queue can handle up to 2 concurrent requests at a time, as defined by the `concurrency_limit`.
Notes
- To ensure unlimited concurrency for an event listener, set `concurrency_limit=None`. This is useful if your function is calling e.g. an external API which handles the rate limiting... | Configuring the Queue | https://gradio.app/guides/queuing | Additional Features - Queuing Guide |
Client side functions are ideal for updating component properties (like visibility, placeholders, interactive state, or styling).
Here's a basic example:
```py
import gradio as gr
with gr.Blocks() as demo:
with gr.Row() as row:
btn = gr.Button("Hide this row")
This function runs in the browser ... | When to Use Client Side Functions | https://gradio.app/guides/client-side-functions | Additional Features - Client Side Functions Guide |
Client side functions have some important restrictions:
* They can only update component properties (not values)
* They cannot take any inputs
Here are some functions that will work with `js=True`:
```py
Simple property updates
lambda: gr.Textbox(lines=4)
Multiple component updates
lambda: [gr.Textbox(lines=4), gr.B... | Limitations | https://gradio.app/guides/client-side-functions | Additional Features - Client Side Functions Guide |
Here's a more complete example showing how client side functions can improve the user experience:
$code_todo_list_js
| Complete Example | https://gradio.app/guides/client-side-functions | Additional Features - Client Side Functions Guide |
When you set `js=True`, Gradio:
1. Transpiles your Python function to JavaScript
2. Runs the function directly in the browser
3. Still sends the request to the server (for consistency and to handle any side effects)
This provides immediate visual feedback while ensuring your application state remains consistent.
| Behind the Scenes | https://gradio.app/guides/client-side-functions | Additional Features - Client Side Functions Guide |
Gradio demos can be easily shared publicly by setting `share=True` in the `launch()` method. Like this:
```python
import gradio as gr
def greet(name):
return "Hello " + name + "!"
demo = gr.Interface(fn=greet, inputs="textbox", outputs="textbox")
demo.launch(share=True) Share your demo with just 1 extra parame... | Sharing Demos | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
If you'd like to have a permanent link to your Gradio demo on the internet, use Hugging Face Spaces. [Hugging Face Spaces](http://huggingface.co/spaces/) provides the infrastructure to permanently host your machine learning model for free!
After you have [created a free Hugging Face account](https://huggingface.co/joi... | Hosting on HF Spaces | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
You can add a button to your Gradio app that creates a unique URL you can use to share your app and all components **as they currently are** with others. This is useful for sharing unique and interesting generations from your application , or for saving a snapshot of your app at a particular point in time.
To add a de... | Sharing Deep Links | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
Once you have hosted your app on Hugging Face Spaces (or on your own server), you may want to embed the demo on a different website, such as your blog or your portfolio. Embedding an interactive demo allows people to try out the machine learning model that you have built, without needing to download or install anything... | Embedding Hosted Spaces | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
=> {
let v = obj.info.version;
content = document.querySelector('.prose');
content.innerHTML = content.innerHTML.replaceAll("{GRADIO_VERSION}", v);
});
</script>
You can see examples of how web components look <a href="https://www.gradio.app">on the Gradio landing page</a>.
You can also customize the appe... | Embedding Hosted Spaces | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
ple of how to use these attributes to create a Gradio app that does not lazy load and has an initial height of 0px.
```html
<gradio-app
space="gradio/Echocardiogram-Segmentation"
eager="true"
initial_height="0px"
></gradio-app>
```
Here's another example of how to use the `render` event. An event listener is used ... | Embedding Hosted Spaces | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
You can use almost any Gradio app as an API! In the footer of a Gradio app [like this one](https://huggingface.co/spaces/gradio/hello_world), you'll see a "Use via API" link.

This is a page that lists the endpoints t... | API Page | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
When a user makes a prediction to your app, you may need the underlying network request, in order to get the request headers (e.g. for advanced authentication), log the client's IP address, getting the query parameters, or for other reasons. Gradio supports this in a similar manner to FastAPI: simply add a function par... | Accessing the Network Request Directly | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
In some cases, you might have an existing FastAPI app, and you'd like to add a path for a Gradio demo.
You can easily do this with `gradio.mount_gradio_app()`.
Here's a complete example:
$code_custom_path
Note that this approach also allows you run your Gradio apps on custom paths (`http://localhost:8000/gradio` in ... | Mounting Within Another FastAPI App | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
Password-protected app
You may wish to put an authentication page in front of your app to limit who can open your app. With the `auth=` keyword argument in the `launch()` method, you can provide a tuple with a username and password, or a list of acceptable username/password tuples; Here's an example that provides pass... | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
Let's update the previous example to include a log out button:
```python
import gradio as gr
def update_message(request: gr.Request):
return f"Welcome, {request.username}"
with gr.Blocks() as demo:
m = gr.Markdown()
logout_button = gr.Button("Logout", link="/logout")
demo.load(update_message, None, ... | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
e. If you want
to perform actions on behalf of the user (e.g. list user's private repos, create repo, etc.), you can retrieve the user
token by adding a parameter of type `gr.OAuthToken`. You must define which scopes you will use in your Space metadata
(see [documentation](https://huggingface.co/docs/hub/spaces-oauthsc... | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
erence is that the `gr.OAuthProfile` or `gr.OAuthToken` will be `None` in the corresponding functions.
OAuth (with external providers)
It is also possible to authenticate with external OAuth providers (e.g. Google OAuth) in your Gradio apps. To do this, first mount your Gradio app within a FastAPI app ([as discussed... | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
entials on the [Google Developer Console](https://console.cloud.google.com/project)):
```python
import os
from authlib.integrations.starlette_client import OAuth, OAuthError
from fastapi import FastAPI, Depends, Request
from starlette.config import Config
from starlette.responses import RedirectResponse
from starlette... | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
direct_uri = urlunparse(urlparse(str(redirect_uri))._replace(scheme='https'))
return await oauth.google.authorize_redirect(request, redirect_uri)
@app.route('/auth')
async def auth(request: Request):
try:
access_token = await oauth.google.authorize_access_token(request)
except OAuthError:
r... | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
Gradio apps can function as MCP (Model Context Protocol) servers, allowing LLMs to use your app's functions as tools. By simply setting `mcp_server=True` in the `.launch()` method, Gradio automatically converts your app's functions into MCP tools that can be called by MCP clients like Claude Desktop, Cursor, or Cline. ... | MCP Servers | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
When publishing your app publicly, and making it available via API or via MCP server, you might want to set rate limits to prevent users from abusing your app. You can identify users using their IP address (using the `gr.Request` object [as discussed above](accessing-the-network-request-directly)) or, if they are logge... | Rate Limits | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
By default, Gradio collects certain analytics to help us better understand the usage of the `gradio` library. This includes the following information:
* What environment the Gradio app is running on (e.g. Colab Notebook, Hugging Face Spaces)
* What input/output components are being used in the Gradio app
* Whether the... | Analytics | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
[Progressive Web Apps (PWAs)](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps) are web applications that are regular web pages or websites, but can appear to the user like installable platform-specific applications.
Gradio apps can be easily served as PWAs by setting the `pwa=True` parameter in the `... | Progressive Web App (PWA) | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
If you already have a recent version of `gradio`, then the `gradio_client` is included as a dependency. But note that this documentation reflects the latest version of the `gradio_client`, so upgrade if you're not sure!
The lightweight `gradio_client` package can be installed from pip (or pip3) and is tested to work w... | Installation | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
Start by connecting instantiating a `Client` object and connecting it to a Gradio app that is running on Hugging Face Spaces.
```python
from gradio_client import Client
client = Client("abidlabs/en2fr") a Space that translates from English to French
```
You can also connect to private Spaces by passing in your HF t... | Connecting to a Gradio App on Hugging Face Spaces | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
While you can use any public Space as an API, you may get rate limited by Hugging Face if you make too many requests. For unlimited usage of a Space, simply duplicate the Space to create a private Space,
and then use it to make as many requests as you'd like!
The `gradio_client` includes a class method: `Client.duplic... | Duplicating a Space for private use | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
If your app is running somewhere else, just provide the full URL instead, including the "http://" or "https://". Here's an example of making predictions to a Gradio app that is running on a share URL:
```python
from gradio_client import Client
client = Client("https://bec81a83-5b5c-471e.gradio.live")
```
| Connecting a general Gradio app | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
If the Gradio application you are connecting to [requires a username and password](/guides/sharing-your-appauthentication), then provide them as a tuple to the `auth` argument of the `Client` class:
```python
from gradio_client import Client
Client(
space_name,
auth=[username, password]
)
```
| Connecting to a Gradio app with auth | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.