text stringlengths 0 2k | heading1 stringlengths 3 79 | source_page_url stringclasses 188
values | source_page_title stringclasses 188
values |
|---|---|---|---|
Parameters ▼
src: str
either the name of the Hugging Face Space to load, (e.g. "abidlabs/whisper-
large-v2") or the full URL (including "http" or "https") of the hosted Gradio
app to load (e.g. "http://mydomain.com/app" or
"https://bec81a83-5b5c-471e.gradio.live/").
token: str | None
d... | Initialization | https://gradio.app/docs/python-client/client | Python Client - Client Docs |
n the remote machine instead.
ssl_verify: bool
default `= True`
if False, skips certificate validation which allows the client to connect to
Gradio apps that are using self-signed certificates.
analytics_enabled: bool
default `= True`
Whether to allow basic telemetry. If None, will u... | Initialization | https://gradio.app/docs/python-client/client | Python Client - Client Docs |
Description
Event listeners allow you to respond to user interactions with the UI
components you've defined in a Gradio Blocks app. When a user interacts with
an element, such as changing a slider value or uploading an image, a function
is called.
Supported Event Listeners
The Client component supports the following... | Event Listeners | https://gradio.app/docs/python-client/client | Python Client - Client Docs |
eters. For hardware upgrades (beyond the basic
CPU tier), you may be required to provide billing information on Hugging Face:
<https://huggingface.co/settings/billing> <br>
Event Parameters
Parameters ▼
args: <class 'inspect._empty'>
The positional arguments to pass to the remote API endpoint. The or... | Event Listeners | https://gradio.app/docs/python-client/client | Python Client - Client Docs |
A Job is a wrapper over the Future class that represents a prediction call
that has been submitted by the Gradio client. This class is not meant to be
instantiated directly, but rather is created by the Client.submit() method.
A Job object includes methods to get the status of the prediction call, as
well to get the ... | Description | https://gradio.app/docs/python-client/job | Python Client - Job Docs |
Parameters ▼
future: Future
The future object that represents the prediction call, created by the
Client.submit() method
communicator: Communicator | None
default `= None`
The communicator object that is used to communicate between the client and the
background thread running the job
... | Initialization | https://gradio.app/docs/python-client/job | Python Client - Job Docs |
Description
Event listeners allow you to respond to user interactions with the UI
components you've defined in a Gradio Blocks app. When a user interacts with
an element, such as changing a slider value or uploading an image, a function
is called.
Supported Event Listeners
The Job component supports the following ev... | Event Listeners | https://gradio.app/docs/python-client/job | Python Client - Job Docs |
All components inherit from one of three classes `Component`, `FormComponent`, or `BlockContext`.
You need to inherit from one so that your component behaves like all other gradio components.
When you start from a template with `gradio cc create --template`, you don't need to worry about which one to choose since the t... | Which Class to Inherit From | https://gradio.app/guides/backend | Custom Components - Backend Guide |
When you inherit from any of these classes, the following methods must be implemented.
Otherwise the Python interpreter will raise an error when you instantiate your component!
`preprocess` and `postprocess`
Explained in the [Key Concepts](./key-component-conceptsthe-value-and-how-it-is-preprocessed-postprocessed) gu... | The methods you need to implement | https://gradio.app/guides/backend | Custom Components - Backend Guide |
pi_info(self) -> dict[str, list[str]]:
"""
A JSON-schema representation of the value that the `preprocess` expects and the `postprocess` returns.
"""
pass
```
`example_payload`
An example payload for your component, e.g. something that can be passed into the `.preprocess()` method
of your component. T... | The methods you need to implement | https://gradio.app/guides/backend | Custom Components - Backend Guide |
"""
Convert the data from the csv or jsonl file into the component state.
"""
return x
```
| The methods you need to implement | https://gradio.app/guides/backend | Custom Components - Backend Guide |
The `data_model` is how you define the expected data format your component's value will be stored in the frontend.
It specifies the data format your `preprocess` method expects and the format the `postprocess` method returns.
It is not necessary to define a `data_model` for your component but it greatly simplifies the ... | The `data_model` | https://gradio.app/guides/backend | Custom Components - Backend Guide |
example, the `Names` model will serialize the data to `{'names': ['freddy', 'pete']}` whereas the `NamesRoot` model will serialize it to `['freddy', 'pete']`.
```python
from typing import List
class Names(GradioModel):
names: List[str]
class NamesRoot(GradioRootModel):
root: List[str]
```
Even if your comp... | The `data_model` | https://gradio.app/guides/backend | Custom Components - Backend Guide |
If your component expects uploaded files as input, or returns saved files to the frontend, you **MUST** use the `FileData` to type the files in your `data_model`.
When you use the `FileData`:
* Gradio knows that it should allow serving this file to the frontend. Gradio automatically blocks requests to serve arbitrary... | Handling Files | https://gradio.app/guides/backend | Custom Components - Backend Guide |
The events triggers for your component are defined in the `EVENTS` class attribute.
This is a list that contains the string names of the events.
Adding an event to this list will automatically add a method with that same name to your component!
You can import the `Events` enum from `gradio.events` to access commonly u... | Adding Event Triggers To Your Component | https://gradio.app/guides/backend | Custom Components - Backend Guide |
Conclusion | https://gradio.app/guides/backend | Custom Components - Backend 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 |
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 |
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 |
No! You can start off from an existing gradio component as a template, see the [five minute guide](./custom-components-in-five-minutes).
You can also start from an existing custom component if you'd like to tweak it further. Once you find the source code of a custom component you like, clone the code to your computer a... | Do I always need to start my component from scratch? | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions Guide |
You can develop and build your custom component without hosting or connecting to HuggingFace.
If you would like to share your component with the gradio community, it is recommended to publish your package to PyPi and host a demo on HuggingFace so that anyone can install it or try it out.
| Do I need to host my custom component on HuggingFace Spaces? | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions Guide |
You must implement the `preprocess`, `postprocess`, `example_payload`, and `example_value` methods. If your component does not use a data model, you must also define the `api_info`, `flag`, and `read_from_flag` methods. Read more in the [backend guide](./backend).
| What methods are mandatory for implementing a custom component in Gradio? | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions Guide |
A `data_model` defines the expected data format for your component, simplifying the component development process and self-documenting your code. It streamlines API usage and example caching.
| What is the purpose of a `data_model` in Gradio custom components? | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions Guide |
Utilizing `FileData` is crucial for components that expect file uploads. It ensures secure file handling, automatic caching, and streamlined client library functionality.
| Why is it important to use `FileData` for components dealing with file uploads? | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions Guide |
You can define event triggers in the `EVENTS` class attribute by listing the desired event names, which automatically adds corresponding methods to your component.
| How can I add event triggers to my custom Gradio component? | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions Guide |
Yes, it is possible to create custom components without a `data_model`, but you are going to have to manually implement `api_info`, `flag`, and `read_from_flag` methods.
| Can I implement a custom Gradio component without defining a `data_model`? | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions Guide |
We have prepared this [collection](https://huggingface.co/collections/gradio/custom-components-65497a761c5192d981710b12) of custom components on the HuggingFace Hub that you can use to get started!
| Are there sample custom components I can learn from? | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions Guide |
We're working on creating a gallery to make it really easy to discover new custom components.
In the meantime, you can search for HuggingFace Spaces that are tagged as a `gradio-custom-component` [here](https://huggingface.co/search/full-text?q=gradio-custom-component&type=space) | How can I find custom components created by the Gradio community? | https://gradio.app/guides/frequently-asked-questions | Custom Components - Frequently Asked Questions 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 |
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 |
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 |
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 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 |
Just like the classic Magic 8 Ball, a user should ask it a question orally and then wait for a response. Under the hood, we'll use Whisper to transcribe the audio and then use an LLM to generate a magic-8-ball-style answer. Finally, we'll use Parler TTS to read the response aloud.
| The Overview | https://gradio.app/guides/streaming-ai-generated-audio | Streaming - Streaming Ai Generated Audio Guide |
First let's define the UI and put placeholders for all the python logic.
```python
import gradio as gr
with gr.Blocks() as block:
gr.HTML(
f"""
<h1 style='text-align: center;'> Magic 8 Ball 🎱 </h1>
<h3 style='text-align: center;'> Ask a question and receive wisdom </h3>
<p style='... | The UI | https://gradio.app/guides/streaming-ai-generated-audio | Streaming - Streaming Ai Generated Audio Guide |
GPU](https://huggingface.co/zero-gpu-explorers) which has time-based quotas. Since generating the response can be done with Hugging Face's Inference API, we shouldn't include that code in our GPU function as it will needlessly use our GPU quota.
| The UI | https://gradio.app/guides/streaming-ai-generated-audio | Streaming - Streaming Ai Generated Audio Guide |
As mentioned above, we'll use [Hugging Face's Inference API](https://huggingface.co/docs/huggingface_hub/guides/inference) to transcribe the audio and generate a response from an LLM. After instantiating the client, I use the `automatic_speech_recognition` method (this automatically uses Whisper running on Hugging Face... | The Logic | https://gradio.app/guides/streaming-ai-generated-audio | Streaming - Streaming Ai Generated Audio Guide |
for you but are you ready for the dog?'")},
{"role": "user", "content": f"Magic 8 Ball please answer this question - {question}"}]
response = client.chat_completion(messages, max_tokens=64, seed=random.randint(1, 5000),
model="mistralai/Mistral-7B-Instruct... | The Logic | https://gradio.app/guides/streaming-ai-generated-audio | Streaming - Streaming Ai Generated Audio Guide |
sage=True
).to(device)
tokenizer = AutoTokenizer.from_pretrained(repo_id)
feature_extractor = AutoFeatureExtractor.from_pretrained(repo_id)
sampling_rate = model.audio_encoder.config.sampling_rate
frame_rate = model.audio_encoder.config.frame_rate
@spaces.GPU
def read_response(answer):
play_steps_in_s = 2.0
... | The Logic | https://gradio.app/guides/streaming-ai-generated-audio | Streaming - Streaming Ai Generated Audio Guide |
You can see our final application [here](https://huggingface.co/spaces/gradio/magic-8-ball)!
| Conclusion | https://gradio.app/guides/streaming-ai-generated-audio | Streaming - Streaming Ai Generated Audio Guide |
The next generation of AI user interfaces is moving towards audio-native experiences. Users will be able to speak to chatbots and receive spoken responses in return. Several models have been built under this paradigm, including GPT-4o and [mini omni](https://github.com/gpt-omni/mini-omni).
In this guide, we'll walk yo... | Introduction | https://gradio.app/guides/conversational-chatbot | Streaming - Conversational Chatbot Guide |
Our application will enable the following user experience:
1. Users click a button to start recording their message
2. The app detects when the user has finished speaking and stops recording
3. The user's audio is passed to the omni model, which streams back a response
4. After omni mini finishes speaking, the user's ... | Application Overview | https://gradio.app/guides/conversational-chatbot | Streaming - Conversational Chatbot Guide |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.