text stringlengths 0 2k | heading1 stringlengths 3 79 | source_page_url stringclasses 189
values | source_page_title stringclasses 189
values |
|---|---|---|---|
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 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 = ... | 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 ... | Important Considerations | https://gradio.app/guides/deploying-gradio-with-docker | Other Tutorials - Deploying Gradio With Docker 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 |
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 |
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... | 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... | 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.... | 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 p... | 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,... | 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_sampl... | 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---VmlldzoyNzU2Nz... | 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 ... | 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 transfe... | 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 |
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
de... | 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 c... | 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.the... | 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 ... | 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 h... | 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")`.... | 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() ... | 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 variab... | 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_pr... | Extending Themes via `.set()` | https://gradio.app/guides/theming-guide | Other Tutorials - Theming Guide Guide |
For a full list of all available CSS variables, see the [CSS Variables Reference](/main/guides/css-variables-reference).
| CSS Variables Reference | 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 wi... | 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... | 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... | 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 [... | Sharing Themes | https://gradio.app/guides/theming-guide | Other Tutorials - Theming Guide Guide |
hey'll see a warning:
```
UserWarning: This theme was created for Gradio 5.0.0, but you are using Gradio 5.1.0. Some styles may not work as expected.
```
This helps prevent unexpected styling issues when themes rely on CSS variables that may have changed between Gradio versions. Patch version differences (e.g. 5.0.0 ... | Sharing Themes | https://gradio.app/guides/theming-guide | Other Tutorials - Theming Guide 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 |
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 ... | 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
... | 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="... | 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 |
The documentation will be generated when running `gradio cc build`. You can pass the `--no-generate-docs` argument to turn off this behaviour.
There is also a standalone `docs` command that allows for greater customisation. If you are running this command manually it should be run _after_ the `version` in your `pyproj... | How do I use it? | https://gradio.app/guides/documenting-custom-components | Custom Components - Documenting Custom Components Guide |
The `gradio cc docs` command will generate an interactive Gradio app and a static README file with various features. You can see an example here:
- [Gradio app deployed on Hugging Face Spaces]()
- [README.md rendered by GitHub]()
The README.md and space both have the following features:
- A description.
- Installati... | What gets generated? | https://gradio.app/guides/documenting-custom-components | Custom Components - Documenting Custom Components Guide |
The documentation generator uses existing standards to extract the necessary information, namely Type Hints and Docstrings. There are no Gradio-specific APIs for documentation, so following best practices will generally yield the best results.
If you already use type hints and docstrings in your component source code,... | What do I need to do? | https://gradio.app/guides/documenting-custom-components | Custom Components - Documenting Custom Components Guide |
be typed.
- `preprocess` parameters and return value should be typed.
If you are using `gradio cc create`, these types should already exist, but you may need to tweak them based on any changes you make.
`__init__`
Here, you only need to type the parameters. If you have cloned a template with `gradio` cc create`, the... | What do I need to do? | https://gradio.app/guides/documenting-custom-components | Custom Components - Documenting Custom Components Guide |
offer a rich in-editor experience like type hints, but unlike type hints, they don't have any specific syntax requirements. They are simple strings and can take almost any form. The only requirement is where they appear. Docstrings should be "a string literal that occurs as the first statement in a module, function, cl... | What do I need to do? | https://gradio.app/guides/documenting-custom-components | Custom Components - Documenting Custom Components Guide |
do not need to do anything as they already have descriptions we can extract:
```py
from gradio.events import Events
class ParamViewer(Component):
...
EVENTS = [
Events.change,
Events.upload,
]
```
Custom events
You can define a custom event if the built-in events are unsuitable for your use case. Thi... | What do I need to do? | https://gradio.app/guides/documenting-custom-components | Custom Components - Documenting Custom Components Guide |
ore complex app for your testing purposes. You can also create other spaces, showcasing more complex examples and linking to them from the main class docstring or the `pyproject.toml` description.
Keep the code concise
The 'getting started' snippet utilises the demo code, which should be as short as possible to keep ... | What do I need to do? | https://gradio.app/guides/documenting-custom-components | Custom Components - Documenting Custom Components Guide |
pyproject.toml` urls section might look like this:
```toml
[project.urls]
repository = "https://github.com/user/repo-name"
space = "https://huggingface.co/spaces/user/space-name"
``` | What do I need to do? | https://gradio.app/guides/documenting-custom-components | Custom Components - Documenting Custom Components Guide |
Every component in Gradio comes in a `static` variant, and most come in an `interactive` version as well.
The `static` version is used when a component is displaying a value, and the user can **NOT** change that value by interacting with it.
The `interactive` version is used when the user is able to change the value b... | Interactive vs Static | https://gradio.app/guides/key-component-concepts | Custom Components - Key Component Concepts Guide |
The most important attribute of a component is its `value`.
Every component has a `value`.
The value that is typically set by the user in the frontend (if the component is interactive) or displayed to the user (if it is static).
It is also this value that is sent to the backend function when a user triggers an event, ... | The value and how it is preprocessed/postprocessed | https://gradio.app/guides/key-component-concepts | Custom Components - Key Component Concepts Guide |
from the format sent by the frontend to the format expected by the python function. This usually involves going from a web-friendly **JSON** structure to a **python-native** data structure, like a `numpy` array or `PIL` image. The `Audio`, `Image` components are good examples of `preprocess` methods.
2. `postprocess`... | The value and how it is preprocessed/postprocessed | https://gradio.app/guides/key-component-concepts | Custom Components - Key Component Concepts Guide |
Gradio apps support providing example inputs -- and these are very useful in helping users get started using your Gradio app.
In `gr.Interface`, you can provide examples using the `examples` keyword, and in `Blocks`, you can provide examples using the special `gr.Examples` component.
At the bottom of this screenshot,... | The "Example Version" of a Component | https://gradio.app/guides/key-component-concepts | Custom Components - Key Component Concepts Guide |
Now that you know the most important pieces to remember about Gradio components, you can start to design and build your own!
| Conclusion | https://gradio.app/guides/key-component-concepts | Custom Components - Key Component Concepts 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 |
In order to use our new component in **any** gradio 4.0 app, simply install it with pip, e.g. `pip install gradio-pdf`. Then you can use it like the built-in `gr.File()` component (except that it will only accept and display PDF files).
Here is a simple demo with the Blocks api:
```python
import gradio as gr
from gra... | Conclusion | https://gradio.app/guides/pdf-component-example | Custom Components - Pdf Component Example Guide |
You will need to have:
* Python 3.10+ (<a href="https://www.python.org/downloads/" target="_blank">install here</a>)
* pip 21.3+ (`python -m pip install --upgrade pip`)
* Node.js 20+ (<a href="https://nodejs.dev/en/download/package-manager/" target="_blank">install here</a>)
* npm 9+ (<a href="https://docs.npmjs.com/d... | Installation | https://gradio.app/guides/custom-components-in-five-minutes | Custom Components - Custom Components In Five Minutes Guide |
The Custom Components workflow consists of 4 steps: create, dev, build, and publish.
1. create: creates a template for you to start developing a custom component.
2. dev: launches a development server with a sample app & hot reloading allowing you to easily develop your custom component
3. build: builds a python packa... | The Workflow | https://gradio.app/guides/custom-components-in-five-minutes | Custom Components - Custom Components In Five Minutes Guide |
Bootstrap a new template by running the following in any working directory:
```bash
gradio cc create MyComponent --template SimpleTextbox
```
Instead of `MyComponent`, give your component any name.
Instead of `SimpleTextbox`, you can use any Gradio component as a template. `SimpleTextbox` is actually a special compo... | 1. create | https://gradio.app/guides/custom-components-in-five-minutes | Custom Components - Custom Components In Five Minutes Guide |
Once you have created your new component, you can start a development server by `entering the directory` and running
```bash
gradio cc dev
```
You'll see several lines that are printed to the console.
The most important one is the one that says:
> Frontend Server (Go here): http://localhost:7861/
The port number mi... | 2. dev | https://gradio.app/guides/custom-components-in-five-minutes | Custom Components - Custom Components In Five Minutes Guide |
Once you are satisfied with your custom component's implementation, you can `build` it to use it outside of the development server.
From your component directory, run:
```bash
gradio cc build
```
This will create a `tar.gz` and `.whl` file in a `dist/` subdirectory.
If you or anyone installs that `.whl` file (`pip i... | 3. build | https://gradio.app/guides/custom-components-in-five-minutes | Custom Components - Custom Components In Five Minutes Guide |
Right now, your package is only available on a `.whl` file on your computer.
You can share that file with the world with the `publish` command!
Simply run the following command from your component directory:
```bash
gradio cc publish
```
This will guide you through the following process:
1. Upload your distribution... | 4. publish | https://gradio.app/guides/custom-components-in-five-minutes | Custom Components - Custom Components In Five Minutes Guide |
Now that you know the high-level workflow of creating custom components, you can go in depth in the next guides!
After reading the guides, check out this [collection](https://huggingface.co/collections/gradio/custom-components-65497a761c5192d981710b12) of custom components on the HuggingFace Hub so you can learn from o... | Conclusion | https://gradio.app/guides/custom-components-in-five-minutes | Custom Components - Custom Components In Five Minutes 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 |
Before using Custom Components, make sure you have Python 3.10+, Node.js v18+, npm 9+, and Gradio 4.0+ (preferably Gradio 5.0+) installed.
| What do I need to install before using Custom Components? | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions Guide |
Custom components built with Gradio 5.0 should be compatible with Gradio 4.0. If you built your custom component in Gradio 4.0 you will have to rebuild your component to be compatible with Gradio 5.0. Simply follow these steps:
1. Update the `@gradio/preview` package. `cd` into the `frontend` directory and run `npm upd... | Are custom components compatible between Gradio 4.0 and 5.0? | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions Guide |
Run `gradio cc show` to see the list of built-in templates.
You can also start off from other's custom components!
Simply `git clone` their repository and make your modifications.
| What templates can I use to create my custom component? | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions Guide |
When you run `gradio cc dev`, a development server will load and run a Gradio app of your choosing.
This is like when you run `python <app-file>.py`, however the `gradio` command will hot reload so you can instantly see your changes.
| What is the development server? | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions Guide |
**1. Check your terminal and browser console**
Make sure there are no syntax errors or other obvious problems in your code. Exceptions triggered from python will be displayed in the terminal. Exceptions from javascript will be displayed in the browser console and/or the terminal.
**2. Are you developing on Windows?**... | The development server didn't work for me | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions Guide |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.