text stringlengths 0 2k | heading1 stringlengths 3 79 | source_page_url stringclasses 189
values | source_page_title stringclasses 189
values |
|---|---|---|---|
Building a dashboard from a public Google Sheet is very easy, thanks to the [`pandas` library](https://pandas.pydata.org/):
1\. Get the URL of the Google Sheets that you want to use. To do this, simply go to the Google Sheets, click on the "Share" button in the top-right corner, and then click on the "Get shareable li... | Public Google Sheets | https://gradio.app/guides/creating-a-realtime-dashboard-from-google-sheets | Other Tutorials - Creating A Realtime Dashboard From Google Sheets Guide |
For private Google Sheets, the process requires a little more work, but not that much! The key difference is that now, you must authenticate yourself to authorize access to the private Google Sheets.
Authentication
To authenticate yourself, obtain credentials from Google Cloud. Here's [how to set up google cloud cred... | Private Google Sheets | https://gradio.app/guides/creating-a-realtime-dashboard-from-google-sheets | Other Tutorials - Creating A Realtime Dashboard From Google Sheets Guide |
google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/email_id"
}
```
Querying
Once you have the credentials `.json` file, you can use the following steps to query your Google Sheet:
1\. Cl... | Private Google Sheets | https://gradio.app/guides/creating-a-realtime-dashboard-from-google-sheets | Other Tutorials - Creating A Realtime Dashboard From Google Sheets Guide |
. To do this, we just pass the function into the respective components, and set the `every` parameter based on how frequently (in seconds) we would like the component to refresh. Here's the Gradio code:
```python
import gradio as gr
with gr.Blocks() as demo:
gr.Markdown("📈 Real-Time Line Plot")
with gr.Row()... | Private Google Sheets | https://gradio.app/guides/creating-a-realtime-dashboard-from-google-sheets | Other Tutorials - Creating A Realtime Dashboard From Google Sheets Guide |
And that's all there is to it! With just a few lines of code, you can use `gradio` and other libraries to read data from a public or private Google Sheet and then display and plot the data in a real-time dashboard.
| Conclusion | https://gradio.app/guides/creating-a-realtime-dashboard-from-google-sheets | Other Tutorials - Creating A Realtime Dashboard From Google Sheets Guide |
When you demo a machine learning model, you might want to collect data from users who try the model, particularly data points in which the model is not behaving as expected. Capturing these "hard" data points is valuable because it allows you to improve your machine learning model and make it more reliable and robust.
... | Introduction | https://gradio.app/guides/using-flagging | Other Tutorials - Using Flagging Guide |
Flagging with Gradio's `Interface` is especially easy. By default, underneath the output components, there is a button marked **Flag**. When a user testing your model sees input with interesting output, they can click the flag button to send the input and output data back to the machine where the demo is running. The s... | The **Flag** button in `gradio.Interface` | https://gradio.app/guides/using-flagging | Other Tutorials - Using Flagging Guide |
flagged data is stored.
- `flagging_callback`: this parameter takes an instance of a subclass of the `FlaggingCallback` class
- Using this parameter allows you to write custom code that gets run when the flag button is clicked
- By default, this is set to an instance of `gr.JSONLogger`
| The **Flag** button in `gradio.Interface` | https://gradio.app/guides/using-flagging | Other Tutorials - Using Flagging Guide |
Within the directory provided by the `flagging_dir` argument, a JSON file will log the flagged data.
Here's an example: The code below creates the calculator interface embedded below it:
```python
import gradio as gr
def calculator(num1, operation, num2):
if operation == "add":
return num1 + num2
el... | What happens to flagged data? | https://gradio.app/guides/using-flagging | Other Tutorials - Using Flagging Guide |
` argument of Interface. Users will have to select one of these choices when flagging, and the option will be saved as an additional column to the CSV.
If we go back to the calculator example, the following code will create the interface embedded below it.
```python
iface = gr.Interface(
calculator,
["number"... | What happens to flagged data? | https://gradio.app/guides/using-flagging | Other Tutorials - Using Flagging Guide |
What about if you are using `gradio.Blocks`? On one hand, you have even more flexibility
with Blocks -- you can write whatever Python code you want to run when a button is clicked,
and assign that using the built-in events in Blocks.
At the same time, you might want to use an existing `FlaggingCallback` to avoid writi... | Flagging with Blocks | https://gradio.app/guides/using-flagging | Other Tutorials - Using Flagging Guide |
Important Note: please make sure your users understand when the data they submit is being saved, and what you plan on doing with it. This is especially important when you use `flagging_mode=auto` (when all of the data submitted through the demo is being flagged)
That's all! Happy building :)
| Privacy | https://gradio.app/guides/using-flagging | Other Tutorials - Using Flagging Guide |
Data visualization is a crucial aspect of data analysis and machine learning. The Gradio `DataFrame` component is a popular way to display tabular data within a web application.
But what if you want to stylize the table of data? What if you want to add background colors, partially highlight cells, or change the displ... | Introduction | https://gradio.app/guides/styling-the-gradio-dataframe | Other Tutorials - Styling The Gradio Dataframe Guide |
The Gradio `DataFrame` component now supports values of the type `Styler` from the `pandas` class. This allows us to reuse the rich existing API and documentation of the `Styler` class instead of inventing a new style format on our own. Here's a complete example of how it looks:
```python
import pandas as pd
import g... | The Pandas `Styler` | https://gradio.app/guides/styling-the-gradio-dataframe | Other Tutorials - Styling The Gradio Dataframe Guide |
, 32, 23]
})
Applying style to highlight the maximum value in each row
styler = df.style.highlight_max(color = 'lightgreen', axis = 0)
```
Now, we simply pass this object into the Gradio `DataFrame` and we can visualize our colorful table of data in 4 lines of python:
```python
import gradio as gr
with gr.Blocks()... | The Pandas `Styler` | https://gradio.app/guides/styling-the-gradio-dataframe | Other Tutorials - Styling The Gradio Dataframe Guide |
on of numbers displayed. Here's how you can do this:
```python
import pandas as pd
import gradio as gr
Creating a sample dataframe with floating numbers
df = pd.DataFrame({
"A" : [14.12345, 4.23456, 5.34567, 4.45678, 1.56789],
"B" : [5.67891, 2.78912, 54.89123, 3.91234, 2.12345],
... other columns
})
... | The Pandas `Styler` | https://gradio.app/guides/styling-the-gradio-dataframe | Other Tutorials - Styling The Gradio Dataframe Guide |
So far, we've been restricting ourselves to styling that is supported by the Pandas `Styler` class. But what if you want to create custom styles like partially highlighting cells based on their values:
. If the `DataFrame` component is interactive, then the styling information is ignored and instead the raw table values are shown instead.
The `DataFrame` component ... | Note about Interactivity | https://gradio.app/guides/styling-the-gradio-dataframe | Other Tutorials - Styling The Gradio Dataframe Guide |
This is just a taste of what's possible using the `gradio.DataFrame` component with the `Styler` class from `pandas`. Try it out and let us know what you think! | Conclusion 🎉 | https://gradio.app/guides/styling-the-gradio-dataframe | Other Tutorials - Styling The Gradio Dataframe Guide |
App-level parameters have been moved from `Blocks` to `launch()`
The `gr.Blocks` class constructor previously contained several parameters that applied to your entire Gradio app, specifically:
* `theme`: The theme for your Gradio app
* `css`: Custom CSS code as a string
* `css_paths`: Paths to custom CSS files
* `js`... | App-level Changes | https://gradio.app/guides/gradio-6-migration-guide | Other Tutorials - Gradio 6 Migration Guide Guide |
he "Built with Gradio" link
- `"settings"`: Shows the settings link
**Before (Gradio 5.x):**
```python
import gradio as gr
with gr.Blocks() as demo:
gr.Textbox(label="Input")
demo.launch(show_api=False)
```
**After (Gradio 6.x):**
```python
import gradio as gr
with gr.Blocks() as demo:
gr.Textbox(label... | App-level Changes | https://gradio.app/guides/gradio-6-migration-guide | Other Tutorials - Gradio 6 Migration Guide Guide |
o as gr
with gr.Blocks() as demo:
btn = gr.Button("Click me")
output = gr.Textbox()
btn.click(fn=lambda: "Hello", outputs=output, show_api=False)
demo.launch()
```
Or to completely disable the API:
```python
btn.click(fn=lambda: "Hello", outputs=output, api_name=False)
```
**After (Gradio 6.x)... | App-level Changes | https://gradio.app/guides/gradio-6-migration-guide | Other Tutorials - Gradio 6 Migration Guide Guide |
.ChatInterface` now use the name of the function you pass in as the default API endpoint name
- This makes the API more descriptive and consistent with `gr.Blocks` behavior
E.g. if your Gradio app is:
```python
import gradio as gr
def generate_text(prompt):
return f"Generated: {prompt}"
demo = gr.Interface(fn=g... | App-level Changes | https://gradio.app/guides/gradio-6-migration-guide | Other Tutorials - Gradio 6 Migration Guide Guide |
```python
chatbot = gr.Chatbot(value=[["Hello", "Hi there!"]], type="tuples")
```
**After (Gradio 6.x):**
```python
import gradio as gr
Must use messages format
chatbot = gr.Chatbot(
value=[
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hi there!"}
],
type="mes... | App-level Changes | https://gradio.app/guides/gradio-6-migration-guide | Other Tutorials - Gradio 6 Migration Guide Guide |
": "text", "text": "What is the capital of France?"}]},
{"role": "assistant", "content": [{"type": "text", "text": "Paris"}]}
]
```
**With files:**
When files are uploaded in the chat, they are represented as content blocks with `"type": "file"`. All content blocks (files and text) are grouped together in the sam... | App-level Changes | https://gradio.app/guides/gradio-6-migration-guide | Other Tutorials - Gradio 6 Migration Guide Guide |
Interface(
fn=predict,
inputs="text",
outputs="text",
examples=["Hello", "World"],
cache_examples=True,
cache_mode="lazy"
)
```
If you previously used `cache_examples=True` (which implied eager caching), no changes are required, as `cache_mode` defaults to `"eager"`.
| App-level Changes | https://gradio.app/guides/gradio-6-migration-guide | Other Tutorials - Gradio 6 Migration Guide Guide |
`gr.Video` no longer accepts tuple values for video and subtitles
The tuple format for returning video with subtitles has been deprecated. Instead of returning a tuple `(video_path, subtitle_path)`, you should now use the `gr.Video` component directly with the `subtitles` parameter.
**In Gradio 5.x:**
- You could ret... | Component-level Changes | https://gradio.app/guides/gradio-6-migration-guide | Other Tutorials - Gradio 6 Migration Guide Guide |
present in Gradio 5.x, explicitly set `padding=True`:
```python
html = gr.HTML("<div>Content</div>", padding=True)
```
`gr.Dataframe` `row_count` and `col_count` parameters restructured
The `row_count` and `col_count` parameters in `gr.Dataframe` have been restructured to provide more flexibility and clarity. The t... | Component-level Changes | https://gradio.app/guides/gradio-6-migration-guide | Other Tutorials - Gradio 6 Migration Guide Guide |
r.Dataframe(row_count=5, row_limits=None, column_count=3, column_limits=None)
```
Or with min/max constraints:
```python
Rows between 3 and 10, columns between 2 and 5
df = gr.Dataframe(row_count=5, row_limits=(3, 10), column_count=3, column_limits=(2, 5))
```
**Migration examples:**
- `row_count=(5, "fixed")` → `r... | Component-level Changes | https://gradio.app/guides/gradio-6-migration-guide | Other Tutorials - Gradio 6 Migration Guide Guide |
e`:
```python
import gradio as gr
chatbot = gr.Chatbot(allow_tags=False)
```
**Note:** You can also specify a list of specific tags to allow:
```python
chatbot = gr.Chatbot(allow_tags=["thinking", "tool_call"])
```
This will only preserve `<thinking>` and `<tool_call>` tags while removing all other custom tags.
... | Component-level Changes | https://gradio.app/guides/gradio-6-migration-guide | Other Tutorials - Gradio 6 Migration Guide Guide |
fore (Gradio 5.x):**
```python
audio = gr.Audio(min_length=1, max_length=10)
```
**After (Gradio 6.x):**
```python
audio = gr.Audio()
audio.upload(
fn=process_audio,
validator=lambda audio: gr.validators.is_audio_correct_length(audio, min_length=1, max_length=10),
inputs=audio
)
```
**`show_download_butt... | Component-level Changes | https://gradio.app/guides/gradio-6-migration-guide | Other Tutorials - Gradio 6 Migration Guide Guide |
``python
image = gr.Image(buttons=["download", "share", "fullscreen"])
```
`gr.Video` removed parameters
**`mirror_webcam`** - This parameter has been removed. Use `webcam_options` with `gr.WebcamOptions` instead.
**Before (Gradio 5.x):**
```python
video = gr.Video(mirror_webcam=True)
```
**After (Gradio 6.x):**
``... | Component-level Changes | https://gradio.app/guides/gradio-6-migration-guide | Other Tutorials - Gradio 6 Migration Guide Guide |
`gr.LogoutButton`** - This component has been removed. Use `gr.LoginButton` instead, which handles both login and logout processes.
**Before (Gradio 5.x):**
```python
logout_btn = gr.LogoutButton()
```
**After (Gradio 6.x):**
```python
login_btn = gr.LoginButton()
```
Native plot components removed parameters
The f... | Component-level Changes | https://gradio.app/guides/gradio-6-migration-guide | Other Tutorials - Gradio 6 Migration Guide Guide |
buttons=["copy"])
```
`gr.Markdown` removed parameters
**`show_copy_button`** - This parameter has been removed. Use the `buttons` parameter instead.
**Before (Gradio 5.x):**
```python
markdown = gr.Markdown(show_copy_button=True)
```
**After (Gradio 6.x):**
```python
markdown = gr.Markdown(buttons=["copy"])
```
`... | Component-level Changes | https://gradio.app/guides/gradio-6-migration-guide | Other Tutorials - Gradio 6 Migration Guide Guide |
`gradio sketch` command removed
The `gradio sketch` command-line tool has been deprecated and completely removed in Gradio 6. This tool was used to create Gradio apps through a visual interface.
**In Gradio 5.x:**
- You could run `gradio sketch` to launch an interactive GUI for building Gradio apps
- The tool would g... | CLI Changes | https://gradio.app/guides/gradio-6-migration-guide | Other Tutorials - Gradio 6 Migration Guide Guide |
`hf_token` parameter renamed to `token` in `Client`
The `hf_token` parameter in the `Client` class has been renamed to `token` for consistency and simplicity.
**Before (Gradio 5.x):**
```python
from gradio_client import Client
client = Client("abidlabs/my-private-space", hf_token="hf_...")
```
**After (Gradio 6.x)... | Python Client Changes | https://gradio.app/guides/gradio-6-migration-guide | Other Tutorials - Gradio 6 Migration Guide Guide |
"username/space-name")
result = client.predict("/predict", inputs)
except AppError as e:
Explicitly catch AppError
print(f"App error: {e}")
except ValueError as e:
This will no longer catch AppError
print(f"Value error: {e}")
```
| Python Client Changes | https://gradio.app/guides/gradio-6-migration-guide | Other Tutorials - Gradio 6 Migration Guide Guide |
Gradio is a Python library that allows you to quickly create customizable web apps for your machine learning models and data processing pipelines. Gradio apps can be deployed on [Hugging Face Spaces](https://hf.space) for free.
In some cases though, you might want to deploy a Gradio app on your own web server. You mig... | Introduction | https://gradio.app/guides/running-gradio-on-your-web-server-with-nginx | Other Tutorials - Running Gradio On Your Web Server With Nginx Guide |
1. Start by editing the Nginx configuration file on your web server. By default, this is located at: `/etc/nginx/nginx.conf`
In the `http` block, add the following line to include server block configurations from a separate file:
```bash
include /etc/nginx/sites-enabled/*;
```
2. Create a new file in the `/etc/nginx... | Editing your Nginx configuration file | https://gradio.app/guides/running-gradio-on-your-web-server-with-nginx | Other Tutorials - Running Gradio On Your Web Server With Nginx Guide |
1. Before you launch your Gradio app, you'll need to set the `root_path` to be the same as the subpath that you specified in your nginx configuration. This is necessary for Gradio to run on any subpath besides the root of the domain.
*Note:* Instead of a subpath, you can also provide a complete URL for `root_path`... | Run your Gradio app on your web server | https://gradio.app/guides/running-gradio-on-your-web-server-with-nginx | Other Tutorials - Running Gradio On Your Web Server With Nginx Guide |
1. If you are in a tmux session, exit by typing CTRL+B (or CMD+B), followed by the "D" key.
2. Finally, restart nginx by running `sudo systemctl restart nginx`.
And that's it! If you visit `https://example.com/gradio-demo` on your browser, you should see your Gradio app running there
| Restart Nginx | https://gradio.app/guides/running-gradio-on-your-web-server-with-nginx | Other Tutorials - Running Gradio On Your Web Server With Nginx Guide |
Encoder functions to send audio as base64-encoded data and images as base64-encoded JPEG.
```python
import base64
import numpy as np
from io import BytesIO
from PIL import Image
def encode_audio(data: np.ndarray) -> dict:
"""Encode audio data (int16 mono) for Gemini."""
return {
"mime_type": "audio/pc... | 1) Encoders for audio and images | https://gradio.app/guides/create-immersive-demo | Other Tutorials - Create Immersive Demo Guide |
This handler:
- Opens a Gemini Live session on startup
- Receives streaming audio from Gemini and yields it back to the client
- Sends microphone audio as it arrives
- Sends a video frame at most once per second (to avoid flooding the API)
- Optionally sends an uploaded image (`gr.Image`) alongside the webcam frame
``... | 2) Implement the Gemini audio-video handler | https://gradio.app/guides/create-immersive-demo | Other Tutorials - Create Immersive Demo Guide |
model="gemini-2.0-flash-exp",
config=config,
) as session:
self.session = session
while not self.quit.is_set():
turn = self.session.receive()
try:
async for response in turn:
if data := response.dat... | 2) Implement the Gemini audio-video handler | https://gradio.app/guides/create-immersive-demo | Other Tutorials - Create Immersive Demo Guide |
Audio: emit Gemini’s audio back to the client
async def emit(self):
array = await wait_for_item(self.audio_queue, 0.01)
if array is not None:
return (self.output_sample_rate, array)
return array
async def shutdown(self) -> None:
if self.session:
self.qui... | 2) Implement the Gemini audio-video handler | https://gradio.app/guides/create-immersive-demo | Other Tutorials - Create Immersive Demo Guide |
We’ll add an optional `gr.Image` input alongside the `WebRTC` component. The handler will access this in `self.latest_args[1]` when sending frames to Gemini.
```python
import gradio as gr
from fastrtc import Stream, WebRTC, get_hf_turn_credentials
stream = Stream(
handler=GeminiHandler(),
modality="audio-vid... | 3) Setup Stream and Gradio UI | https://gradio.app/guides/create-immersive-demo | Other Tutorials - Create Immersive Demo Guide |
This guide explains how you can run background tasks from your gradio app.
Background tasks are operations that you'd like to perform outside the request-response
lifecycle of your app either once or on a periodic schedule.
Examples of background tasks include periodically synchronizing data to an external database or
... | Introduction | https://gradio.app/guides/running-background-tasks | Other Tutorials - Running Background Tasks Guide |
We will be creating a simple "Google-forms-style" application to gather feedback from users of the gradio library.
We will use a local sqlite database to store our data, but we will periodically synchronize the state of the database
with a [HuggingFace Dataset](https://huggingface.co/datasets) so that our user reviews ... | Overview | https://gradio.app/guides/running-background-tasks | Other Tutorials - Running Background Tasks Guide |
Our application will store the name of the reviewer, their rating of gradio on a scale of 1 to 5, as well as
any comments they want to share about the library. Let's write some code that creates a database table to
store this data. We'll also write some functions to insert a review into that table and fetch the latest ... | Step 1 - Write your database logic 💾 | https://gradio.app/guides/running-background-tasks | Other Tutorials - Running Background Tasks Guide |
Now that we have our database logic defined, we can use gradio create a dynamic web page to ask our users for feedback!
```python
with gr.Blocks() as demo:
with gr.Row():
with gr.Column():
name = gr.Textbox(label="Name", placeholder="What is your name?")
review = gr.Radio(label="How... | Step 2 - Create a gradio app ⚡ | https://gradio.app/guides/running-background-tasks | Other Tutorials - Running Background Tasks Guide |
We could call `demo.launch()` after step 2 and have a fully functioning application. However,
our data would be stored locally on our machine. If the sqlite file were accidentally deleted, we'd lose all of our reviews!
Let's back up our data to a dataset on the HuggingFace hub.
Create a dataset [here](https://huggingf... | Step 3 - Synchronize with HuggingFace Datasets 🤗 | https://gradio.app/guides/running-background-tasks | Other Tutorials - Running Background Tasks Guide |
print("updating db")
repo.push_to_hub(blocking=False, commit_message=f"Updating data at {datetime.datetime.now()}")
scheduler = BackgroundScheduler()
scheduler.add_job(func=backup_db, trigger="interval", seconds=60)
scheduler.start()
```
| Step 3 - Synchronize with HuggingFace Datasets 🤗 | https://gradio.app/guides/running-background-tasks | Other Tutorials - Running Background Tasks Guide |
You can use the HuggingFace [Spaces](https://huggingface.co/spaces) platform to deploy this application for free ✨
If you haven't used Spaces before, follow the previous guide [here](/using_hugging_face_integrations).
You will have to use the `HUB_TOKEN` environment variable as a secret in the Guides.
| Step 4 (Bonus) - Deployment to HuggingFace Spaces | https://gradio.app/guides/running-background-tasks | Other Tutorials - Running Background Tasks Guide |
Congratulations! You know how to run background tasks from your gradio app on a schedule ⏲️.
Checkout the application running on Spaces [here](https://huggingface.co/spaces/freddyaboulton/gradio-google-forms).
The complete code is [here](https://huggingface.co/spaces/freddyaboulton/gradio-google-forms/blob/main/app.py... | Conclusion | https://gradio.app/guides/running-background-tasks | Other Tutorials - Running Background Tasks Guide |
In this Guide, we'll walk you through:
- Introduction of ONNX, ONNX model zoo, Gradio, and Hugging Face Spaces
- How to setup a Gradio demo for EfficientNet-Lite4
- How to contribute your own Gradio demos for the ONNX organization on Hugging Face
Here's an [example](https://onnx-efficientnet-lite4.hf.space/) of an ON... | Introduction | https://gradio.app/guides/Gradio-and-ONNX-on-Hugging-Face | Other Tutorials - Gradio And Onnx On Hugging Face Guide |
Open Neural Network Exchange ([ONNX](https://onnx.ai/)) is an open standard format for representing machine learning models. ONNX is supported by a community of partners who have implemented it in many frameworks and tools. For example, if you have trained a model in TensorFlow or PyTorch, you can convert it to ONNX ea... | What is the ONNX Model Zoo? | https://gradio.app/guides/Gradio-and-ONNX-on-Hugging-Face | Other Tutorials - Gradio And Onnx On Hugging Face Guide |
Gradio
Gradio lets users demo their machine learning models as a web app all in python code. Gradio wraps a python function into a user interface and the demos can be launched inside jupyter notebooks, colab notebooks, as well as embedded in your own website and hosted on Hugging Face Spaces for free.
Get started [he... | What are Hugging Face Spaces & Gradio? | https://gradio.app/guides/Gradio-and-ONNX-on-Hugging-Face | Other Tutorials - Gradio And Onnx On Hugging Face Guide |
There are a lot of Jupyter notebooks in the ONNX Model Zoo for users to test models. Previously, users needed to download the models themselves and run those notebooks locally for testing. With Hugging Face, the testing process can be much simpler and more user-friendly. Users can easily try certain ONNX Model Zoo mode... | How did Hugging Face help the ONNX Model Zoo? | https://gradio.app/guides/Gradio-and-ONNX-on-Hugging-Face | Other Tutorials - Gradio And Onnx On Hugging Face Guide |
ONNX Runtime is a cross-platform inference and training machine-learning accelerator. It makes live Gradio demos with ONNX Model Zoo model on Hugging Face possible.
ONNX Runtime inference can enable faster customer experiences and lower costs, supporting models from deep learning frameworks such as PyTorch and TensorF... | What is the role of ONNX Runtime? | https://gradio.app/guides/Gradio-and-ONNX-on-Hugging-Face | Other Tutorials - Gradio And Onnx On Hugging Face Guide |
EfficientNet-Lite 4 is the largest variant and most accurate of the set of EfficientNet-Lite models. It is an integer-only quantized model that produces the highest accuracy of all of the EfficientNet models. It achieves 80.4% ImageNet top-1 accuracy, while still running in real-time (e.g. 30ms/image) on a Pixel 4 CPU.... | Setting up a Gradio Demo for EfficientNet-Lite4 | https://gradio.app/guides/Gradio-and-ONNX-on-Hugging-Face | Other Tutorials - Gradio And Onnx On Hugging Face Guide |
the image with a proportional scale
def resize_with_aspectratio(img, out_height, out_width, scale=87.5, inter_pol=cv2.INTER_LINEAR):
height, width, _ = img.shape
new_height = int(100. * out_height / scale)
new_width = int(100. * out_width / scale)
if height > width:
w = new_width
h = int... | Setting up a Gradio Demo for EfficientNet-Lite4 | https://gradio.app/guides/Gradio-and-ONNX-on-Hugging-Face | Other Tutorials - Gradio And Onnx On Hugging Face Guide |
examples=examples).launch()
```
| Setting up a Gradio Demo for EfficientNet-Lite4 | https://gradio.app/guides/Gradio-and-ONNX-on-Hugging-Face | Other Tutorials - Gradio And Onnx On Hugging Face Guide |
- Add model to the [onnx model zoo](https://github.com/onnx/models/blob/main/.github/PULL_REQUEST_TEMPLATE.md)
- Create an account on Hugging Face [here](https://huggingface.co/join).
- See list of models left to add to ONNX organization, please refer to the table with the [Models list](https://github.com/onnx/modelsmo... | How to contribute Gradio demos on HF spaces using ONNX models | https://gradio.app/guides/Gradio-and-ONNX-on-Hugging-Face | Other Tutorials - Gradio And Onnx On Hugging Face Guide |
When you are building a Gradio demo, particularly out of Blocks, you may find it cumbersome to keep re-running your code to test your changes.
To make it faster and more convenient to write your code, we've made it easier to "reload" your Gradio apps instantly when you are developing in a **Python IDE** (like VS Code,... | Why Hot Reloading? | https://gradio.app/guides/developing-faster-with-reload-mode | Other Tutorials - Developing Faster With Reload Mode Guide |
If you are building Gradio Blocks using a Python IDE, your file of code (let's name it `run.py`) might look something like this:
```python
import gradio as gr
with gr.Blocks() as demo:
gr.Markdown("Greetings from Gradio!")
inp = gr.Textbox(placeholder="What is your name?")
out = gr.Textbox()
inp.chan... | Python IDE Reload 🔥 | https://gradio.app/guides/developing-faster-with-reload-mode | Other Tutorials - Developing Faster With Reload Mode Guide |
emo as the 2nd parameter in your code. So if your `run.py` file looked like this:
```python
import gradio as gr
with gr.Blocks() as my_demo:
gr.Markdown("Greetings from Gradio!")
inp = gr.Textbox(placeholder="What is your name?")
out = gr.Textbox()
inp.change(fn=lambda x: f"Welcome, {x}!",
... | Python IDE Reload 🔥 | https://gradio.app/guides/developing-faster-with-reload-mode | Other Tutorials - Developing Faster With Reload Mode Guide |
By default, reload mode will re-run your entire script for every change you make.
But there are some cases where this is not desirable.
For example, loading a machine learning model should probably only happen once to save time. There are also some Python libraries that use C or Rust extensions that throw errors when t... | Controlling the Reload 🎛️ | https://gradio.app/guides/developing-faster-with-reload-mode | Other Tutorials - Developing Faster With Reload Mode Guide |
You can also enable Gradio's **Vibe Mode**, which, which provides an in-browser chat that can be used to write or edit your Gradio app using natural language. To enable this, simply run use the `--vibe` flag with Gradio, e.g. `gradio --vibe app.py`.
Vibe Mode lets you describe commands using natural language and have ... | Vibe Mode | https://gradio.app/guides/developing-faster-with-reload-mode | Other Tutorials - Developing Faster With Reload Mode Guide |
What about if you use Jupyter Notebooks (or Colab Notebooks, etc.) to develop code? We got something for you too!
We've developed a **magic command** that will create and run a Blocks demo for you. To use this, load the gradio extension at the top of your notebook:
`%load_ext gradio`
Then, in the cell that you are d... | Jupyter Notebook Magic 🔮 | https://gradio.app/guides/developing-faster-with-reload-mode | Other Tutorials - Developing Faster With Reload Mode Guide |
Now that you know how to develop quickly using Gradio, start building your own!
If you are looking for inspiration, try exploring demos other people have built with Gradio, [browse public Hugging Face Spaces](http://hf.space/) 🤗
| Next Steps | https://gradio.app/guides/developing-faster-with-reload-mode | Other Tutorials - Developing Faster With Reload Mode Guide |
Image classification is a central task in computer vision. Building better classifiers to classify what object is present in a picture is an active area of research, as it has applications stretching from facial recognition to manufacturing quality control.
State-of-the-art image classifiers are based on the _transfor... | Introduction | https://gradio.app/guides/image-classification-with-vision-transformers | Other Tutorials - Image Classification With Vision Transformers Guide |
First, we will need an image classification model. For this tutorial, we will use a model from the [Hugging Face Model Hub](https://huggingface.co/models?pipeline_tag=image-classification). The Hub contains thousands of models covering dozens of different machine learning tasks.
Expand the Tasks category on the left s... | Step 1 — Choosing a Vision Image Classification Model | https://gradio.app/guides/image-classification-with-vision-transformers | Other Tutorials - Image Classification With Vision Transformers Guide |
When using a model from the Hugging Face Hub, we do not need to define the input or output components for the demo. Similarly, we do not need to be concerned with the details of preprocessing or postprocessing.
All of these are automatically inferred from the model tags.
Besides the import statement, it only takes a s... | Step 2 — Loading the Vision Transformer Model with Gradio | https://gradio.app/guides/image-classification-with-vision-transformers | Other Tutorials - Image Classification With Vision Transformers Guide |
**[OpenAPI](https://www.openapis.org/)** is a widely adopted standard for describing RESTful APIs in a machine-readable format, typically as a JSON file.
You can create a Gradio UI from an OpenAPI Spec **in 1 line of Python**, instantly generating an interactive web interface for any API, making it accessible for de... | Introduction | https://gradio.app/guides/from-openapi-spec | Other Tutorials - From Openapi Spec Guide |
Gradio now provides a convenient function, `gr.load_openapi`, that can automatically generate a Gradio app from an OpenAPI v3 specification. This function parses the spec, creates UI components for each endpoint and parameter, and lets you interact with the API directly from your browser.
Here's a minimal example:
``... | How it works | https://gradio.app/guides/from-openapi-spec | Other Tutorials - From Openapi Spec Guide |
Once your Gradio app is running, you can share the URL with others so they can try out the API through a friendly web interface—no code required. For even more power, you can launch the app as an MCP (Model Control Protocol) server using [Gradio's MCP integration](https://www.gradio.app/guides/building-mcp-server-with-... | Next steps | https://gradio.app/guides/from-openapi-spec | Other Tutorials - From Openapi Spec Guide |
To use Gradio with BigQuery, you will need to obtain your BigQuery credentials and use them with the [BigQuery Python client](https://pypi.org/project/google-cloud-bigquery/). If you already have BigQuery credentials (as a `.json` file), you can skip this section. If not, you can do this for free in just a couple of mi... | Setting up your BigQuery Credentials | https://gradio.app/guides/creating-a-dashboard-from-bigquery-data | Other Tutorials - Creating A Dashboard From Bigquery Data Guide |
Once you have the credentials, you will need to use the BigQuery Python client to authenticate using your credentials. To do this, you will need to install the BigQuery Python client by running the following command in the terminal:
```bash
pip install google-cloud-bigquery[pandas]
```
You'll notice that we've instal... | Using the BigQuery Client | https://gradio.app/guides/creating-a-dashboard-from-bigquery-data | Other Tutorials - Creating A Dashboard From Bigquery Data Guide |
Once you have a function to query the data, you can use the `gr.DataFrame` component from the Gradio library to display the results in a tabular format. This is a useful way to inspect the data and make sure that it has been queried correctly.
Here is an example of how to use the `gr.DataFrame` component to display th... | Building the Real-Time Dashboard | https://gradio.app/guides/creating-a-dashboard-from-bigquery-data | Other Tutorials - Creating A Dashboard From Bigquery Data Guide |
It seems that cryptocurrencies, [NFTs](https://www.nytimes.com/interactive/2022/03/18/technology/nft-guide.html), and the web3 movement are all the rage these days! Digital assets are being listed on marketplaces for astounding amounts of money, and just about every celebrity is debuting their own NFT collection. While... | Introduction | https://gradio.app/guides/create-your-own-friends-with-a-gan | Other Tutorials - Create Your Own Friends With A Gan Guide |
Originally proposed in [Goodfellow et al. 2014](https://arxiv.org/abs/1406.2661), GANs are made up of neural networks which compete with the intention of outsmarting each other. One network, known as the _generator_, is responsible for generating images. The other network, the _discriminator_, receives an image at a ti... | GANs: a very brief introduction | https://gradio.app/guides/create-your-own-friends-with-a-gan | Other Tutorials - Create Your Own Friends With A Gan Guide |
To generate new images with a GAN, you only need the generator model. There are many different architectures that the generator could use, but for this demo we'll use a pretrained GAN generator model with the following architecture:
```python
from torch import nn
class Generator(nn.Module):
Refer to the link belo... | Step 1 — Create the Generator model | https://gradio.app/guides/create-your-own-friends-with-a-gan | Other Tutorials - Create Your Own Friends With A Gan Guide |
The `predict` function is the key to making Gradio work! Whatever inputs we choose through the Gradio interface will get passed through our `predict` function, which should operate on the inputs and generate outputs that we can display with Gradio output components. For GANs it's common to pass random noise into our mo... | Step 2 — Defining a `predict` function | https://gradio.app/guides/create-your-own-friends-with-a-gan | Other Tutorials - Create Your Own Friends With A Gan Guide |
At this point you can even run the code you have with `predict(<SOME_NUMBER>)`, and you'll find your freshly generated punks in your file system at `./punks.png`. To make a truly interactive demo, though, we'll build out a simple interface with Gradio. Our goals here are to:
- Set a slider input so users can choose th... | Step 3 — Creating a Gradio interface | https://gradio.app/guides/create-your-own-friends-with-a-gan | Other Tutorials - Create Your Own Friends With A Gan Guide |
Generating 4 punks at a time is a good start, but maybe we'd like to control how many we want to make each time. Adding more inputs to our Gradio interface is as simple as adding another item to the `inputs` list that we pass to `gr.Interface`:
```python
gr.Interface(
predict,
inputs=[
gr.Slider(0, 100... | Step 4 — Even more punks! | https://gradio.app/guides/create-your-own-friends-with-a-gan | Other Tutorials - Create Your Own Friends With A Gan Guide |
Your Gradio app is pretty much good to go, but you can add a few extra things to really make it ready for the spotlight ✨
We can add some examples that users can easily try out by adding this to the `gr.Interface`:
```python
gr.Interface(
...
keep everything as it is, and then add
examples=[[123, 15], [42... | Step 5 - Polishing it up | https://gradio.app/guides/create-your-own-friends-with-a-gan | Other Tutorials - Create Your Own Friends With A Gan Guide |
4, 2, 0, bias=False),
nn.BatchNorm2d(ngf),
nn.ReLU(True),
nn.ConvTranspose2d(ngf, nc, 4, 2, 1, bias=False),
nn.Tanh(),
)
def forward(self, input):
output = self.network(input)
return output
model = Generator()
weights_path = hf_hub_download(... | Step 5 - Polishing it up | https://gradio.app/guides/create-your-own-friends-with-a-gan | Other Tutorials - Create Your Own Friends With A Gan Guide |
Gradio features [blocks](https://www.gradio.app/docs/blocks) to easily layout applications. To use this feature, you need to stack or nest layout components and create a hierarchy with them. This isn't difficult to implement and maintain for small projects, but after the project gets more complex, this component hierar... | Introduction | https://gradio.app/guides/wrapping-layouts | Other Tutorials - Wrapping Layouts Guide |
We are going to follow the implementation from this Huggingface Space example:
<gradio-app
space="gradio/wrapping-layouts">
</gradio-app>
| Example | https://gradio.app/guides/wrapping-layouts | Other Tutorials - Wrapping Layouts Guide |
The wrapping utility has two important classes. The first one is the ```LayoutBase``` class and the other one is the ```Application``` class.
We are going to look at the ```render``` and ```attach_event``` functions of them for brevity. You can look at the full implementation from [the example code](https://huggingfac... | Implementation | https://gradio.app/guides/wrapping-layouts | Other Tutorials - Wrapping Layouts Guide |
at this means is by calling the components' render functions under the ```with``` syntax, we are actually simulating the default implementation.
So now let's consider two nested ```with```s to see how the outer one works. For this, let's expand our example with the ```Tab``` component:
```python
with Tab():
with ... | Implementation | https://gradio.app/guides/wrapping-layouts | Other Tutorials - Wrapping Layouts Guide |
ct``` variable in the ```Application``` class's ```attach_event``` function.
Application Class
1. Render Function
```python
other Application implementations
def _render(self):
with self.app:
for child in self.children:
child.render()
self.app.render()
```
From ... | Implementation | https://gradio.app/guides/wrapping-layouts | Other Tutorials - Wrapping Layouts Guide |
Blocks``` class, we can see that it is calling the ```attach_load_events``` function which is used for setting event triggers to components. So we have to use the ```with``` syntax to trigger the ```__exit__``` function.
Of course, we can call ```attach_load_events``` without using the ```with``` syntax, but the funct... | Implementation | https://gradio.app/guides/wrapping-layouts | Other Tutorials - Wrapping Layouts Guide |
In this guide, we saw
- How we can wrap the layouts
- How components are rendered
- How we can structure our application with wrapped layout classes
Because the classes used in this guide are used for demonstration purposes, they may still not be totally optimized or modular. But that would make the guide much longer... | Conclusion | https://gradio.app/guides/wrapping-layouts | Other Tutorials - Wrapping Layouts Guide |
The Hugging Face Hub is a central platform that has hundreds of thousands of [models](https://huggingface.co/models), [datasets](https://huggingface.co/datasets) and [demos](https://huggingface.co/spaces) (also known as Spaces).
Gradio has multiple features that make it extremely easy to leverage existing models and ... | Introduction | https://gradio.app/guides/using-hugging-face-integrations | Other Tutorials - Using Hugging Face Integrations Guide |
Hugging Face has a service called [Serverless Inference Endpoints](https://huggingface.co/docs/api-inference/index), which allows you to send HTTP requests to models on the Hub. The API includes a generous free tier, and you can switch to [dedicated Inference Endpoints](https://huggingface.co/inference-endpoints/dedica... | Demos with the Hugging Face Inference Endpoints | https://gradio.app/guides/using-hugging-face-integrations | Other Tutorials - Using Hugging Face Integrations Guide |
[Hugging Face Spaces](https://hf.co/spaces) allows anyone to host their Gradio demos freely, and uploading your Gradio demos take a couple of minutes. You can head to [hf.co/new-space](https://huggingface.co/new-space), select the Gradio SDK, create an `app.py` file, and voila! You have a demo you can share with anyone... | Hosting your Gradio demos on Spaces | https://gradio.app/guides/using-hugging-face-integrations | Other Tutorials - Using Hugging Face Integrations Guide |
You can also use and remix existing Gradio demos on Hugging Face Spaces. For example, you could take two existing Gradio demos on Spaces and put them as separate tabs and create a new demo. You can run this new demo locally, or upload it to Spaces, allowing endless possibilities to remix and create new demos!
Here's a... | Loading demos from Spaces | https://gradio.app/guides/using-hugging-face-integrations | Other Tutorials - Using Hugging Face Integrations Guide |
Hugging Face's popular `transformers` library has a very easy-to-use abstraction, [`pipeline()`](https://huggingface.co/docs/transformers/v4.16.2/en/main_classes/pipelinestransformers.pipeline) that handles most of the complex code to offer a simple API for common tasks. By specifying the task and an (optional) model, ... | Demos with the `Pipeline` in `transformers` | https://gradio.app/guides/using-hugging-face-integrations | Other Tutorials - Using Hugging Face Integrations Guide |
That's it! Let's recap the various ways Gradio and Hugging Face work together:
1. You can build a demo around Inference Endpoints without having to load the model, by using `gr.load()`.
2. You host your Gradio demo on Hugging Face Spaces, either using the GUI or entirely in Python.
3. You can load demos from Hugging F... | Recap | https://gradio.app/guides/using-hugging-face-integrations | Other Tutorials - Using Hugging Face Integrations Guide |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.