text
stringlengths
0
2k
heading1
stringlengths
4
79
source_page_url
stringclasses
180 values
source_page_title
stringclasses
180 values
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 autonomous vehicles to medical imaging. Such models are perfect to use with Gradio's _image_ input component, so in this tutorial we will build a web demo to classify images using Gradio. We will be able to build the whole web application in Python, and it will look like the demo on the bottom of the page. Let's get started! Prerequisites Make sure you have the `gradio` Python package already [installed](/getting_started). We will be using a pretrained image classification model, so you should also have `torch` installed.
Introduction
https://gradio.app/guides/image-classification-in-pytorch
Other Tutorials - Image Classification In Pytorch Guide
First, we will need an image classification model. For this tutorial, we will use a pretrained Resnet-18 model, as it is easily downloadable from [PyTorch Hub](https://pytorch.org/hub/pytorch_vision_resnet/). You can use a different pretrained model or train your own. ```python import torch model = torch.hub.load('pytorch/vision:v0.6.0', 'resnet18', pretrained=True).eval() ``` Because we will be using the model for inference, we have called the `.eval()` method.
Step 1 — Setting up the Image Classification Model
https://gradio.app/guides/image-classification-in-pytorch
Other Tutorials - Image Classification In Pytorch Guide
Next, we will need to define a function that takes in the _user input_, which in this case is an image, and returns the prediction. The prediction should be returned as a dictionary whose keys are class name and values are confidence probabilities. We will load the class names from this [text file](https://git.io/JJkYN). In the case of our pretrained model, it will look like this: ```python import requests from PIL import Image from torchvision import transforms Download human-readable labels for ImageNet. response = requests.get("https://git.io/JJkYN") labels = response.text.split("\n") def predict(inp): inp = transforms.ToTensor()(inp).unsqueeze(0) with torch.no_grad(): prediction = torch.nn.functional.softmax(model(inp)[0], dim=0) confidences = {labels[i]: float(prediction[i]) for i in range(1000)} return confidences ``` Let's break this down. The function takes one parameter: - `inp`: the input image as a `PIL` image Then, the function converts the image to a PIL Image and then eventually a PyTorch `tensor`, passes it through the model, and returns: - `confidences`: the predictions, as a dictionary whose keys are class labels and whose values are confidence probabilities
Step 2 — Defining a `predict` function
https://gradio.app/guides/image-classification-in-pytorch
Other Tutorials - Image Classification In Pytorch Guide
Now that we have our predictive function set up, we can create a Gradio Interface around it. In this case, the input component is a drag-and-drop image component. To create this input, we use `Image(type="pil")` which creates the component and handles the preprocessing to convert that to a `PIL` image. The output component will be a `Label`, which displays the top labels in a nice form. Since we don't want to show all 1,000 class labels, we will customize it to show only the top 3 images by constructing it as `Label(num_top_classes=3)`. Finally, we'll add one more parameter, the `examples`, which allows us to prepopulate our interfaces with a few predefined examples. The code for Gradio looks like this: ```python import gradio as gr gr.Interface(fn=predict, inputs=gr.Image(type="pil"), outputs=gr.Label(num_top_classes=3), examples=["lion.jpg", "cheetah.jpg"]).launch() ``` This produces the following interface, which you can try right here in your browser (try uploading your own examples!): <gradio-app space="gradio/pytorch-image-classifier"> --- And you're done! That's all the code you need to build a web demo for an image classifier. If you'd like to share with others, try setting `share=True` when you `launch()` the Interface!
Step 3 — Creating a Gradio Interface
https://gradio.app/guides/image-classification-in-pytorch
Other Tutorials - Image Classification In Pytorch Guide
Named-entity recognition (NER), also known as token classification or text tagging, is the task of taking a sentence and classifying every word (or "token") into different categories, such as names of people or names of locations, or different parts of speech. For example, given the sentence: > Does Chicago have any Pakistani restaurants? A named-entity recognition algorithm may identify: - "Chicago" as a **location** - "Pakistani" as an **ethnicity** and so on. Using `gradio` (specifically the `HighlightedText` component), you can easily build a web demo of your NER model and share that with the rest of your team. Here is an example of a demo that you'll be able to build: $demo_ner_pipeline This tutorial will show how to take a pretrained NER model and deploy it with a Gradio interface. We will show two different ways to use the `HighlightedText` component -- depending on your NER model, either of these two ways may be easier to learn! Prerequisites Make sure you have the `gradio` Python package already [installed](/getting_started). You will also need a pretrained named-entity recognition model. You can use your own, while in this tutorial, we will use one from the `transformers` library. Approach 1: List of Entity Dictionaries Many named-entity recognition models output a list of dictionaries. Each dictionary consists of an _entity_, a "start" index, and an "end" index. This is, for example, how NER models in the `transformers` library operate: ```py from transformers import pipeline ner_pipeline = pipeline("ner") ner_pipeline("Does Chicago have any Pakistani restaurants") ``` Output: ```bash [{'entity': 'I-LOC', 'score': 0.9988978, 'index': 2, 'word': 'Chicago', 'start': 5, 'end': 12}, {'entity': 'I-MISC', 'score': 0.9958592, 'index': 5, 'word': 'Pakistani', 'start': 22, 'end': 31}] ``` If you have such a model, it is very easy to hook it up to Gradio's `HighlightedText` component. All you need to do is pass in this
Introduction
https://gradio.app/guides/named-entity-recognition
Other Tutorials - Named Entity Recognition Guide
index': 5, 'word': 'Pakistani', 'start': 22, 'end': 31}] ``` If you have such a model, it is very easy to hook it up to Gradio's `HighlightedText` component. All you need to do is pass in this **list of entities**, along with the **original text** to the model, together as dictionary, with the keys being `"entities"` and `"text"` respectively. Here is a complete example: $code_ner_pipeline $demo_ner_pipeline Approach 2: List of Tuples An alternative way to pass data into the `HighlightedText` component is a list of tuples. The first element of each tuple should be the word or words that are being classified into a particular entity. The second element should be the entity label (or `None` if they should be unlabeled). The `HighlightedText` component automatically strings together the words and labels to display the entities. In some cases, this can be easier than the first approach. Here is a demo showing this approach using Spacy's parts-of-speech tagger: $code_text_analysis $demo_text_analysis --- And you're done! That's all you need to know to build a web-based GUI for your NER model. Fun tip: you can share your NER demo instantly with others simply by setting `share=True` in `launch()`.
Introduction
https://gradio.app/guides/named-entity-recognition
Other Tutorials - Named Entity Recognition Guide
This guide explains how you can use Gradio to plot geographical data on a map using the `gradio.Plot` component. The Gradio `Plot` component works with Matplotlib, Bokeh and Plotly. Plotly is what we will be working with in this guide. Plotly allows developers to easily create all sorts of maps with their geographical data. Take a look [here](https://plotly.com/python/maps/) for some examples.
Introduction
https://gradio.app/guides/plot-component-for-maps
Other Tutorials - Plot Component For Maps Guide
We will be using the New York City Airbnb dataset, which is hosted on kaggle [here](https://www.kaggle.com/datasets/dgomonov/new-york-city-airbnb-open-data). I've uploaded it to the Hugging Face Hub as a dataset [here](https://huggingface.co/datasets/gradio/NYC-Airbnb-Open-Data) for easier use and download. Using this data we will plot Airbnb locations on a map output and allow filtering based on price and location. Below is the demo that we will be building. ⚡️ $demo_map_airbnb
Overview
https://gradio.app/guides/plot-component-for-maps
Other Tutorials - Plot Component For Maps Guide
Let's start by loading the Airbnb NYC data from the Hugging Face Hub. ```python from datasets import load_dataset dataset = load_dataset("gradio/NYC-Airbnb-Open-Data", split="train") df = dataset.to_pandas() def filter_map(min_price, max_price, boroughs): new_df = df[(df['neighbourhood_group'].isin(boroughs)) & (df['price'] > min_price) & (df['price'] < max_price)] names = new_df["name"].tolist() prices = new_df["price"].tolist() text_list = [(names[i], prices[i]) for i in range(0, len(names))] ``` In the code above, we first load the csv data into a pandas dataframe. Let's begin by defining a function that we will use as the prediction function for the gradio app. This function will accept the minimum price and maximum price range as well as the list of boroughs to filter the resulting map. We can use the passed in values (`min_price`, `max_price`, and list of `boroughs`) to filter the dataframe and create `new_df`. Next we will create `text_list` of the names and prices of each Airbnb to use as labels on the map.
Step 1 - Loading CSV data 💾
https://gradio.app/guides/plot-component-for-maps
Other Tutorials - Plot Component For Maps Guide
Plotly makes it easy to work with maps. Let's take a look below how we can create a map figure. ```python import plotly.graph_objects as go fig = go.Figure(go.Scattermapbox( customdata=text_list, lat=new_df['latitude'].tolist(), lon=new_df['longitude'].tolist(), mode='markers', marker=go.scattermapbox.Marker( size=6 ), hoverinfo="text", hovertemplate='<b>Name</b>: %{customdata[0]}<br><b>Price</b>: $%{customdata[1]}' )) fig.update_layout( mapbox_style="open-street-map", hovermode='closest', mapbox=dict( bearing=0, center=go.layout.mapbox.Center( lat=40.67, lon=-73.90 ), pitch=0, zoom=9 ), ) ``` Above, we create a scatter plot on mapbox by passing it our list of latitudes and longitudes to plot markers. We also pass in our custom data of names and prices for additional info to appear on every marker we hover over. Next we use `update_layout` to specify other map settings such as zoom, and centering. More info [here](https://plotly.com/python/scattermapbox/) on scatter plots using Mapbox and Plotly.
Step 2 - Map Figure 🌐
https://gradio.app/guides/plot-component-for-maps
Other Tutorials - Plot Component For Maps Guide
We will use two `gr.Number` components and a `gr.CheckboxGroup` to allow users of our app to specify price ranges and borough locations. We will then use the `gr.Plot` component as an output for our Plotly + Mapbox map we created earlier. ```python with gr.Blocks() as demo: with gr.Column(): with gr.Row(): min_price = gr.Number(value=250, label="Minimum Price") max_price = gr.Number(value=1000, label="Maximum Price") boroughs = gr.CheckboxGroup(choices=["Queens", "Brooklyn", "Manhattan", "Bronx", "Staten Island"], value=["Queens", "Brooklyn"], label="Select Boroughs:") btn = gr.Button(value="Update Filter") map = gr.Plot() demo.load(filter_map, [min_price, max_price, boroughs], map) btn.click(filter_map, [min_price, max_price, boroughs], map) ``` We layout these components using the `gr.Column` and `gr.Row` and we'll also add event triggers for when the demo first loads and when our "Update Filter" button is clicked in order to trigger the map to update with our new filters. This is what the full demo code looks like: $code_map_airbnb
Step 3 - Gradio App ⚡️
https://gradio.app/guides/plot-component-for-maps
Other Tutorials - Plot Component For Maps Guide
If you run the code above, your app will start running locally. You can even get a temporary shareable link by passing the `share=True` parameter to `launch`. But what if you want to a permanent deployment solution? Let's deploy our Gradio app to the free HuggingFace Spaces platform. If you haven't used Spaces before, follow the previous guide [here](/using_hugging_face_integrations).
Step 4 - Deployment 🤗
https://gradio.app/guides/plot-component-for-maps
Other Tutorials - Plot Component For Maps Guide
And you're all done! That's all the code you need to build a map demo. Here's a link to the demo [Map demo](https://huggingface.co/spaces/gradio/map_airbnb) and [complete code](https://huggingface.co/spaces/gradio/map_airbnb/blob/main/run.py) (on Hugging Face Spaces)
Conclusion 🎉
https://gradio.app/guides/plot-component-for-maps
Other Tutorials - Plot Component For Maps Guide
A virtual environment in Python is a self-contained directory that holds a Python installation for a particular version of Python, along with a number of additional packages. This environment is isolated from the main Python installation and other virtual environments. Each environment can have its own independent set of installed Python packages, which allows you to maintain different versions of libraries for different projects without conflicts. Using virtual environments ensures that you can work on multiple Python projects on the same machine without any conflicts. This is particularly useful when different projects require different versions of the same library. It also simplifies dependency management and enhances reproducibility, as you can easily share the requirements of your project with others.
Virtual Environments
https://gradio.app/guides/installing-gradio-in-a-virtual-environment
Other Tutorials - Installing Gradio In A Virtual Environment Guide
To install Gradio on a Windows system in a virtual environment, follow these steps: 1. **Install Python**: Ensure you have Python 3.10 or higher installed. You can download it from [python.org](https://www.python.org/). You can verify the installation by running `python --version` or `python3 --version` in Command Prompt. 2. **Create a Virtual Environment**: Open Command Prompt and navigate to your project directory. Then create a virtual environment using the following command: ```bash python -m venv gradio-env ``` This command creates a new directory `gradio-env` in your project folder, containing a fresh Python installation. 3. **Activate the Virtual Environment**: To activate the virtual environment, run: ```bash .\gradio-env\Scripts\activate ``` Your command prompt should now indicate that you are working inside `gradio-env`. Note: you can choose a different name than `gradio-env` for your virtual environment in this step. 4. **Install Gradio**: Now, you can install Gradio using pip: ```bash pip install gradio ``` 5. **Verification**: To verify the installation, run `python` and then type: ```python import gradio as gr print(gr.__version__) ``` This will display the installed version of Gradio.
Installing Gradio on Windows
https://gradio.app/guides/installing-gradio-in-a-virtual-environment
Other Tutorials - Installing Gradio In A Virtual Environment Guide
The installation steps on MacOS and Linux are similar to Windows but with some differences in commands. 1. **Install Python**: Python usually comes pre-installed on MacOS and most Linux distributions. You can verify the installation by running `python --version` in the terminal (note that depending on how Python is installed, you might have to use `python3` instead of `python` throughout these steps). Ensure you have Python 3.10 or higher installed. If you do not have it installed, you can download it from [python.org](https://www.python.org/). 2. **Create a Virtual Environment**: Open Terminal and navigate to your project directory. Then create a virtual environment using: ```bash python -m venv gradio-env ``` Note: you can choose a different name than `gradio-env` for your virtual environment in this step. 3. **Activate the Virtual Environment**: To activate the virtual environment on MacOS/Linux, use: ```bash source gradio-env/bin/activate ``` 4. **Install Gradio**: With the virtual environment activated, install Gradio using pip: ```bash pip install gradio ``` 5. **Verification**: To verify the installation, run `python` and then type: ```python import gradio as gr print(gr.__version__) ``` This will display the installed version of Gradio. By following these steps, you can successfully install Gradio in a virtual environment on your operating system, ensuring a clean and managed workspace for your Python projects.
Installing Gradio on MacOS/Linux
https://gradio.app/guides/installing-gradio-in-a-virtual-environment
Other Tutorials - Installing Gradio In A Virtual Environment Guide
Let’s start with a simple example of integrating a C++ program into a Gradio app. Suppose we have the following C++ program that adds two numbers: ```cpp // add.cpp include <iostream> int main() { double a, b; std::cin >> a >> b; std::cout << a + b << std::endl; return 0; } ``` This program reads two numbers from standard input, adds them, and outputs the result. We can build a Gradio interface around this C++ program using Python's `subprocess` module. Here’s the corresponding Python code: ```python import gradio as gr import subprocess def add_numbers(a, b): process = subprocess.Popen( ['./add'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) output, error = process.communicate(input=f"{a} {b}\n".encode()) if error: return f"Error: {error.decode()}" return float(output.decode().strip()) demo = gr.Interface( fn=add_numbers, inputs=[gr.Number(label="Number 1"), gr.Number(label="Number 2")], outputs=gr.Textbox(label="Result") ) demo.launch() ``` Here, `subprocess.Popen` is used to execute the compiled C++ program (`add`), pass the input values, and capture the output. You can compile the C++ program by running: ```bash g++ -o add add.cpp ``` This example shows how easy it is to call C++ from Python using `subprocess` and build a Gradio interface around it.
Using Gradio with C++
https://gradio.app/guides/using-gradio-in-other-programming-languages
Other Tutorials - Using Gradio In Other Programming Languages Guide
Now, let’s move to another example: calling a Rust program to apply a sepia filter to an image. The Rust code could look something like this: ```rust // sepia.rs extern crate image; use image::{GenericImageView, ImageBuffer, Rgba}; fn sepia_filter(input: &str, output: &str) { let img = image::open(input).unwrap(); let (width, height) = img.dimensions(); let mut img_buf = ImageBuffer::new(width, height); for (x, y, pixel) in img.pixels() { let (r, g, b, a) = (pixel[0] as f32, pixel[1] as f32, pixel[2] as f32, pixel[3]); let tr = (0.393 * r + 0.769 * g + 0.189 * b).min(255.0); let tg = (0.349 * r + 0.686 * g + 0.168 * b).min(255.0); let tb = (0.272 * r + 0.534 * g + 0.131 * b).min(255.0); img_buf.put_pixel(x, y, Rgba([tr as u8, tg as u8, tb as u8, a])); } img_buf.save(output).unwrap(); } fn main() { let args: Vec<String> = std::env::args().collect(); if args.len() != 3 { eprintln!("Usage: sepia <input_file> <output_file>"); return; } sepia_filter(&args[1], &args[2]); } ``` This Rust program applies a sepia filter to an image. It takes two command-line arguments: the input image path and the output image path. You can compile this program using: ```bash cargo build --release ``` Now, we can call this Rust program from Python and use Gradio to build the interface: ```python import gradio as gr import subprocess def apply_sepia(input_path): output_path = "output.png" process = subprocess.Popen( ['./target/release/sepia', input_path, output_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE ) process.wait() return output_path demo = gr.Interface( fn=apply_sepia, inputs=gr.Image(type="filepath", label="Input Image"), outputs=gr.Image(label="Sepia Image") ) demo.launch() ``` Here, when a user uploads an image and clicks submit, Gradio calls the Rust binary (`sepia`) to process the image, and re
Using Gradio with Rust
https://gradio.app/guides/using-gradio-in-other-programming-languages
Other Tutorials - Using Gradio In Other Programming Languages Guide
nput Image"), outputs=gr.Image(label="Sepia Image") ) demo.launch() ``` Here, when a user uploads an image and clicks submit, Gradio calls the Rust binary (`sepia`) to process the image, and returns the sepia-filtered output to Gradio. This setup showcases how you can integrate performance-critical or specialized code written in Rust into a Gradio interface.
Using Gradio with Rust
https://gradio.app/guides/using-gradio-in-other-programming-languages
Other Tutorials - Using Gradio In Other Programming Languages Guide
Integrating Gradio with R is particularly straightforward thanks to the `reticulate` package, which allows you to run Python code directly in R. Let’s walk through an example of using Gradio in R. **Installation** First, you need to install the `reticulate` package in R: ```r install.packages("reticulate") ``` Once installed, you can use the package to run Gradio directly from within an R script. ```r library(reticulate) py_install("gradio", pip = TRUE) gr <- import("gradio") import gradio as gr ``` **Building a Gradio Application** With gradio installed and imported, we now have access to gradio's app building methods. Let's build a simple app for an R function that returns a greeting ```r greeting <- \(name) paste("Hello", name) app <- gr$Interface( fn = greeting, inputs = gr$Text(label = "Name"), outputs = gr$Text(label = "Greeting"), title = "Hello! &128515 &128075" ) app$launch(server_name = "localhost", server_port = as.integer(3000)) ``` Credit to [@IfeanyiIdiaye](https://github.com/Ifeanyi55) for contributing this section. You can see more examples [here](https://github.com/Ifeanyi55/Gradio-in-R/tree/main/Code), including using Gradio Blocks to build a machine learning application in R.
Using Gradio with R (via `reticulate`)
https://gradio.app/guides/using-gradio-in-other-programming-languages
Other Tutorials - Using Gradio In Other Programming Languages 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. Gradio simplifies the collection of this data by including a **Flag** button with every `Interface`. This allows a user or tester to easily send data back to the machine where the demo is running. In this Guide, we discuss more about how to use the flagging feature, both with `gradio.Interface` as well as with `gradio.Blocks`.
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 sample is saved to a CSV log file (by default). If the demo involves images, audio, video, or other types of files, these are saved separately in a parallel directory and the paths to these files are saved in the CSV file. There are [four parameters](https://gradio.app/docs/interfaceinitialization) in `gradio.Interface` that control how flagging works. We will go over them in greater detail. - `flagging_mode`: this parameter can be set to either `"manual"` (default), `"auto"`, or `"never"`. - `manual`: users will see a button to flag, and samples are only flagged when the button is clicked. - `auto`: users will not see a button to flag, but every sample will be flagged automatically. - `never`: users will not see a button to flag, and no sample will be flagged. - `flagging_options`: this parameter can be either `None` (default) or a list of strings. - If `None`, then the user simply clicks on the **Flag** button and no additional options are shown. - If a list of strings are provided, then the user sees several buttons, corresponding to each of the strings that are provided. For example, if the value of this parameter is `["Incorrect", "Ambiguous"]`, then buttons labeled **Flag as Incorrect** and **Flag as Ambiguous** appear. This only applies if `flagging_mode` is `"manual"`. - The chosen option is then logged along with the input and output. - `flagging_dir`: this parameter takes a string. - It represents what to name the directory where 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 whe
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 elif operation == "subtract": return num1 - num2 elif operation == "multiply": return num1 * num2 elif operation == "divide": return num1 / num2 iface = gr.Interface( calculator, ["number", gr.Radio(["add", "subtract", "multiply", "divide"]), "number"], "number", flagging_mode="manual" ) iface.launch() ``` <gradio-app space="gradio/calculator-flagging-basic"></gradio-app> When you click the flag button above, the directory where the interface was launched will include a new flagged subfolder, with a csv file inside it. This csv file includes all the data that was flagged. ```directory +-- flagged/ | +-- logs.csv ``` _flagged/logs.csv_ ```csv num1,operation,num2,Output,timestamp 5,add,7,12,2022-01-31 11:40:51.093412 6,subtract,1.5,4.5,2022-01-31 03:25:32.023542 ``` If the interface involves file data, such as for Image and Audio components, folders will be created to store those flagged data as well. For example an `image` input to `image` output interface will create the following structure. ```directory +-- flagged/ | +-- logs.csv | +-- image/ | | +-- 0.png | | +-- 1.png | +-- Output/ | | +-- 0.png | | +-- 1.png ``` _flagged/logs.csv_ ```csv im,Output timestamp im/0.png,Output/0.png,2022-02-04 19:49:58.026963 im/1.png,Output/1.png,2022-02-02 10:40:51.093412 ``` If you wish for the user to provide a reason for flagging, you can pass a list of strings to the `flagging_options` 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 fo
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", gr.Radio(["add", "subtract", "multiply", "divide"]), "number"], "number", flagging_mode="manual", flagging_options=["wrong sign", "off by one", "other"] ) iface.launch() ``` <gradio-app space="gradio/calculator-flagging-options"></gradio-app> When users click the flag button, the csv file will now include a column indicating the selected option. _flagged/logs.csv_ ```csv num1,operation,num2,Output,flag,timestamp 5,add,7,-12,wrong sign,2022-02-04 11:40:51.093412 6,subtract,1.5,3.5,off by one,2022-02-04 11:42:32.062512 ```
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 writing extra code. This requires two steps: 1. You have to run your callback's `.setup()` somewhere in the code prior to the first time you flag data 2. When the flagging button is clicked, then you trigger the callback's `.flag()` method, making sure to collect the arguments correctly and disabling the typical preprocessing. Here is an example with an image sepia filter Blocks demo that lets you flag data using the default `CSVLogger`: $code_blocks_flag $demo_blocks_flag
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
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 ONNX model.
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 easily, and from there run it on a variety of devices using an engine/compiler like ONNX Runtime. The [ONNX Model Zoo](https://github.com/onnx/models) is a collection of pre-trained, state-of-the-art models in the ONNX format contributed by community members. Accompanying each model are Jupyter notebooks for model training and running inference with the trained model. The notebooks are written in Python and include links to the training dataset as well as references to the original paper that describes the model architecture.
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 [here](https://gradio.app/getting_started) Hugging Face Spaces Hugging Face Spaces is a free hosting option for Gradio demos. Spaces comes with 3 SDK options: Gradio, Streamlit and Static HTML demos. Spaces can be public or private and the workflow is similar to github repos. There are over 2000+ spaces currently on Hugging Face. Learn more about spaces [here](https://huggingface.co/spaces/launch). Hugging Face Models Hugging Face Model Hub also supports ONNX models and ONNX models can be filtered through the [ONNX tag](https://huggingface.co/models?library=onnx&sort=downloads)
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 model on Hugging Face Spaces and run a quick demo powered by Gradio with ONNX Runtime, all on cloud without downloading anything locally. Note, there are various runtimes for ONNX, e.g., [ONNX Runtime](https://github.com/microsoft/onnxruntime), [MXNet](https://github.com/apache/incubator-mxnet).
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 TensorFlow/Keras as well as classical machine learning libraries such as scikit-learn, LightGBM, XGBoost, etc. ONNX Runtime is compatible with different hardware, drivers, and operating systems, and provides optimal performance by leveraging hardware accelerators where applicable alongside graph optimizations and transforms. For more information please see the [official website](https://onnxruntime.ai/).
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. To learn more read the [model card](https://github.com/onnx/models/tree/main/vision/classification/efficientnet-lite4) Here we walk through setting up a example demo for EfficientNet-Lite4 using Gradio First we import our dependencies and download and load the efficientnet-lite4 model from the onnx model zoo. Then load the labels from the labels_map.txt file. We then setup our preprocessing functions, load the model for inference, and setup the inference function. Finally, the inference function is wrapped into a gradio interface for a user to interact with. See the full code below. ```python import numpy as np import math import matplotlib.pyplot as plt import cv2 import json import gradio as gr from huggingface_hub import hf_hub_download from onnx import hub import onnxruntime as ort loads ONNX model from ONNX Model Zoo model = hub.load("efficientnet-lite4") loads the labels text file labels = json.load(open("labels_map.txt", "r")) sets image file dimensions to 224x224 by resizing and cropping image from center def pre_process_edgetpu(img, dims): output_height, output_width, _ = dims img = resize_with_aspectratio(img, output_height, output_width, inter_pol=cv2.INTER_LINEAR) img = center_crop(img, output_height, output_width) img = np.asarray(img, dtype='float32') converts jpg pixel value from [0 - 255] to float array [-1.0 - 1.0] img -= [127.0, 127.0, 127.0] img /= [128.0, 128.0, 128.0] return img resizes 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_he
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(new_height * height / width) else: h = new_height w = int(new_width * width / height) img = cv2.resize(img, (w, h), interpolation=inter_pol) return img crops the image around the center based on given height and width def center_crop(img, out_height, out_width): height, width, _ = img.shape left = int((width - out_width) / 2) right = int((width + out_width) / 2) top = int((height - out_height) / 2) bottom = int((height + out_height) / 2) img = img[top:bottom, left:right] return img sess = ort.InferenceSession(model) def inference(img): img = cv2.imread(img) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = pre_process_edgetpu(img, (224, 224, 3)) img_batch = np.expand_dims(img, axis=0) results = sess.run(["Softmax:0"], {"images:0": img_batch})[0] result = reversed(results[0].argsort()[-5:]) resultdic = {} for r in result: resultdic[labels[str(r)]] = float(results[0][r]) return resultdic title = "EfficientNet-Lite4" description = "EfficientNet-Lite 4 is the largest variant and most accurate of the set of EfficientNet-Lite model. 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." examples = [['catonnx.jpg']] gr.Interface(inference, gr.Image(type="filepath"), "label", title=title, description=description, 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
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/modelsmodels) - Add Gradio Demo under your username, see this [blog post](https://huggingface.co/blog/gradio-spaces) for setting up Gradio Demo on Hugging Face. - Request to join ONNX Organization [here](https://huggingface.co/onnx). - Once approved transfer model from your username to ONNX organization - Add a badge for model in model table, see examples in [Models list](https://github.com/onnx/modelsmodels)
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
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 sending a report of model predictions via email.
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 are always backed up. The synchronization will happen in a background task running every 60 seconds. At the end of the demo, you'll have a fully working application like this one: <gradio-app space="freddyaboulton/gradio-google-forms"> </gradio-app>
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 10 reviews. We're going to use the `sqlite3` library to connect to our sqlite database but gradio will work with any library. The code will look like this: ```python DB_FILE = "./reviews.db" db = sqlite3.connect(DB_FILE) Create table if it doesn't already exist try: db.execute("SELECT * FROM reviews").fetchall() db.close() except sqlite3.OperationalError: db.execute( ''' CREATE TABLE reviews (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, name TEXT, review INTEGER, comments TEXT) ''') db.commit() db.close() def get_latest_reviews(db: sqlite3.Connection): reviews = db.execute("SELECT * FROM reviews ORDER BY id DESC limit 10").fetchall() total_reviews = db.execute("Select COUNT(id) from reviews").fetchone()[0] reviews = pd.DataFrame(reviews, columns=["id", "date_created", "name", "review", "comments"]) return reviews, total_reviews def add_review(name: str, review: int, comments: str): db = sqlite3.connect(DB_FILE) cursor = db.cursor() cursor.execute("INSERT INTO reviews(name, review, comments) VALUES(?,?,?)", [name, review, comments]) db.commit() reviews, total_reviews = get_latest_reviews(db) db.close() return reviews, total_reviews ``` Let's also write a function to load the latest reviews when the gradio application loads: ```python def load_data(): db = sqlite3.connect(DB_FILE) reviews, total_reviews = get_latest_reviews(db) db.close() return reviews, total_reviews ```
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 satisfied are you with using gradio?", choices=[1, 2, 3, 4, 5]) comments = gr.Textbox(label="Comments", lines=10, placeholder="Do you have any feedback on gradio?") submit = gr.Button(value="Submit Feedback") with gr.Column(): data = gr.Dataframe(label="Most recently created 10 rows") count = gr.Number(label="Total number of reviews") submit.click(add_review, [name, review, comments], [data, count]) demo.load(load_data, None, [data, count]) ```
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://huggingface.co/datasets) before proceeding. Now at the **top** of our script, we'll use the [huggingface hub client library](https://huggingface.co/docs/huggingface_hub/index) to connect to our dataset and pull the latest backup. ```python TOKEN = os.environ.get('HUB_TOKEN') repo = huggingface_hub.Repository( local_dir="data", repo_type="dataset", clone_from="<name-of-your-dataset>", use_auth_token=TOKEN ) repo.git_pull() shutil.copyfile("./data/reviews.db", DB_FILE) ``` Note that you'll have to get an access token from the "Settings" tab of your HuggingFace for the above code to work. In the script, the token is securely accessed via an environment variable. ![access_token](https://github.com/gradio-app/gradio/blob/main/guides/assets/access_token.png?raw=true) Now we will create a background task to synch our local database to the dataset hub every 60 seconds. We will use the [AdvancedPythonScheduler](https://apscheduler.readthedocs.io/en/3.x/) to handle the scheduling. However, this is not the only task scheduling library available. Feel free to use whatever you are comfortable with. The function to back up our data will look like this: ```python from apscheduler.schedulers.background import BackgroundScheduler def backup_db(): shutil.copyfile(DB_FILE, "./data/reviews.db") db = sqlite3.connect(DB_FILE) reviews = db.execute("SELECT * FROM reviews").fetchall() pd.DataFrame(reviews).to_csv("./data/reviews.csv", index=False) 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, trigge
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
**[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 demos, testing, or sharing with non-developers, without writing custom frontend code.
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: ```python import gradio as gr demo = gr.load_openapi( openapi_spec="https://petstore3.swagger.io/api/v3/openapi.json", base_url="https://petstore3.swagger.io/api/v3", paths=["/pet.*"], methods=["get", "post"], ) demo.launch() ``` **Parameters:** - **openapi_spec**: URL, file path, or Python dictionary containing the OpenAPI v3 spec (JSON format only). - **base_url**: The base URL for the API endpoints (e.g., `https://api.example.com/v1`). - **paths** (optional): List of endpoint path patterns (supports regex) to include. If not set, all paths are included. - **methods** (optional): List of HTTP methods (e.g., `["get", "post"]`) to include. If not set, all methods are included. The generated app will display a sidebar with available endpoints and create interactive forms for each operation, letting you make API calls and view responses in real time.
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-gradio), enabling programmatic access and orchestration of your API via the MCP ecosystem. This makes it easy to build, share, and automate API workflows with minimal effort.
Next steps
https://gradio.app/guides/from-openapi-spec
Other Tutorials - From Openapi Spec Guide
Let's go through a simple example to understand how to containerize a Gradio app using Docker. Step 1: Create Your Gradio App First, we need a simple Gradio app. Let's create a Python file named `app.py` with the following content: ```python import gradio as gr def greet(name): return f"Hello {name}!" iface = gr.Interface(fn=greet, inputs="text", outputs="text").launch() ``` This app creates a simple interface that greets the user by name. Step 2: Create a Dockerfile Next, we'll create a Dockerfile to specify how our app should be built and run in a Docker container. Create a file named `Dockerfile` in the same directory as your app with the following content: ```dockerfile FROM python:3.10-slim WORKDIR /usr/src/app COPY . . RUN pip install --no-cache-dir gradio EXPOSE 7860 ENV GRADIO_SERVER_NAME="0.0.0.0" CMD ["python", "app.py"] ``` This Dockerfile performs the following steps: - Starts from a Python 3.10 slim image. - Sets the working directory and copies the app into the container. - Installs Gradio (you should install all other requirements as well). - Exposes port 7860 (Gradio's default port). - Sets the `GRADIO_SERVER_NAME` environment variable to ensure Gradio listens on all network interfaces. - Specifies the command to run the app. Step 3: Build and Run Your Docker Container With the Dockerfile in place, you can build and run your container: ```bash docker build -t gradio-app . docker run -p 7860:7860 gradio-app ``` Your Gradio app should now be accessible at `http://localhost:7860`.
How to Dockerize a Gradio App
https://gradio.app/guides/deploying-gradio-with-docker
Other Tutorials - Deploying Gradio With Docker Guide
When running Gradio applications in Docker, there are a few important things to keep in mind: Running the Gradio app on `"0.0.0.0"` and exposing port 7860 In the Docker environment, setting `GRADIO_SERVER_NAME="0.0.0.0"` as an environment variable (or directly in your Gradio app's `launch()` function) is crucial for allowing connections from outside the container. And the `EXPOSE 7860` directive in the Dockerfile tells Docker to expose Gradio's default port on the container to enable external access to the Gradio app. Enable Stickiness for Multiple Replicas When deploying Gradio apps with multiple replicas, such as on AWS ECS, it's important to enable stickiness with `sessionAffinity: ClientIP`. This ensures that all requests from the same user are routed to the same instance. This is important because Gradio's communication protocol requires multiple separate connections from the frontend to the backend in order for events to be processed correctly. (If you use Terraform, you'll want to add a [stickiness block](https://registry.terraform.io/providers/hashicorp/aws/3.14.1/docs/resources/lb_target_groupstickiness) into your target group definition.) Deploying Behind a Proxy If you're deploying your Gradio app behind a proxy, like Nginx, it's essential to configure the proxy correctly. Gradio provides a [Guide that walks through the necessary steps](https://www.gradio.app/guides/running-gradio-on-your-web-server-with-nginx). This setup ensures your app is accessible and performs well in production environments.
Important Considerations
https://gradio.app/guides/deploying-gradio-with-docker
Other Tutorials - Deploying Gradio With Docker 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, Sublime Text, PyCharm, or so on) or generally running your Python code from the terminal. We've also developed an analogous "magic command" that allows you to re-run cells faster if you use **Jupyter Notebooks** (or any similar environment like Colab). This short Guide will cover both of these methods, so no matter how you write Python, you'll leave knowing how to build Gradio apps faster.
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.change(fn=lambda x: f"Welcome, {x}!", inputs=inp, outputs=out) if __name__ == "__main__": demo.launch() ``` The problem is that anytime that you want to make a change to your layout, events, or components, you have to close and rerun your app by writing `python run.py`. Instead of doing this, you can run your code in **reload mode** by changing 1 word: `python` to `gradio`: In the terminal, run `gradio run.py`. That's it! Now, you'll see that after you'll see something like this: ```bash Watching: '/Users/freddy/sources/gradio/gradio', '/Users/freddy/sources/gradio/demo/' Running on local URL: http://127.0.0.1:7860 ``` The important part here is the line that says `Watching...` What's happening here is that Gradio will be observing the directory where `run.py` file lives, and if the file changes, it will automatically rerun the file for you. So you can focus on writing your code, and your Gradio demo will refresh automatically 🥳 Tip: the `gradio` command does not detect the parameters passed to the `launch()` methods because the `launch()` method is never called in reload mode. For example, setting `auth`, or `show_error` in `launch()` will not be reflected in the app. There is one important thing to keep in mind when using the reload mode: Gradio specifically looks for a Gradio Blocks/Interface demo called `demo` in your code. If you have named your demo something else, you will need to pass in the name of your demo 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.
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}!", inputs=inp, outputs=out) if __name__ == "__main__": my_demo.launch() ``` Then you would launch it in reload mode like this: `gradio run.py --demo-name=my_demo`. By default, the Gradio use UTF-8 encoding for scripts. **For reload mode**, If you are using encoding formats other than UTF-8 (such as cp1252), make sure you've done like this: 1. Configure encoding declaration of python script, for example: `-*- coding: cp1252 -*-` 2. Confirm that your code editor has identified that encoding format. 3. Run like this: `gradio run.py --encoding cp1252` 🔥 If your application accepts command line arguments, you can pass them in as well. Here's an example: ```python import gradio as gr import argparse parser = argparse.ArgumentParser() parser.add_argument("--name", type=str, default="User") args, unknown = parser.parse_known_args() with gr.Blocks() as demo: gr.Markdown(f"Greetings {args.name}!") inp = gr.Textbox() out = gr.Textbox() inp.change(fn=lambda x: x, inputs=inp, outputs=out) if __name__ == "__main__": demo.launch() ``` Which you could run like this: `gradio run.py --name Gretel` As a small aside, this auto-reloading happens if you change your `run.py` source code or the Gradio source code. Meaning that this can be useful if you decide to [contribute to Gradio itself](https://github.com/gradio-app/gradio/blob/main/CONTRIBUTING.md) ✅
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 they are reloaded, like `numpy` and `tiktoken`. In these situations, you can place code that you do not want to be re-run inside an `if gr.NO_RELOAD:` codeblock. Here's an example of how you can use it to only load a transformers model once during the development process. Tip: The value of `gr.NO_RELOAD` is `True`. So you don't have to change your script when you are done developing and want to run it in production. Simply run the file with `python` instead of `gradio`. ```python import gradio as gr if gr.NO_RELOAD: from transformers import pipeline pipe = pipeline("text-classification", model="cardiffnlp/twitter-roberta-base-sentiment-latest") demo = gr.Interface(lambda s: {d["label"]: d["score"] for d in pipe(s)}, gr.Textbox(), gr.Label()) if __name__ == "__main__": demo.launch() ```
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 an LLM write or edit the code in your Gradio app. The LLM is powered by Hugging Face's [Inference Providers](https://huggingface.co/docs/inference-providers/en/index), so you must be logged into Hugging Face locally to use this. Note: When Vibe Mode is enabled, anyone who can access the Gradio endpoint can modify files and run arbitrary code on the host machine. Use only for local development.
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 developing your Gradio demo, simply write the magic command **`%%blocks`** at the top, and then write the layout and components like you would normally: ```py %%blocks import gradio as gr with gr.Blocks() as demo: gr.Markdown(f"Greetings {args.name}!") inp = gr.Textbox() out = gr.Textbox() inp.change(fn=lambda x: x, inputs=inp, outputs=out) ``` Notice that: - You do not need to launch your demo — Gradio does that for you automatically! - Every time you rerun the cell, Gradio will re-render your app on the same port and using the same underlying web server. This means you'll see your changes _much, much faster_ than if you were rerunning the cell normally. Here's what it looks like in a jupyter notebook: ![](https://gradio-builds.s3.amazonaws.com/demo-files/jupyter_reload.gif) 🪄 This works in colab notebooks too! [Here's a colab notebook](https://colab.research.google.com/drive/1zAuWoiTIb3O2oitbtVb2_ekv1K6ggtC1?usp=sharing) where you can see the Blocks magic in action. Try making some changes and re-running the cell with the Gradio code! Tip: You may have to use `%%blocks --share` in Colab to get the demo to appear in the cell. The Notebook Magic is now the author's preferred way of building Gradio demos. Regardless of how you write Python code, we hope either of these methods will give you a much better development experience using Gradio. ---
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
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 hierarchy becomes difficult to maintain and reuse. In this guide, we are going to explore how we can wrap the layout classes to create more maintainable and easy-to-read applications without sacrificing flexibility.
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://huggingface.co/spaces/WoWoWoWololo/wrapping-layouts/blob/main/app.py). So let's start with the ```LayoutBase``` class. LayoutBase Class 1. Render Function Let's look at the ```render``` function in the ```LayoutBase``` class: ```python other LayoutBase implementations def render(self) -> None: with self.main_layout: for renderable in self.renderables: renderable.render() self.main_layout.render() ``` This is a little confusing at first but if you consider the default implementation you can understand it easily. Let's look at an example: In the default implementation, this is what we're doing: ```python with Row(): left_textbox = Textbox(value="left_textbox") right_textbox = Textbox(value="right_textbox") ``` Now, pay attention to the Textbox variables. These variables' ```render``` parameter is true by default. So as we use the ```with``` syntax and create these variables, they are calling the ```render``` function under the ```with``` syntax. We know the render function is called in the constructor with the implementation from the ```gradio.blocks.Block``` class: ```python class Block: constructor parameters are omitted for brevity def __init__(self, ...): other assign functions if render: self.render() ``` So our implementation looks like this: ```python self.main_layout -> Row() with self.main_layout: left_textbox.render() right_textbox.render() ``` What 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 ho
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 Row(): first_textbox = Textbox(value="first_textbox") second_textbox = Textbox(value="second_textbox") ``` Pay attention to the Row and Tab components this time. We have created the Textbox variables above and added them to Row with the ```with``` syntax. Now we need to add the Row component to the Tab component. You can see that the Row component is created with default parameters, so its render parameter is true, that's why the render function is going to be executed under the Tab component's ```with``` syntax. To mimic this implementation, we need to call the ```render``` function of the ```main_layout``` variable after the ```with``` syntax of the ```main_layout``` variable. So the implementation looks like this: ```python with tab_main_layout: with row_main_layout: first_textbox.render() second_textbox.render() row_main_layout.render() tab_main_layout.render() ``` The default implementation and our implementation are the same, but we are using the render function ourselves. So it requires a little work. Now, let's take a look at the ```attach_event``` function. 2. Attach Event Function The function is left as not implemented because it is specific to the class, so each class has to implement its `attach_event` function. ```python other LayoutBase implementations def attach_event(self, block_dict: Dict[str, Block]) -> None: raise NotImplementedError ``` Check out the ```block_dict``` variable in the ```Application``` class's ```attach_event``` function. Application Class 1. Render Function ```python other Application implementations def _render(self):
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 the explanation of the ```LayoutBase``` class's ```render``` function, we can understand the ```child.render``` part. So let's look at the bottom part, why are we calling the ```app``` variable's ```render``` function? It's important to call this function because if we look at the implementation in the ```gradio.blocks.Blocks``` class, we can see that it is adding the components and event functions into the root component. To put it another way, it is creating and structuring the gradio application. 2. Attach Event Function Let's see how we can attach events to components: ```python other Application implementations def _attach_event(self): block_dict: Dict[str, Block] = {} for child in self.children: block_dict.update(child.global_children_dict) with self.app: for child in self.children: try: child.attach_event(block_dict=block_dict) except NotImplementedError: print(f"{child.name}'s attach_event is not implemented") ``` You can see why the ```global_children_list``` is used in the ```LayoutBase``` class from the example code. With this, all the components in the application are gathered into one dictionary, so the component can access all the components with their names. The ```with``` syntax is used here again to attach events to components. If we look at the ```__exit__``` function in the ```gradio.blocks.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 ```_
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 function needs a ```Context.root_block```, and it is set in the ```__enter__``` function. So we used the ```with``` syntax here rather than calling the function ourselves.
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! I hope this guide helps you gain another view of the layout classes and gives you an idea about how you can use them for your needs. See the full implementation of our example [here](https://huggingface.co/spaces/WoWoWoWololo/wrapping-layouts/blob/main/app.py).
Conclusion
https://gradio.app/guides/wrapping-layouts
Other Tutorials - Wrapping Layouts 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 minutes. 1. First, log in to your Google Cloud account and go to the Google Cloud Console (https://console.cloud.google.com/) 2. In the Cloud Console, click on the hamburger menu in the top-left corner and select "APIs & Services" from the menu. If you do not have an existing project, you will need to create one. 3. Then, click the "+ Enabled APIs & services" button, which allows you to enable specific services for your project. Search for "BigQuery API", click on it, and click the "Enable" button. If you see the "Manage" button, then the BigQuery is already enabled, and you're all set. 4. In the APIs & Services menu, click on the "Credentials" tab and then click on the "Create credentials" button. 5. In the "Create credentials" dialog, select "Service account key" as the type of credentials to create, and give it a name. Also grant the service account permissions by giving it a role such as "BigQuery User", which will allow you to run queries. 6. After selecting the service account, select the "JSON" key type and then click on the "Create" button. This will download the JSON key file containing your credentials to your computer. It will look something like this: ```json { "type": "service_account", "project_id": "your project", "private_key_id": "your private key id", "private_key": "private key", "client_email": "email", "client_id": "client id", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://accounts.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" } ```
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 installed the pandas add-on, which will be helpful for processing the BigQuery dataset as a pandas dataframe. Once the client is installed, you can authenticate using your credentials by running the following code: ```py from google.cloud import bigquery client = bigquery.Client.from_service_account_json("path/to/key.json") ``` With your credentials authenticated, you can now use the BigQuery Python client to interact with your BigQuery datasets. Here is an example of a function which queries the `covid19_nyt.us_counties` dataset in BigQuery to show the top 20 counties with the most confirmed cases as of the current day: ```py import numpy as np QUERY = ( 'SELECT * FROM `bigquery-public-data.covid19_nyt.us_counties` ' 'ORDER BY date DESC,confirmed_cases DESC ' 'LIMIT 20') def run_query(): query_job = client.query(QUERY) query_result = query_job.result() df = query_result.to_dataframe() Select a subset of columns df = df[["confirmed_cases", "deaths", "county", "state_name"]] Convert numeric columns to standard numpy types df = df.astype({"deaths": np.int64, "confirmed_cases": np.int64}) return df ```
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 the results. By passing in the `run_query` function to `gr.DataFrame`, we instruct Gradio to run the function as soon as the page loads and show the results. In addition, you also pass in the keyword `every` to tell the dashboard to refresh every hour (60\*60 seconds). ```py import gradio as gr with gr.Blocks() as demo: gr.DataFrame(run_query, every=gr.Timer(60*60)) demo.launch() ``` Perhaps you'd like to add a visualization to our dashboard. You can use the `gr.ScatterPlot()` component to visualize the data in a scatter plot. This allows you to see the relationship between different variables such as case count and case deaths in the dataset and can be useful for exploring the data and gaining insights. Again, we can do this in real-time by passing in the `every` parameter. Here is a complete example showing how to use the `gr.ScatterPlot` to visualize in addition to displaying data with the `gr.DataFrame` ```py import gradio as gr with gr.Blocks() as demo: gr.Markdown("💉 Covid Dashboard (Updated Hourly)") with gr.Row(): gr.DataFrame(run_query, every=gr.Timer(60*60)) gr.ScatterPlot(run_query, every=gr.Timer(60*60), x="confirmed_cases", y="deaths", tooltip="county", width=500, height=500) demo.queue().launch() Run the demo with queuing enabled ```
Building the Real-Time Dashboard
https://gradio.app/guides/creating-a-dashboard-from-bigquery-data
Other Tutorials - Creating A Dashboard From Bigquery Data 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 display precision of numbers? This Guide is for you! Let's dive in! **Prerequisites**: We'll be using the `gradio.Blocks` class in our examples. You can [read the Guide to Blocks first](https://gradio.app/blocks-and-event-listeners) if you are not already familiar with it. Also please make sure you are using the **latest version** version of Gradio: `pip install --upgrade gradio`.
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 gradio as gr Creating a sample dataframe df = pd.DataFrame({ "A" : [14, 4, 5, 4, 1], "B" : [5, 2, 54, 3, 2], "C" : [20, 20, 7, 3, 8], "D" : [14, 3, 6, 2, 6], "E" : [23, 45, 64, 32, 23] }) Applying style to highlight the maximum value in each row styler = df.style.highlight_max(color = 'lightgreen', axis = 0) Displaying the styled dataframe in Gradio with gr.Blocks() as demo: gr.DataFrame(styler) demo.launch() ``` The Styler class can be used to apply conditional formatting and styling to dataframes, making them more visually appealing and interpretable. You can highlight certain values, apply gradients, or even use custom CSS to style the DataFrame. The Styler object is applied to a DataFrame and it returns a new object with the relevant styling properties, which can then be previewed directly, or rendered dynamically in a Gradio interface. To read more about the Styler object, read the official `pandas` documentation at: https://pandas.pydata.org/docs/user_guide/style.html Below, we'll explore a few examples: Highlighting Cells Ok, so let's revisit the previous example. We start by creating a `pd.DataFrame` object and then highlight the highest value in each row with a light green color: ```python import pandas as pd Creating a sample dataframe df = pd.DataFrame({ "A" : [14, 4, 5, 4, 1], "B" : [5, 2, 54, 3, 2], "C" : [20, 20, 7, 3, 8], "D" : [14, 3, 6, 2, 6], "E" : [23, 45, 64, 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 `DataFra
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() as demo: gr.Dataframe(styler) demo.launch() ``` Here's how it looks: ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/df-highlight.png) Font Colors Apart from highlighting cells, you might want to color specific text within the cells. Here's how you can change text colors for certain columns: ```python import pandas as pd import gradio as gr Creating a sample dataframe df = pd.DataFrame({ "A" : [14, 4, 5, 4, 1], "B" : [5, 2, 54, 3, 2], "C" : [20, 20, 7, 3, 8], "D" : [14, 3, 6, 2, 6], "E" : [23, 45, 64, 32, 23] }) Function to apply text color def highlight_cols(x): df = x.copy() df.loc[:, :] = 'color: purple' df[['B', 'C', 'E']] = 'color: green' return df Applying the style function s = df.style.apply(highlight_cols, axis = None) Displaying the styled dataframe in Gradio with gr.Blocks() as demo: gr.DataFrame(s) demo.launch() ``` In this script, we define a custom function highlight_cols that changes the text color to purple for all cells, but overrides this for columns B, C, and E with green. Here's how it looks: ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/df-color.png) Display Precision Sometimes, the data you are dealing with might have long floating numbers, and you may want to display only a fixed number of decimals for simplicity. The pandas Styler object allows you to format the precision 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.
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 }) Setting the precision of numbers to 2 decimal places s = df.style.format("{:.2f}") Displaying the styled dataframe in Gradio with gr.Blocks() as demo: gr.DataFrame(s) demo.launch() ``` In this script, the format method of the Styler object is used to set the precision of numbers to two decimal places. Much cleaner now: ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/df-precision.png)
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: ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/dataframe_custom_styling.png) This isn't possible with `Styler`, but you can do this by creating your own **`styling`** array, which is a 2D array the same size and shape as your data. Each element in this list should be a CSS style string (e.g. `"background-color: green"`) that applies to the `<td>` element containing the cell value (or an empty string if no custom CSS should be applied). Similarly, you can create a **`display_value`** array which controls the value that is displayed in each cell (which can be different the underlying value which is the one that is used for searching/sorting). Here's the complete code for how to can use custom styling with `gr.Dataframe` as in the screenshot above: $code_dataframe_custom_styling
Custom Styling
https://gradio.app/guides/styling-the-gradio-dataframe
Other Tutorials - Styling The Gradio Dataframe Guide
One thing to keep in mind is that the gradio `DataFrame` component only accepts custom styling objects when it is non-interactive (i.e. in "static" mode). If the `DataFrame` component is interactive, then the styling information is ignored and instead the raw table values are shown instead. The `DataFrame` component is by default non-interactive, unless it is used as an input to an event. In which case, you can force the component to be non-interactive by setting the `interactive` prop like this: ```python c = gr.DataFrame(styler, interactive=False) ```
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
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. Configure this with the `equal_height` argument. ```python with gr.Blocks() as demo: with gr.Row(equal_height=True): textbox = gr.Textbox() btn2 = gr.Button("Button 2") ``` The widths of elements in a Row can be controlled via a combination of `scale` and `min_width` arguments that are present in every Component. - `scale` is an integer that defines how an element will take up space in a Row. If scale is set to `0`, the element will not expand to take up space. If scale is set to `1` or greater, the element will expand. Multiple elements in a row will expand proportional to their scale. Below, `btn2` will expand twice as much as `btn1`, while `btn0` will not expand at all: ```python with gr.Blocks() as demo: with gr.Row(): btn0 = gr.Button("Button 0", scale=0) btn1 = gr.Button("Button 1", scale=1) btn2 = gr.Button("Button 2", scale=2) ``` - `min_width` will set the minimum width the element will take. The Row will wrap if there isn't sufficient space to satisfy all `min_width` values. Learn more about Rows in the [docs](https://gradio.app/docs/row).
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. The second column has an Image and Button arranged vertically. Notice how the relative widths of the two columns is set by the `scale` parameter. The column with twice the `scale` value takes up twice the width. Learn more about Columns in the [docs](https://gradio.app/docs/column). Fill Browser Height / Width To make an app take the full width of the browser by removing the side padding, use `gr.Blocks(fill_width=True)`. To make top level Components expand to take the full height of the browser, use `fill_height` and apply scale to the expanding Components. ```python import gradio as gr with gr.Blocks(fill_height=True) as demo: gr.Chatbot(scale=1) gr.Textbox(scale=0) ```
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 with gr.Blocks() as demo: im = gr.ImageEditor(width="50vw") demo.launch() ```
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 example: $code_blocks_flipper $demo_blocks_flipper Also note the `gr.Accordion('label')` in this example. The Accordion is a layout that can be toggled open or closed. Like `Tabs`, it is a layout element that can selectively hide or show content. Any components that are defined inside of a `with gr.Accordion('label'):` will be hidden or shown when the accordion's toggle icon is clicked. Learn more about [Tabs](https://gradio.app/docs/tab) and [Accordions](https://gradio.app/docs/accordion) in the docs.
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 developers responsibility to progress through each step, by setting the appropriate ID for the parent `Walkthrough` which should correspond to an ID provided to an indvidual `Step`. $demo_walkthrough Learn more about [Walkthrough](https://gradio.app/docs/gradio/walkthrough) in the docs.
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 the input component, but then render it later, after you have defined the `gr.Examples` object. The solution to this is to define the `gr.Textbox` outside of the `gr.Blocks()` scope and use the component's `.render()` method wherever you'd like it placed in the UI. Here's a full code example: ```python input_textbox = gr.Textbox() with gr.Blocks() as demo: gr.Examples(["hello", "bonjour", "merhaba"], input_textbox) input_textbox.render() ``` Similarly, if you have already defined a component in a Gradio app, but wish to unrender it so that you can define in a different part of your application, then you can call the `.unrender()` method. In the following example, the `Textbox` will appear in the third column: ```py import gradio as gr with gr.Blocks() as demo: with gr.Row(): with gr.Column(): gr.Markdown("Row 1") textbox = gr.Textbox() with gr.Column(): gr.Markdown("Row 2") textbox.unrender() with gr.Column(): gr.Markdown("Row 3") textbox.render() demo.launch() ```
Defining and Rendering Components Separately
https://gradio.app/guides/controlling-layout
Building With Blocks - Controlling Layout Guide
Did you know that apart from being a full-stack machine learning demo, a Gradio Blocks app is also a regular-old python function!? This means that if you have a gradio Blocks (or Interface) app called `demo`, you can use `demo` like you would any python function. So doing something like `output = demo("Hello", "friend")` will run the first event defined in `demo` on the inputs "Hello" and "friend" and store it in the variable `output`. If I put you to sleep 🥱, please bear with me! By using apps like functions, you can seamlessly compose Gradio apps. The following section will show how.
Introduction
https://gradio.app/guides/using-blocks-like-functions
Building With Blocks - Using Blocks Like Functions Guide
Let's say we have the following demo that translates english text to german text. $code_english_translator I already went ahead and hosted it in Hugging Face spaces at [gradio/english_translator](https://huggingface.co/spaces/gradio/english_translator). You can see the demo below as well: $demo_english_translator Now, let's say you have an app that generates english text, but you wanted to additionally generate german text. You could either: 1. Copy the source code of my english-to-german translation and paste it in your app. 2. Load my english-to-german translation in your app and treat it like a normal python function. Option 1 technically always works, but it often introduces unwanted complexity. Option 2 lets you borrow the functionality you want without tightly coupling our apps. All you have to do is call the `Blocks.load` class method in your source file. After that, you can use my translation app like a regular python function! The following code snippet and demo shows how to use `Blocks.load`. Note that the variable `english_translator` is my english to german app, but its used in `generate_text` like a regular function. $code_generate_english_german $demo_generate_english_german
Treating Blocks like functions
https://gradio.app/guides/using-blocks-like-functions
Building With Blocks - Using Blocks Like Functions Guide
If the app you are loading defines more than one function, you can specify which function to use with the `fn_index` and `api_name` parameters. In the code for our english to german demo, you'll see the following line: ```python translate_btn.click(translate, inputs=english, outputs=german, api_name="translate-to-german") ``` The `api_name` gives this function a unique name in our app. You can use this name to tell gradio which function in the upstream space you want to use: ```python english_generator(text, api_name="translate-to-german")[0]["generated_text"] ``` You can also use the `fn_index` parameter. Imagine my app also defined an english to spanish translation function. In order to use it in our text generation app, we would use the following code: ```python english_generator(text, fn_index=1)[0]["generated_text"] ``` Functions in gradio spaces are zero-indexed, so since the spanish translator would be the second function in my space, you would use index 1.
How to control which function in the app to use
https://gradio.app/guides/using-blocks-like-functions
Building With Blocks - Using Blocks Like Functions Guide
We showed how treating a Blocks app like a regular python helps you compose functionality across different apps. Any Blocks app can be treated like a function, but a powerful pattern is to `load` an app hosted on [Hugging Face Spaces](https://huggingface.co/spaces) prior to treating it like a function in your own app. You can also load models hosted on the [Hugging Face Model Hub](https://huggingface.co/models) - see the [Using Hugging Face Integrations](/using_hugging_face_integrations) guide for an example. Happy building! ⚒️
Parting Remarks
https://gradio.app/guides/using-blocks-like-functions
Building With Blocks - Using Blocks Like Functions 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 gradio as gr Shared between all users visitor_count = 0 def increment_counter(): global visitor_count visitor_count += 1 return visitor_count with gr.Blocks() as demo: number = gr.Textbox(label="Total Visitors", value="Counting...") demo.load(increment_counter, inputs=None, outputs=number) demo.launch() ``` This means that any time you do _not_ want to share a value between users, you should declare it _within_ a function. But what if you need to share values between function calls, e.g. a chat history? In that case, you should use one of the subsequent approaches to manage state.
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: 1. Create a `gr.State()` object. If there is a default value to this stateful object, pass that into the constructor. Note that `gr.State` objects must be [deepcopy-able](https://docs.python.org/3/library/copy.html), otherwise you will need to use a different approach as described below. 2. In the event listener, put the `State` object as an input and output as needed. 3. In the event listener function, add the variable to the input parameters and the return value. Let's take a look at a simple example. We have a simple checkout app below where you add items to a cart. You can also see the size of the cart. $code_simple_state Notice how we do this with state: 1. We store the cart items in a `gr.State()` object, initialized here to be an empty list. 2. When adding items to the cart, the event listener uses the cart as both input and output - it returns the updated cart with all the items inside. 3. We can attach a `.change` listener to cart, that uses the state variable as input as well. You can think of `gr.State` as an invisible Gradio component that can store any kind of value. Here, `cart` is not visible in the frontend but is used for calculations. The `.change` listener for a state variable triggers after any event listener changes the value of a state variable. If the state variable holds a sequence (like a `list`, `set`, or `dict`), a change is triggered if any of the elements inside change. If it holds an object or primitive, a change is triggered 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 `__
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 stored on in the app backend for 60 minutes after the user closes the tab (this can be configured by the `delete_cache` parameter in `gr.Blocks`). Learn more about `State` in the [docs](https://gradio.app/docs/gradio/state). **What about objects that cannot be deepcopied?** As mentioned earlier, the value stored in `gr.State` must be [deepcopy-able](https://docs.python.org/3/library/copy.html). If you are working with a complex object that cannot be deepcopied, you can take a different approach to manually read the user's `session_hash` and store a global `dictionary` with instances of your object for each user. Here's how you would do that: ```py import gradio as gr class NonDeepCopyable: def __init__(self): from threading import Lock self.counter = 0 self.lock = Lock() Lock objects cannot be deepcopied def increment(self): with self.lock: self.counter += 1 return self.counter Global dictionary to store user-specific instances instances = {} def initialize_instance(request: gr.Request): instances[request.session_hash] = NonDeepCopyable() return "Session initialized!" def cleanup_instance(request: gr.Request): if request.session_hash in instances: del instances[request.session_hash] def increment_counter(request: gr.Request): if request.session_hash in instances: instance = instances[request.session_hash] return instance.increment() 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 Co
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 loads demo.load(initialize_instance, inputs=None, outputs=output) Clean up instance when page is closed/refreshed demo.unload(cleanup_instance) demo.launch() ```
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 optionally provide an initial default value and a key to identify the data in the browser's localStorage. 2. Use it like a regular `gr.State` component in event listeners as inputs and outputs. Here's a simple example that saves a user's username and password across sessions: $code_browserstate Note: The value stored in `gr.BrowserState` does not persist if the Grado app is restarted. To persist it, you can hardcode specific values of `storage_key` and `secret` in the `gr.BrowserState` component and restart the Gradio app on the same server name and server port. However, this should only be done if you are running trusted Gradio apps, as in principle, this can allow one Gradio app to access localStorage data that was created by a different Gradio app.
Browser State
https://gradio.app/guides/state-in-blocks
Building With Blocks - State In Blocks 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, Components are automatically added to the Blocks as they are created within the `with` clause. - Finally, the `click()` event listener. Event listeners define the data flow within the app. In the example above, the listener ties the two Textboxes together. The Textbox `name` acts as the input and Textbox `output` acts as the output to the `greet` method. This dataflow is triggered when the Button `greet_btn` is clicked. Like an Interface, an event listener can take multiple inputs or outputs. You can also attach event listeners using decorators - skip the `fn` argument and assign `inputs` and `outputs` directly: $code_hello_blocks_decorator
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 override the default behavior and directly configure the interactivity of a Component with the boolean `interactive` keyword argument, e.g. `gr.Textbox(interactive=True)`. ```python output = gr.Textbox(label="Output", interactive=True) ``` _Note_: What happens if a Gradio component is neither an input nor an output? If a component is constructed with a default value, then it is presumed to be displaying content and is rendered non-interactive. Otherwise, it is rendered interactive. Again, this behavior can be overridden by specifying a value for the `interactive` argument.
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 supports a `play()` event listener, triggered when a user presses play. See the [Docs](http://gradio.app/docscomponents) for the event listeners for each Component.
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 example of a "multi-step" demo, where the output of one model (a speech-to-text model) gets fed into the next model (a sentiment classifier). $code_blocks_speech_text_sentiment $demo_blocks_speech_text_sentiment
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 see an example of each: $code_calculator_list_and_dict Both `add()` and `sub()` take `a` and `b` as inputs. However, the syntax is different between these listeners. 1. To the `add_btn` listener, we pass the inputs as a list. The function `add()` takes each of these inputs as arguments. The value of `a` maps to the argument `num1`, and the value of `b` maps to the argument `num2`. 2. To the `sub_btn` listener, we pass the inputs as a set (note the curly brackets!). The function `sub()` takes a single dictionary argument `data`, where the keys are the input components, and the values are the values of those components. It is a matter of preference which syntax you prefer! For functions with many input components, option 2 may be easier to manage. $demo_calculator_list_and_dict
Function Input List vs Dict
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, label="Food Count") status_box = gr.Textbox() def eat(food): if food > 0: return food - 1, "full" else: return 0, "hungry" gr.Button("Eat").click( fn=eat, inputs=food_box, outputs=[food_box, status_box] ) ``` Above, each return statement returns two values corresponding to `food_box` and `status_box`, respectively. **Note:** if your event listener has a single output component, you should **not** return it as a single-item list. This will not work, since Gradio does not know whether to interpret that outer list as part of your return value. You should instead just return that value directly. Now, let's see option (2). Instead of returning a list of values corresponding to each output component in order, you can also return a dictionary, with the key corresponding to the output component and the value as the new value. This also allows you to skip updating some output components. ```python with gr.Blocks() as demo: food_box = gr.Number(value=10, label="Food Count") status_box = gr.Textbox() def eat(food): if food > 0: return {food_box: food - 1, status_box: "full"} else: return {status_box: "hungry"} gr.Button("Eat").click( fn=eat, inputs=food_box, outputs=[food_box, status_box] ) ``` Notice how when there is no food, we only update the `status_box` element. We skipped updating the `food_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,
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 $demo_blocks_essay_simple See how we can configure the Textbox itself through a new `gr.Textbox()` method. The `value=` argument can still be used to update the value along with Component configuration. Any arguments we do not set will preserve their previous values.
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 difference between returning `None` (which generally resets a component's value to an empty state) versus returning `gr.skip()`, which leaves the component value unchanged. Tip: if you have multiple output components, and you want to leave all of their values unchanged, you can just return a single `gr.skip()` instead of returning a tuple of skips, one for each element.
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 message immediately, and then update the chatbot with the computer response after a simulated delay. $code_chatbot_consecutive $demo_chatbot_consecutive The `.then()` method of an event listener executes the subsequent event regardless of whether the previous event raised any errors. If you'd like to only run subsequent events if the previous event executed successfully, use the `.success()` method, which takes the same arguments as `.then()`. Conversely, if you'd like to only run subsequent events if the previous event failed (i.e., raised an error), use the `.failure()` method. This is particularly useful for error handling workflows, such as displaying error messages or restoring previous states when an operation fails.
Running Events Consecutively
https://gradio.app/guides/blocks-and-event-listeners
Building With Blocks - Blocks And Event Listeners Guide