text stringlengths 0 2k | heading1 stringlengths 3 79 | source_page_url stringclasses 188
values | source_page_title stringclasses 188
values |
|---|---|---|---|
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 |
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 |
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 |
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 |
**Prerequisite**: Gradio requires [Python 3.10 or higher](https://www.python.org/downloads/).
We recommend installing Gradio using `pip`, which is included by default in Python. Run this in your terminal or command prompt:
```bash
pip install --upgrade gradio
```
Tip: It is best to install Gradio in a virtual envi... | Installation | https://gradio.app/guides/quickstart | Getting Started - Quickstart Guide |
You can run Gradio in your favorite code editor, Jupyter notebook, Google Colab, or anywhere else you write Python. Let's write your first Gradio app:
$code_hello_world_4
Tip: We shorten the imported name from <code>gradio</code> to <code>gr</code>. This is a widely adopted convention for better readability of code... | Building Your First Demo | https://gradio.app/guides/quickstart | Getting Started - Quickstart Guide |
turn one or more outputs.
The `Interface` class has three core arguments:
- `fn`: the function to wrap a user interface (UI) around
- `inputs`: the Gradio component(s) to use for the input. The number of components should match the number of arguments in your function.
- `outputs`: the Gradio component(s) to use for... | Building Your First Demo | https://gradio.app/guides/quickstart | Getting Started - Quickstart Guide |
What good is a beautiful demo if you can't share it? Gradio lets you easily share a machine learning demo without having to worry about the hassle of hosting on a web server. Simply set `share=True` in `launch()`, and a publicly accessible URL will be created for your demo. Let's revisit our example demo, but change t... | Sharing Your Demo | https://gradio.app/guides/quickstart | Getting Started - Quickstart Guide |
So far, we've been discussing the `Interface` class, which is a high-level class that lets you build demos quickly with Gradio. But what else does Gradio include?
Custom Demos with `gr.Blocks`
Gradio offers a low-level approach for designing web apps with more customizable layouts and data flows with the `gr.Blocks` ... | An Overview of Gradio | https://gradio.app/guides/quickstart | Getting Started - Quickstart Guide |
.app/guides/getting-started-with-the-python-client) (`gradio_client`): query any Gradio app programmatically in Python.
* [Gradio JavaScript Client](https://www.gradio.app/guides/getting-started-with-the-js-client) (`@gradio/client`): query any Gradio app programmatically in JavaScript.
* [Hugging Face Spaces](https://... | An Overview of Gradio | https://gradio.app/guides/quickstart | Getting Started - Quickstart Guide |
Keep learning about Gradio sequentially using the Gradio Guides, which include explanations as well as example code and embedded interactive demos. Next up: [let's dive deeper into the Interface class](https://www.gradio.app/guides/the-interface-class).
Or, if you already know the basics and are looking for something ... | What's Next? | https://gradio.app/guides/quickstart | Getting Started - Quickstart 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 |
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 |
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 is used to let Gradio know that the same component is being generated when your render function re-runs. This does two things:
1. The same element in the browser is re-used from the previous render for this Component. This gives browser performance gains - as there's no need to destroy and rebuild ... | 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 |
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 |
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 |
Let's start by using `llama-index` on top of `openai` to build a RAG chatbot on any text or PDF files that you can demo and share in less than 30 lines of code. You'll need to have an OpenAI key for this example (keep reading for the free, open-source equivalent!)
$code_llm_llamaindex
| Llama Index | https://gradio.app/guides/chatinterface-examples | Chatbots - Chatinterface Examples Guide |
Here's an example using `langchain` on top of `openai` to build a general-purpose chatbot. As before, you'll need to have an OpenAI key for this example.
$code_llm_langchain
Tip: For quick prototyping, the community-maintained <a href='https://github.com/AK391/langchain-gradio'>langchain-gradio repo</a> makes it eve... | LangChain | https://gradio.app/guides/chatinterface-examples | Chatbots - Chatinterface Examples Guide |
Of course, we could also use the `openai` library directy. Here a similar example to the LangChain , but this time with streaming as well:
Tip: For quick prototyping, the <a href='https://github.com/gradio-app/openai-gradio'>openai-gradio library</a> makes it even easier to build chatbots on top of OpenAI models.
| OpenAI | https://gradio.app/guides/chatinterface-examples | Chatbots - Chatinterface Examples Guide |
Of course, in many cases you want to run a chatbot locally. Here's the equivalent example using the SmolLM2-135M-Instruct model using the Hugging Face `transformers` library.
$code_llm_hf_transformers
| Hugging Face `transformers` | https://gradio.app/guides/chatinterface-examples | Chatbots - Chatinterface Examples Guide |
The SambaNova Cloud API provides access to full-precision open-source models, such as the Llama family. Here's an example of how to build a Gradio app around the SambaNova API
$code_llm_sambanova
Tip: For quick prototyping, the <a href='https://github.com/gradio-app/sambanova-gradio'>sambanova-gradio library</a> mak... | SambaNova | https://gradio.app/guides/chatinterface-examples | Chatbots - Chatinterface Examples Guide |
The Hyperbolic AI API provides access to many open-source models, such as the Llama family. Here's an example of how to build a Gradio app around the Hyperbolic
$code_llm_hyperbolic
Tip: For quick prototyping, the <a href='https://github.com/HyperbolicLabs/hyperbolic-gradio'>hyperbolic-gradio library</a> makes it ev... | Hyperbolic | https://gradio.app/guides/chatinterface-examples | Chatbots - Chatinterface Examples Guide |
Anthropic's Claude model can also be used via API. Here's a simple 20 questions-style game built on top of the Anthropic API:
$code_llm_claude
| Anthropic's Claude | https://gradio.app/guides/chatinterface-examples | Chatbots - Chatinterface Examples Guide |
Chatbots are a popular application of large language models (LLMs). Using Gradio, you can easily build a chat application and share that with your users, or try it yourself using an intuitive UI.
This tutorial uses `gr.ChatInterface()`, which is a high-level abstraction that allows you to create your chatbot UI fast, ... | Introduction | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
If you have a chat server serving an OpenAI-API compatible endpoint (such as Ollama), you can spin up a ChatInterface in a single line of Python. First, also run `pip install openai`. Then, with your own URL, model, and optional token:
```python
import gradio as gr
gr.load_chat("http://localhost:11434/v1/", model="ll... | Note for OpenAI-API compatible endpoints | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
To create a chat application with `gr.ChatInterface()`, the first thing you should do is define your **chat function**. In the simplest case, your chat function should accept two arguments: `message` and `history` (the arguments can be named anything, but must be in this order).
- `message`: a `str` representing the u... | Defining a chat function | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
t take user input or the previous history into account! Here's another simple example showing how to incorporate a user's input as well as the history.
```python
import gradio as gr
def alternatingly_agree(message, history):
if len([h for h in history if h['role'] == "assistant"]) % 2 == 0:
return f"Yes, ... | Defining a chat function | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
In your chat function, you can use `yield` to generate a sequence of partial responses, each replacing the previous ones. This way, you'll end up with a streaming chatbot. It's that simple!
```python
import time
import gradio as gr
def slow_echo(message, history):
for i in range(len(message)):
time.sleep(... | Streaming chatbots | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
If you're familiar with Gradio's `gr.Interface` class, the `gr.ChatInterface` includes many of the same arguments that you can use to customize the look and feel of your Chatbot. For example, you can:
- add a title and description above your chatbot using `title` and `description` arguments.
- add a theme or custom cs... | Customizing the Chat UI | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
le of how we to apply the parameters we've discussed in this section:
```python
import gradio as gr
def yes_man(message, history):
if message.endswith("?"):
return "Yes"
else:
return "Ask me anything!"
gr.ChatInterface(
yes_man,
chatbot=gr.Chatbot(height=300),
textbox=gr.Textbox(p... | Customizing the Chat UI | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
You may want to add multimodal capabilities to your chat interface. For example, you may want users to be able to upload images or files to your chatbot and ask questions about them. You can make your chatbot "multimodal" by passing in a single parameter (`multimodal=True`) to the `gr.ChatInterface` class.
When `multi... | Multimodal Chat Interface | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
ox` to the `textbox` parameter. You can customize the `MultimodalTextbox` further by passing in the `sources` parameter, which is a list of sources to enable. Here's an example that illustrates how to set up and customize and multimodal chat interface:
```python
import gradio as gr
def count_images(message, history... | Multimodal Chat Interface | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
You may want to add additional inputs to your chat function and expose them to your users through the chat UI. For example, you could add a textbox for a system prompt, or a slider that sets the number of tokens in the chatbot's response. The `gr.ChatInterface` class supports an `additional_inputs` parameter which can ... | Additional Inputs | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
s to the `examples` parameter, where each inner list represents one sample, and each inner list should be `1 + len(additional_inputs)` long. The first element in the inner list should be the example value for the chat message, and each subsequent element should be an example value for one of the additional inputs, in o... | Additional Inputs | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
In the same way that you can accept additional inputs into your chat function, you can also return additional outputs. Simply pass in a list of components to the `additional_outputs` parameter in `gr.ChatInterface` and return additional values for each component from your chat function. Here's an example that extracts ... | Additional Outputs | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
We mentioned earlier that in the simplest case, your chat function should return a `str` response, which will be rendered as Markdown in the chatbot. However, you can also return more complex responses as we discuss below:
**Returning files or Gradio components**
Currently, the following Gradio components can be dis... | Returning Complex Responses | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
ma of the `gr.ChatMessage` data class as well as two internal typed dictionaries:
```py
MessageContent = Union[str, FileDataDict, FileData, Component]
@dataclass
class ChatMessage:
content: MessageContent | list[MessageContent]
metadata: MetadataDict = None
options: list[OptionDict] = None
class Metada... | Returning Complex Responses | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
corresponding to the `options` key should be a list of dictionaries, each with a `value` (a string that is the value that should be sent to the chat function when this response is clicked) and an optional `label` (if provided, is the text displayed as the preset response instead of the `value`).
This example illustr... | Returning Complex Responses | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
You may wish to modify the value of the chatbot with your own events, other than those prebuilt in the `gr.ChatInterface`. For example, you could create a dropdown that prefills the chat history with certain conversations or add a separate button to clear the conversation history. The `gr.ChatInterface` supports these ... | Modifying the Chatbot Value Directly | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.