text
stringlengths
0
2k
heading1
stringlengths
4
79
source_page_url
stringclasses
183 values
source_page_title
stringclasses
183 values
Finally, we will read the data from the Supabase dataset using the same `supabase` Python library and create a realtime dashboard using `gradio`. Note: We repeat certain steps in this section (like creating the Supabase client) in case you did not go through the previous sections. As described in Step 7, you will need the project URL and API Key for your database. 9\. Write a function that loads the data from the `Product` table and returns it as a pandas Dataframe: ```python import supabase import pandas as pd client = supabase.create_client('SUPABASE_URL', 'SUPABASE_SECRET_KEY') def read_data(): response = client.table('Product').select("*").execute() df = pd.DataFrame(response.data) return df ``` 10\. Create a small Gradio Dashboard with 2 Barplots that plots the prices and inventories of all of the items every minute and updates in real-time: ```python import gradio as gr with gr.Blocks() as dashboard: with gr.Row(): gr.BarPlot(read_data, x="product_id", y="price", title="Prices", every=gr.Timer(60)) gr.BarPlot(read_data, x="product_id", y="inventory_count", title="Inventory", every=gr.Timer(60)) dashboard.queue().launch() ``` Notice that by passing in a function to `gr.BarPlot()`, we have the BarPlot query the database as soon as the web app loads (and then again every 60 seconds because of the `every` parameter). Your final dashboard should look something like this: <gradio-app space="gradio/supabase"></gradio-app>
Visualize the Data in a Real-Time Gradio Dashboard
https://gradio.app/guides/creating-a-dashboard-from-supabase-data
Other Tutorials - Creating A Dashboard From Supabase Data Guide
That's it! In this tutorial, you learned how to write data to a Supabase dataset, and then read that data and plot the results as bar plots. If you update the data in the Supabase database, you'll notice that the Gradio dashboard will update within a minute. Try adding more plots and visualizations to this example (or with a different dataset) to build a more complex dashboard!
Conclusion
https://gradio.app/guides/creating-a-dashboard-from-supabase-data
Other Tutorials - Creating A Dashboard From Supabase Data 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
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
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
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
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
In this guide we will demonstrate some of the ways you can use Gradio with Comet. We will cover the basics of using Comet with Gradio and show you some of the ways that you can leverage Gradio's advanced features such as [Embedding with iFrames](https://www.gradio.app/guides/sharing-your-app/embedding-with-iframes) and [State](https://www.gradio.app/docs/state) to build some amazing model evaluation workflows. Here is a list of the topics covered in this guide. 1. Logging Gradio UI's to your Comet Experiments 2. Embedding Gradio Applications directly into your Comet Projects 3. Embedding Hugging Face Spaces directly into your Comet Projects 4. Logging Model Inferences from your Gradio Application to Comet
Introduction
https://gradio.app/guides/Gradio-and-Comet
Other Tutorials - Gradio And Comet Guide
[Comet](https://www.comet.com?utm_source=gradio&utm_medium=referral&utm_campaign=gradio-integration&utm_content=gradio-docs) is an MLOps Platform that is designed to help Data Scientists and Teams build better models faster! Comet provides tooling to Track, Explain, Manage, and Monitor your models in a single place! It works with Jupyter Notebooks and Scripts and most importantly it's 100% free!
What is Comet?
https://gradio.app/guides/Gradio-and-Comet
Other Tutorials - Gradio And Comet Guide
First, install the dependencies needed to run these examples ```shell pip install comet_ml torch torchvision transformers gradio shap requests Pillow ``` Next, you will need to [sign up for a Comet Account](https://www.comet.com/signup?utm_source=gradio&utm_medium=referral&utm_campaign=gradio-integration&utm_content=gradio-docs). Once you have your account set up, [grab your API Key](https://www.comet.com/docs/v2/guides/getting-started/quickstart/get-an-api-key?utm_source=gradio&utm_medium=referral&utm_campaign=gradio-integration&utm_content=gradio-docs) and configure your Comet credentials If you're running these examples as a script, you can either export your credentials as environment variables ```shell export COMET_API_KEY="<Your API Key>" export COMET_WORKSPACE="<Your Workspace Name>" export COMET_PROJECT_NAME="<Your Project Name>" ``` or set them in a `.comet.config` file in your working directory. You file should be formatted in the following way. ```shell [comet] api_key=<Your API Key> workspace=<Your Workspace Name> project_name=<Your Project Name> ``` If you are using the provided Colab Notebooks to run these examples, please run the cell with the following snippet before starting the Gradio UI. Running this cell allows you to interactively add your API key to the notebook. ```python import comet_ml comet_ml.init() ```
Setup
https://gradio.app/guides/Gradio-and-Comet
Other Tutorials - Gradio And Comet Guide
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/comet-ml/comet-examples/blob/master/integrations/model-evaluation/gradio/notebooks/Gradio_and_Comet.ipynb) In this example, we will go over how to log your Gradio Applications to Comet and interact with them using the Gradio Custom Panel. Let's start by building a simple Image Classification example using `resnet18`. ```python import comet_ml import requests import torch from PIL import Image from torchvision import transforms torch.hub.download_url_to_file("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") if torch.cuda.is_available(): device = "cuda" else: device = "cpu" model = torch.hub.load("pytorch/vision:v0.6.0", "resnet18", pretrained=True).eval() model = model.to(device) Download human-readable labels for ImageNet. response = requests.get("https://git.io/JJkYN") labels = response.text.split("\n") def predict(inp): inp = Image.fromarray(inp.astype("uint8"), "RGB") inp = transforms.ToTensor()(inp).unsqueeze(0) with torch.no_grad(): prediction = torch.nn.functional.softmax(model(inp.to(device))[0], dim=0) return {labels[i]: float(prediction[i]) for i in range(1000)} inputs = gr.Image() outputs = gr.Label(num_top_classes=3) io = gr.Interface( fn=predict, inputs=inputs, outputs=outputs, examples=["dog.jpg"] ) io.launch(inline=False, share=True) experiment = comet_ml.Experiment() experiment.add_tag("image-classifier") io.integrate(comet_ml=experiment) ``` The last line in this snippet will log the URL of the Gradio Application to your Comet Experiment. You can find the URL in the Text Tab of your Experiment. <video width="560" height="315" controls> <source src="https://user-images.githubusercontent.com/7529846/214328034-09369d4d-8b94-4c4a-aa3c-25e3ed8394c4.mp4"></source> </video> Add the Gradio Panel to your Experiment to interact with your application. <video width=
1. Logging Gradio UI's to your Comet Experiments
https://gradio.app/guides/Gradio-and-Comet
Other Tutorials - Gradio And Comet Guide
r-images.githubusercontent.com/7529846/214328034-09369d4d-8b94-4c4a-aa3c-25e3ed8394c4.mp4"></source> </video> Add the Gradio Panel to your Experiment to interact with your application. <video width="560" height="315" controls> <source src="https://user-images.githubusercontent.com/7529846/214328194-95987f83-c180-4929-9bed-c8a0d3563ed7.mp4"></source> </video>
1. Logging Gradio UI's to your Comet Experiments
https://gradio.app/guides/Gradio-and-Comet
Other Tutorials - Gradio And Comet Guide
<iframe width="560" height="315" src="https://www.youtube.com/embed/KZnpH7msPq0?start=9" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> If you are permanently hosting your Gradio application, you can embed the UI using the Gradio Panel Extended custom Panel. Go to your Comet Project page, and head over to the Panels tab. Click the `+ Add` button to bring up the Panels search page. <img width="560" alt="adding-panels" src="https://user-images.githubusercontent.com/7529846/214329314-70a3ff3d-27fb-408c-a4d1-4b58892a3854.jpeg"> Next, search for Gradio Panel Extended in the Public Panels section and click `Add`. <img width="560" alt="gradio-panel-extended" src="https://user-images.githubusercontent.com/7529846/214325577-43226119-0292-46be-a62a-0c7a80646ebb.png"> Once you have added your Panel, click `Edit` to access to the Panel Options page and paste in the URL of your Gradio application. ![Edit-Gradio-Panel-Options](https://user-images.githubusercontent.com/7529846/214573001-23814b5a-ca65-4ace-a8a5-b27cdda70f7a.gif) <img width="560" alt="Edit-Gradio-Panel-URL" src="https://user-images.githubusercontent.com/7529846/214334843-870fe726-0aa1-4b21-bbc6-0c48f56c48d8.png">
2. Embedding Gradio Applications directly into your Comet Projects
https://gradio.app/guides/Gradio-and-Comet
Other Tutorials - Gradio And Comet Guide
<iframe width="560" height="315" src="https://www.youtube.com/embed/KZnpH7msPq0?start=107" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> You can also embed Gradio Applications that are hosted on Hugging Faces Spaces into your Comet Projects using the Hugging Face Spaces Panel. Go to your Comet Project page, and head over to the Panels tab. Click the `+ Add` button to bring up the Panels search page. Next, search for the Hugging Face Spaces Panel in the Public Panels section and click `Add`. <img width="560" height="315" alt="huggingface-spaces-panel" src="https://user-images.githubusercontent.com/7529846/214325606-99aa3af3-b284-4026-b423-d3d238797e12.png"> Once you have added your Panel, click Edit to access to the Panel Options page and paste in the path of your Hugging Face Space e.g. `pytorch/ResNet` <img width="560" height="315" alt="Edit-HF-Space" src="https://user-images.githubusercontent.com/7529846/214335868-c6f25dee-13db-4388-bcf5-65194f850b02.png">
3. Embedding Hugging Face Spaces directly into your Comet Projects
https://gradio.app/guides/Gradio-and-Comet
Other Tutorials - Gradio And Comet Guide
<iframe width="560" height="315" src="https://www.youtube.com/embed/KZnpH7msPq0?start=176" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe> [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/comet-ml/comet-examples/blob/master/integrations/model-evaluation/gradio/notebooks/Logging_Model_Inferences_with_Comet_and_Gradio.ipynb) In the previous examples, we demonstrated the various ways in which you can interact with a Gradio application through the Comet UI. Additionally, you can also log model inferences, such as SHAP plots, from your Gradio application to Comet. In the following snippet, we're going to log inferences from a Text Generation model. We can persist an Experiment across multiple inference calls using Gradio's [State](https://www.gradio.app/docs/state) object. This will allow you to log multiple inferences from a model to a single Experiment. ```python import comet_ml import gradio as gr import shap import torch from transformers import AutoModelForCausalLM, AutoTokenizer if torch.cuda.is_available(): device = "cuda" else: device = "cpu" MODEL_NAME = "gpt2" model = AutoModelForCausalLM.from_pretrained(MODEL_NAME) set model decoder to true model.config.is_decoder = True set text-generation params under task_specific_params model.config.task_specific_params["text-generation"] = { "do_sample": True, "max_length": 50, "temperature": 0.7, "top_k": 50, "no_repeat_ngram_size": 2, } model = model.to(device) tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) explainer = shap.Explainer(model, tokenizer) def start_experiment(): """Returns an APIExperiment object that is thread safe and can be used to log inferences to a single Experiment """ try: api = comet_ml.API() workspace = api.get_default_
4. Logging Model Inferences to Comet
https://gradio.app/guides/Gradio-and-Comet
Other Tutorials - Gradio And Comet Guide
"""Returns an APIExperiment object that is thread safe and can be used to log inferences to a single Experiment """ try: api = comet_ml.API() workspace = api.get_default_workspace() project_name = comet_ml.config.get_config()["comet.project_name"] experiment = comet_ml.APIExperiment( workspace=workspace, project_name=project_name ) experiment.log_other("Created from", "gradio-inference") message = f"Started Experiment: [{experiment.name}]({experiment.url})" return (experiment, message) except Exception as e: return None, None def predict(text, state, message): experiment = state shap_values = explainer([text]) plot = shap.plots.text(shap_values, display=False) if experiment is not None: experiment.log_other("message", message) experiment.log_html(plot) return plot with gr.Blocks() as demo: start_experiment_btn = gr.Button("Start New Experiment") experiment_status = gr.Markdown() Log a message to the Experiment to provide more context experiment_message = gr.Textbox(label="Experiment Message") experiment = gr.State() input_text = gr.Textbox(label="Input Text", lines=5, interactive=True) submit_btn = gr.Button("Submit") output = gr.HTML(interactive=True) start_experiment_btn.click( start_experiment, outputs=[experiment, experiment_status] ) submit_btn.click( predict, inputs=[input_text, experiment, experiment_message], outputs=[output] ) ``` Inferences from this snippet will be saved in the HTML tab of your experiment. <video width="560" height="315" controls> <source src="https://user-images.githubusercontent.com/7529846/214328610-466e5c81-4814-49b9-887c-065aca14dd30.mp4"></source> </video>
4. Logging Model Inferences to Comet
https://gradio.app/guides/Gradio-and-Comet
Other Tutorials - Gradio And Comet Guide
887c-065aca14dd30.mp4"></source> </video>
4. Logging Model Inferences to Comet
https://gradio.app/guides/Gradio-and-Comet
Other Tutorials - Gradio And Comet Guide
We hope you found this guide useful and that it provides some inspiration to help you build awesome model evaluation workflows with Comet and Gradio.
Conclusion
https://gradio.app/guides/Gradio-and-Comet
Other Tutorials - Gradio And Comet Guide
- Create an account on Hugging Face [here](https://huggingface.co/join). - Add Gradio Demo under your username, see this [course](https://huggingface.co/course/chapter9/4?fw=pt) for setting up Gradio Demo on Hugging Face. - Request to join the Comet organization [here](https://huggingface.co/Comet).
How to contribute Gradio demos on HF spaces on the Comet organization
https://gradio.app/guides/Gradio-and-Comet
Other Tutorials - Gradio And Comet Guide
- [Comet Documentation](https://www.comet.com/docs/v2/?utm_source=gradio&utm_medium=referral&utm_campaign=gradio-integration&utm_content=gradio-docs)
Additional Resources
https://gradio.app/guides/Gradio-and-Comet
Other Tutorials - Gradio And Comet Guide
3D models are becoming more popular in machine learning and make for some of the most fun demos to experiment with. Using `gradio`, you can easily build a demo of your 3D image model and share it with anyone. The Gradio 3D Model component accepts 3 file types including: _.obj_, _.glb_, & _.gltf_. This guide will show you how to build a demo for your 3D image model in a few lines of code; like the one below. Play around with 3D object by clicking around, dragging and zooming: <gradio-app space="gradio/Model3D"> </gradio-app> Prerequisites Make sure you have the `gradio` Python package already [installed](https://gradio.app/guides/quickstart).
Introduction
https://gradio.app/guides/how-to-use-3D-model-component
Other Tutorials - How To Use 3D Model Component Guide
Let's take a look at how to create the minimal interface above. The prediction function in this case will just return the original 3D model mesh, but you can change this function to run inference on your machine learning model. We'll take a look at more complex examples below. ```python import gradio as gr import os def load_mesh(mesh_file_name): return mesh_file_name demo = gr.Interface( fn=load_mesh, inputs=gr.Model3D(), outputs=gr.Model3D( clear_color=[0.0, 0.0, 0.0, 0.0], label="3D Model"), examples=[ [os.path.join(os.path.dirname(__file__), "files/Bunny.obj")], [os.path.join(os.path.dirname(__file__), "files/Duck.glb")], [os.path.join(os.path.dirname(__file__), "files/Fox.gltf")], [os.path.join(os.path.dirname(__file__), "files/face.obj")], ], ) if __name__ == "__main__": demo.launch() ``` Let's break down the code above: `load_mesh`: This is our 'prediction' function and for simplicity, this function will take in the 3D model mesh and return it. Creating the Interface: - `fn`: the prediction function that is used when the user clicks submit. In our case this is the `load_mesh` function. - `inputs`: create a model3D input component. The input expects an uploaded file as a {str} filepath. - `outputs`: create a model3D output component. The output component also expects a file as a {str} filepath. - `clear_color`: this is the background color of the 3D model canvas. Expects RGBa values. - `label`: the label that appears on the top left of the component. - `examples`: list of 3D model files. The 3D model component can accept _.obj_, _.glb_, & _.gltf_ file types. - `cache_examples`: saves the predicted output for the examples, to save time on inference.
Taking a Look at the Code
https://gradio.app/guides/how-to-use-3D-model-component
Other Tutorials - How To Use 3D Model Component Guide
Below is a demo that uses the DPT model to predict the depth of an image and then uses 3D Point Cloud to create a 3D object. Take a look at the [app.py](https://huggingface.co/spaces/gradio/dpt-depth-estimation-3d-obj/blob/main/app.py) file for a peek into the code and the model prediction function. <gradio-app space="gradio/dpt-depth-estimation-3d-obj"> </gradio-app> --- And you're done! That's all the code you need to build an interface for your Model3D model. Here are some references that you may find useful: - Gradio's ["Getting Started" guide](https://gradio.app/getting_started/) - The first [3D Model Demo](https://huggingface.co/spaces/gradio/Model3D) and [complete code](https://huggingface.co/spaces/gradio/Model3D/tree/main) (on Hugging Face Spaces)
Exploring a more complex Model3D Demo:
https://gradio.app/guides/how-to-use-3D-model-component
Other Tutorials - How To Use 3D Model Component 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
Gradio features a built-in theming engine that lets you customize the look and feel of your app. You can choose from a variety of themes, or create your own. To do so, pass the `theme=` kwarg to the `launch()` method of `Blocks` or `Interface`. For example: ```python with gr.Blocks() as demo: ... your code here demo.launch(theme=gr.themes.Soft()) ... ``` <div class="wrapper"> <iframe src="https://gradio-theme-soft.hf.space?__theme=light" frameborder="0" ></iframe> </div> Gradio comes with a set of prebuilt themes which you can load from `gr.themes.*`. These are: * `gr.themes.Base()` - the `"base"` theme sets the primary color to blue but otherwise has minimal styling, making it particularly useful as a base for creating new, custom themes. * `gr.themes.Default()` - the `"default"` Gradio 5 theme, with a vibrant orange primary color and gray secondary color. * `gr.themes.Origin()` - the `"origin"` theme is most similar to Gradio 4 styling. Colors, especially in light mode, are more subdued than the Gradio 5 default theme. * `gr.themes.Citrus()` - the `"citrus"` theme uses a yellow primary color, highlights form elements that are in focus, and includes fun 3D effects when buttons are clicked. * `gr.themes.Monochrome()` - the `"monochrome"` theme uses a black primary and white secondary color, and uses serif-style fonts, giving the appearance of a black-and-white newspaper. * `gr.themes.Soft()` - the `"soft"` theme uses a purple primary color and white secondary color. It also increases the border radius around buttons and form elements and highlights labels. * `gr.themes.Glass()` - the `"glass"` theme has a blue primary color and a transclucent gray secondary color. The theme also uses vertical gradients to create a glassy effect. * `gr.themes.Ocean()` - the `"ocean"` theme has a blue-green primary color and gray secondary color. The theme also uses horizontal gradients, especially for buttons and some form elements. Each of these themes set values
Introduction
https://gradio.app/guides/theming-guide
Other Tutorials - Theming Guide Guide
the `"ocean"` theme has a blue-green primary color and gray secondary color. The theme also uses horizontal gradients, especially for buttons and some form elements. Each of these themes set values for hundreds of CSS variables. You can use prebuilt themes as a starting point for your own custom themes, or you can create your own themes from scratch. Let's take a look at each approach.
Introduction
https://gradio.app/guides/theming-guide
Other Tutorials - Theming Guide Guide
The easiest way to build a theme is using the Theme Builder. To launch the Theme Builder locally, run the following code: ```python import gradio as gr gr.themes.builder() ``` $demo_theme_builder You can use the Theme Builder running on Spaces above, though it runs much faster when you launch it locally via `gr.themes.builder()`. As you edit the values in the Theme Builder, the app will preview updates in real time. You can download the code to generate the theme you've created so you can use it in any Gradio app. In the rest of the guide, we will cover building themes programmatically.
Using the Theme Builder
https://gradio.app/guides/theming-guide
Other Tutorials - Theming Guide Guide
Although each theme has hundreds of CSS variables, the values for most these variables are drawn from 8 core variables which can be set through the constructor of each prebuilt theme. Modifying these 8 arguments allows you to quickly change the look and feel of your app. Core Colors The first 3 constructor arguments set the colors of the theme and are `gradio.themes.Color` objects. Internally, these Color objects hold brightness values for the palette of a single hue, ranging from 50, 100, 200..., 800, 900, 950. Other CSS variables are derived from these 3 colors. The 3 color constructor arguments are: - `primary_hue`: This is the color draws attention in your theme. In the default theme, this is set to `gradio.themes.colors.orange`. - `secondary_hue`: This is the color that is used for secondary elements in your theme. In the default theme, this is set to `gradio.themes.colors.blue`. - `neutral_hue`: This is the color that is used for text and other neutral elements in your theme. In the default theme, this is set to `gradio.themes.colors.gray`. You could modify these values using their string shortcuts, such as ```python with gr.Blocks() as demo: ... your code here demo.launch(theme=gr.themes.Default(primary_hue="red", secondary_hue="pink")) ... ``` or you could use the `Color` objects directly, like this: ```python with gr.Blocks() as demo: ... your code here demo.launch(theme=gr.themes.Default(primary_hue=gr.themes.colors.red, secondary_hue=gr.themes.colors.pink)) ``` <div class="wrapper"> <iframe src="https://gradio-theme-extended-step-1.hf.space?__theme=light" frameborder="0" ></iframe> </div> Predefined colors are: - `slate` - `gray` - `zinc` - `neutral` - `stone` - `red` - `orange` - `amber` - `yellow` - `lime` - `green` - `emerald` - `teal` - `cyan` - `sky` - `blue` - `indigo` - `violet` - `purple` - `fuchsia` - `pink` - `rose` You could also create your own custom `Color` objects and pass them in. Core Sizing The nex
Extending Themes via the Constructor
https://gradio.app/guides/theming-guide
Other Tutorials - Theming Guide Guide
ld` - `teal` - `cyan` - `sky` - `blue` - `indigo` - `violet` - `purple` - `fuchsia` - `pink` - `rose` You could also create your own custom `Color` objects and pass them in. Core Sizing The next 3 constructor arguments set the sizing of the theme and are `gradio.themes.Size` objects. Internally, these Size objects hold pixel size values that range from `xxs` to `xxl`. Other CSS variables are derived from these 3 sizes. - `spacing_size`: This sets the padding within and spacing between elements. In the default theme, this is set to `gradio.themes.sizes.spacing_md`. - `radius_size`: This sets the roundedness of corners of elements. In the default theme, this is set to `gradio.themes.sizes.radius_md`. - `text_size`: This sets the font size of text. In the default theme, this is set to `gradio.themes.sizes.text_md`. You could modify these values using their string shortcuts, such as ```python with gr.Blocks() as demo: ... your code here demo.launch(theme=gr.themes.Default(spacing_size="sm", radius_size="none")) ... ``` or you could use the `Size` objects directly, like this: ```python with gr.Blocks() as demo: ... your code here demo.launch(theme=gr.themes.Default(spacing_size=gr.themes.sizes.spacing_sm, radius_size=gr.themes.sizes.radius_none)) ... ``` <div class="wrapper"> <iframe src="https://gradio-theme-extended-step-2.hf.space?__theme=light" frameborder="0" ></iframe> </div> The predefined size objects are: - `radius_none` - `radius_sm` - `radius_md` - `radius_lg` - `spacing_sm` - `spacing_md` - `spacing_lg` - `text_sm` - `text_md` - `text_lg` You could also create your own custom `Size` objects and pass them in. Core Fonts The final 2 constructor arguments set the fonts of the theme. You can pass a list of fonts to each of these arguments to specify fallbacks. If you provide a string, it will be loaded as a system font. If you provide a `gradio.themes.GoogleFont`, the font will be loaded from Google Fonts. - `font`: Th
Extending Themes via the Constructor
https://gradio.app/guides/theming-guide
Other Tutorials - Theming Guide Guide
these arguments to specify fallbacks. If you provide a string, it will be loaded as a system font. If you provide a `gradio.themes.GoogleFont`, the font will be loaded from Google Fonts. - `font`: This sets the primary font of the theme. In the default theme, this is set to `gradio.themes.GoogleFont("IBM Plex Sans")`. - `font_mono`: This sets the monospace font of the theme. In the default theme, this is set to `gradio.themes.GoogleFont("IBM Plex Mono")`. You could modify these values such as the following: ```python with gr.Blocks() as demo: ... your code here demo.launch(theme=gr.themes.Default(font=[gr.themes.GoogleFont("Inconsolata"), "Arial", "sans-serif"])) ... ``` <div class="wrapper"> <iframe src="https://gradio-theme-extended-step-3.hf.space?__theme=light" frameborder="0" ></iframe> </div>
Extending Themes via the Constructor
https://gradio.app/guides/theming-guide
Other Tutorials - Theming Guide Guide
You can also modify the values of CSS variables after the theme has been loaded. To do so, use the `.set()` method of the theme object to get access to the CSS variables. For example: ```python theme = gr.themes.Default(primary_hue="blue").set( loader_color="FF0000", slider_color="FF0000", ) with gr.Blocks() as demo: ... your code here demo.launch(theme=theme) ``` In the example above, we've set the `loader_color` and `slider_color` variables to `FF0000`, despite the overall `primary_color` using the blue color palette. You can set any CSS variable that is defined in the theme in this manner. Your IDE type hinting should help you navigate these variables. Since there are so many CSS variables, let's take a look at how these variables are named and organized. CSS Variable Naming Conventions CSS variable names can get quite long, like `button_primary_background_fill_hover_dark`! However they follow a common naming convention that makes it easy to understand what they do and to find the variable you're looking for. Separated by underscores, the variable name is made up of: 1. The target element, such as `button`, `slider`, or `block`. 2. The target element type or sub-element, such as `button_primary`, or `block_label`. 3. The property, such as `button_primary_background_fill`, or `block_label_border_width`. 4. Any relevant state, such as `button_primary_background_fill_hover`. 5. If the value is different in dark mode, the suffix `_dark`. For example, `input_border_color_focus_dark`. Of course, many CSS variable names are shorter than this, such as `table_border_color`, or `input_shadow`. CSS Variable Organization Though there are hundreds of CSS variables, they do not all have to have individual values. They draw their values by referencing a set of core variables and referencing each other. This allows us to only have to modify a few variables to change the look and feel of the entire theme, while also getting finer control of indi
Extending Themes via `.set()`
https://gradio.app/guides/theming-guide
Other Tutorials - Theming Guide Guide
cing a set of core variables and referencing each other. This allows us to only have to modify a few variables to change the look and feel of the entire theme, while also getting finer control of individual elements that we may want to modify. Referencing Core Variables To reference one of the core constructor variables, precede the variable name with an asterisk. To reference a core color, use the `*primary_`, `*secondary_`, or `*neutral_` prefix, followed by the brightness value. For example: ```python theme = gr.themes.Default(primary_hue="blue").set( button_primary_background_fill="*primary_200", button_primary_background_fill_hover="*primary_300", ) ``` In the example above, we've set the `button_primary_background_fill` and `button_primary_background_fill_hover` variables to `*primary_200` and `*primary_300`. These variables will be set to the 200 and 300 brightness values of the blue primary color palette, respectively. Similarly, to reference a core size, use the `*spacing_`, `*radius_`, or `*text_` prefix, followed by the size value. For example: ```python theme = gr.themes.Default(radius_size="md").set( button_primary_border_radius="*radius_xl", ) ``` In the example above, we've set the `button_primary_border_radius` variable to `*radius_xl`. This variable will be set to the `xl` setting of the medium radius size range. Referencing Other Variables Variables can also reference each other. For example, look at the example below: ```python theme = gr.themes.Default().set( button_primary_background_fill="FF0000", button_primary_background_fill_hover="FF0000", button_primary_border="FF0000", ) ``` Having to set these values to a common color is a bit tedious. Instead, we can reference the `button_primary_background_fill` variable in the `button_primary_background_fill_hover` and `button_primary_border` variables, using a `*` prefix. ```python theme = gr.themes.Default().set( button_primary_background_fill="F
Extending Themes via `.set()`
https://gradio.app/guides/theming-guide
Other Tutorials - Theming Guide Guide
ll` variable in the `button_primary_background_fill_hover` and `button_primary_border` variables, using a `*` prefix. ```python theme = gr.themes.Default().set( button_primary_background_fill="FF0000", button_primary_background_fill_hover="*button_primary_background_fill", button_primary_border="*button_primary_background_fill", ) ``` Now, if we change the `button_primary_background_fill` variable, the `button_primary_background_fill_hover` and `button_primary_border` variables will automatically update as well. This is particularly useful if you intend to share your theme - it makes it easy to modify the theme without having to change every variable. Note that dark mode variables automatically reference each other. For example: ```python theme = gr.themes.Default().set( button_primary_background_fill="FF0000", button_primary_background_fill_dark="AAAAAA", button_primary_border="*button_primary_background_fill", button_primary_border_dark="*button_primary_background_fill_dark", ) ``` `button_primary_border_dark` will draw its value from `button_primary_background_fill_dark`, because dark mode always draw from the dark version of the variable.
Extending Themes via `.set()`
https://gradio.app/guides/theming-guide
Other Tutorials - Theming Guide Guide
Let's say you want to create a theme from scratch! We'll go through it step by step - you can also see the source of prebuilt themes in the gradio source repo for reference - [here's the source](https://github.com/gradio-app/gradio/blob/main/gradio/themes/monochrome.py) for the Monochrome theme. Our new theme class will inherit from `gradio.themes.Base`, a theme that sets a lot of convenient defaults. Let's make a simple demo that creates a dummy theme called Seafoam, and make a simple app that uses it. $code_theme_new_step_1 <div class="wrapper"> <iframe src="https://gradio-theme-new-step-1.hf.space?__theme=light" frameborder="0" ></iframe> </div> The Base theme is very barebones, and uses `gr.themes.Blue` as it primary color - you'll note the primary button and the loading animation are both blue as a result. Let's change the defaults core arguments of our app. We'll overwrite the constructor and pass new defaults for the core constructor arguments. We'll use `gr.themes.Emerald` as our primary color, and set secondary and neutral hues to `gr.themes.Blue`. We'll make our text larger using `text_lg`. We'll use `Quicksand` as our default font, loaded from Google Fonts. $code_theme_new_step_2 <div class="wrapper"> <iframe src="https://gradio-theme-new-step-2.hf.space?__theme=light" frameborder="0" ></iframe> </div> See how the primary button and the loading animation are now green? These CSS variables are tied to the `primary_hue` variable. Let's modify the theme a bit more directly. We'll call the `set()` method to overwrite CSS variable values explicitly. We can use any CSS logic, and reference our core constructor arguments using the `*` prefix. $code_theme_new_step_3 <div class="wrapper"> <iframe src="https://gradio-theme-new-step-3.hf.space?__theme=light" frameborder="0" ></iframe> </div> Look how fun our theme looks now! With just a few variable changes, our theme looks completely different. You may find it helpful to explore the [source code
Creating a Full Theme
https://gradio.app/guides/theming-guide
Other Tutorials - Theming Guide Guide
ght" frameborder="0" ></iframe> </div> Look how fun our theme looks now! With just a few variable changes, our theme looks completely different. You may find it helpful to explore the [source code of the other prebuilt themes](https://github.com/gradio-app/gradio/blob/main/gradio/themes) to see how they modified the base theme. You can also find your browser's Inspector useful to select elements from the UI and see what CSS variables are being used in the styles panel.
Creating a Full Theme
https://gradio.app/guides/theming-guide
Other Tutorials - Theming Guide Guide
Once you have created a theme, you can upload it to the HuggingFace Hub to let others view it, use it, and build off of it! Uploading a Theme There are two ways to upload a theme, via the theme class instance or the command line. We will cover both of them with the previously created `seafoam` theme. - Via the class instance Each theme instance has a method called `push_to_hub` we can use to upload a theme to the HuggingFace hub. ```python seafoam.push_to_hub(repo_name="seafoam", version="0.0.1", token="<token>") ``` - Via the command line First save the theme to disk ```python seafoam.dump(filename="seafoam.json") ``` Then use the `upload_theme` command: ```bash upload_theme\ "seafoam.json"\ "seafoam"\ --version "0.0.1"\ --token "<token>" ``` In order to upload a theme, you must have a HuggingFace account and pass your [Access Token](https://huggingface.co/docs/huggingface_hub/quick-startlogin) as the `token` argument. However, if you log in via the [HuggingFace command line](https://huggingface.co/docs/huggingface_hub/quick-startlogin) (which comes installed with `gradio`), you can omit the `token` argument. The `version` argument lets you specify a valid [semantic version](https://www.geeksforgeeks.org/introduction-semantic-versioning/) string for your theme. That way your users are able to specify which version of your theme they want to use in their apps. This also lets you publish updates to your theme without worrying about changing how previously created apps look. The `version` argument is optional. If omitted, the next patch version is automatically applied. Theme Previews By calling `push_to_hub` or `upload_theme`, the theme assets will be stored in a [HuggingFace space](https://huggingface.co/docs/hub/spaces-overview). For example, the theme preview for the calm seafoam theme is here: [calm seafoam preview](https://huggingface.co/spaces/shivalikasingh/calm_seafoam). <div class="wrapper"> <iframe src="ht
Sharing Themes
https://gradio.app/guides/theming-guide
Other Tutorials - Theming Guide Guide
verview). For example, the theme preview for the calm seafoam theme is here: [calm seafoam preview](https://huggingface.co/spaces/shivalikasingh/calm_seafoam). <div class="wrapper"> <iframe src="https://shivalikasingh-calm-seafoam.hf.space/?__theme=light" frameborder="0" ></iframe> </div> Discovering Themes The [Theme Gallery](https://huggingface.co/spaces/gradio/theme-gallery) shows all the public gradio themes. After publishing your theme, it will automatically show up in the theme gallery after a couple of minutes. You can sort the themes by the number of likes on the space and from most to least recently created as well as toggling themes between light and dark mode. <div class="wrapper"> <iframe src="https://gradio-theme-gallery.static.hf.space" frameborder="0" ></iframe> </div> Downloading To use a theme from the hub, use the `from_hub` method on the `ThemeClass` and pass it to your app: ```python my_theme = gr.Theme.from_hub("gradio/seafoam") with gr.Blocks() as demo: ... your code here demo.launch(theme=my_theme) ``` You can also pass the theme string directly to the `launch()` method of `Blocks` or `Interface` (e.g. `demo.launch(theme="gradio/seafoam")`) You can pin your app to an upstream theme version by using semantic versioning expressions. For example, the following would ensure the theme we load from the `seafoam` repo was between versions `0.0.1` and `0.1.0`: ```python with gr.Blocks() as demo: ... your code here demo.launch(theme="gradio/seafoam@>=0.0.1,<0.1.0") .... ``` Enjoy creating your own themes! If you make one you're proud of, please share it with the world by uploading it to the hub! If you tag us on [Twitter](https://twitter.com/gradio) we can give your theme a shout out! <style> .wrapper { position: relative; padding-bottom: 56.25%; padding-top: 25px; height: 0; } .wrapper iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } </style>
Sharing Themes
https://gradio.app/guides/theming-guide
Other Tutorials - Theming Guide Guide
ion: relative; padding-bottom: 56.25%; padding-top: 25px; height: 0; } .wrapper iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } </style>
Sharing Themes
https://gradio.app/guides/theming-guide
Other Tutorials - Theming Guide Guide
Image classification is a central task in computer vision. Building better classifiers to classify what object is present in a picture is an active area of research, as it has applications stretching from facial recognition to manufacturing quality control. State-of-the-art image classifiers are based on the _transformers_ architectures, originally popularized for NLP tasks. Such architectures are typically called vision transformers (ViT). 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 a **single line of 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).
Introduction
https://gradio.app/guides/image-classification-with-vision-transformers
Other Tutorials - Image Classification With Vision Transformers Guide
First, we will need an image classification model. For this tutorial, we will use a model from the [Hugging Face Model Hub](https://huggingface.co/models?pipeline_tag=image-classification). The Hub contains thousands of models covering dozens of different machine learning tasks. Expand the Tasks category on the left sidebar and select "Image Classification" as our task of interest. You will then see all of the models on the Hub that are designed to classify images. At the time of writing, the most popular one is `google/vit-base-patch16-224`, which has been trained on ImageNet images at a resolution of 224x224 pixels. We will use this model for our demo.
Step 1 — Choosing a Vision Image Classification Model
https://gradio.app/guides/image-classification-with-vision-transformers
Other Tutorials - Image Classification With Vision Transformers Guide
When using a model from the Hugging Face Hub, we do not need to define the input or output components for the demo. Similarly, we do not need to be concerned with the details of preprocessing or postprocessing. All of these are automatically inferred from the model tags. Besides the import statement, it only takes a single line of Python to load and launch the demo. We use the `gr.Interface.load()` method and pass in the path to the model including the `huggingface/` to designate that it is from the Hugging Face Hub. ```python import gradio as gr gr.Interface.load( "huggingface/google/vit-base-patch16-224", examples=["alligator.jpg", "laptop.jpg"]).launch() ``` Notice that we have added one more parameter, the `examples`, which allows us to prepopulate our interfaces with a few predefined examples. This produces the following interface, which you can try right here in your browser. When you input an image, it is automatically preprocessed and sent to the Hugging Face Hub API, where it is passed through the model and returned as a human-interpretable prediction. Try uploading your own image! <gradio-app space="gradio/vision-transformer"> --- And you're done! In one line of code, you have built 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 2 — Loading the Vision Transformer Model with Gradio
https://gradio.app/guides/image-classification-with-vision-transformers
Other Tutorials - Image Classification With Vision Transformers Guide
**[OpenAPI](https://www.openapis.org/)** is a widely adopted standard for describing RESTful APIs in a machine-readable format, typically as a JSON file. You can create a Gradio UI from an OpenAPI Spec **in 1 line of Python**, instantly generating an interactive web interface for any API, making it accessible for 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
By default, every Gradio demo includes a built-in queuing system that scales to thousands of requests. When a user of your app submits a request (i.e. submits an input to your function), Gradio adds the request to the queue, and requests are processed in order, generally speaking (this is not exactly true, as discussed below). When the user's request has finished processing, the Gradio server returns the result back to the user using server-side events (SSE). The SSE protocol has several advantages over simply using HTTP POST requests: (1) They do not time out -- most browsers raise a timeout error if they do not get a response to a POST request after a short period of time (e.g. 1 min). This can be a problem if your inference function takes longer than 1 minute to run or if many people are trying out your demo at the same time, resulting in increased latency. (2) They allow the server to send multiple updates to the frontend. This means, for example, that the server can send a real-time ETA of how long your prediction will take to complete. To configure the queue, simply call the `.queue()` method before launching an `Interface`, `TabbedInterface`, `ChatInterface` or any `Blocks`. Here's an example: ```py import gradio as gr app = gr.Interface(lambda x:x, "image", "image") app.queue() <-- Sets up a queue with default parameters app.launch() ``` **How Requests are Processed from the Queue** When a Gradio server is launched, a pool of threads is used to execute requests from the queue. By default, the maximum size of this thread pool is `40` (which is the default inherited from FastAPI, on which the Gradio server is based). However, this does *not* mean that 40 requests are always processed in parallel from the queue. Instead, Gradio uses a **single-function-single-worker** model by default. This means that each worker thread is only assigned a single function from among all of the functions that could be part of your Gradio app. This ensures that you do
Overview of Gradio's Queueing System
https://gradio.app/guides/setting-up-a-demo-for-maximum-performance
Other Tutorials - Setting Up A Demo For Maximum Performance Guide
-single-worker** model by default. This means that each worker thread is only assigned a single function from among all of the functions that could be part of your Gradio app. This ensures that you do not see, for example, out-of-memory errors, due to multiple workers calling a machine learning model at the same time. Suppose you have 3 functions in your Gradio app: A, B, and C. And you see the following sequence of 7 requests come in from users using your app: ``` 1 2 3 4 5 6 7 ------------- A B A A C B A ``` Initially, 3 workers will get dispatched to handle requests 1, 2, and 5 (corresponding to functions: A, B, C). As soon as any of these workers finish, they will start processing the next function in the queue of the same function type, e.g. the worker that finished processing request 1 will start processing request 3, and so on. If you want to change this behavior, there are several parameters that can be used to configure the queue and help reduce latency. Let's go through them one-by-one. The `default_concurrency_limit` parameter in `queue()` The first parameter we will explore is the `default_concurrency_limit` parameter in `queue()`. This controls how many workers can execute the same event. By default, this is set to `1`, but you can set it to a higher integer: `2`, `10`, or even `None` (in the last case, there is no limit besides the total number of available workers). This is useful, for example, if your Gradio app does not call any resource-intensive functions. If your app only queries external APIs, then you can set the `default_concurrency_limit` much higher. Increasing this parameter can **linearly multiply the capacity of your server to handle requests**. So why not set this parameter much higher all the time? Keep in mind that since requests are processed in parallel, each request will consume memory to store the data and weights for processing. This means that you might get out-of-memory errors if you increase the `default_concurrenc
Overview of Gradio's Queueing System
https://gradio.app/guides/setting-up-a-demo-for-maximum-performance
Other Tutorials - Setting Up A Demo For Maximum Performance Guide
sts are processed in parallel, each request will consume memory to store the data and weights for processing. This means that you might get out-of-memory errors if you increase the `default_concurrency_limit` too high. You may also start to get diminishing returns if the `default_concurrency_limit` is too high because of costs of switching between different worker threads. **Recommendation**: Increase the `default_concurrency_limit` parameter as high as you can while you continue to see performance gains or until you hit memory limits on your machine. You can [read about Hugging Face Spaces machine specs here](https://huggingface.co/docs/hub/spaces-overview). The `concurrency_limit` parameter in events You can also set the number of requests that can be processed in parallel for each event individually. These take priority over the `default_concurrency_limit` parameter described previously. To do this, set the `concurrency_limit` parameter of any event listener, e.g. `btn.click(..., concurrency_limit=20)` or in the `Interface` or `ChatInterface` classes: e.g. `gr.Interface(..., concurrency_limit=20)`. By default, this parameter is set to the global `default_concurrency_limit`. The `max_threads` parameter in `launch()` If your demo uses non-async functions, e.g. `def` instead of `async def`, they will be run in a threadpool. This threadpool has a size of 40 meaning that only 40 threads can be created to run your non-async functions. If you are running into this limit, you can increase the threadpool size with `max_threads`. The default value is 40. Tip: You should use async functions whenever possible to increase the number of concurrent requests your app can handle. Quick functions that are not CPU-bound are good candidates to be written as `async`. This [guide](https://fastapi.tiangolo.com/async/) is a good primer on the concept. The `max_size` parameter in `queue()` A more blunt way to reduce the wait times is simply to prevent too many pe
Overview of Gradio's Queueing System
https://gradio.app/guides/setting-up-a-demo-for-maximum-performance
Other Tutorials - Setting Up A Demo For Maximum Performance Guide
is [guide](https://fastapi.tiangolo.com/async/) is a good primer on the concept. The `max_size` parameter in `queue()` A more blunt way to reduce the wait times is simply to prevent too many people from joining the queue in the first place. You can set the maximum number of requests that the queue processes using the `max_size` parameter of `queue()`. If a request arrives when the queue is already of the maximum size, it will not be allowed to join the queue and instead, the user will receive an error saying that the queue is full and to try again. By default, `max_size=None`, meaning that there is no limit to the number of users that can join the queue. Paradoxically, setting a `max_size` can often improve user experience because it prevents users from being dissuaded by very long queue wait times. Users who are more interested and invested in your demo will keep trying to join the queue, and will be able to get their results faster. **Recommendation**: For a better user experience, set a `max_size` that is reasonable given your expectations of how long users might be willing to wait for a prediction. The `max_batch_size` parameter in events Another way to increase the parallelism of your Gradio demo is to write your function so that it can accept **batches** of inputs. Most deep learning models can process batches of samples more efficiently than processing individual samples. If you write your function to process a batch of samples, Gradio will automatically batch incoming requests together and pass them into your function as a batch of samples. You need to set `batch` to `True` (by default it is `False`) and set a `max_batch_size` (by default it is `4`) based on the maximum number of samples your function is able to handle. These two parameters can be passed into `gr.Interface()` or to an event in Blocks such as `.click()`. While setting a batch is conceptually similar to having workers process requests in parallel, it is often _faster_ than set
Overview of Gradio's Queueing System
https://gradio.app/guides/setting-up-a-demo-for-maximum-performance
Other Tutorials - Setting Up A Demo For Maximum Performance Guide
e passed into `gr.Interface()` or to an event in Blocks such as `.click()`. While setting a batch is conceptually similar to having workers process requests in parallel, it is often _faster_ than setting the `concurrency_count` for deep learning models. The downside is that you might need to adapt your function a little bit to accept batches of samples instead of individual samples. Here's an example of a function that does _not_ accept a batch of inputs -- it processes a single input at a time: ```py import time def trim_words(word, length): return word[:int(length)] ``` Here's the same function rewritten to take in a batch of samples: ```py import time def trim_words(words, lengths): trimmed_words = [] for w, l in zip(words, lengths): trimmed_words.append(w[:int(l)]) return [trimmed_words] ``` The second function can be used with `batch=True` and an appropriate `max_batch_size` parameter. **Recommendation**: If possible, write your function to accept batches of samples, and then set `batch` to `True` and the `max_batch_size` as high as possible based on your machine's memory limits.
Overview of Gradio's Queueing System
https://gradio.app/guides/setting-up-a-demo-for-maximum-performance
Other Tutorials - Setting Up A Demo For Maximum Performance Guide
If you have done everything above, and your demo is still not fast enough, you can upgrade the hardware that your model is running on. Changing the model from running on CPUs to running on GPUs will usually provide a 10x-50x increase in inference time for deep learning models. It is particularly straightforward to upgrade your Hardware on Hugging Face Spaces. Simply click on the "Settings" tab in your Space and choose the Space Hardware you'd like. ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/hub/spaces-gpu-settings.png) While you might need to adapt portions of your machine learning inference code to run on a GPU (here's a [handy guide](https://cnvrg.io/pytorch-cuda/) if you are using PyTorch), Gradio is completely agnostic to the choice of hardware and will work completely fine if you use it with CPUs, GPUs, TPUs, or any other hardware! Note: your GPU memory is different than your CPU memory, so if you upgrade your hardware, you might need to adjust the value of the `default_concurrency_limit` parameter described above.
Upgrading your Hardware (GPUs, TPUs, etc.)
https://gradio.app/guides/setting-up-a-demo-for-maximum-performance
Other Tutorials - Setting Up A Demo For Maximum Performance Guide
Congratulations! You know how to set up a Gradio demo for maximum performance. Good luck on your next viral demo!
Conclusion
https://gradio.app/guides/setting-up-a-demo-for-maximum-performance
Other Tutorials - Setting Up A Demo For Maximum Performance 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
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
The Hugging Face Hub is a central platform that has hundreds of thousands of [models](https://huggingface.co/models), [datasets](https://huggingface.co/datasets) and [demos](https://huggingface.co/spaces) (also known as Spaces). Gradio has multiple features that make it extremely easy to leverage existing models and Spaces on the Hub. This guide walks through these features.
Introduction
https://gradio.app/guides/using-hugging-face-integrations
Other Tutorials - Using Hugging Face Integrations Guide
Hugging Face has a service called [Serverless Inference Endpoints](https://huggingface.co/docs/api-inference/index), which allows you to send HTTP requests to models on the Hub. The API includes a generous free tier, and you can switch to [dedicated Inference Endpoints](https://huggingface.co/inference-endpoints/dedicated) when you want to use it in production. Gradio integrates directly with Serverless Inference Endpoints so that you can create a demo simply by specifying a model's name (e.g. `Helsinki-NLP/opus-mt-en-es`), like this: ```python import gradio as gr demo = gr.load("Helsinki-NLP/opus-mt-en-es", src="models") demo.launch() ``` For any Hugging Face model supported in Inference Endpoints, Gradio automatically infers the expected input and output and make the underlying server calls, so you don't have to worry about defining the prediction function. Notice that we just put specify the model name and state that the `src` should be `models` (Hugging Face's Model Hub). There is no need to install any dependencies (except `gradio`) since you are not loading the model on your computer. You might notice that the first inference takes a little bit longer. This happens since the Inference Endpoints is loading the model in the server. You get some benefits afterward: - The inference will be much faster. - The server caches your requests. - You get built-in automatic scaling.
Demos with the Hugging Face Inference Endpoints
https://gradio.app/guides/using-hugging-face-integrations
Other Tutorials - Using Hugging Face Integrations Guide
[Hugging Face Spaces](https://hf.co/spaces) allows anyone to host their Gradio demos freely, and uploading your Gradio demos take a couple of minutes. You can head to [hf.co/new-space](https://huggingface.co/new-space), select the Gradio SDK, create an `app.py` file, and voila! You have a demo you can share with anyone else. To learn more, read [this guide how to host on Hugging Face Spaces using the website](https://huggingface.co/blog/gradio-spaces). Alternatively, you can create a Space programmatically, making use of the [huggingface_hub client library](https://huggingface.co/docs/huggingface_hub/index) library. Here's an example: ```python from huggingface_hub import ( create_repo, get_full_repo_name, upload_file, ) create_repo(name=target_space_name, token=hf_token, repo_type="space", space_sdk="gradio") repo_name = get_full_repo_name(model_id=target_space_name, token=hf_token) file_url = upload_file( path_or_fileobj="file.txt", path_in_repo="app.py", repo_id=repo_name, repo_type="space", token=hf_token, ) ``` Here, `create_repo` creates a gradio repo with the target name under a specific account using that account's Write Token. `repo_name` gets the full repo name of the related repo. Finally `upload_file` uploads a file inside the repo with the name `app.py`.
Hosting your Gradio demos on Spaces
https://gradio.app/guides/using-hugging-face-integrations
Other Tutorials - Using Hugging Face Integrations Guide
You can also use and remix existing Gradio demos on Hugging Face Spaces. For example, you could take two existing Gradio demos on Spaces and put them as separate tabs and create a new demo. You can run this new demo locally, or upload it to Spaces, allowing endless possibilities to remix and create new demos! Here's an example that does exactly that: ```python import gradio as gr with gr.Blocks() as demo: with gr.Tab("Translate to Spanish"): gr.load("gradio/en2es", src="spaces") with gr.Tab("Translate to French"): gr.load("abidlabs/en2fr", src="spaces") demo.launch() ``` Notice that we use `gr.load()`, the same method we used to load models using Inference Endpoints. However, here we specify that the `src` is `spaces` (Hugging Face Spaces). Note: loading a Space in this way may result in slight differences from the original Space. In particular, any attributes that apply to the entire Blocks, such as the theme or custom CSS/JS, will not be loaded. You can copy these properties from the Space you are loading into your own `Blocks` object.
Loading demos from Spaces
https://gradio.app/guides/using-hugging-face-integrations
Other Tutorials - Using Hugging Face Integrations Guide
Hugging Face's popular `transformers` library has a very easy-to-use abstraction, [`pipeline()`](https://huggingface.co/docs/transformers/v4.16.2/en/main_classes/pipelinestransformers.pipeline) that handles most of the complex code to offer a simple API for common tasks. By specifying the task and an (optional) model, you can build a demo around an existing model with few lines of Python: ```python import gradio as gr from transformers import pipeline pipe = pipeline("translation", model="Helsinki-NLP/opus-mt-en-es") def predict(text): return pipe(text)[0]["translation_text"] demo = gr.Interface( fn=predict, inputs='text', outputs='text', ) demo.launch() ``` But `gradio` actually makes it even easier to convert a `pipeline` to a demo, simply by using the `gradio.Interface.from_pipeline` methods, which skips the need to specify the input and output components: ```python from transformers import pipeline import gradio as gr pipe = pipeline("translation", model="Helsinki-NLP/opus-mt-en-es") demo = gr.Interface.from_pipeline(pipe) demo.launch() ``` The previous code produces the following interface, which you can try right here in your browser: <gradio-app space="gradio/en2es"></gradio-app>
Demos with the `Pipeline` in `transformers`
https://gradio.app/guides/using-hugging-face-integrations
Other Tutorials - Using Hugging Face Integrations Guide
That's it! Let's recap the various ways Gradio and Hugging Face work together: 1. You can build a demo around Inference Endpoints without having to load the model, by using `gr.load()`. 2. You host your Gradio demo on Hugging Face Spaces, either using the GUI or entirely in Python. 3. You can load demos from Hugging Face Spaces to remix and create new Gradio demos using `gr.load()`. 4. You can convert a `transformers` pipeline into a Gradio demo using `from_pipeline()`. 🤗
Recap
https://gradio.app/guides/using-hugging-face-integrations
Other Tutorials - Using Hugging Face Integrations Guide
In this Guide, we'll walk you through: - Introduction of Gradio, and Hugging Face Spaces, and Wandb - How to setup a Gradio demo using the Wandb integration for JoJoGAN - How to contribute your own Gradio demos after tracking your experiments on wandb to the Wandb organization on Hugging Face
Introduction
https://gradio.app/guides/Gradio-and-Wandb-Integration
Other Tutorials - Gradio And Wandb Integration Guide
Weights and Biases (W&B) allows data scientists and machine learning scientists to track their machine learning experiments at every stage, from training to production. Any metric can be aggregated over samples and shown in panels in a customizable and searchable dashboard, like below: <img alt="Screen Shot 2022-08-01 at 5 54 59 PM" src="https://user-images.githubusercontent.com/81195143/182252755-4a0e1ca8-fd25-40ff-8c91-c9da38aaa9ec.png">
What is Wandb?
https://gradio.app/guides/Gradio-and-Wandb-Integration
Other Tutorials - Gradio And Wandb Integration Guide
Gradio Gradio lets users demo their machine learning models as a web app, all in a few lines of Python. Gradio wraps any Python function (such as a machine learning model's inference 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).
What are Hugging Face Spaces & Gradio?
https://gradio.app/guides/Gradio-and-Wandb-Integration
Other Tutorials - Gradio And Wandb Integration Guide
Now, let's walk you through how to do this on your own. We'll make the assumption that you're new to W&B and Gradio for the purposes of this tutorial. Let's get started! 1. Create a W&B account Follow [these quick instructions](https://app.wandb.ai/login) to create your free account if you don’t have one already. It shouldn't take more than a couple minutes. Once you're done (or if you've already got an account), next, we'll run a quick colab. 2. Open Colab Install Gradio and W&B We'll be following along with the colab provided in the JoJoGAN repo with some minor modifications to use Wandb and Gradio more effectively. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/mchong6/JoJoGAN/blob/main/stylize.ipynb) Install Gradio and Wandb at the top: ```sh pip install gradio wandb ``` 3. Finetune StyleGAN and W&B experiment tracking This next step will open a W&B dashboard to track your experiments and a gradio panel showing pretrained models to choose from a drop down menu from a Gradio Demo hosted on Huggingface Spaces. Here's the code you need for that: ```python alpha = 1.0 alpha = 1-alpha preserve_color = True num_iter = 100 log_interval = 50 samples = [] column_names = ["Reference (y)", "Style Code(w)", "Real Face Image(x)"] wandb.init(project="JoJoGAN") config = wandb.config config.num_iter = num_iter config.preserve_color = preserve_color wandb.log( {"Style reference": [wandb.Image(transforms.ToPILImage()(target_im))]}, step=0) load discriminator for perceptual loss discriminator = Discriminator(1024, 2).eval().to(device) ckpt = torch.load('models/stylegan2-ffhq-config-f.pt', map_location=lambda storage, loc: storage) discriminator.load_state_dict(ckpt["d"], strict=False) reset generator del generator generator = deepcopy(original_generator) g_optim = optim.Adam(generator.parameters(),
Setting up a Gradio Demo for JoJoGAN
https://gradio.app/guides/Gradio-and-Wandb-Integration
Other Tutorials - Gradio And Wandb Integration Guide
: storage) discriminator.load_state_dict(ckpt["d"], strict=False) reset generator del generator generator = deepcopy(original_generator) g_optim = optim.Adam(generator.parameters(), lr=2e-3, betas=(0, 0.99)) Which layers to swap for generating a family of plausible real images -> fake image if preserve_color: id_swap = [9,11,15,16,17] else: id_swap = list(range(7, generator.n_latent)) for idx in tqdm(range(num_iter)): mean_w = generator.get_latent(torch.randn([latents.size(0), latent_dim]).to(device)).unsqueeze(1).repeat(1, generator.n_latent, 1) in_latent = latents.clone() in_latent[:, id_swap] = alpha*latents[:, id_swap] + (1-alpha)*mean_w[:, id_swap] img = generator(in_latent, input_is_latent=True) with torch.no_grad(): real_feat = discriminator(targets) fake_feat = discriminator(img) loss = sum([F.l1_loss(a, b) for a, b in zip(fake_feat, real_feat)])/len(fake_feat) wandb.log({"loss": loss}, step=idx) if idx % log_interval == 0: generator.eval() my_sample = generator(my_w, input_is_latent=True) generator.train() my_sample = transforms.ToPILImage()(utils.make_grid(my_sample, normalize=True, range=(-1, 1))) wandb.log( {"Current stylization": [wandb.Image(my_sample)]}, step=idx) table_data = [ wandb.Image(transforms.ToPILImage()(target_im)), wandb.Image(img), wandb.Image(my_sample), ] samples.append(table_data) g_optim.zero_grad() loss.backward() g_optim.step() out_table = wandb.Table(data=samples, columns=column_names) wandb.log({"Current Samples": out_table}) ``` 4. Save, Download, and Load Model Here's how to save and download your model. ```python from PIL import Image import torch torch.backends.cudnn.benchmark = True from torchvision impor
Setting up a Gradio Demo for JoJoGAN
https://gradio.app/guides/Gradio-and-Wandb-Integration
Other Tutorials - Gradio And Wandb Integration Guide
ave, Download, and Load Model Here's how to save and download your model. ```python from PIL import Image import torch torch.backends.cudnn.benchmark = True from torchvision import transforms, utils from util import * import math import random import numpy as np from torch import nn, autograd, optim from torch.nn import functional as F from tqdm import tqdm import lpips from model import * from e4e_projection import projection as e4e_projection from copy import deepcopy import imageio import os import sys import torchvision.transforms as transforms from argparse import Namespace from e4e.models.psp import pSp from util import * from huggingface_hub import hf_hub_download from google.colab import files torch.save({"g": generator.state_dict()}, "your-model-name.pt") files.download('your-model-name.pt') latent_dim = 512 device="cuda" model_path_s = hf_hub_download(repo_id="akhaliq/jojogan-stylegan2-ffhq-config-f", filename="stylegan2-ffhq-config-f.pt") original_generator = Generator(1024, latent_dim, 8, 2).to(device) ckpt = torch.load(model_path_s, map_location=lambda storage, loc: storage) original_generator.load_state_dict(ckpt["g_ema"], strict=False) mean_latent = original_generator.mean_latent(10000) generator = deepcopy(original_generator) ckpt = torch.load("/content/JoJoGAN/your-model-name.pt", map_location=lambda storage, loc: storage) generator.load_state_dict(ckpt["g"], strict=False) generator.eval() plt.rcParams['figure.dpi'] = 150 transform = transforms.Compose( [ transforms.Resize((1024, 1024)), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)), ] ) def inference(img): img.save('out.jpg') aligned_face = align_face('out.jpg') my_w = e4e_projection(aligned_face, "out.pt", device).unsqueeze(0)
Setting up a Gradio Demo for JoJoGAN
https://gradio.app/guides/Gradio-and-Wandb-Integration
Other Tutorials - Gradio And Wandb Integration Guide
.5, 0.5)), ] ) def inference(img): img.save('out.jpg') aligned_face = align_face('out.jpg') my_w = e4e_projection(aligned_face, "out.pt", device).unsqueeze(0) with torch.no_grad(): my_sample = generator(my_w, input_is_latent=True) npimage = my_sample[0].cpu().permute(1, 2, 0).detach().numpy() imageio.imwrite('filename.jpeg', npimage) return 'filename.jpeg' ```` 5. Build a Gradio Demo ```python import gradio as gr title = "JoJoGAN" description = "Gradio Demo for JoJoGAN: One Shot Face Stylization. To use it, simply upload your image, or click one of the examples to load them. Read more at the links below." demo = gr.Interface( inference, gr.Image(type="pil"), gr.Image(type="file"), title=title, description=description ) demo.launch(share=True) ``` 6. Integrate Gradio into your W&B Dashboard The last step—integrating your Gradio demo with your W&B dashboard—is just one extra line: ```python demo.integrate(wandb=wandb) ``` Once you call integrate, a demo will be created and you can integrate it into your dashboard or report. Outside of W&B with Web components, using the `gradio-app` tags, anyone can embed Gradio demos on HF spaces directly into their blogs, websites, documentation, etc.: ```html <gradio-app space="akhaliq/JoJoGAN"> </gradio-app> ``` 7. (Optional) Embed W&B plots in your Gradio App It's also possible to embed W&B plots within Gradio apps. To do so, you can create a W&B Report of your plots and embed them within your Gradio app within a `gr.HTML` block. The Report will need to be public and you will need to wrap the URL within an iFrame like this: ```python import gradio as gr def wandb_report(url): iframe = f'<iframe src={url} style="border:none;height:1024px;width:100%">' return gr.HTML(iframe) with gr.Blocks() a
Setting up a Gradio Demo for JoJoGAN
https://gradio.app/guides/Gradio-and-Wandb-Integration
Other Tutorials - Gradio And Wandb Integration Guide
``python import gradio as gr def wandb_report(url): iframe = f'<iframe src={url} style="border:none;height:1024px;width:100%">' return gr.HTML(iframe) with gr.Blocks() as demo: report_url = 'https://wandb.ai/_scott/pytorch-sweeps-demo/reports/loss-22-10-07-16-00-17---VmlldzoyNzU2NzAx' report = wandb_report(report_url) demo.launch(share=True) ```
Setting up a Gradio Demo for JoJoGAN
https://gradio.app/guides/Gradio-and-Wandb-Integration
Other Tutorials - Gradio And Wandb Integration Guide
We hope you enjoyed this brief demo of embedding a Gradio demo to a W&B report! Thanks for making it to the end. To recap: - Only one single reference image is needed for fine-tuning JoJoGAN which usually takes about 1 minute on a GPU in colab. After training, style can be applied to any input image. Read more in the paper. - W&B tracks experiments with just a few lines of code added to a colab and you can visualize, sort, and understand your experiments in a single, centralized dashboard. - Gradio, meanwhile, demos the model in a user friendly interface to share anywhere on the web.
Conclusion
https://gradio.app/guides/Gradio-and-Wandb-Integration
Other Tutorials - Gradio And Wandb Integration Guide
- Create an account on Hugging Face [here](https://huggingface.co/join). - Add Gradio Demo under your username, see this [course](https://huggingface.co/course/chapter9/4?fw=pt) for setting up Gradio Demo on Hugging Face. - Request to join wandb organization [here](https://huggingface.co/wandb). - Once approved transfer model from your username to Wandb organization
How to contribute Gradio demos on HF spaces on the Wandb organization
https://gradio.app/guides/Gradio-and-Wandb-Integration
Other Tutorials - Gradio And Wandb Integration 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