text stringlengths 0 2k | heading1 stringlengths 3 79 | source_page_url stringclasses 189
values | source_page_title stringclasses 189
values |
|---|---|---|---|
/main/gradio-guides/Screen%20Recording%202024-12-19%20at%203.30.00%E2%80%AFPM.gif)
If you build a Slack bot from a Gradio app, feel free to share it on X and tag [the Gradio account](https://x.com/Gradio), and we are happy to help you amplify! | Prerequisites | https://gradio.app/guides/creating-a-slack-bot-from-a-gradio-app | Chatbots - Creating A Slack Bot From A Gradio App Guide |
The Discord bot will listen to messages mentioning it in channels. When it receives a message (which can include text as well as files), it will send it to your Gradio app via Gradio's built-in API. Your bot will reply with the response it receives from the API.
Because Gradio's API is very flexible, you can create D... | How does it work? | https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app | Chatbots - Creating A Discord Bot From A Gradio App Guide |
* Install the latest version of `gradio` and the `discord.py` libraries:
```
pip install --upgrade gradio discord.py~=2.0
```
* Have a running Gradio app. This app can be running locally or on Hugging Face Spaces. In this example, we will be using the [Gradio Playground Space](https://huggingface.co/spaces/abidlabs/g... | Prerequisites | https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app | Chatbots - Creating A Discord Bot From A Gradio App Guide |
CORD BOT TOKEN HERE
client = discord.Client()
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
client.run(TOKEN)
```
Now, run this file: `python bot.py`, which should run and print a message like:
```text
We have logged in as GradioPlaygroundBot1451
```
If that is working,... | Prerequisites | https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app | Chatbots - Creating A Discord Bot From A Gradio App Guide |
.filename.lower().endswith(ext) for ext in ['png', 'jpg', 'jpeg', 'gif', 'webp']):
image_path = download_image(attachment)
files.append(handle_file(image_path))
break
Stream the responses to the channel
for response in gradio_client.su... | Prerequisites | https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app | Chatbots - Creating A Discord Bot From A Gradio App Guide |
c example - you can extend it to handle more types of files, add error handling, or integrate with different Gradio apps.

If you build a Discord bot from a Gra... | Prerequisites | https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app | Chatbots - Creating A Discord Bot From A Gradio App Guide |
**Important Note**: if you are getting started, we recommend using the `gr.ChatInterface` to create chatbots -- its a high-level abstraction that makes it possible to create beautiful chatbot applications fast, often with a single line of code. [Read more about it here](/guides/creating-a-chatbot-fast).
This tutorial ... | Introduction | https://gradio.app/guides/creating-a-custom-chatbot-with-blocks | Chatbots - Creating A Custom Chatbot With Blocks Guide |
Let's start with recreating the simple demo above. As you may have noticed, our bot simply randomly responds "How are you?", "Today is a great day", or "I'm very hungry" to any input. Here's the code to create this with Gradio:
$code_chatbot_simple
There are three Gradio components here:
- A `Chatbot`, whose value s... | A Simple Chatbot Demo | https://gradio.app/guides/creating-a-custom-chatbot-with-blocks | Chatbots - Creating A Custom Chatbot With Blocks Guide |
There are several ways we can improve the user experience of the chatbot above. First, we can stream responses so the user doesn't have to wait as long for a message to be generated. Second, we can have the user message appear immediately in the chat history, while the chatbot's response is being generated. Here's the ... | Add Streaming to your Chatbot | https://gradio.app/guides/creating-a-custom-chatbot-with-blocks | Chatbots - Creating A Custom Chatbot With Blocks Guide |
The `gr.Chatbot` component supports a subset of markdown including bold, italics, and code. For example, we could write a function that responds to a user's message, with a bold **That's cool!**, like this:
```py
def bot(history):
response = {"role": "assistant", "content": "**That's cool!**"}
history.append(r... | Adding Markdown, Images, Audio, or Videos | https://gradio.app/guides/creating-a-custom-chatbot-with-blocks | Chatbots - Creating A Custom Chatbot With Blocks Guide |
ggingface.co/spaces/gradio/chatbot_streaming): A streaming chatbot demo built with `gr.Chatbot` and Blocks.
- [gradio/chatbot_examples](https://huggingface.co/spaces/gradio/chatbot_examples): A chatbot that presents new visitors with a list of multimodal examples they can use to start the conversation.
| Adding Markdown, Images, Audio, or Videos | https://gradio.app/guides/creating-a-custom-chatbot-with-blocks | Chatbots - Creating A Custom Chatbot With Blocks Guide |
Just like the classic Magic 8 Ball, a user should ask it a question orally and then wait for a response. Under the hood, we'll use Whisper to transcribe the audio and then use an LLM to generate a magic-8-ball-style answer. Finally, we'll use Parler TTS to read the response aloud.
| The Overview | https://gradio.app/guides/streaming-ai-generated-audio | Streaming - Streaming Ai Generated Audio Guide |
First let's define the UI and put placeholders for all the python logic.
```python
import gradio as gr
with gr.Blocks() as block:
gr.HTML(
f"""
<h1 style='text-align: center;'> Magic 8 Ball 🎱 </h1>
<h3 style='text-align: center;'> Ask a question and receive wisdom </h3>
<p style='... | The UI | https://gradio.app/guides/streaming-ai-generated-audio | Streaming - Streaming Ai Generated Audio Guide |
GPU](https://huggingface.co/zero-gpu-explorers) which has time-based quotas. Since generating the response can be done with Hugging Face's Inference API, we shouldn't include that code in our GPU function as it will needlessly use our GPU quota.
| The UI | https://gradio.app/guides/streaming-ai-generated-audio | Streaming - Streaming Ai Generated Audio Guide |
As mentioned above, we'll use [Hugging Face's Inference API](https://huggingface.co/docs/huggingface_hub/guides/inference) to transcribe the audio and generate a response from an LLM. After instantiating the client, I use the `automatic_speech_recognition` method (this automatically uses Whisper running on Hugging Face... | The Logic | https://gradio.app/guides/streaming-ai-generated-audio | Streaming - Streaming Ai Generated Audio Guide |
for you but are you ready for the dog?'")},
{"role": "user", "content": f"Magic 8 Ball please answer this question - {question}"}]
response = client.chat_completion(messages, max_tokens=64, seed=random.randint(1, 5000),
model="mistralai/Mistral-7B-Instruct... | The Logic | https://gradio.app/guides/streaming-ai-generated-audio | Streaming - Streaming Ai Generated Audio Guide |
sage=True
).to(device)
tokenizer = AutoTokenizer.from_pretrained(repo_id)
feature_extractor = AutoFeatureExtractor.from_pretrained(repo_id)
sampling_rate = model.audio_encoder.config.sampling_rate
frame_rate = model.audio_encoder.config.frame_rate
@spaces.GPU
def read_response(answer):
play_steps_in_s = 2.0
... | The Logic | https://gradio.app/guides/streaming-ai-generated-audio | Streaming - Streaming Ai Generated Audio Guide |
You can see our final application [here](https://huggingface.co/spaces/gradio/magic-8-ball)!
| Conclusion | https://gradio.app/guides/streaming-ai-generated-audio | Streaming - Streaming Ai Generated Audio Guide |
Modern voice applications should feel natural and responsive, moving beyond the traditional "click-to-record" pattern. By combining Groq's fast inference capabilities with automatic speech detection, we can create a more intuitive interaction model where users can simply start talking whenever they want to engage with ... | Introduction | https://gradio.app/guides/automatic-voice-detection | Streaming - Automatic Voice Detection Guide |
Many voice apps currently work by the user clicking record, speaking, then stopping the recording. While this can be a powerful demo, the most natural mode of interaction with voice requires the app to dynamically detect when the user is speaking, so they can talk back and forth without having to continually click a re... | Background | https://gradio.app/guides/automatic-voice-detection | Streaming - Automatic Voice Detection Guide |
- **Gradio**: Provides the web interface and audio handling capabilities
- **@ricky0123/vad-web**: Handles voice activity detection
- **Groq**: Powers fast LLM inference for natural conversations
- **Whisper**: Transcribes speech to text
Setting Up the Environment
First, let’s install and import our essential librari... | Key Components | https://gradio.app/guides/automatic-voice-detection | Streaming - Automatic Voice Detection Guide |
e’ll create a function to transcribe the user’s audio input into text using Whisper, a powerful transcription model hosted on Groq. This transcription will also help us determine whether there’s meaningful speech in the input. Here’s how:
```python
def transcribe_audio(client, file_name):
if file_name is None:
... | Key Components | https://gradio.app/guides/automatic-voice-detection | Streaming - Automatic Voice Detection Guide |
ext.strip()
return None
```
We also need to interpret the audio data response. The process_whisper_response function takes the resulting completion from Whisper and checks if the audio was just background noise or had actual speaking that was transcribed. It uses a threshold of 0.7 to interpret the no_speech_... | Key Components | https://gradio.app/guides/automatic-voice-detection | Streaming - Automatic Voice Detection Guide |
ly detect when someone starts or stops speaking. Here’s how to implement it using ONNX in JavaScript:
```javascript
async function main() {
const script1 = document.createElement("script");
script1.src = "https://cdn.jsdelivr.net/npm/onnxruntime-web@1.14.0/dist/ort.js";
document.head.appendChild(script1)
const... | Key Components | https://gradio.app/guides/automatic-voice-detection | Streaming - Automatic Voice Detection Guide |
",
streaming=False,
waveform_options=gr.WaveformOptions(waveform_color="B83A4B"),
)
with gr.Row():
chatbot = gr.Chatbot(label="Conversation")
state = gr.State(value=AppState())
demo.launch(theme=theme, js=js)
```
In this code block, we’re using Gradio’s `Blocks` API to c... | Key Components | https://gradio.app/guides/automatic-voice-detection | Streaming - Automatic Voice Detection Guide |
1. When you open the app, the VAD system automatically initializes and starts listening for speech
2. As soon as you start talking, it triggers the recording automatically
3. When you stop speaking, the recording ends and:
- The audio is transcribed using Whisper
- The transcribed text is sent to the LLM
- The... | Summary | https://gradio.app/guides/automatic-voice-detection | Streaming - Automatic Voice Detection Guide |
Automatic speech recognition (ASR), the conversion of spoken speech to text, is a very important and thriving area of machine learning. ASR algorithms run on practically every smartphone, and are becoming increasingly embedded in professional workflows, such as digital assistants for nurses and doctors. Because ASR alg... | Introduction | https://gradio.app/guides/real-time-speech-recognition | Streaming - Real Time Speech Recognition Guide |
First, you will need to have an ASR model that you have either trained yourself or you will need to download a pretrained model. In this tutorial, we will start by using a pretrained ASR model from the model, `whisper`.
Here is the code to load `whisper` from Hugging Face `transformers`.
```python
from transformers i... | 1. Set up the Transformers ASR Model | https://gradio.app/guides/real-time-speech-recognition | Streaming - Real Time Speech Recognition Guide |
We will start by creating a _full-context_ ASR demo, in which the user speaks the full audio before using the ASR model to run inference. This is very easy with Gradio -- we simply create a function around the `pipeline` object above.
We will use `gradio`'s built in `Audio` component, configured to take input from the... | 2. Create a Full-Context ASR Demo with Transformers | https://gradio.app/guides/real-time-speech-recognition | Streaming - Real Time Speech Recognition Guide |
To make this a *streaming* demo, we need to make these changes:
1. Set `streaming=True` in the `Audio` component
2. Set `live=True` in the `Interface`
3. Add a `state` to the interface to store the recorded audio of a user
Tip: You can also set `time_limit` and `stream_every` parameters in the interface. The `time_li... | 3. Create a Streaming ASR Demo with Transformers | https://gradio.app/guides/real-time-speech-recognition | Streaming - Real Time Speech Recognition Guide |
First, we'll install the following requirements in our system:
```
opencv-python
torch
transformers>=4.43.0
spaces
```
Then, we'll download the model from the Hugging Face Hub:
```python
from transformers import RTDetrForObjectDetection, RTDetrImageProcessor
image_processor = RTDetrImageProcessor.from_pretrained("P... | Setting up the Model | https://gradio.app/guides/object-detection-from-video | Streaming - Object Detection From Video Guide |
Our inference function will accept a video and a desired confidence threshold.
Object detection models identify many objects and assign a confidence score to each object. The lower the confidence, the higher the chance of a false positive. So we will let our users set the confidence threshold.
Our function will iterat... | The Inference Function | https://gradio.app/guides/object-detection-from-video | Streaming - Object Detection From Video Guide |
frame = cv2.resize( frame, (0,0), fx=0.5, fy=0.5)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
if n_frames % SUBSAMPLE == 0:
batch.append(frame)
if len(batch) == 2 * desired_fps:
inputs = image_processor(images=batch, return_tensors="pt").to("cuda")
w... | The Inference Function | https://gradio.app/guides/object-detection-from-video | Streaming - Object Detection From Video Guide |
dth, height))` line. The `video_codec` is how we specify the type of video file. Only "mp4" and "ts" files are supported for video sreaming at the moment.
2. **The Inference Loop**
For each frame in the video, we will resize it to be half the size. OpenCV reads files in `BGR` format, so will convert to the expected ... | The Inference Function | https://gradio.app/guides/object-detection-from-video | Streaming - Object Detection From Video Guide |
The UI code is pretty similar to other kinds of Gradio apps.
We'll use a standard two-column layout so that users can see the input and output videos side by side.
In order for streaming to work, we have to set `streaming=True` in the output video. Setting the video
to autoplay is not necessary but it's a better expe... | The Gradio Demo | https://gradio.app/guides/object-detection-from-video | Streaming - Object Detection From Video Guide |
You can check out our demo hosted on Hugging Face Spaces [here](https://huggingface.co/spaces/gradio/rt-detr-object-detection).
It is also embedded on this page below
$demo_rt-detr-object-detection | Conclusion | https://gradio.app/guides/object-detection-from-video | Streaming - Object Detection From Video Guide |
The next generation of AI user interfaces is moving towards audio-native experiences. Users will be able to speak to chatbots and receive spoken responses in return. Several models have been built under this paradigm, including GPT-4o and [mini omni](https://github.com/gpt-omni/mini-omni).
In this guide, we'll walk yo... | Introduction | https://gradio.app/guides/conversational-chatbot | Streaming - Conversational Chatbot Guide |
Our application will enable the following user experience:
1. Users click a button to start recording their message
2. The app detects when the user has finished speaking and stops recording
3. The user's audio is passed to the omni model, which streams back a response
4. After omni mini finishes speaking, the user's ... | Application Overview | https://gradio.app/guides/conversational-chatbot | Streaming - Conversational Chatbot Guide |
We'll stream the user's audio from their microphone to the server and determine if the user has stopped speaking on each new chunk of audio.
Here's our `process_audio` function:
```python
import numpy as np
from utils import determine_pause
def process_audio(audio: tuple, state: AppState):
if state.stream is Non... | Processing User Audio | https://gradio.app/guides/conversational-chatbot | Streaming - Conversational Chatbot Guide |
After processing the user's audio, we need to generate and stream the chatbot's response. Here's our `response` function:
```python
import io
import tempfile
from pydub import AudioSegment
def response(state: AppState):
if not state.pause_detected and not state.started_talking:
return None, AppState()
... | Generating the Response | https://gradio.app/guides/conversational-chatbot | Streaming - Conversational Chatbot Guide |
Now let's put it all together using Gradio's Blocks API:
```python
import gradio as gr
def start_recording_user(state: AppState):
if not state.stopped:
return gr.Audio(recording=True)
with gr.Blocks() as demo:
with gr.Row():
with gr.Column():
input_audio = gr.Audio(
... | Building the Gradio App | https://gradio.app/guides/conversational-chatbot | Streaming - Conversational Chatbot Guide |
This guide demonstrates how to build a conversational chatbot application using Gradio and the mini omni model. You can adapt this framework to create various audio-based chatbot demos. To see the full application in action, visit the Hugging Face Spaces demo: https://huggingface.co/spaces/gradio/omni-mini
Feel free t... | Conclusion | https://gradio.app/guides/conversational-chatbot | Streaming - Conversational Chatbot Guide |
Start by installing all the dependencies. Add the following lines to a `requirements.txt` file and run `pip install -r requirements.txt`:
```bash
opencv-python
fastrtc
onnxruntime-gpu
```
We'll use the ONNX runtime to speed up YOLOv10 inference. This guide assumes you have access to a GPU. If you don't, change `onnxr... | Setting up | https://gradio.app/guides/object-detection-from-webcam-with-webrtc | Streaming - Object Detection From Webcam With Webrtc Guide |
We'll download the YOLOv10 model from the Hugging Face hub and instantiate a custom inference class to use this model.
The implementation of the inference class isn't covered in this guide, but you can find the source code [here](https://huggingface.co/spaces/freddyaboulton/webrtc-yolov10n/blob/main/inference.pyL9) i... | The Inference Function | https://gradio.app/guides/object-detection-from-webcam-with-webrtc | Streaming - Object Detection From Webcam With Webrtc Guide |
The Gradio demo is straightforward, but we'll implement a few specific features:
1. Use the `WebRTC` custom component to ensure input and output are sent to/from the server with WebRTC.
2. The [WebRTC](https://github.com/freddyaboulton/gradio-webrtc) component will serve as both an input and output component.
3. Util... | The Gradio Demo | https://gradio.app/guides/object-detection-from-webcam-with-webrtc | Streaming - Object Detection From Webcam With Webrtc Guide |
Our app is hosted on Hugging Face Spaces [here](https://huggingface.co/spaces/freddyaboulton/webrtc-yolov10n).
You can use this app as a starting point to build real-time image applications with Gradio. Don't hesitate to open issues in the space or in the [FastRTC GitHub repo](https://github.com/gradio-app/fastrtc) i... | Conclusion | https://gradio.app/guides/object-detection-from-webcam-with-webrtc | Streaming - Object Detection From Webcam With Webrtc Guide |
Gradio themes are the easiest way to customize the look and feel of your app. You can choose from a variety of themes, or create your own. To do so, pass the `theme=` kwarg to the `launch()` method of the `Blocks` constructor. For example:
```python
with gr.Blocks() as demo:
... your code here
demo.launch(theme=gr... | Adding custom CSS to your demo | https://gradio.app/guides/custom-CSS-and-JS | Building With Blocks - Custom Css And Js Guide |
You can `elem_id` to add an HTML element `id` to any component, and `elem_classes` to add a class or list of classes. This will allow you to select elements more easily with CSS. This approach is also more likely to be stable across Gradio versions as built-in class names or ids may change (however, as mentioned in the... | The `elem_id` and `elem_classes` Arguments | https://gradio.app/guides/custom-CSS-and-JS | Building With Blocks - Custom Css And Js Guide |
There are 3 ways to add javascript code to your Gradio demo:
1. You can add JavaScript code as a string to the `js` parameter of the `Blocks` or `Interface` initializer. This will run the JavaScript code when the demo is first loaded.
Below is an example of adding custom js to show an animated welcome message when th... | Adding custom JavaScript to your demo | https://gradio.app/guides/custom-CSS-and-JS | Building With Blocks - Custom Css And Js Guide |
n open-source web application showcasing various features and capabilities.">
<!-- Facebook Meta Tags -->
<meta property="og:url" content="https://example.com">
<meta property="og:type" content="website">
<meta property="og:title" content="Sample App">
<meta property="og:description" content="An open-source web applic... | Adding custom JavaScript to your demo | https://gradio.app/guides/custom-CSS-and-JS | Building With Blocks - Custom Css And Js Guide |
"input":
case "textarea":
break;
default:
if (e.key.toLowerCase() == "s" && e.shiftKey) {
document.getElementById("my_btn").click();
}
}
}
document.addEventListener('keypress', shortcuts, false);
</script>
"""
with gr.Blocks() as demo:
action_button = gr.Butt... | Adding custom JavaScript to your demo | https://gradio.app/guides/custom-CSS-and-JS | Building With Blocks - Custom Css And Js Guide |
In the example below, we will create a variable number of Textboxes. When the user edits the input Textbox, we create a Textbox for each letter in the input. Try it out below:
$code_render_split_simple
$demo_render_split_simple
See how we can now create a variable number of Textboxes using our custom logic - in this ... | Dynamic Number of Components | https://gradio.app/guides/dynamic-apps-with-render-decorator | Building With Blocks - Dynamic Apps With Render Decorator Guide |
If you're creating components, you probably want to attach event listeners to them as well. Let's take a look at an example that takes in a variable number of Textbox as input, and merges all the text into a single box.
$code_render_merge_simple
$demo_render_merge_simple
Let's take a look at what's happening here:
1... | Dynamic Event Listeners | https://gradio.app/guides/dynamic-apps-with-render-decorator | Building With Blocks - Dynamic Apps With Render Decorator Guide |
The `key=` argument tells Gradio that a component being created in a render function corresponds to the same logical component as in the previous render.
This allows Gradio to reuse the existing browser element instead of destroying and recreating it on every render. It also preserves the user's entered value across r... | Closer Look at `keys=` parameter | https://gradio.app/guides/dynamic-apps-with-render-decorator | Building With Blocks - Dynamic Apps With Render Decorator Guide |
Let's look at two examples that use all the features above. First, try out the to-do list app below:
$code_todo_list
$demo_todo_list
Note that almost the entire app is inside a single `gr.render` that reacts to the tasks `gr.State` variable. This variable is a nested list, which presents some complexity. If you desi... | Putting it Together | https://gradio.app/guides/dynamic-apps-with-render-decorator | Building With Blocks - Dynamic Apps With Render Decorator Guide |
The `gr.HTML` component can also be used to create custom input components by triggering events. You will provide `js_on_load`, javascript code that runs when the component loads. The code has access to the `trigger` function to trigger events that Gradio can listen to, and the object `props` which has access to all th... | Triggering Events and Custom Input Components | https://gradio.app/guides/custom-HTML-components | Building With Blocks - Custom Html Components Guide |
ce when the component is first rendered. If your component creates new elements dynamically that need event listeners, attach the event listener to a parent element that exists when the component loads, and check for the target. For example:
```js
element.addEventListener('click', (e) =>
if (e.target && e.target.m... | Triggering Events and Custom Input Components | https://gradio.app/guides/custom-HTML-components | Building With Blocks - Custom Html Components Guide |
The `watch` function, available inside `js_on_load`, lets you run a callback whenever specific props change when the component is an output to a Python event listener. Read current values directly from `props` inside the callback.
```js
// Watch a single prop
watch('value', () => {
console.log('value is now:', pro... | Watching Props with `watch` | https://gradio.app/guides/custom-HTML-components | Building With Blocks - Custom Html Components Guide |
The `head` parameter lets you load external JavaScript or CSS libraries directly on the component. The `head` content is injected and loaded **before** `js_on_load` runs, so your code can immediately use the library.
```python
gr.HTML(
value=[30, 70, 45, 90, 60],
html_template="<canvas id='chart'></canvas>",
... | Loading Third-Party Scripts with `head` | https://gradio.app/guides/custom-HTML-components | Building With Blocks - Custom Html Components Guide |
You can call Python functions directly from your `js_on_load` code using the `server_functions` parameter. Pass a list of Python functions to `server_functions`, and they become available as async methods on a `server` object inside `js_on_load`.
$code_html_server_functions
$demo_html_server_functions
| Server Functions | https://gradio.app/guides/custom-HTML-components | Building With Blocks - Custom Html Components Guide |
If you are reusing the same HTML component in multiple places, you can create a custom component class by subclassing `gr.HTML` and setting default values for the templates and other arguments. Here's an example of creating a reusable StarRating component.
$code_star_rating_component
$demo_star_rating_component
Note:... | Component Classes | https://gradio.app/guides/custom-HTML-components | Building With Blocks - Custom Html Components Guide |
The `gr.HTML` component can also be used as a container for other Gradio components using the `@children` placeholder. This allows you to create custom layouts with HTML/CSS.
The `@children` must be at the top-level of the `html_template`. Since children cannot be nested inside the template, target the parent element... | Embedding Components in HTML | https://gradio.app/guides/custom-HTML-components | Building With Blocks - Custom Html Components Guide |
Once you've built a custom HTML component, you can share it with the community by pushing it to the [HTML Components Gallery](https://www.gradio.app/custom-components/html-gallery). The gallery lets anyone browse, interact with, and copy the Python code for community-contributed components.
Call `push_to_hub` on any `... | Sharing Components with `push_to_hub` | https://gradio.app/guides/custom-HTML-components | Building With Blocks - Custom Html Components Guide |
Keep in mind that using `gr.HTML` to create custom components involves injecting raw HTML and JavaScript into your Gradio app. Be cautious about using untrusted user input into `html_template` and `js_on_load`, as this could lead to cross-site scripting (XSS) vulnerabilities.
You should also expect that any Python ev... | Security Considerations | https://gradio.app/guides/custom-HTML-components | Building With Blocks - Custom Html Components Guide |
- Browse the [HTML Components Gallery](https://www.gradio.app/custom-components/html-gallery) to see what the community has built and copy components into your own apps.
- Check out more examples in [this directory](https://github.com/gradio-app/gradio/tree/main/gradio/components/custom_html_components).
- Share your o... | Next Steps | https://gradio.app/guides/custom-HTML-components | Building With Blocks - Custom Html Components Guide |
Elements within a `with gr.Row` clause will all be displayed horizontally. For example, to display two Buttons side by side:
```python
with gr.Blocks() as demo:
with gr.Row():
btn1 = gr.Button("Button 1")
btn2 = gr.Button("Button 2")
```
You can set every element in a Row to have the same height. ... | Rows | https://gradio.app/guides/controlling-layout | Building With Blocks - Controlling Layout Guide |
Components within a Column will be placed vertically atop each other. Since the vertical layout is the default layout for Blocks apps anyway, to be useful, Columns are usually nested within Rows. For example:
$code_rows_and_columns
$demo_rows_and_columns
See how the first column has two Textboxes arranged vertically.... | Columns and Nesting | https://gradio.app/guides/controlling-layout | Building With Blocks - Controlling Layout Guide |
Some components support setting height and width. These parameters accept either a number (interpreted as pixels) or a string. Using a string allows the direct application of any CSS unit to the encapsulating Block element.
Below is an example illustrating the use of viewport width (vw):
```python
import gradio as gr... | Dimensions | https://gradio.app/guides/controlling-layout | Building With Blocks - Controlling Layout Guide |
You can also create Tabs using the `with gr.Tab('tab_name'):` clause. Any component created inside of a `with gr.Tab('tab_name'):` context appears in that tab. Consecutive Tab clauses are grouped together so that a single tab can be selected at one time, and only the components within that Tab's context are shown.
For... | Tabs and Accordions | https://gradio.app/guides/controlling-layout | Building With Blocks - Controlling Layout Guide |
The sidebar is a collapsible panel that renders child components on the left side of the screen and can be expanded or collapsed.
For example:
$code_blocks_sidebar
Learn more about [Sidebar](https://gradio.app/docs/gradio/sidebar) in the docs.
| Sidebar | https://gradio.app/guides/controlling-layout | Building With Blocks - Controlling Layout Guide |
In order to provide a guided set of ordered steps, a controlled workflow, you can use the `Walkthrough` component with accompanying `Step` components.
The `Walkthrough` component has a visual style and user experience tailored for this usecase.
Authoring this component is very similar to `Tab`, except it is the app d... | Multi-step walkthroughs | https://gradio.app/guides/controlling-layout | Building With Blocks - Controlling Layout Guide |
Both Components and Layout elements have a `visible` argument that can set initially and also updated. Setting `gr.Column(visible=...)` on a Column can be used to show or hide a set of Components.
$code_blocks_form
$demo_blocks_form
| Visibility | https://gradio.app/guides/controlling-layout | Building With Blocks - Controlling Layout Guide |
In some cases, you might want to define components before you actually render them in your UI. For instance, you might want to show an examples section using `gr.Examples` above the corresponding `gr.Textbox` input. Since `gr.Examples` requires as a parameter the input component object, you will need to first define th... | Defining and Rendering Components Separately | https://gradio.app/guides/controlling-layout | Building With Blocks - Controlling Layout Guide |
Take a look at the demo below.
$code_hello_blocks
$demo_hello_blocks
- First, note the `with gr.Blocks() as demo:` clause. The Blocks app code will be contained within this clause.
- Next come the Components. These are the same Components used in `Interface`. However, instead of being passed to some constructor, Comp... | Blocks Structure | https://gradio.app/guides/blocks-and-event-listeners | Building With Blocks - Blocks And Event Listeners Guide |
In the example above, you'll notice that you are able to edit Textbox `name`, but not Textbox `output`. This is because any Component that acts as an input to an event listener is made interactive. However, since Textbox `output` acts only as an output, Gradio determines that it should not be made interactive. You can ... | Event Listeners and Interactivity | https://gradio.app/guides/blocks-and-event-listeners | Building With Blocks - Blocks And Event Listeners Guide |
Take a look at the demo below:
$code_blocks_hello
$demo_blocks_hello
Instead of being triggered by a click, the `welcome` function is triggered by typing in the Textbox `inp`. This is due to the `change()` event listener. Different Components support different event listeners. For example, the `Video` Component suppo... | Types of Event Listeners | https://gradio.app/guides/blocks-and-event-listeners | Building With Blocks - Blocks And Event Listeners Guide |
A Blocks app is not limited to a single data flow the way Interfaces are. Take a look at the demo below:
$code_reversible_flow
$demo_reversible_flow
Note that `num1` can act as input to `num2`, and also vice-versa! As your apps get more complex, you will have many data flows connecting various Components.
Here's an ... | Multiple Data Flows | https://gradio.app/guides/blocks-and-event-listeners | Building With Blocks - Blocks And Event Listeners Guide |
The event listeners you've seen so far have a single input component. If you'd like to have multiple input components pass data to the function, you have two options on how the function can accept input component values:
1. as a list of arguments, or
2. as a single dictionary of values, keyed by the component
Let's s... | Function Input List vs Set | https://gradio.app/guides/blocks-and-event-listeners | Building With Blocks - Blocks And Event Listeners Guide |
Similarly, you may return values for multiple output components either as:
1. a list of values, or
2. a dictionary keyed by the component
Let's first see an example of (1), where we set the values of two output components by returning two values:
```python
with gr.Blocks() as demo:
food_box = gr.Number(value=10,... | Function Return List vs Dict | https://gradio.app/guides/blocks-and-event-listeners | Building With Blocks - Blocks And Event Listeners Guide |
d_box` component.
Dictionary returns are helpful when an event listener affects many components on return, or conditionally affects outputs and not others.
Keep in mind that with dictionary returns, we still need to specify the possible outputs in the event listener.
| Function Return List vs Dict | https://gradio.app/guides/blocks-and-event-listeners | Building With Blocks - Blocks And Event Listeners Guide |
The return value of an event listener function is usually the updated value of the corresponding output Component. Sometimes we want to update the configuration of the Component as well, such as the visibility. In this case, we return a new Component, setting the properties we want to change.
$code_blocks_essay_simple... | Updating Component Configurations | https://gradio.app/guides/blocks-and-event-listeners | Building With Blocks - Blocks And Event Listeners Guide |
In some cases, you may want to leave a component's value unchanged. Gradio includes a special function, `gr.skip()`, which can be returned from your function. Returning this function will keep the output component (or components') values as is. Let us illustrate with an example:
$code_skip
$demo_skip
Note the differe... | Not Changing a Component's Value | https://gradio.app/guides/blocks-and-event-listeners | Building With Blocks - Blocks And Event Listeners Guide |
You can also run events consecutively by using the `then` method of an event listener. This will run an event after the previous event has finished running. This is useful for running events that update components in multiple steps.
For example, in the chatbot example below, we first update the chatbot with the user m... | Running Events Consecutively | https://gradio.app/guides/blocks-and-event-listeners | Building With Blocks - Blocks And Event Listeners Guide |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.