text
stringlengths
0
2k
heading1
stringlengths
3
79
source_page_url
stringclasses
190 values
source_page_title
stringclasses
190 values
examples=examples).launch() ```
Setting up a Gradio Demo for EfficientNet-Lite4
https://gradio.app/guides/Gradio-and-ONNX-on-Hugging-Face
Other Tutorials - Gradio And Onnx On Hugging Face Guide
- Add model to the [onnx model zoo](https://github.com/onnx/models/blob/main/.github/PULL_REQUEST_TEMPLATE.md) - Create an account on Hugging Face [here](https://huggingface.co/join). - See list of models left to add to ONNX organization, please refer to the table with the [Models list](https://github.com/onnx/modelsmo...
How to contribute Gradio demos on HF spaces using ONNX models
https://gradio.app/guides/Gradio-and-ONNX-on-Hugging-Face
Other Tutorials - Gradio And Onnx On Hugging Face Guide
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 i...
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('py...
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...
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 com...
Step 3 β€” Creating a Gradio Interface
https://gradio.app/guides/image-classification-in-pytorch
Other Tutorials - Image Classification In Pytorch Guide
Named-entity recognition (NER), also known as token classification or text tagging, is the task of taking a sentence and classifying every word (or "token") into different categories, such as names of people or names of locations, or different parts of speech. For example, given the sentence: > Does Chicago have any ...
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 `"entit...
Introduction
https://gradio.app/guides/named-entity-recognition
Other Tutorials - Named Entity Recognition Guide
Let's deploy a Gradio-style "Hello, world" app that lets a user input their name and then responds with a short greeting. We're not going to use this code as-is in our app, but it's useful to see what the initial Gradio version looks like. ```python import gradio as gr A simple Gradio interface for a greeting functio...
Deploying a simple Gradio app on Modal
https://gradio.app/guides/deploying-gradio-with-modal
Other Tutorials - Deploying Gradio With Modal Guide
. Step 2: Wrap the Gradio app in a Modal-deployed FastAPI app Like many Gradio apps, the example above is run by calling `launch()` on our demo at the end of the script. However, Modal doesn't run scripts, it runs functions - serverless functions to be exact. To get Modal to serve our `demo`, we can leverage Gradio a...
Deploying a simple Gradio app on Modal
https://gradio.app/guides/deploying-gradio-with-modal
Other Tutorials - Deploying Gradio With Modal Guide
fastapi` app). To use this decorator, your ASGI app needs to be the return value from the function. Step 3: Deploying on Modal To deploy the app, just run the following command: ```bash modal deploy <path-to-file> ``` The first time you run your app, Modal will build and cache the image which, takes about 30 seconds....
Deploying a simple Gradio app on Modal
https://gradio.app/guides/deploying-gradio-with-modal
Other Tutorials - Deploying Gradio With Modal Guide
Sticky Sessions Gradio relies on a REST API, which is itself stateless. But it does require sticky sessions, meaning that every request from a particular client must be routed to the same container. A simple way to satisfy this constraint is to set `max_containers = 1` in the `@app.function` decorator and setting the ...
Important Considerations
https://gradio.app/guides/deploying-gradio-with-modal
Other Tutorials - Deploying Gradio With Modal Guide
sion is done through the SDK ([sessions.start()](https://modal.com/docs/sdk/py/latest/Serversessionsstart)) or calling the HTTP endpoint (`$SERVER_URL/_modal/sessions/start`). This returns a `modal_session_token` that you can add as a query parameter `$SERVER_URL/?modal_session_token=$SESSION_TOKEN` to authorize and ro...
Important Considerations
https://gradio.app/guides/deploying-gradio-with-modal
Other Tutorials - Deploying Gradio With Modal Guide
e concurrency limit for that Function. If requests come in and the concurrency limit is already satisfied, Modal will spin up a new container - up to the maximum set for the Function. In our case, our Gradio app is represented by one Modal Function, so all requests share one queue and concurrency limit. Therefore Modal...
Important Considerations
https://gradio.app/guides/deploying-gradio-with-modal
Other Tutorials - Deploying Gradio With Modal Guide
The Hugging Face Hub is a central platform that has hundreds of thousands of [models](https://huggingface.co/models), [datasets](https://huggingface.co/datasets) and [demos](https://huggingface.co/spaces) (also known as Spaces). Gradio has multiple features that make it extremely easy to leverage existing models and ...
Introduction
https://gradio.app/guides/using-hugging-face-integrations
Other Tutorials - Using Hugging Face Integrations Guide
Hugging Face has a service called [Serverless Inference Endpoints](https://huggingface.co/docs/api-inference/index), which allows you to send HTTP requests to models on the Hub. The API includes a generous free tier, and you can switch to [dedicated Inference Endpoints](https://huggingface.co/inference-endpoints/dedica...
Demos with the Hugging Face Inference Endpoints
https://gradio.app/guides/using-hugging-face-integrations
Other Tutorials - Using Hugging Face Integrations Guide
[Hugging Face Spaces](https://hf.co/spaces) allows anyone to host their Gradio demos freely, and uploading your Gradio demos take a couple of minutes. You can head to [hf.co/new-space](https://huggingface.co/new-space), select the Gradio SDK, create an `app.py` file, and voila! You have a demo you can share with anyone...
Hosting your Gradio demos on Spaces
https://gradio.app/guides/using-hugging-face-integrations
Other Tutorials - Using Hugging Face Integrations Guide
You can also use and remix existing Gradio demos on Hugging Face Spaces. For example, you could take two existing Gradio demos on Spaces and put them as separate tabs and create a new demo. You can run this new demo locally, or upload it to Spaces, allowing endless possibilities to remix and create new demos! Here's a...
Loading demos from Spaces
https://gradio.app/guides/using-hugging-face-integrations
Other Tutorials - Using Hugging Face Integrations Guide
Hugging Face's popular `transformers` library has a very easy-to-use abstraction, [`pipeline()`](https://huggingface.co/docs/transformers/v4.16.2/en/main_classes/pipelinestransformers.pipeline) that handles most of the complex code to offer a simple API for common tasks. By specifying the task and an (optional) model, ...
Demos with the `Pipeline` in `transformers`
https://gradio.app/guides/using-hugging-face-integrations
Other Tutorials - Using Hugging Face Integrations Guide
That's it! Let's recap the various ways Gradio and Hugging Face work together: 1. You can build a demo around Inference Endpoints without having to load the model, by using `gr.load()`. 2. You host your Gradio demo on Hugging Face Spaces, either using the GUI or entirely in Python. 3. You can load demos from Hugging F...
Recap
https://gradio.app/guides/using-hugging-face-integrations
Other Tutorials - Using Hugging Face Integrations Guide
it's a gradio app that reads a graph out of a json file and gives you a canvas. the whole thing is this: ```python import gradio as gr def reverse(text: str) -> str: return (text or "")[::-1] demo = gr.Workflow(graph="workflow.json", bind={"reverse": reverse}) demo.launch() ``` `bind` is you handing the canvas ...
what gr.Workflow actually is
https://gradio.app/guides/gradio-workflows-vs-n8n-vs-comfyui
Other Tutorials - Gradio Workflows Vs N8N Vs Comfyui Guide
here's the bit that actually changes how you work. the sidebar ships with a curated set of spaces and models so it isn't an empty search box on day one, and searching it searches that set. everything else on the hub you reach by pasting: drop `owner/repo` or a url into the sidebar's space box, or into the picker on a ...
the hub is the node library
https://gradio.app/guides/gradio-workflows-vs-n8n-vs-comfyui
Other Tutorials - Gradio Workflows Vs N8N Vs Comfyui Guide
the execution logic that runs when you click through the canvas also exists in python, so your graph runs fine with nobody watching it. which means the thing you dragged together is also an api. build a graph where a text box feeds a local function, a model, and a space, all landing on outputs. gradio knows they're c...
the workflow is an api
https://gradio.app/guides/gradio-workflows-vs-n8n-vs-comfyui
Other Tutorials - Gradio Workflows Vs N8N Vs Comfyui Guide
n8n is automation. cron jobs. webhooks. it watches your inbox. it has a credentials store hooked into a few hundred services, it replays failed runs, it has fallback workflows for when something dies at 4am and you're asleep. "when a stripe charge goes through, write a row to postgres and post in sales" β€” n8n solved t...
vs n8n
https://gradio.app/guides/gradio-workflows-vs-n8n-vs-comfyui
Other Tutorials - Gradio Workflows Vs N8N Vs Comfyui Guide
comfy lives a floor below this. its nodes are the guts of image generation, samplers and schedulers and loras and all of it. you want to change how one step of a twenty step generation behaves? comfy. and that custom node ecosystem is genuinely wild, people have built insane things in there. but getting a new node in...
vs comfyui
https://gradio.app/guides/gradio-workflows-vs-n8n-vs-comfyui
Other Tutorials - Gradio Workflows Vs N8N Vs Comfyui Guide
everything flows one way. no cycles, no while loops, no loop-until-it's-good-enough. in the canvas, independent branches run at the same time. called as an api, the python executor walks the graph one node at a time β€” same results, no parallelism. saving is gated. locally you need the write-access link gradio prints ...
before you start
https://gradio.app/guides/gradio-workflows-vs-n8n-vs-comfyui
Other Tutorials - Gradio Workflows Vs N8N Vs Comfyui Guide
**can i use any hugging face model?** yes, any model you can run through hf inference. it's in the sidebar if it's curated, otherwise paste the repo id into a node's picker. ports come from the model's pipeline tag. **does every gradio space work as a node?** most do. it needs to be awake and it needs an api endpoint ...
quick answers to stuff people ask
https://gradio.app/guides/gradio-workflows-vs-n8n-vs-comfyui
Other Tutorials - Gradio Workflows Vs N8N Vs Comfyui 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...
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. ...
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 ...
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 th...
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 `default_concurrency_limit` for deep learning models. The downside is that you might need to adapt your function a ...
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 upg...
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
To use Gradio with BigQuery, you will need to obtain your BigQuery credentials and use them with the [BigQuery Python client](https://pypi.org/project/google-cloud-bigquery/). If you already have BigQuery credentials (as a `.json` file), you can skip this section. If not, you can do this for free in just a couple of mi...
Setting up your BigQuery Credentials
https://gradio.app/guides/creating-a-dashboard-from-bigquery-data
Other Tutorials - Creating A Dashboard From Bigquery Data Guide
Once you have the credentials, you will need to use the BigQuery Python client to authenticate using your credentials. To do this, you will need to install the BigQuery Python client by running the following command in the terminal: ```bash pip install google-cloud-bigquery[pandas] ``` You'll notice that we've instal...
Using the BigQuery Client
https://gradio.app/guides/creating-a-dashboard-from-bigquery-data
Other Tutorials - Creating A Dashboard From Bigquery Data Guide
Once you have a function to query the data, you can use the `gr.DataFrame` component from the Gradio library to display the results in a tabular format. This is a useful way to inspect the data and make sure that it has been queried correctly. Here is an example of how to use the `gr.DataFrame` component to display th...
Building the Real-Time Dashboard
https://gradio.app/guides/creating-a-dashboard-from-bigquery-data
Other Tutorials - Creating A Dashboard From Bigquery Data Guide
It seems that cryptocurrencies, [NFTs](https://www.nytimes.com/interactive/2022/03/18/technology/nft-guide.html), and the web3 movement are all the rage these days! Digital assets are being listed on marketplaces for astounding amounts of money, and just about every celebrity is debuting their own NFT collection. While...
Introduction
https://gradio.app/guides/create-your-own-friends-with-a-gan
Other Tutorials - Create Your Own Friends With A Gan Guide
Originally proposed in [Goodfellow et al. 2014](https://arxiv.org/abs/1406.2661), GANs are made up of neural networks which compete with the intention of outsmarting each other. One network, known as the _generator_, is responsible for generating images. The other network, the _discriminator_, receives an image at a ti...
GANs: a very brief introduction
https://gradio.app/guides/create-your-own-friends-with-a-gan
Other Tutorials - Create Your Own Friends With A Gan Guide
To generate new images with a GAN, you only need the generator model. There are many different architectures that the generator could use, but for this demo we'll use a pretrained GAN generator model with the following architecture: ```python from torch import nn class Generator(nn.Module): Refer to the link belo...
Step 1 β€” Create the Generator model
https://gradio.app/guides/create-your-own-friends-with-a-gan
Other Tutorials - Create Your Own Friends With A Gan Guide
The `predict` function is the key to making Gradio work! Whatever inputs we choose through the Gradio interface will get passed through our `predict` function, which should operate on the inputs and generate outputs that we can display with Gradio output components. For GANs it's common to pass random noise into our mo...
Step 2 β€” Defining a `predict` function
https://gradio.app/guides/create-your-own-friends-with-a-gan
Other Tutorials - Create Your Own Friends With A Gan Guide
At this point you can even run the code you have with `predict(<SOME_NUMBER>)`, and you'll find your freshly generated punks in your file system at `./punks.png`. To make a truly interactive demo, though, we'll build out a simple interface with Gradio. Our goals here are to: - Set a slider input so users can choose th...
Step 3 β€” Creating a Gradio interface
https://gradio.app/guides/create-your-own-friends-with-a-gan
Other Tutorials - Create Your Own Friends With A Gan Guide
Generating 4 punks at a time is a good start, but maybe we'd like to control how many we want to make each time. Adding more inputs to our Gradio interface is as simple as adding another item to the `inputs` list that we pass to `gr.Interface`: ```python gr.Interface( predict, inputs=[ gr.Slider(0, 100...
Step 4 β€” Even more punks!
https://gradio.app/guides/create-your-own-friends-with-a-gan
Other Tutorials - Create Your Own Friends With A Gan Guide
Your Gradio app is pretty much good to go, but you can add a few extra things to really make it ready for the spotlight ✨ We can add some examples that users can easily try out by adding this to the `gr.Interface`: ```python gr.Interface( ... keep everything as it is, and then add examples=[[123, 15], [42...
Step 5 - Polishing it up
https://gradio.app/guides/create-your-own-friends-with-a-gan
Other Tutorials - Create Your Own Friends With A Gan Guide
, ngf, 4, 2, 0, bias=False), nn.BatchNorm2d(ngf), nn.ReLU(True), nn.ConvTranspose2d(ngf, nc, 4, 2, 1, bias=False), nn.Tanh(), ) def forward(self, input): output = self.network(input) return output model = Generator() weights_path = hf_hub_dow...
Step 5 - Polishing it up
https://gradio.app/guides/create-your-own-friends-with-a-gan
Other Tutorials - Create Your Own Friends With A Gan Guide
First of all, we need some data to visualize. Following this [excellent guide](https://supabase.com/blog/loading-data-supabase-python), we'll create fake commerce data and put it in Supabase. 1\. Start by creating a new project in Supabase. Once you're logged in, click the "New Project" button 2\. Give your project a...
Create a table in Supabase
https://gradio.app/guides/creating-a-dashboard-from-supabase-data
Other Tutorials - Creating A Dashboard From Supabase Data Guide
The next step is to write data to a Supabase dataset. We will use the Supabase Python library to do this. 6\. Install `supabase` by running the following command in your terminal: ```bash pip install supabase ``` 7\. Get your project URL and API key. Click the Settings (gear icon) on the left pane and click 'API'. T...
Write data to Supabase
https://gradio.app/guides/creating-a-dashboard-from-supabase-data
Other Tutorials - Creating A Dashboard From Supabase Data Guide
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...
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...
Conclusion
https://gradio.app/guides/creating-a-dashboard-from-supabase-data
Other Tutorials - Creating A Dashboard From Supabase Data 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 ...
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 ...
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)) & ...
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='m...
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():...
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...
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
**[OpenAPI](https://www.openapis.org/)** is a widely adopted standard for describing RESTful APIs in a machine-readable format, typically as a JSON file. You can create a Gradio UI from an OpenAPI Spec **in 1 line of Python**, instantly generating an interactive web interface for any API, making it accessible for de...
Introduction
https://gradio.app/guides/from-openapi-spec
Other Tutorials - From Openapi Spec Guide
Gradio now provides a convenient function, `gr.load_openapi`, that can automatically generate a Gradio app from an OpenAPI v3 specification. This function parses the spec, creates UI components for each endpoint and parameter, and lets you interact with the API directly from your browser. Here's a minimal example: ``...
How it works
https://gradio.app/guides/from-openapi-spec
Other Tutorials - From Openapi Spec Guide
Once your Gradio app is running, you can share the URL with others so they can try out the API through a friendly web interfaceβ€”no code required. For even more power, you can launch the app as an MCP (Model Control Protocol) server using [Gradio's MCP integration](https://www.gradio.app/guides/building-mcp-server-with-...
Next steps
https://gradio.app/guides/from-openapi-spec
Other Tutorials - From Openapi Spec Guide
Adding examples to an Interface is as easy as providing a list of lists to the `examples` keyword argument. Each sublist is a data sample, where each element corresponds to an input of the prediction function. The inputs must be ordered in the same order as the prediction function expects them. If your interface only ...
Providing Examples
https://gradio.app/guides/more-on-examples
Building Interfaces - More On Examples Guide
You may wish to provide some cached examples of your model for users to quickly try out, in case your model takes a while to run normally. If `cache_examples=True`, your Gradio app will run all of the examples and save the outputs when you call the `launch()` method. This data will be saved in a directory called `gradi...
Caching examples
https://gradio.app/guides/more-on-examples
Building Interfaces - More On Examples Guide
If the state is something that should be accessible to all function calls and all users, you can create a variable outside the function call and access it inside the function. For example, you may load a large model outside the function and use it inside the function so that every function call does not need to reload ...
Global State
https://gradio.app/guides/interface-state
Building Interfaces - Interface State Guide
Another type of data persistence Gradio supports is session state, where data persists across multiple submits within a page session. However, data is _not_ shared between different users of your model. To store data in a session state, you need to do three things: 1. Pass in an extra parameter into your function, whi...
Session State
https://gradio.app/guides/interface-state
Building Interfaces - Interface State Guide
You can make interfaces automatically refresh by setting `live=True` in the interface. Now the interface will recalculate as soon as the user input changes. $code_calculator_live $demo_calculator_live Note there is no submit button, because the interface resubmits automatically on change.
Live Interfaces
https://gradio.app/guides/reactive-interfaces
Building Interfaces - Reactive Interfaces Guide
Some components have a "streaming" mode, such as `Audio` component in microphone mode, or the `Image` component in webcam mode. Streaming means data is sent continuously to the backend and the `Interface` function is continuously being rerun. The difference between `gr.Audio(source='microphone')` and `gr.Audio(source=...
Streaming Components
https://gradio.app/guides/reactive-interfaces
Building Interfaces - Reactive Interfaces Guide
Gradio includes more than 30 pre-built components (as well as many [community-built _custom components_](https://www.gradio.app/custom-components/gallery)) that can be used as inputs or outputs in your demo. These components correspond to common data types in machine learning and data science, e.g. the `gr.Image` compo...
Gradio Components
https://gradio.app/guides/the-interface-class
Building Interfaces - The Interface Class Guide
We used the default versions of the `gr.Textbox` and `gr.Slider`, but what if you want to change how the UI components look or behave? Let's say you want to customize the slider to have values from 1 to 10, with a default of 2. And you wanted to customize the output text field β€” you want it to be larger and have a lab...
Components Attributes
https://gradio.app/guides/the-interface-class
Building Interfaces - The Interface Class Guide
Suppose you had a more complex function, with multiple outputs as well. In the example below, we define a function that takes a string, boolean, and number, and returns a string and number. $code_hello_world_3 $demo_hello_world_3 Just as each component in the `inputs` list corresponds to one of the parameters of the...
Multiple Input and Output Components
https://gradio.app/guides/the-interface-class
Building Interfaces - The Interface Class Guide
Gradio supports many types of components, such as `Image`, `DataFrame`, `Video`, or `Label`. Let's try an image-to-image function to get a feel for these! $code_sepia_filter $demo_sepia_filter When using the `Image` component as input, your function will receive a NumPy array with the shape `(height, width, 3)`, wher...
An Image Example
https://gradio.app/guides/the-interface-class
Building Interfaces - The Interface Class Guide
You can provide example data that a user can easily load into `Interface`. This can be helpful to demonstrate the types of inputs the model expects, as well as to provide a way to explore your dataset in conjunction with your model. To load example data, you can provide a **nested list** to the `examples=` keyword argu...
Example Inputs
https://gradio.app/guides/the-interface-class
Building Interfaces - The Interface Class Guide
In the previous example, you may have noticed the `title=` and `description=` keyword arguments in the `Interface` constructor that helps users understand your app. There are three arguments in the `Interface` constructor to specify where this content should go: - `title`: which accepts text and can display it at the...
Descriptive Content
https://gradio.app/guides/the-interface-class
Building Interfaces - The Interface Class Guide
If your prediction function takes many inputs, you may want to hide some of them within a collapsed accordion to avoid cluttering the UI. The `Interface` class takes an `additional_inputs` argument which is similar to `inputs` but any input components included here are not visible by default. The user must click on the...
Additional Inputs within an Accordion
https://gradio.app/guides/the-interface-class
Building Interfaces - The Interface Class Guide
To create a demo that has both the input and the output components, you simply need to set the values of the `inputs` and `outputs` parameter in `Interface()`. Here's an example demo of a simple image filter: $code_sepia_filter $demo_sepia_filter
Standard demos
https://gradio.app/guides/four-kinds-of-interfaces
Building Interfaces - Four Kinds Of Interfaces Guide
What about demos that only contain outputs? In order to build such a demo, you simply set the value of the `inputs` parameter in `Interface()` to `None`. Here's an example demo of a mock image generation model: $code_fake_gan_no_input $demo_fake_gan_no_input
Output-only demos
https://gradio.app/guides/four-kinds-of-interfaces
Building Interfaces - Four Kinds Of Interfaces Guide
Similarly, to create a demo that only contains inputs, set the value of `outputs` parameter in `Interface()` to be `None`. Here's an example demo that saves any uploaded image to disk: $code_save_file_no_output $demo_save_file_no_output
Input-only demos
https://gradio.app/guides/four-kinds-of-interfaces
Building Interfaces - Four Kinds Of Interfaces Guide
A demo that has a single component as both the input and the output. It can simply be created by setting the values of the `inputs` and `outputs` parameter as the same component. Here's an example demo of a text generation model: $code_unified_demo_text_generation $demo_unified_demo_text_generation It may be the case...
Unified demos
https://gradio.app/guides/four-kinds-of-interfaces
Building Interfaces - Four Kinds Of Interfaces Guide
The frontend code should have, at minimum, three files: * `Index.svelte`: This is the main export and where your component's layout and logic should live. * `Example.svelte`: This is where the example view of the component is defined. Feel free to add additional files and subdirectories. If you want to export any ad...
The directory structure
https://gradio.app/guides/frontend
Custom Components - Frontend Guide
Your component should expose the following props that will be passed down from the parent Gradio application. ```typescript import type { LoadingStatus } from "@gradio/statustracker"; import type { Gradio } from "@gradio/utils"; export let gradio: Gradio<{ event_1: never; event_2: never; }>; export let elem_...
The Index.svelte file
https://gradio.app/guides/frontend
Custom Components - Frontend Guide
null; export let min_width: number | undefined = undefined; export let loading_status: LoadingStatus | undefined = undefined; export let mode: "static" | "interactive"; </script> <Block visible={true} {elem_id} {elem_classes} {scale} {min_width} allow_overflow={false} padding={true} > {if loading_status...
The Index.svelte file
https://gradio.app/guides/frontend
Custom Components - Frontend Guide
The `Example.svelte` file should expose the following props: ```typescript export let value: string; export let type: "gallery" | "table"; export let selected = false; export let index: number; ``` * `value`: The example value that should be displayed. * `type`: This is a variable that can be either ...
The Example.svelte file
https://gradio.app/guides/frontend
Custom Components - Frontend Guide
If your component deals with files, these files **should** be uploaded to the backend server. The `@gradio/client` npm package provides the `upload` and `prepare_files` utility functions to help you do this. The `prepare_files` function will convert the browser's `File` datatype to gradio's internal `FileData` type. ...
Handling Files
https://gradio.app/guides/frontend
Custom Components - Frontend Guide
he `upload` function. ```typescript <script lang="ts"> import { getContext } from "svelte"; const upload_fn = getContext<typeof upload_files>("upload_files"); async function handle_upload(file_data: FileData[]): Promise<void> { await tick(); await upload(file_data, root, upload_fn); } ...
Handling Files
https://gradio.app/guides/frontend
Custom Components - Frontend Guide
Most of Gradio's frontend components are published on [npm](https://www.npmjs.com/), the javascript package repository. This means that you can use them to save yourself time while incorporating common patterns in your component, like uploading files. For example, the `@gradio/upload` package has `Upload` and `ModifyUp...
Leveraging Existing Gradio Components
https://gradio.app/guides/frontend
Custom Components - Frontend Guide
You can explore our component library via Storybook. You'll be able to interact with our components and see them in their various states. For those interested in design customization, we provide the CSS variables consisting of our color palette, radii, spacing, and the icons we use - so you can easily match up your cu...
Matching Gradio Core's Design System
https://gradio.app/guides/frontend
Custom Components - Frontend Guide
If you want to make use of the vast vite ecosystem, you can use the `gradio.config.js` file to configure your component's build process. This allows you to make use of tools like tailwindcss, mdsvex, and more. Currently, it is possible to configure the following: Vite options: - `plugins`: A list of vite plugins to u...
Custom configuration
https://gradio.app/guides/frontend
Custom Components - Frontend Guide
.css"; [...] </script> ``` Example for Svelte options In `gradio.config.js` you can also specify a some Svelte options to apply to the Svelte compilation. In this example we will add support for [`mdsvex`](https://mdsvex.pngwn.io), a Markdown preprocessor for Svelte. In order to do this we will need to add a [Svelt...
Custom configuration
https://gradio.app/guides/frontend
Custom Components - Frontend Guide
You now know how to create delightful frontends for your components!
Conclusion
https://gradio.app/guides/frontend
Custom Components - Frontend Guide
By default, all custom component packages are called `gradio_<component-name>` where `component-name` is the name of the component's python class in lowercase. As an example, let's walkthrough changing the name of a component from `gradio_mytextbox` to `supertextbox`. 1. Modify the `name` in the `pyproject.toml` fil...
The Package Name
https://gradio.app/guides/configuration
Custom Components - Configuration Guide
By default, only the custom component python class is a top level export. This means that when users type `from gradio_<component-name> import ...`, the only class that will be available is the custom component class. To add more classes as top level exports, modify the `__all__` property in `__init__.py` ```python f...
Top Level Python Exports
https://gradio.app/guides/configuration
Custom Components - Configuration Guide
You can add python dependencies by modifying the `dependencies` key in `pyproject.toml` ```bash dependencies = ["gradio", "numpy", "PIL"] ``` Tip: Remember to run `gradio cc install` when you add dependencies!
Python Dependencies
https://gradio.app/guides/configuration
Custom Components - Configuration Guide
You can add JavaScript dependencies by modifying the `"dependencies"` key in `frontend/package.json` ```json "dependencies": { "@gradio/atoms": "0.2.0-beta.4", "@gradio/statustracker": "0.3.0-beta.6", "@gradio/utils": "0.2.0-beta.4", "your-npm-package": "<version>" } ```
Javascript Dependencies
https://gradio.app/guides/configuration
Custom Components - Configuration Guide
By default, the CLI will place the Python code in `backend` and the JavaScript code in `frontend`. It is not recommended to change this structure since it makes it easy for a potential contributor to look at your source code and know where everything is. However, if you did want to this is what you would have to do: 1...
Directory Structure
https://gradio.app/guides/configuration
Custom Components - Configuration Guide
Sticking to the defaults will make it easy for others to understand and contribute to your custom component. After all, the beauty of open source is that anyone can help improve your code! But if you ever need to deviate from the defaults, you know how!
Conclusion
https://gradio.app/guides/configuration
Custom Components - Configuration Guide
For this demo we will be tweaking the existing Gradio `Chatbot` component to display text and media files in the same message. Let's create a new custom component directory by templating off of the `Chatbot` component source code. ```bash gradio cc create MultimodalChatbot --template Chatbot ``` And we're ready to go...
Part 1 - Creating our project
https://gradio.app/guides/multimodal-chatbot-part1
Custom Components - Multimodal Chatbot Part1 Guide
Open up the `multimodalchatbot.py` file in your favorite code editor and let's get started modifying the backend of our component. The first thing we will do is create the `data_model` of our component. The `data_model` is the data format that your python component will receive and send to the javascript client runnin...
Part 2a - The backend data_model
https://gradio.app/guides/multimodal-chatbot-part1
Custom Components - Multimodal Chatbot Part1 Guide
For the `preprocess` method, we will keep it simple and pass a list of `MultimodalMessage`s to the python functions that use this component as input. This will let users of our component access the chatbot data with `.text` and `.files` attributes. This is a design choice that you can modify in your implementation! We...
Part 2b - The pre and postprocess methods
https://gradio.app/guides/multimodal-chatbot-part1
Custom Components - Multimodal Chatbot Part1 Guide
The frontend for the `Chatbot` component is divided into two parts - the `Index.svelte` file and the `shared/Chatbot.svelte` file. The `Index.svelte` file applies some processing to the data received from the server and then delegates the rendering of the conversation to the `shared/Chatbot.svelte` file. First we will ...
Part 3a - The Index.svelte file
https://gradio.app/guides/multimodal-chatbot-part1
Custom Components - Multimodal Chatbot Part1 Guide
Let's begin similarly to the `Index.svelte` file and let's first modify the type annotations. Import `Mulimodal` message at the top of the `<script>` section and use it to type the `value` and `old_value` variables. ```ts import type { MultimodalMessage } from "./utils"; export let value: | [ Multimod...
Part 3b - the Chatbot.svelte file
https://gradio.app/guides/multimodal-chatbot-part1
Custom Components - Multimodal Chatbot Part1 Guide
own message={message.text} {latex_delimiters} {sanitize_html} {render_markdown} {line_breaks} on:load={scroll} /> {each message.files as file, k} {if file !== null && file.file.mime_type?.includes("audio")} <audio data-testid="chatbot-audio" controls ...
Part 3b - the Chatbot.svelte file
https://gradio.app/guides/multimodal-chatbot-part1
Custom Components - Multimodal Chatbot Part1 Guide
For this tutorial, let's keep the demo simple and just display a static conversation between a hypothetical user and a bot. This demo will show how both the user and the bot can send files. In part 2 of this tutorial series we will build a fully functional chatbot demo! The demo code will look like the following: ``...
Part 4 - The demo
https://gradio.app/guides/multimodal-chatbot-part1
Custom Components - Multimodal Chatbot Part1 Guide