text stringlengths 0 2k | heading1 stringlengths 3 79 | source_page_url stringclasses 189
values | source_page_title stringclasses 189
values |
|---|---|---|---|
- **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 |
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 |
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 |
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 |
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 |
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 |
To create a demo that has both the input and the output components, you simply need to set the values of the `inputs` and `outputs` parameter in `Interface()`. Here's an example demo of a simple image filter:
$code_sepia_filter
$demo_sepia_filter
| Standard demos | https://gradio.app/guides/four-kinds-of-interfaces | Building Interfaces - Four Kinds Of Interfaces Guide |
What about demos that only contain outputs? In order to build such a demo, you simply set the value of the `inputs` parameter in `Interface()` to `None`. Here's an example demo of a mock image generation model:
$code_fake_gan_no_input
$demo_fake_gan_no_input
| Output-only demos | https://gradio.app/guides/four-kinds-of-interfaces | Building Interfaces - Four Kinds Of Interfaces Guide |
Similarly, to create a demo that only contains inputs, set the value of `outputs` parameter in `Interface()` to be `None`. Here's an example demo that saves any uploaded image to disk:
$code_save_file_no_output
$demo_save_file_no_output
| Input-only demos | https://gradio.app/guides/four-kinds-of-interfaces | Building Interfaces - Four Kinds Of Interfaces Guide |
A demo that has a single component as both the input and the output. It can simply be created by setting the values of the `inputs` and `outputs` parameter as the same component. Here's an example demo of a text generation model:
$code_unified_demo_text_generation
$demo_unified_demo_text_generation
It may be the case... | Unified demos | https://gradio.app/guides/four-kinds-of-interfaces | Building Interfaces - Four Kinds Of Interfaces Guide |
Gradio includes more than 30 pre-built components (as well as many [community-built _custom components_](https://www.gradio.app/custom-components/gallery)) that can be used as inputs or outputs in your demo. These components correspond to common data types in machine learning and data science, e.g. the `gr.Image` compo... | Gradio Components | https://gradio.app/guides/the-interface-class | Building Interfaces - The Interface Class Guide |
We used the default versions of the `gr.Textbox` and `gr.Slider`, but what if you want to change how the UI components look or behave?
Let's say you want to customize the slider to have values from 1 to 10, with a default of 2. And you wanted to customize the output text field — you want it to be larger and have a lab... | Components Attributes | https://gradio.app/guides/the-interface-class | Building Interfaces - The Interface Class Guide |
Suppose you had a more complex function, with multiple outputs as well. In the example below, we define a function that takes a string, boolean, and number, and returns a string and number.
$code_hello_world_3
$demo_hello_world_3
Just as each component in the `inputs` list corresponds to one of the parameters of the... | Multiple Input and Output Components | https://gradio.app/guides/the-interface-class | Building Interfaces - The Interface Class Guide |
Gradio supports many types of components, such as `Image`, `DataFrame`, `Video`, or `Label`. Let's try an image-to-image function to get a feel for these!
$code_sepia_filter
$demo_sepia_filter
When using the `Image` component as input, your function will receive a NumPy array with the shape `(height, width, 3)`, wher... | An Image Example | https://gradio.app/guides/the-interface-class | Building Interfaces - The Interface Class Guide |
You can provide example data that a user can easily load into `Interface`. This can be helpful to demonstrate the types of inputs the model expects, as well as to provide a way to explore your dataset in conjunction with your model. To load example data, you can provide a **nested list** to the `examples=` keyword argu... | Example Inputs | https://gradio.app/guides/the-interface-class | Building Interfaces - The Interface Class Guide |
In the previous example, you may have noticed the `title=` and `description=` keyword arguments in the `Interface` constructor that helps users understand your app.
There are three arguments in the `Interface` constructor to specify where this content should go:
- `title`: which accepts text and can display it at the... | Descriptive Content | https://gradio.app/guides/the-interface-class | Building Interfaces - The Interface Class Guide |
If your prediction function takes many inputs, you may want to hide some of them within a collapsed accordion to avoid cluttering the UI. The `Interface` class takes an `additional_inputs` argument which is similar to `inputs` but any input components included here are not visible by default. The user must click on the... | Additional Inputs within an Accordion | https://gradio.app/guides/the-interface-class | Building Interfaces - The Interface Class Guide |
If the state is something that should be accessible to all function calls and all users, you can create a variable outside the function call and access it inside the function. For example, you may load a large model outside the function and use it inside the function so that every function call does not need to reload ... | Global State | https://gradio.app/guides/interface-state | Building Interfaces - Interface State Guide |
Another type of data persistence Gradio supports is session state, where data persists across multiple submits within a page session. However, data is _not_ shared between different users of your model. To store data in a session state, you need to do three things:
1. Pass in an extra parameter into your function, whi... | Session State | https://gradio.app/guides/interface-state | Building Interfaces - Interface State Guide |
Adding examples to an Interface is as easy as providing a list of lists to the `examples`
keyword argument.
Each sublist is a data sample, where each element corresponds to an input of the prediction function.
The inputs must be ordered in the same order as the prediction function expects them.
If your interface only ... | Providing Examples | https://gradio.app/guides/more-on-examples | Building Interfaces - More On Examples Guide |
You may wish to provide some cached examples of your model for users to quickly try out, in case your model takes a while to run normally.
If `cache_examples=True`, your Gradio app will run all of the examples and save the outputs when you call the `launch()` method. This data will be saved in a directory called `gradi... | Caching examples | https://gradio.app/guides/more-on-examples | Building Interfaces - More On Examples Guide |
You can make interfaces automatically refresh by setting `live=True` in the interface. Now the interface will recalculate as soon as the user input changes.
$code_calculator_live
$demo_calculator_live
Note there is no submit button, because the interface resubmits automatically on change.
| Live Interfaces | https://gradio.app/guides/reactive-interfaces | Building Interfaces - Reactive Interfaces Guide |
Some components have a "streaming" mode, such as `Audio` component in microphone mode, or the `Image` component in webcam mode. Streaming means data is sent continuously to the backend and the `Interface` function is continuously being rerun.
The difference between `gr.Audio(source='microphone')` and `gr.Audio(source=... | Streaming Components | https://gradio.app/guides/reactive-interfaces | Building Interfaces - Reactive Interfaces Guide |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.