text stringlengths 0 2k | heading1 stringlengths 3 79 | source_page_url stringclasses 189
values | source_page_title stringclasses 189
values |
|---|---|---|---|
No! You can start off from an existing gradio component as a template, see the [five minute guide](./custom-components-in-five-minutes).
You can also start from an existing custom component if you'd like to tweak it further. Once you find the source code of a custom component you like, clone the code to your computer a... | Do I always need to start my component from scratch? | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions Guide |
You can develop and build your custom component without hosting or connecting to HuggingFace.
If you would like to share your component with the gradio community, it is recommended to publish your package to PyPi and host a demo on HuggingFace so that anyone can install it or try it out.
| Do I need to host my custom component on HuggingFace Spaces? | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions Guide |
You must implement the `preprocess`, `postprocess`, `example_payload`, and `example_value` methods. If your component does not use a data model, you must also define the `api_info`, `flag`, and `read_from_flag` methods. Read more in the [backend guide](./backend).
| What methods are mandatory for implementing a custom component in Gradio? | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions Guide |
A `data_model` defines the expected data format for your component, simplifying the component development process and self-documenting your code. It streamlines API usage and example caching.
| What is the purpose of a `data_model` in Gradio custom components? | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions Guide |
Utilizing `FileData` is crucial for components that expect file uploads. It ensures secure file handling, automatic caching, and streamlined client library functionality.
| Why is it important to use `FileData` for components dealing with file uploads? | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions Guide |
You can define event triggers in the `EVENTS` class attribute by listing the desired event names, which automatically adds corresponding methods to your component.
| How can I add event triggers to my custom Gradio component? | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions Guide |
Yes, it is possible to create custom components without a `data_model`, but you are going to have to manually implement `api_info`, `flag`, and `read_from_flag` methods.
| Can I implement a custom Gradio component without defining a `data_model`? | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions Guide |
We have prepared this [collection](https://huggingface.co/collections/gradio/custom-components-65497a761c5192d981710b12) of custom components on the HuggingFace Hub that you can use to get started!
| Are there sample custom components I can learn from? | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions Guide |
We're working on creating a gallery to make it really easy to discover new custom components.
In the meantime, you can search for HuggingFace Spaces that are tagged as a `gradio-custom-component` [here](https://huggingface.co/search/full-text?q=gradio-custom-component&type=space) | How can I find custom components created by the Gradio community? | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions Guide |
By default, all custom component packages are called `gradio_<component-name>` where `component-name` is the name of the component's python class in lowercase.
As an example, let's walkthrough changing the name of a component from `gradio_mytextbox` to `supertextbox`.
1. Modify the `name` in the `pyproject.toml` fil... | The Package Name | https://gradio.app/guides/configuration | Custom Components - Configuration Guide |
By default, only the custom component python class is a top level export.
This means that when users type `from gradio_<component-name> import ...`, the only class that will be available is the custom component class.
To add more classes as top level exports, modify the `__all__` property in `__init__.py`
```python
f... | Top Level Python Exports | https://gradio.app/guides/configuration | Custom Components - Configuration Guide |
You can add python dependencies by modifying the `dependencies` key in `pyproject.toml`
```bash
dependencies = ["gradio", "numpy", "PIL"]
```
Tip: Remember to run `gradio cc install` when you add dependencies!
| Python Dependencies | https://gradio.app/guides/configuration | Custom Components - Configuration Guide |
You can add JavaScript dependencies by modifying the `"dependencies"` key in `frontend/package.json`
```json
"dependencies": {
"@gradio/atoms": "0.2.0-beta.4",
"@gradio/statustracker": "0.3.0-beta.6",
"@gradio/utils": "0.2.0-beta.4",
"your-npm-package": "<version>"
}
```
| Javascript Dependencies | https://gradio.app/guides/configuration | Custom Components - Configuration Guide |
By default, the CLI will place the Python code in `backend` and the JavaScript code in `frontend`.
It is not recommended to change this structure since it makes it easy for a potential contributor to look at your source code and know where everything is.
However, if you did want to this is what you would have to do:
1... | Directory Structure | https://gradio.app/guides/configuration | Custom Components - Configuration Guide |
Sticking to the defaults will make it easy for others to understand and contribute to your custom component.
After all, the beauty of open source is that anyone can help improve your code!
But if you ever need to deviate from the defaults, you know how! | Conclusion | https://gradio.app/guides/configuration | Custom Components - Configuration Guide |
For this demo we will be tweaking the existing Gradio `Chatbot` component to display text and media files in the same message.
Let's create a new custom component directory by templating off of the `Chatbot` component source code.
```bash
gradio cc create MultimodalChatbot --template Chatbot
```
And we're ready to go... | Part 1 - Creating our project | https://gradio.app/guides/multimodal-chatbot-part1 | Custom Components - Multimodal Chatbot Part1 Guide |
Open up the `multimodalchatbot.py` file in your favorite code editor and let's get started modifying the backend of our component.
The first thing we will do is create the `data_model` of our component.
The `data_model` is the data format that your python component will receive and send to the javascript client runnin... | Part 2a - The backend data_model | https://gradio.app/guides/multimodal-chatbot-part1 | Custom Components - Multimodal Chatbot Part1 Guide |
For the `preprocess` method, we will keep it simple and pass a list of `MultimodalMessage`s to the python functions that use this component as input.
This will let users of our component access the chatbot data with `.text` and `.files` attributes.
This is a design choice that you can modify in your implementation!
We... | Part 2b - The pre and postprocess methods | https://gradio.app/guides/multimodal-chatbot-part1 | Custom Components - Multimodal Chatbot Part1 Guide |
The frontend for the `Chatbot` component is divided into two parts - the `Index.svelte` file and the `shared/Chatbot.svelte` file.
The `Index.svelte` file applies some processing to the data received from the server and then delegates the rendering of the conversation to the `shared/Chatbot.svelte` file.
First we will ... | Part 3a - The Index.svelte file | https://gradio.app/guides/multimodal-chatbot-part1 | Custom Components - Multimodal Chatbot Part1 Guide |
Let's begin similarly to the `Index.svelte` file and let's first modify the type annotations.
Import `Mulimodal` message at the top of the `<script>` section and use it to type the `value` and `old_value` variables.
```ts
import type { MultimodalMessage } from "./utils";
export let value:
| [
Multimod... | Part 3b - the Chatbot.svelte file | https://gradio.app/guides/multimodal-chatbot-part1 | Custom Components - Multimodal Chatbot Part1 Guide |
own
message={message.text}
{latex_delimiters}
{sanitize_html}
{render_markdown}
{line_breaks}
on:load={scroll}
/>
{each message.files as file, k}
{if file !== null && file.file.mime_type?.includes("audio")}
<audio
data-testid="chatbot-audio"
controls
... | Part 3b - the Chatbot.svelte file | https://gradio.app/guides/multimodal-chatbot-part1 | Custom Components - Multimodal Chatbot Part1 Guide |
For this tutorial, let's keep the demo simple and just display a static conversation between a hypothetical user and a bot.
This demo will show how both the user and the bot can send files.
In part 2 of this tutorial series we will build a fully functional chatbot demo!
The demo code will look like the following:
``... | Part 4 - The demo | https://gradio.app/guides/multimodal-chatbot-part1 | Custom Components - Multimodal Chatbot Part1 Guide |
Let's build and deploy our demo with `gradio cc build` and `gradio cc deploy`!
You can check out our component deployed to [HuggingFace Spaces](https://huggingface.co/spaces/freddyaboulton/gradio_multimodalchatbot) and all of the source code is available [here](https://huggingface.co/spaces/freddyaboulton/gradio_multi... | Part 5 - Deploying and Conclusion | https://gradio.app/guides/multimodal-chatbot-part1 | Custom Components - Multimodal Chatbot Part1 Guide |
All components inherit from one of three classes `Component`, `FormComponent`, or `BlockContext`.
You need to inherit from one so that your component behaves like all other gradio components.
When you start from a template with `gradio cc create --template`, you don't need to worry about which one to choose since the t... | Which Class to Inherit From | https://gradio.app/guides/backend | Custom Components - Backend Guide |
When you inherit from any of these classes, the following methods must be implemented.
Otherwise the Python interpreter will raise an error when you instantiate your component!
`preprocess` and `postprocess`
Explained in the [Key Concepts](./key-component-conceptsthe-value-and-how-it-is-preprocessed-postprocessed) gu... | The methods you need to implement | https://gradio.app/guides/backend | Custom Components - Backend Guide |
pi_info(self) -> dict[str, list[str]]:
"""
A JSON-schema representation of the value that the `preprocess` expects and the `postprocess` returns.
"""
pass
```
`example_payload`
An example payload for your component, e.g. something that can be passed into the `.preprocess()` method
of your component. T... | The methods you need to implement | https://gradio.app/guides/backend | Custom Components - Backend Guide |
"""
Convert the data from the csv or jsonl file into the component state.
"""
return x
```
| The methods you need to implement | https://gradio.app/guides/backend | Custom Components - Backend Guide |
The `data_model` is how you define the expected data format your component's value will be stored in the frontend.
It specifies the data format your `preprocess` method expects and the format the `postprocess` method returns.
It is not necessary to define a `data_model` for your component but it greatly simplifies the ... | The `data_model` | https://gradio.app/guides/backend | Custom Components - Backend Guide |
example, the `Names` model will serialize the data to `{'names': ['freddy', 'pete']}` whereas the `NamesRoot` model will serialize it to `['freddy', 'pete']`.
```python
from typing import List
class Names(GradioModel):
names: List[str]
class NamesRoot(GradioRootModel):
root: List[str]
```
Even if your comp... | The `data_model` | https://gradio.app/guides/backend | Custom Components - Backend Guide |
If your component expects uploaded files as input, or returns saved files to the frontend, you **MUST** use the `FileData` to type the files in your `data_model`.
When you use the `FileData`:
* Gradio knows that it should allow serving this file to the frontend. Gradio automatically blocks requests to serve arbitrary... | Handling Files | https://gradio.app/guides/backend | Custom Components - Backend Guide |
The events triggers for your component are defined in the `EVENTS` class attribute.
This is a list that contains the string names of the events.
Adding an event to this list will automatically add a method with that same name to your component!
You can import the `Events` enum from `gradio.events` to access commonly u... | Adding Event Triggers To Your Component | https://gradio.app/guides/backend | Custom Components - Backend Guide |
Conclusion | https://gradio.app/guides/backend | Custom Components - Backend 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 |
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 |
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 |
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 |
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 |
```python
from sqlalchemy import create_engine
import pandas as pd
engine = create_engine('sqlite:///your_database.db')
with gr.Blocks() as demo:
gr.LinePlot(pd.read_sql_query("SELECT time, price from flight_info;", engine), x="time", y="price")
```
Let's see a a more interactive plot involving filters that modi... | SQLite | https://gradio.app/guides/connecting-to-a-database | Data Science And Plots - Connecting To A Database Guide |
If you're using a different database format, all you have to do is swap out the engine, e.g.
```python
engine = create_engine('postgresql://username:password@host:port/database_name')
```
```python
engine = create_engine('mysql://username:password@host:port/database_name')
```
```python
engine = create_engine('oracl... | Postgres, mySQL, and other databases | https://gradio.app/guides/connecting-to-a-database | Data Science And Plots - Connecting To A Database Guide |
Use any of the standard Gradio form components to filter your data. You can do this via event listeners or function-as-value syntax. Let's look at the event listener approach first:
$code_plot_guide_filters_events
$demo_plot_guide_filters_events
And this would be the function-as-value approach for the same demo.
$co... | Filters | https://gradio.app/guides/filters-tables-and-stats | Data Science And Plots - Filters Tables And Stats Guide |
Add `gr.DataFrame` and `gr.Label` to your dashboard for some hard numbers.
$code_plot_guide_tables_stats
$demo_plot_guide_tables_stats
| Tables and Stats | https://gradio.app/guides/filters-tables-and-stats | Data Science And Plots - Filters Tables And Stats Guide |
Plots accept a pandas Dataframe as their value. The plot also takes `x` and `y` which represent the names of the columns that represent the x and y axes respectively. Here's a simple example:
$code_plot_guide_line
$demo_plot_guide_line
All plots have the same API, so you could swap this out with a `gr.ScatterPlot`:
... | Creating a Plot with a pd.Dataframe | https://gradio.app/guides/creating-plots | Data Science And Plots - Creating Plots Guide |
You can break out your plot into series using the `color` argument.
$code_plot_guide_series_nominal
$demo_plot_guide_series_nominal
If you wish to assign series specific colors, use the `color_map` arg, e.g. `gr.ScatterPlot(..., color_map={'white': 'FF9988', 'asian': '88EEAA', 'black': '333388'})`
The color column c... | Breaking out Series by Color | https://gradio.app/guides/creating-plots | Data Science And Plots - Creating Plots Guide |
You can aggregate values into groups using the `x_bin` and `y_aggregate` arguments. If your x-axis is numeric, providing an `x_bin` will create a histogram-style binning:
$code_plot_guide_aggregate_quantitative
$demo_plot_guide_aggregate_quantitative
If your x-axis is a string type instead, they will act as the categ... | Aggregating Values | https://gradio.app/guides/creating-plots | Data Science And Plots - Creating Plots Guide |
You can use the `.select` listener to select regions of a plot. Click and drag on the plot below to select part of the plot.
$code_plot_guide_selection
$demo_plot_guide_selection
You can combine this and the `.double_click` listener to create some zoom in/out effects by changing `x_lim` which sets the bounds of the x... | Selecting Regions | https://gradio.app/guides/creating-plots | Data Science And Plots - Creating Plots Guide |
Take a look how you can have an interactive dashboard where the plots are functions of other Components.
$code_plot_guide_interactive
$demo_plot_guide_interactive
It's that simple to filter and control the data presented in your visualization! | Making an Interactive Dashboard | https://gradio.app/guides/creating-plots | Data Science And Plots - Creating Plots Guide |
Time plots need a datetime column on the x-axis. Here's a simple example with some flight data:
$code_plot_guide_temporal
$demo_plot_guide_temporal
| Creating a Plot with a pd.Dataframe | https://gradio.app/guides/time-plots | Data Science And Plots - Time Plots Guide |
You may wish to bin data by time buckets. Use `x_bin` to do so, using a string suffix with "s", "m", "h" or "d", such as "15m" or "1d".
$code_plot_guide_aggregate_temporal
$demo_plot_guide_aggregate_temporal
| Aggregating by Time | https://gradio.app/guides/time-plots | Data Science And Plots - Time Plots Guide |
You can use `gr.DateTime` to accept input datetime data. This works well with plots for defining the x-axis range for the data.
$code_plot_guide_datetime
$demo_plot_guide_datetime
Note how `gr.DateTime` can accept a full datetime string, or a shorthand using `now - [0-9]+[smhd]` format to refer to a past time.
You w... | DateTime Components | https://gradio.app/guides/time-plots | Data Science And Plots - Time Plots Guide |
In many cases, you're working with live, realtime date, not a static dataframe. In this case, you'd update the plot regularly with a `gr.Timer()`. Assuming there's a `get_data` method that gets the latest dataframe:
```python
with gr.Blocks() as demo:
timer = gr.Timer(5)
plot1 = gr.BarPlot(x="time", y="price")... | RealTime Data | https://gradio.app/guides/time-plots | Data Science And Plots - Time Plots 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 |
If you're using LLMs in your workflow, adding this server will augment them with just the right context on gradio - which makes your experience a lot faster and smoother.
<video src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/mcp-docs.mp4" style="width:100%" controls p... | Why an MCP Server? | https://gradio.app/guides/using-docs-mcp | Mcp - Using Docs Mcp Guide |
For clients that support streamable HTTP (e.g. Cursor, Windsurf, Cline), simply add the following configuration to your MCP config:
```json
{
"mcpServers": {
"gradio": {
"url": "https://gradio-docs-mcp.hf.space/gradio_api/mcp/"
}
}
}
```
We've included step-by-step instructions for Cursor below, but... | Installing in the Clients | https://gradio.app/guides/using-docs-mcp | Mcp - Using Docs Mcp Guide |
There are currently only two tools in the server: `gradio_docs_mcp_load_gradio_docs` and `gradio_docs_mcp_search_gradio_docs`.
1. `gradio_docs_mcp_load_gradio_docs`: This tool takes no arguments and will load an /llms.txt style summary of Gradio's latest, full documentation. Very useful context the LLM can parse befo... | Tools | https://gradio.app/guides/using-docs-mcp | Mcp - Using Docs Mcp Guide |
The Model Context Protocol (MCP) standardizes how applications provide context to LLMs. It allows Claude to interact with external tools, like image generators, file systems, or APIs, etc.
| What is MCP? | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
- Python 3.10+
- An Anthropic API key
- Basic understanding of Python programming
| Prerequisites | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
First, install the required packages:
```bash
pip install gradio anthropic mcp
```
Create a `.env` file in your project directory and add your Anthropic API key:
```
ANTHROPIC_API_KEY=your_api_key_here
```
| Setup | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
The server provides tools that Claude can use. In this example, we'll create a server that generates images through [a HuggingFace space](https://huggingface.co/spaces/ysharma/SanaSprint).
Create a file named `gradio_mcp_server.py`:
```python
from mcp.server.fastmcp import FastMCP
import json
import sys
import io
imp... | Part 1: Building the MCP Server | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
"message": f"Error generating image: {str(e)}"
})
if __name__ == "__main__":
mcp.run(transport='stdio')
```
What this server does:
1. It creates an MCP server that exposes a `generate_image` tool
2. The tool connects to the SanaSprint model hosted on HuggingFace Spaces
3. It handles the asynchronous na... | Part 1: Building the MCP Server | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
Now let's create a Gradio chat interface as MCP Client that connects Claude to our MCP server.
Create a file named `app.py`:
```python
import asyncio
import os
import json
from typing import List, Dict, Any, Union
from contextlib import AsyncExitStack
import gradio as gr
from gradio.components.chatbot import ChatMes... | Part 2: Building the MCP Client with Gradio | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
iption,
"input_schema": tool.inputSchema
} for tool in response.tools]
tool_names = [tool["name"] for tool in self.tools]
return f"Connected to MCP server. Available tools: {', '.join(tool_names)}"
def process_message(self, message: str, history: List[Union[Dict[str... | Part 2: Building the MCP Client with Gradio | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
ntent": content.text
})
elif content.type == 'tool_use':
tool_name = content.name
tool_args = content.input
result_messages.append({
"role": "assistant",
"content": f"I'l... | Part 2: Building the MCP Client with Gradio | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
})
result_content = result.content
if isinstance(result_content, list):
result_content = "\n".join(str(item) for item in result_content)
try:
result_json = json.loads(result_content)
... | Part 2: Building the MCP Client with Gradio | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
"parent_id": f"result_{tool_name}",
"id": f"raw_result_{tool_name}",
"title": "Raw Output"
}
})
claude_messages.append({"role": "user", "content": f"Tool result for {tool_name}: {result_... | Part 2: Building the MCP Client with Gradio | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.