text
stringlengths
0
2k
heading1
stringlengths
3
79
source_page_url
stringclasses
189 values
source_page_title
stringclasses
189 values
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
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. As long...
Deploying a simple Gradio app on Modal
https://gradio.app/guides/deploying-gradio-with-modal
Other Tutorials - Deploying Gradio With Modal Guide
Sticky Sessions Modal Functions are serverless which means that each client request is considered independent. While this facilitates autoscaling, it can also mean that extra care should be taken if your application requires any sort of server-side statefulness. Gradio relies on a REST API, which is itself stateless. ...
Important Considerations
https://gradio.app/guides/deploying-gradio-with-modal
Other Tutorials - Deploying Gradio With Modal Guide
tionally expensive requests. Thinking carefully about how these queues and limits interact can help you optimize your app's performance and resource optimization while avoiding unwanted results like shared or lost state. Creating a GPU Function Another option to manage GPU utilization is to deploy your GPU computati...
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
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
Let's build and deploy our demo with `gradio cc build` and `gradio cc deploy`! You can check out our component deployed to [HuggingFace Spaces](https://huggingface.co/spaces/freddyaboulton/gradio_multimodalchatbot) and all of the source code is available [here](https://huggingface.co/spaces/freddyaboulton/gradio_multi...
Part 5 - Deploying and Conclusion
https://gradio.app/guides/multimodal-chatbot-part1
Custom Components - Multimodal Chatbot Part1 Guide
Make sure you have gradio 5.0 or higher installed as well as node 20+. As of the time of publication, the latest release is 4.1.1. Also, please read the [Five Minute Tour](./custom-components-in-five-minutes) of custom components and the [Key Concepts](./key-component-concepts) guide before starting.
Step 0: Prerequisites
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
Navigate to a directory of your choosing and run the following command: ```bash gradio cc create PDF ``` Tip: You should change the name of the component. Some of the screenshots assume the component is called `PDF` but the concepts are the same! This will create a subdirectory called `pdf` in your current working ...
Step 1: Creating the custom component
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
We're going to use the [pdfjs](https://mozilla.github.io/pdf.js/) javascript library to display the pdfs in the frontend. Let's start off by adding it to our frontend project's dependencies, as well as adding a couple of other projects we'll need. From within the `frontend` directory, run `npm install @gradio/client ...
Step 2: Frontend - modify javascript dependencies
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
Run the `dev` command to launch the development server. This will open the demo in `demo/app.py` in an environment where changes to the `frontend` and `backend` directories will reflect instantaneously in the launched app. After launching the dev server, you should see a link printed to your console that says `Fronten...
Step 3: Frontend - Launching the Dev Server
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
We're going to start off by first writing the skeleton of our frontend and then adding the pdf rendering logic. Add the following imports and expose the following properties to the top of your file in the `<script>` tag. You may get some warnings from your code editor that some props are not used. That's ok. ```ts ...
Step 4: Frontend - The basic skeleton
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
lets our users upload a new document. We're going to use the `Upload` and `ModifyUpload` components that come with the `@gradio/upload` package to do this. Underneath the `</script>` tag, delete all the current code and add the following: ```svelte <Block {visible} {elem_id} {elem_classes} {container} {scale} {min_wi...
Step 4: Frontend - The basic skeleton
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
The `Upload your PDF` text looks a bit small and barebones. Lets customize it! Create a new file called `PdfUploadText.svelte` and copy the following code. Its creating a new div to display our "upload text" with some custom styling. Tip: Notice that we're leveraging Gradio core's existing css variables here: `var(-...
Step 5: Frontend - Nicer Upload Text
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
This is the most advanced javascript part. It took me a while to figure it out! Do not worry if you have trouble, the important thing is to not be discouraged 💪 Ask for help in the gradio [discord](https://discord.gg/hugging-face-879548962464493619) if you need and ask for help. With that out of the way, let's start ...
Step 6: PDF Rendering logic
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
$: if(JSON.stringify(old_value) != JSON.stringify(_value)) { if (_value){ get_doc(_value); } old_value = _value; gradio.dispatch("change"); } ``` Tip: The `$:` syntax in svelte is how you declare statements to be reactive. Whenever any of the inputs of the statement...
Step 6: PDF Rendering logic
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
Now for the fun part - actually rendering the PDF when the file is uploaded! Add the following functions to the `<script>` tag: ```ts async function handle_clear() { _value = null; await tick(); gradio.dispatch("change"); } async function handle_upload({detail}: CustomEvent<FileDat...
Step 7: Handling The File Upload And Clear
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
If a user uploads a PDF document with multiple pages, they will only be able to see the first one. Let's add some buttons to help them navigate the page. We will use the `BaseButton` from `@gradio/button` so that they look like regular Gradio buttons. Import the `BaseButton` and add the following functions that will r...
Step 8: Adding buttons to navigate pages
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
We're going to want users of our component to get a preview of the PDF if its used as an `example` in a `gr.Interface` or `gr.Examples`. To do so, we're going to add some of the pdf rendering logic in `Index.svelte` to `Example.svelte`. ```svelte <script lang="ts"> export let value: string; export let type: "galle...
Step 8.5: The Example view
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
The backend changes needed are smaller. We're almost done! What we're going to do is: * Add `change` and `upload` events to our component. * Add a `height` property to let users control the height of the PDF. * Set the `data_model` of our component to be `FileData`. This is so that Gradio can automatically cache and s...
Step 9: The backend
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
show_label=show_label, container=container, scale=scale, min_width=min_width, interactive=interactive, visible=visible, elem_id=elem_id, elem_classes=elem_classes, render=render, load_fn=load_fn, ever...
Step 9: The backend
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
To test our backend code, let's add a more complex demo that performs Document Question and Answering with huggingface transformers. In our `demo` directory, create a `requirements.txt` file with the following packages ``` torch transformers pdf2image pytesseract ``` Tip: Remember to install these yourself and rest...
Step 10: Add a demo and publish!
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide