text
stringlengths
0
2k
heading1
stringlengths
4
79
source_page_url
stringclasses
183 values
source_page_title
stringclasses
183 values
""" 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 process of creating a custom component. If you define a custom component you only need to implement four methods - `preprocess`, `postprocess`, `example_payload`, and `example_value`! You define a `data_model` by defining a [pydantic model](https://docs.pydantic.dev/latest/concepts/models/basic-model-usage) that inherits from either `GradioModel` or `GradioRootModel`. This is best explained with an example. Let's look at the core `Video` component, which stores the video data as a JSON object with two keys `video` and `subtitles` which point to separate files. ```python from gradio.data_classes import FileData, GradioModel class VideoData(GradioModel): video: FileData subtitles: Optional[FileData] = None class Video(Component): data_model = VideoData ``` By adding these four lines of code, your component automatically implements the methods needed for API usage, the flagging methods, and example caching methods! It also has the added benefit of self-documenting your code. Anyone who reads your component code will know exactly the data it expects. Tip: If your component expects files to be uploaded from the frontend, your must use the `FileData` model! It will be explained in the following section. Tip: Read the pydantic docs [here](https://docs.pydantic.dev/latest/concepts/models/basic-model-usage). The difference between a `GradioModel` and a `GradioRootModel` is that the `RootModel` will not serialize the data to a dictionary. For 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 clas
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 component does not expect a "complex" JSON data structure it can be beneficial to define a `GradioRootModel` so that you don't have to worry about implementing the API and flagging methods. Tip: Use classes from the Python typing library to type your models. e.g. `List` instead of `list`.
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 files in the computer running the server. * Gradio will automatically place the file in a cache so that duplicate copies of the file don't get saved. * The client libraries will automatically know that they should upload input files prior to sending the request. They will also automatically download files. If you do not use the `FileData`, your component will not work as expected!
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 used events in the core gradio components. For example, the following code will define `text_submit`, `file_upload` and `change` methods in the `MyComponent` class. ```python from gradio.events import Events from gradio.components import FormComponent class MyComponent(FormComponent): EVENTS = [ "text_submit", "file_upload", Events.change ] ``` Tip: Don't forget to also handle these events in the JavaScript code!
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
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 `pyproject.toml` has been bumped but before building the component. All arguments are optional. ```bash gradio cc docs path The directory of the custom component. --demo-dir Path to the demo directory. --demo-name Name of the demo file --space-url URL of the Hugging Face Space to link to --generate-space create a documentation space. --no-generate-space do not create a documentation space --readme-path Path to the README.md file. --generate-readme create a REAMDE.md file --no-generate-readme do not create a README.md file --suppress-demo-check suppress validation checks and warnings ```
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. - Installation instructions. - A fully functioning code snippet. - Optional links to PyPi, GitHub, and Hugging Face Spaces. - API documentation including: - An argument table for component initialisation showing types, defaults, and descriptions. - A description of how the component affects the user's predict function. - A table of events and their descriptions. - Any additional interfaces or classes that may be used during initialisation or in the pre- or post- processors. Additionally, the Gradio includes: - A live demo. - A richer, interactive version of the parameter tables. - Nicer styling!
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, you don't need to do much to benefit from this feature, but there are some details that you should be aware of. Python version To get the best documentation experience, you need to use Python `3.10` or greater when generating documentation. This is because some introspection features used to generate the documentation were only added in `3.10`. Type hints Python type hints are used extensively to provide helpful information for users. <details> <summary> What are type hints?</summary> If you need to become more familiar with type hints in Python, they are a simple way to express what Python types are expected for arguments and return values of functions and methods. They provide a helpful in-editor experience, aid in maintenance, and integrate with various other tools. These types can be simple primitives, like `list` `str` `bool`; they could be more compound types like `list[str]`, `str | None` or `tuple[str, float | int]`; or they can be more complex types using utility classed like [`TypedDict`](https://peps.python.org/pep-0589/abstract). [Read more about type hints in Python.](https://realpython.com/lessons/type-hinting/) </details> What do I need to add hints to? You do not need to add type hints to every part of your code. For the documentation to work correctly, you will need to add type hints to the following component methods: - `__init__` parameters should be typed. - `postprocess` parameters and return value should 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 ma
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`, these should already be in place. You will only need to add new hints for anything you have added or changed: ```py def __init__( self, value: str | None = None, *, sources: Literal["upload", "microphone"] = "upload, every: Timer | float | None = None, ... ): ... ``` `preprocess` and `postprocess` The `preprocess` and `postprocess` methods determine the value passed to the user function and the value that needs to be returned. Even if the design of your component is primarily as an input or an output, it is worth adding type hints to both the input parameters and the return values because Gradio has no way of limiting how components can be used. In this case, we specifically care about: - The return type of `preprocess`. - The input type of `postprocess`. ```py def preprocess( self, payload: FileData | None input is optional ) -> tuple[int, str] | str | None: user function input is the preprocess return ▲ user function output is the postprocess input ▼ def postprocess( self, value: tuple[int, str] | None ) -> FileData | bytes | None: return is optional ... ``` Docstrings Docstrings are also used extensively to extract more meaningful, human-readable descriptions of certain parts of the API. <details> <summary> What are docstrings?</summary> If you need to become more familiar with docstrings in Python, they are a way to annotate parts of your code with human-readable decisions and explanations. They 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 i
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, class, or method definition". [Read more about Python docstrings.](https://peps.python.org/pep-0257/what-is-a-docstring) </details> While docstrings don't have any syntax requirements, we need a particular structure for documentation purposes. As with type hint, the specific information we care about is as follows: - `__init__` parameter docstrings. - `preprocess` return docstrings. - `postprocess` input parameter docstrings. Everything else is optional. Docstrings should always take this format to be picked up by the documentation generator: Classes ```py """ A description of the class. This can span multiple lines and can _contain_ *markdown*. """ ``` Methods and functions Markdown in these descriptions will not be converted into formatted text. ```py """ Parameters: param_one: A description for this parameter. param_two: A description for this parameter. Returns: A description for this return value. """ ``` Events In custom components, events are expressed as a list stored on the `events` field of the component class. While we do not need types for events, we _do_ need a human-readable description so users can understand the behaviour of the event. To facilitate this, we must create the event in a specific way. There are two ways to add events to a custom component. Built-in events Gradio comes with a variety of built-in events that may be enough for your component. If you are using built-in events, you 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.up
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. This is a straightforward process, but you must create the event in this way for docstrings to work correctly: ```py from gradio.events import Events, EventListener class ParamViewer(Component): ... EVENTS = [ Events.change, EventListener( "bingbong", doc="This listener is triggered when the user does a bingbong." ) ] ``` Demo The `demo/app.py`, often used for developing the component, generates the live demo and code snippet. The only strict rule here is that the `demo.launch()` command must be contained with a `__name__ == "__main__"` conditional as below: ```py if __name__ == "__main__": demo.launch() ``` The documentation generator will scan for such a clause and error if absent. If you are _not_ launching the demo inside the `demo/app.py`, then you can pass `--suppress-demo-check` to turn off this check. Demo recommendations Although there are no additional rules, there are some best practices you should bear in mind to get the best experience from the documentation generator. These are only guidelines, and every situation is unique, but they are sound principles to remember. Keep the demo compact Compact demos look better and make it easier for users to understand what the demo does. Try to remove as many extraneous UI elements as possible to focus the users' attention on the core use case. Sometimes, it might make sense to have a `demo/app.py` just for the docs and an additional, more 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.
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 users engaged and avoid confusion. It isn't the job of the sample snippet to demonstrate the whole API; this snippet should be the shortest path to success for a new user. It should be easy to type or copy-paste and easy to understand. Explanatory comments should be brief and to the point. Avoid external dependencies As mentioned above, users should be able to copy-paste a snippet and have a fully working app. Try to avoid third-party library dependencies to facilitate this. You should carefully consider any examples; avoiding examples that require additional files or that make assumptions about the environment is generally a good idea. Ensure the `demo` directory is self-contained Only the `demo` directory will be uploaded to Hugging Face spaces in certain instances, as the component will be installed via PyPi if possible. It is essential that this directory is self-contained and any files needed for the correct running of the demo are present. Additional URLs The documentation generator will generate a few buttons, providing helpful information and links to users. They are obtained automatically in some cases, but some need to be explicitly included in the `pyproject.yaml`. - PyPi Version and link - This is generated automatically. - GitHub Repository - This is populated via the `pyproject.toml`'s `project.urls.repository`. - Hugging Face Space - This is populated via the `pyproject.toml`'s `project.urls.space`. An example `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
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
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` file. ```bash [project] name = "supertextbox" ``` 2. Change all occurrences of `gradio_<component-name>` in `pyproject.toml` to `<component-name>` ```bash [tool.hatch.build] artifacts = ["/backend/supertextbox/templates", "*.pyi"] [tool.hatch.build.targets.wheel] packages = ["/backend/supertextbox"] ``` 3. Rename the `gradio_<component-name>` directory in `backend/` to `<component-name>` ```bash mv backend/gradio_mytextbox backend/supertextbox ``` Tip: Remember to change the import statement in `demo/app.py`!
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 from .mytextbox import MyTextbox from .mytextbox import AdditionalClass, additional_function __all__ = ['MyTextbox', 'AdditionalClass', 'additional_function'] ```
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. Place the Python code in the subdirectory of your choosing. Remember to modify the `[tool.hatch.build]` `[tool.hatch.build.targets.wheel]` in the `pyproject.toml` to match! 2. Place the JavaScript code in the subdirectory of your choosing. 2. Add the `FRONTEND_DIR` property on the component python class. It must be the relative path from the file where the class is defined to the location of the JavaScript directory. ```python class SuperTextbox(Component): FRONTEND_DIR = "../../frontend/" ``` The JavaScript and Python directories must be under the same common directory!
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
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 by interacting with the Gradio UI. Let's see some examples: ```python import gradio as gr with gr.Blocks() as demo: gr.Textbox(value="Hello", interactive=True) gr.Textbox(value="Hello", interactive=False) demo.launch() ``` This will display two textboxes. The only difference: you'll be able to edit the value of the Gradio component on top, and you won't be able to edit the variant on the bottom (i.e. the textbox will be disabled). Perhaps a more interesting example is with the `Image` component: ```python import gradio as gr with gr.Blocks() as demo: gr.Image(interactive=True) gr.Image(interactive=False) demo.launch() ``` The interactive version of the component is much more complex -- you can upload images or snap a picture from your webcam -- while the static version can only be used to display images. Not every component has a distinct interactive version. For example, the `gr.AnnotatedImage` only appears as a static version since there's no way to interactively change the value of the annotations or the image. What you need to remember * Gradio will use the interactive version (if available) of a component if that component is used as the **input** to any event; otherwise, the static version will be used. * When you design custom components, you **must** accept the boolean interactive keyword in the constructor of your Python class. In the frontend, you **may** accept the `interactive` property, a `bool` which represents whether the component should be static or interactive. If you do not use this property in the frontend, the component will appear the same in interactive or static mode.
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, or returned by the user's function e.g. at the end of a prediction. So this value is passed around quite a bit, but sometimes the format of the value needs to change between the frontend and backend. Take a look at this example: ```python import numpy as np import gradio as gr def sepia(input_img): sepia_filter = np.array([ [0.393, 0.769, 0.189], [0.349, 0.686, 0.168], [0.272, 0.534, 0.131] ]) sepia_img = input_img.dot(sepia_filter.T) sepia_img /= sepia_img.max() return sepia_img demo = gr.Interface(sepia, gr.Image(width=200, height=200), "image") demo.launch() ``` This will create a Gradio app which has an `Image` component as the input and the output. In the frontend, the Image component will actually **upload** the file to the server and send the **filepath** but this is converted to a `numpy` array before it is sent to a user's function. Conversely, when the user returns a `numpy` array from their function, the numpy array is converted to a file so that it can be sent to the frontend and displayed by the `Image` component. Tip: By default, the `Image` component sends numpy arrays to the python function because it is a common choice for machine learning engineers, though the Image component also supports other formats using the `type` parameter. Read the `Image` docs [here](https://www.gradio.app/docs/image) to learn more. Each component does two conversions: 1. `preprocess`: Converts the `value` 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 `n
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`: Converts the value returned by the python function to the format expected by the frontend. This usually involves going from a **python-native** data-structure, like a `PIL` image to a **JSON** structure. What you need to remember * Every component must implement `preprocess` and `postprocess` methods. In the rare event that no conversion needs to happen, simply return the value as-is. `Textbox` and `Number` are examples of this. * As a component author, **YOU** control the format of the data displayed in the frontend as well as the format of the data someone using your component will receive. Think of an ergonomic data-structure a **python** developer will find intuitive, and control the conversion from a **Web-friendly JSON** data structure (and vice-versa) with `preprocess` and `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, we show a miniature example image of a cheetah that, when clicked, will populate the same image in the input Image component: ![img](https://user-images.githubusercontent.com/1778297/277548211-a3cb2133-2ffc-4cdf-9a83-3e8363b57ea6.png) To enable the example view, you must have the following two files in the top of the `frontend` directory: * `Example.svelte`: this corresponds to the "example version" of your component * `Index.svelte`: this corresponds to the "regular version" In the backend, you typically don't need to do anything. The user-provided example `value` is processed using the same `.postprocess()` method described earlier. If you'd like to do process the data differently (for example, if the `.postprocess()` method is computationally expensive), then you can write your own `.process_example()` method for your custom component, which will be used instead. The `Example.svelte` file and `process_example()` method will be covered in greater depth in the dedicated [frontend](./frontend) and [backend](./backend) guides respectively. What you need to remember * If you expect your component to be used as input, it is important to define an "Example" view. * If you don't, Gradio will use a default one but it won't be as informative as it can be!
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/downloading-and-installing-node-js-and-npm/" target="_blank">install here</a>) * Gradio 5+ (`pip install --upgrade gradio`)
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 package containing to your custom component's Python and JavaScript code -- this makes things official! 4. publish: uploads your package to [PyPi](https://pypi.org/) and/or a sample app to [HuggingFace Spaces](https://hf.co/spaces). Each of these steps is done via the Custom Component CLI. You can invoke it with `gradio cc` or `gradio component` Tip: Run `gradio cc --help` to get a help menu of all available commands. There are some commands that are not covered in this guide. You can also append `--help` to any command name to bring up a help page for that command, e.g. `gradio cc create --help`.
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 component that a stripped-down version of the `Textbox` component that makes it particularly useful when creating your first custom component. Some other components that are good if you are starting out: `SimpleDropdown`, `SimpleImage`, or `File`. Tip: Run `gradio cc show` to get a list of available component templates. The `create` command will: 1. Create a directory with your component's name in lowercase with the following structure: ```directory - backend/ <- The python code for your custom component - frontend/ <- The javascript code for your custom component - demo/ <- A sample app using your custom component. Modify this to develop your component! - pyproject.toml <- Used to build the package and specify package metadata. ``` 2. Install the component in development mode Each of the directories will have the code you need to get started developing!
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 might be different for you. Click on that link to launch the demo app in hot reload mode. Now, you can start making changes to the backend and frontend you'll see the results reflected live in the sample app! We'll go through a real example in a later guide. Tip: You don't have to run dev mode from your custom component directory. The first argument to `dev` mode is the path to the directory. By default it uses the current directory.
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 install <path-to-whl>`) they will be able to use your custom component in any gradio app! The `build` command will also generate documentation for your custom component. This takes the form of an interactive space and a static `README.md`. You can disable this by passing `--no-generate-docs`. You can read more about the documentation generator in [the dedicated guide](https://gradio.app/guides/documenting-custom-components).
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 files to PyPi. This makes it easier to upload the demo to Hugging Face spaces. Otherwise your package must be at a publicly available url. If you decide to upload to PyPi, you will need a PyPI username and password. You can get one [here](https://pypi.org/account/register/). 2. Upload a demo of your component to hugging face spaces. This is also optional. Here is an example of what publishing looks like: <video autoplay muted loop> <source src="https://gradio-builds.s3.amazonaws.com/assets/text_with_attachments_publish.mov" type="video/mp4" /> </video>
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 other's code. Tip: If you want to start off from someone else's custom component see this [guide](./frequently-asked-questionsdo-i-always-need-to-start-my-component-from-scratch).
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 additional modules, remember to modify the `package.json` file ```json "exports": { ".": "./Index.svelte", "./example": "./Example.svelte", "./package.json": "./package.json" }, ```
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_id = ""; export let elem_classes: string[] = []; export let scale: number | null = null; export let min_width: number | undefined = undefined; export let loading_status: LoadingStatus | undefined = undefined; export let mode: "static" | "interactive"; ``` * `elem_id` and `elem_classes` allow Gradio app developers to target your component with custom CSS and JavaScript from the Python `Blocks` class. * `scale` and `min_width` allow Gradio app developers to control how much space your component takes up in the UI. * `loading_status` is used to display a loading status over the component when it is the output of an event. * `mode` is how the parent Gradio app tells your component whether the `interactive` or `static` version should be displayed. * `gradio`: The `gradio` object is created by the parent Gradio app. It stores some application-level configuration that will be useful in your component, like internationalization. You must use it to dispatch events from your component. A minimal `Index.svelte` file would look like: ```svelte <script lang="ts"> import type { LoadingStatus } from "@gradio/statustracker"; import { Block } from "@gradio/atoms"; import { StatusTracker } from "@gradio/statustracker"; import type { Gradio } from "@gradio/utils"; export let gradio: Gradio<{ event_1: never; event_2: never; }>; export let value = ""; export let elem_id = ""; export let elem_classes: string[] = []; export let scale: number | null = null; export let min_width: number | undefined = undefined; export let loading_status: LoadingStatus | undefined = undefined; export let mode: "static" | "interactive"; </script> <Block visib
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} <StatusTracker autoscroll={gradio.autoscroll} i18n={gradio.i18n} {...loading_status} /> {/if} <p>{value}</p> </Block> ```
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 `"gallery"` or `"table"` depending on how the examples are displayed. The `"gallery"` form is used when the examples correspond to a single input component, while the `"table"` form is used when a user has multiple input components, and the examples need to populate all of them. * `selected`: You can also adjust how the examples are displayed if a user "selects" a particular example by using the selected variable. * `index`: The current index of the selected value. * Any additional props your "non-example" component takes! This is the `Example.svelte` file for the code `Radio` component: ```svelte <script lang="ts"> export let value: string; export let type: "gallery" | "table"; export let selected = false; </script> <div class:table={type === "table"} class:gallery={type === "gallery"} class:selected > {value} </div> <style> .gallery { padding: var(--size-1) var(--size-2); } </style> ```
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. You should use the `FileData` data in your component to keep track of uploaded files. The `upload` function will upload an array of `FileData` values to the server. Here's an example of loading files from an `<input>` element when its value changes. ```svelte <script lang="ts"> import { upload, prepare_files, type FileData } from "@gradio/client"; export let root; export let value; let uploaded_files; async function handle_upload(file_data: FileData[]): Promise<void> { await tick(); uploaded_files = await upload(file_data, root); } async function loadFiles(files: FileList): Promise<void> { let _files: File[] = Array.from(files); if (!files.length) { return; } if (file_count === "single") { _files = [files[0]]; } let file_data = await prepare_files(_files); await handle_upload(file_data); } async function loadFilesFromUpload(e: Event): Promise<void> { const target = e.target; if (!target.files) return; await loadFiles(target.files); } </script> <input type="file" on:change={loadFilesFromUpload} multiple={true} /> ``` The component exposes a prop named `root`. This is passed down by the parent gradio app and it represents the base url that the files will be uploaded to and fetched from. For WASM support, you should get the upload function from the `Context` and pass that as the third parameter of the `upload` function. ```typescript <script lang="ts"> import { getContext } from "svelte"; const upload_fn = getContext<typeof upload_files>("upload_files"); async function handle_uploa
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); } </script> ```
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 `ModifyUpload` components for properly uploading files to the Gradio server. Here is how you can use them to create a user interface to upload and display PDF files. ```svelte <script> import { type FileData, Upload, ModifyUpload } from "@gradio/upload"; import { Empty, UploadText, BlockLabel } from "@gradio/atoms"; </script> <BlockLabel Icon={File} label={label || "PDF"} /> {if value === null && interactive} <Upload filetype="application/pdf" on:load={handle_load} {root} > <UploadText type="file" i18n={gradio.i18n} /> </Upload> {:else if value !== null} {if interactive} <ModifyUpload i18n={gradio.i18n} on:clear={handle_clear}/> {/if} <iframe title={value.orig_name || "PDF"} src={value.data} height="{height}px" width="100%"></iframe> {:else} <Empty size="large"> <File/> </Empty> {/if} ``` You can also combine existing Gradio components to create entirely unique experiences. Like rendering a gallery of chatbot conversations. The possibilities are endless, please read the documentation on our javascript packages [here](https://gradio.app/main/docs/js). We'll be adding more packages and documentation over the coming weeks!
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 custom component with the style of our core components. This Storybook will be regularly updated with any new additions or changes. [Storybook Link](https://gradio.app/main/docs/js/storybook)
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 use. Svelte options: - `preprocess`: A list of svelte preprocessors to use. - `extensions`: A list of file extensions to compile to `.svelte` files. - `build.target`: The target to build for, this may be necessary to support newer javascript features. See the [esbuild docs](https://esbuild.github.io/api/target) for more information. The `gradio.config.js` file should be placed in the root of your component's `frontend` directory. A default config file is created for you when you create a new component. But you can also create your own config file, if one doesn't exist, and use it to customize your component's build process. Example for a Vite plugin Custom components can use Vite plugins to customize the build process. Check out the [Vite Docs](https://vitejs.dev/guide/using-plugins.html) for more information. Here we configure [TailwindCSS](https://tailwindcss.com), a utility-first CSS framework. Setup is easiest using the version 4 prerelease. ``` npm install tailwindcss@next @tailwindcss/vite@next ``` In `gradio.config.js`: ```typescript import tailwindcss from "@tailwindcss/vite"; export default { plugins: [tailwindcss()] }; ``` Then create a `style.css` file with the following content: ```css @import "tailwindcss"; ``` Import this file into `Index.svelte`. Note, that you need to import the css file containing `@import` and cannot just use a `<style>` tag and use `@import` there. ```svelte <script lang="ts"> [...] import "./style.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
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 [Svelte Preprocessor](https://svelte.dev/docs/svelte-compilerpreprocess) to the `svelte` object in `gradio.config.js` and configure the [`extensions`](https://github.com/sveltejs/vite-plugin-svelte/blob/HEAD/docs/config.mdconfig-file) field. Other options are not currently supported. First, install the `mdsvex` plugin: ```bash npm install mdsvex ``` Then add the following to `gradio.config.js`: ```typescript import { mdsvex } from "mdsvex"; export default { svelte: { preprocess: [ mdsvex() ], extensions: [".svelte", ".svx"] } }; ``` Now we can create `mdsvex` documents in our component's `frontend` directory and they will be compiled to `.svelte` files. ```md <!-- HelloWorld.svx --> <script lang="ts"> import { Block } from "@gradio/atoms"; export let title = "Hello World"; </script> <Block label="Hello World"> {title} This is a markdown file. </Block> ``` We can then use the `HelloWorld.svx` file in our components: ```svelte <script lang="ts"> import HelloWorld from "./HelloWorld.svx"; </script> <HelloWorld /> ```
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 update`. 2. Modify the `dependencies` key in `pyproject.toml` to pin the maximum allowed Gradio version at version 5, e.g. `dependencies = ["gradio>=4.0,<6.0"]`. 3. Run the build and publish commands
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?** Chrome on Windows will block the local compiled svelte files for security reasons. We recommend developing your custom component in the windows subsystem for linux (WSL) while the team looks at this issue. **3. Inspect the window.__GRADIO_CC__ variable** In the browser console, print the `window.__GRADIO__CC` variable (just type it into the console). If it is an empty object, that means that the CLI could not find your custom component source code. Typically, this happens when the custom component is installed in a different virtual environment than the one used to run the dev command. Please use the `--python-path` and `gradio-path` CLI arguments to specify the path of the python and gradio executables for the environment your component is installed in. For example, if you are using a virtualenv located at `/Users/mary/venv`, pass in `/Users/mary/bin/python` and `/Users/mary/bin/gradio` respectively. If the `window.__GRADIO__CC` variable is not empty (see below for an example), then the dev server should be working correctly. ![](https://gradio-builds.s3.amazonaws.com/demo-files/gradio_CC_DEV.png) **4. Make sure you are using a virtual environment** It is highly recommended you use a virtual environment to prevent conflicts with other python dependencies installed in your system.
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 and run `gradio cc install`. Then you can run the development server to make changes.If you run into any issues, contact the author of the component by opening an issue in their repository. The [gallery](https://www.gradio.app/custom-components/gallery) is a good place to look for published components. For example, to start from the [PDF component](https://www.gradio.app/custom-components/gallery?id=freddyaboulton%2Fgradio_pdf), clone the space with `git clone https://huggingface.co/spaces/freddyaboulton/gradio_pdf`, `cd` into the `src` directory, and run `gradio cc install`.
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
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 the model. $code_score_tracker In the code above, the `scores` array is shared between all users. If multiple users are accessing this demo, their scores will all be added to the same list, and the returned top 3 scores will be collected from this shared reference.
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, which represents the state of the interface. 2. At the end of the function, return the updated value of the state as an extra return value. 3. Add the `'state'` input and `'state'` output components when creating your `Interface` Here's a simple app to illustrate session state - this app simply stores users previous submissions and displays them back to the user: $code_interface_state $demo_interface_state Notice how the state persists across submits within each page, but if you load this demo in another tab (or refresh the page), the demos will not share chat history. Here, we could not store the submission history in a global variable, otherwise the submission history would then get jumbled between different users. The initial value of the `State` is `None` by default. If you pass a parameter to the `value` argument of `gr.State()`, it is used as the default value of the state instead. Note: the `Interface` class only supports a single session state variable (though it can be a list with multiple elements). For more complex use cases, you can use Blocks, [which supports multiple `State` variables](/guides/state-in-blocks/). Alternatively, if you are building a chatbot that maintains user state, consider using the `ChatInterface` abstraction, [which manages state automatically](/guides/creating-a-chatbot-fast).
Session State
https://gradio.app/guides/interface-state
Building Interfaces - Interface State 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 that none of the 4 cases fulfill your exact needs. In this case, you need to use the `gr.Blocks()` approach!
Unified demos
https://gradio.app/guides/four-kinds-of-interfaces
Building Interfaces - Four Kinds Of Interfaces 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='microphone', streaming=True)`, when both are used in `gr.Interface(live=True)`, is that the first `Component` will automatically submit data and run the `Interface` function when the user stops recording, whereas the second `Component` will continuously send data and run the `Interface` function _during_ recording. Here is example code of streaming images from the webcam. $code_stream_frames Streaming can also be done in an output component. A `gr.Audio(streaming=True)` output component can take a stream of audio data yielded piece-wise by a generator function and combines them into a single audio file. For a detailed example, see our guide on performing [automatic speech recognition](/guides/real-time-speech-recognition) with Gradio.
Streaming Components
https://gradio.app/guides/reactive-interfaces
Building Interfaces - Reactive Interfaces 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 has one input component, then you can provide your examples as a regular list instead of a list of lists. Loading Examples from a Directory You can also specify a path to a directory containing your examples. If your Interface takes only a single file-type input, e.g. an image classifier, you can simply pass a directory filepath to the `examples=` argument, and the `Interface` will load the images in the directory as examples. In the case of multiple inputs, this directory must contain a log.csv file with the example values. In the context of the calculator demo, we can set `examples='/demo/calculator/examples'` and in that directory we include the following `log.csv` file: ```csv num,operation,num2 5,"add",3 4,"divide",2 5,"multiply",3 ``` This can be helpful when browsing flagged data. Simply point to the flagged directory and the `Interface` will load the examples from the flagged data. Providing Partial Examples Sometimes your app has many input components, but you would only like to provide examples for a subset of them. In order to exclude some inputs from the examples, pass `None` for all data samples corresponding to those particular components.
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 `gradio_cached_examples` in your working directory by default. You can also set this directory with the `GRADIO_EXAMPLES_CACHE` environment variable, which can be either an absolute path or a relative path to your working directory. Whenever a user clicks on an example, the output will automatically be populated in the app now, using data from this cached directory instead of actually running the function. This is useful so users can quickly try out your model without adding any load! Alternatively, you can set `cache_examples="lazy"`. This means that each particular example will only get cached after it is first used (by any user) in the Gradio app. This is helpful if your prediction function is long-running and you do not want to wait a long time for your Gradio app to start. Keep in mind once the cache is generated, it will not be updated automatically in future launches. If the examples or function logic change, delete the cache folder to clear the cache and rebuild it with another `launch()`.
Caching examples
https://gradio.app/guides/more-on-examples
Building Interfaces - More On Examples 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` component is designed to handle input or output images, the `gr.Label` component displays classification labels and probabilities, the `gr.LinePlot` component displays line plots, and so on.
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 label. If you use the actual classes for `gr.Textbox` and `gr.Slider` instead of the string shortcuts, you have access to much more customizability through component attributes. $code_hello_world_2 $demo_hello_world_2
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 function, in order, each component in the `outputs` list corresponds to one of the values returned by the function, in order.
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)`, where the last dimension represents the RGB values. We'll return an image as well in the form of a NumPy array. Gradio handles the preprocessing and postprocessing to convert images to NumPy arrays and vice versa. You can also control the preprocessing performed with the `type=` keyword argument. For example, if you wanted your function to take a file path to an image instead of a NumPy array, the input `Image` component could be written as: ```python gr.Image(type="filepath") ``` You can read more about the built-in Gradio components and how to customize them in the [Gradio docs](https://gradio.app/docs).
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 argument of the Interface constructor. Each sublist within the outer list represents a data sample, and each element within the sublist represents an input for each input component. The format of example data for each component is specified in the [Docs](https://gradio.app/docscomponents). $code_calculator $demo_calculator You can load a large dataset into the examples to browse and interact with the dataset through Gradio. The examples will be automatically paginated (you can configure this through the `examples_per_page` argument of `Interface`). Continue learning about examples in the [More On Examples](https://gradio.app/guides/more-on-examples) guide.
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 very top of interface, and also becomes the page title. - `description`: which accepts text, markdown or HTML and places it right under the title. - `article`: which also accepts text, markdown or HTML and places it below the interface. ![annotated](https://github.com/gradio-app/gradio/blob/main/guides/assets/annotated.png?raw=true) Another useful keyword argument is `label=`, which is present in every `Component`. This modifies the label text at the top of each `Component`. You can also add the `info=` keyword argument to form elements like `Textbox` or `Radio` to provide further information on their usage. ```python gr.Number(label='Age', info='In years, must be greater than 0') ```
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 accordion to show these components. The additional inputs are passed into the prediction function, in order, after the standard inputs. You can customize the appearance of the accordion by using the optional `additional_inputs_accordion` argument, which accepts a string (in which case, it becomes the label of the accordion), or an instance of the `gr.Accordion()` class (e.g. this lets you control whether the accordion is open or closed by default). Here's an example: $code_interface_with_additional_inputs $demo_interface_with_additional_inputs
Additional Inputs within an Accordion
https://gradio.app/guides/the-interface-class
Building Interfaces - The Interface Class Guide
If you already have a recent version of `gradio`, then the `gradio_client` is included as a dependency. But note that this documentation reflects the latest version of the `gradio_client`, so upgrade if you're not sure! The lightweight `gradio_client` package can be installed from pip (or pip3) and is tested to work with **Python versions 3.10 or higher**: ```bash $ pip install --upgrade gradio_client ```
Installation
https://gradio.app/guides/getting-started-with-the-python-client
Gradio Clients And Lite - Getting Started With The Python Client Guide
Start by connecting instantiating a `Client` object and connecting it to a Gradio app that is running on Hugging Face Spaces. ```python from gradio_client import Client client = Client("abidlabs/en2fr") a Space that translates from English to French ``` You can also connect to private Spaces by passing in your HF token with the `token` parameter. You can get your HF token here: https://huggingface.co/settings/tokens ```python from gradio_client import Client client = Client("abidlabs/my-private-space", token="...") ```
Connecting to a Gradio App on Hugging Face Spaces
https://gradio.app/guides/getting-started-with-the-python-client
Gradio Clients And Lite - Getting Started With The Python Client Guide
While you can use any public Space as an API, you may get rate limited by Hugging Face if you make too many requests. For unlimited usage of a Space, simply duplicate the Space to create a private Space, and then use it to make as many requests as you'd like! The `gradio_client` includes a class method: `Client.duplicate()` to make this process simple (you'll need to pass in your [Hugging Face token](https://huggingface.co/settings/tokens) or be logged in using the Hugging Face CLI): ```python import os from gradio_client import Client, handle_file HF_TOKEN = os.environ.get("HF_TOKEN") client = Client.duplicate("abidlabs/whisper", token=HF_TOKEN) client.predict(handle_file("audio_sample.wav")) >> "This is a test of the whisper speech recognition model." ``` If you have previously duplicated a Space, re-running `duplicate()` will _not_ create a new Space. Instead, the Client will attach to the previously-created Space. So it is safe to re-run the `Client.duplicate()` method multiple times. **Note:** if the original Space uses GPUs, your private Space will as well, and your Hugging Face account will get billed based on the price of the GPU. To minimize charges, your Space will automatically go to sleep after 1 hour of inactivity. You can also set the hardware using the `hardware` parameter of `duplicate()`.
Duplicating a Space for private use
https://gradio.app/guides/getting-started-with-the-python-client
Gradio Clients And Lite - Getting Started With The Python Client Guide
If your app is running somewhere else, just provide the full URL instead, including the "http://" or "https://". Here's an example of making predictions to a Gradio app that is running on a share URL: ```python from gradio_client import Client client = Client("https://bec81a83-5b5c-471e.gradio.live") ```
Connecting a general Gradio app
https://gradio.app/guides/getting-started-with-the-python-client
Gradio Clients And Lite - Getting Started With The Python Client Guide
If the Gradio application you are connecting to [requires a username and password](/guides/sharing-your-appauthentication), then provide them as a tuple to the `auth` argument of the `Client` class: ```python from gradio_client import Client Client( space_name, auth=[username, password] ) ```
Connecting to a Gradio app with auth
https://gradio.app/guides/getting-started-with-the-python-client
Gradio Clients And Lite - Getting Started With The Python Client Guide
Once you have connected to a Gradio app, you can view the APIs that are available to you by calling the `Client.view_api()` method. For the Whisper Space, we see the following: ```bash Client.predict() Usage Info --------------------------- Named API endpoints: 1 - predict(audio, api_name="/predict") -> output Parameters: - [Audio] audio: filepath (required) Returns: - [Textbox] output: str ``` We see that we have 1 API endpoint in this space, and shows us how to use the API endpoint to make a prediction: we should call the `.predict()` method (which we will explore below), providing a parameter `input_audio` of type `str`, which is a `filepath or URL`. We should also provide the `api_name='/predict'` argument to the `predict()` method. Although this isn't necessary if a Gradio app has only 1 named endpoint, it does allow us to call different endpoints in a single app if they are available.
Inspecting the API endpoints
https://gradio.app/guides/getting-started-with-the-python-client
Gradio Clients And Lite - Getting Started With The Python Client Guide
As an alternative to running the `.view_api()` method, you can click on the "Use via API" link in the footer of the Gradio app, which shows us the same information, along with example usage. ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/view-api.png) The View API page also includes an "API Recorder" that lets you interact with the Gradio UI normally and converts your interactions into the corresponding code to run with the Python Client.
The "View API" Page
https://gradio.app/guides/getting-started-with-the-python-client
Gradio Clients And Lite - Getting Started With The Python Client Guide
The simplest way to make a prediction is simply to call the `.predict()` function with the appropriate arguments: ```python from gradio_client import Client client = Client("abidlabs/en2fr") client.predict("Hello", api_name='/predict') >> Bonjour ``` If there are multiple parameters, then you should pass them as separate arguments to `.predict()`, like this: ```python from gradio_client import Client client = Client("gradio/calculator") client.predict(4, "add", 5) >> 9.0 ``` It is recommended to provide key-word arguments instead of positional arguments: ```python from gradio_client import Client client = Client("gradio/calculator") client.predict(num1=4, operation="add", num2=5) >> 9.0 ``` This allows you to take advantage of default arguments. For example, this Space includes the default value for the Slider component so you do not need to provide it when accessing it with the client. ```python from gradio_client import Client client = Client("abidlabs/image_generator") client.predict(text="an astronaut riding a camel") ``` The default value is the initial value of the corresponding Gradio component. If the component does not have an initial value, but if the corresponding argument in the predict function has a default value of `None`, then that parameter is also optional in the client. Of course, if you'd like to override it, you can include it as well: ```python from gradio_client import Client client = Client("abidlabs/image_generator") client.predict(text="an astronaut riding a camel", steps=25) ``` For providing files or URLs as inputs, you should pass in the filepath or URL to the file enclosed within `gradio_client.handle_file()`. This takes care of uploading the file to the Gradio server and ensures that the file is preprocessed correctly: ```python from gradio_client import Client, handle_file client = Client("abidlabs/whisper") client.predict( audio=handle_file("https://audio-samples.github.io/samples/mp3/blizzard_unconditional/s
Making a prediction
https://gradio.app/guides/getting-started-with-the-python-client
Gradio Clients And Lite - Getting Started With The Python Client Guide
```python from gradio_client import Client, handle_file client = Client("abidlabs/whisper") client.predict( audio=handle_file("https://audio-samples.github.io/samples/mp3/blizzard_unconditional/sample-0.mp3") ) >> "My thought I have nobody by a beauty and will as you poured. Mr. Rochester is serve in that so don't find simpus, and devoted abode, to at might in a r—" ```
Making a prediction
https://gradio.app/guides/getting-started-with-the-python-client
Gradio Clients And Lite - Getting Started With The Python Client Guide
One should note that `.predict()` is a _blocking_ operation as it waits for the operation to complete before returning the prediction. In many cases, you may be better off letting the job run in the background until you need the results of the prediction. You can do this by creating a `Job` instance using the `.submit()` method, and then later calling `.result()` on the job to get the result. For example: ```python from gradio_client import Client client = Client(space="abidlabs/en2fr") job = client.submit("Hello", api_name="/predict") This is not blocking Do something else job.result() This is blocking >> Bonjour ```
Running jobs asynchronously
https://gradio.app/guides/getting-started-with-the-python-client
Gradio Clients And Lite - Getting Started With The Python Client Guide
Alternatively, one can add one or more callbacks to perform actions after the job has completed running, like this: ```python from gradio_client import Client def print_result(x): print("The translated result is: {x}") client = Client(space="abidlabs/en2fr") job = client.submit("Hello", api_name="/predict", result_callbacks=[print_result]) Do something else >> The translated result is: Bonjour ```
Adding callbacks
https://gradio.app/guides/getting-started-with-the-python-client
Gradio Clients And Lite - Getting Started With The Python Client Guide
The `Job` object also allows you to get the status of the running job by calling the `.status()` method. This returns a `StatusUpdate` object with the following attributes: `code` (the status code, one of a set of defined strings representing the status. See the `utils.Status` class), `rank` (the current position of this job in the queue), `queue_size` (the total queue size), `eta` (estimated time this job will complete), `success` (a boolean representing whether the job completed successfully), and `time` (the time that the status was generated). ```py from gradio_client import Client client = Client(src="gradio/calculator") job = client.submit(5, "add", 4, api_name="/predict") job.status() >> <Status.STARTING: 'STARTING'> ``` _Note_: The `Job` class also has a `.done()` instance method which returns a boolean indicating whether the job has completed.
Status
https://gradio.app/guides/getting-started-with-the-python-client
Gradio Clients And Lite - Getting Started With The Python Client Guide
The `Job` class also has a `.cancel()` instance method that cancels jobs that have been queued but not started. For example, if you run: ```py client = Client("abidlabs/whisper") job1 = client.submit(handle_file("audio_sample1.wav")) job2 = client.submit(handle_file("audio_sample2.wav")) job1.cancel() will return False, assuming the job has started job2.cancel() will return True, indicating that the job has been canceled ``` If the first job has started processing, then it will not be canceled. If the second job has not yet started, it will be successfully canceled and removed from the queue.
Cancelling Jobs
https://gradio.app/guides/getting-started-with-the-python-client
Gradio Clients And Lite - Getting Started With The Python Client Guide
Some Gradio API endpoints do not return a single value, rather they return a series of values. You can get the series of values that have been returned at any time from such a generator endpoint by running `job.outputs()`: ```py from gradio_client import Client client = Client(src="gradio/count_generator") job = client.submit(3, api_name="/count") while not job.done(): time.sleep(0.1) job.outputs() >> ['0', '1', '2'] ``` Note that running `job.result()` on a generator endpoint only gives you the _first_ value returned by the endpoint. The `Job` object is also iterable, which means you can use it to display the results of a generator function as they are returned from the endpoint. Here's the equivalent example using the `Job` as a generator: ```py from gradio_client import Client client = Client(src="gradio/count_generator") job = client.submit(3, api_name="/count") for o in job: print(o) >> 0 >> 1 >> 2 ``` You can also cancel jobs that that have iterative outputs, in which case the job will finish as soon as the current iteration finishes running. ```py from gradio_client import Client import time client = Client("abidlabs/test-yield") job = client.submit("abcdef") time.sleep(3) job.cancel() job cancels after 2 iterations ```
Generator Endpoints
https://gradio.app/guides/getting-started-with-the-python-client
Gradio Clients And Lite - Getting Started With The Python Client Guide
Gradio demos can include [session state](https://www.gradio.app/guides/state-in-blocks), which provides a way for demos to persist information from user interactions within a page session. For example, consider the following demo, which maintains a list of words that a user has submitted in a `gr.State` component. When a user submits a new word, it is added to the state, and the number of previous occurrences of that word is displayed: ```python import gradio as gr def count(word, list_of_words): return list_of_words.count(word), list_of_words + [word] with gr.Blocks() as demo: words = gr.State([]) textbox = gr.Textbox() number = gr.Number() textbox.submit(count, inputs=[textbox, words], outputs=[number, words]) demo.launch() ``` If you were to connect this this Gradio app using the Python Client, you would notice that the API information only shows a single input and output: ```csv Client.predict() Usage Info --------------------------- Named API endpoints: 1 - predict(word, api_name="/count") -> value_31 Parameters: - [Textbox] word: str (required) Returns: - [Number] value_31: float ``` That is because the Python client handles state automatically for you -- as you make a series of requests, the returned state from one request is stored internally and automatically supplied for the subsequent request. If you'd like to reset the state, you can do that by calling `Client.reset_session()`.
Demos with Session State
https://gradio.app/guides/getting-started-with-the-python-client
Gradio Clients And Lite - Getting Started With The Python Client Guide
Install the @gradio/client package to interact with Gradio APIs using Node.js version >=18.0.0 or in browser-based projects. Use npm or any compatible package manager: ```bash npm i @gradio/client ``` This command adds @gradio/client to your project dependencies, allowing you to import it in your JavaScript or TypeScript files.
Installation via npm
https://gradio.app/guides/getting-started-with-the-js-client
Gradio Clients And Lite - Getting Started With The Js Client Guide
For quick addition to your web project, you can use the jsDelivr CDN to load the latest version of @gradio/client directly into your HTML: ```html <script type="module"> import { Client } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js"; ... </script> ``` Be sure to add this to the `<head>` of your HTML. This will install the latest version but we advise hardcoding the version in production. You can find all available versions [here](https://www.jsdelivr.com/package/npm/@gradio/client). This approach is ideal for experimental or prototying purposes, though has some limitations. A complete example would look like this: ```html <!DOCTYPE html> <html lang="en"> <head> <script type="module"> import { Client } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js"; const client = await Client.connect("abidlabs/en2fr"); const result = await client.predict("/predict", { text: "My name is Hannah" }); console.log(result); </script> </head> </html> ```
Installation via CDN
https://gradio.app/guides/getting-started-with-the-js-client
Gradio Clients And Lite - Getting Started With The Js Client Guide
Start by connecting instantiating a `client` instance and connecting it to a Gradio app that is running on Hugging Face Spaces or generally anywhere on the web.
Connecting to a running Gradio App
https://gradio.app/guides/getting-started-with-the-js-client
Gradio Clients And Lite - Getting Started With The Js Client Guide
```js import { Client } from "@gradio/client"; const app = await Client.connect("abidlabs/en2fr"); // a Space that translates from English to French ``` You can also connect to private Spaces by passing in your HF token with the `token` property of the options parameter. You can get your HF token here: https://huggingface.co/settings/tokens ```js import { Client } from "@gradio/client"; const app = await Client.connect("abidlabs/my-private-space", { token: "hf_..." }) ```
Connecting to a Hugging Face Space
https://gradio.app/guides/getting-started-with-the-js-client
Gradio Clients And Lite - Getting Started With The Js Client Guide
While you can use any public Space as an API, you may get rate limited by Hugging Face if you make too many requests. For unlimited usage of a Space, simply duplicate the Space to create a private Space, and then use it to make as many requests as you'd like! You'll need to pass in your [Hugging Face token](https://huggingface.co/settings/tokens)). `Client.duplicate` is almost identical to `Client.connect`, the only difference is under the hood: ```js import { Client, handle_file } from "@gradio/client"; const response = await fetch( "https://audio-samples.github.io/samples/mp3/blizzard_unconditional/sample-0.mp3" ); const audio_file = await response.blob(); const app = await Client.duplicate("abidlabs/whisper", { token: "hf_..." }); const transcription = await app.predict("/predict", [handle_file(audio_file)]); ``` If you have previously duplicated a Space, re-running `Client.duplicate` will _not_ create a new Space. Instead, the client will attach to the previously-created Space. So it is safe to re-run the `Client.duplicate` method multiple times with the same space. **Note:** if the original Space uses GPUs, your private Space will as well, and your Hugging Face account will get billed based on the price of the GPU. To minimize charges, your Space will automatically go to sleep after 5 minutes of inactivity. You can also set the hardware using the `hardware` and `timeout` properties of `duplicate`'s options object like this: ```js import { Client } from "@gradio/client"; const app = await Client.duplicate("abidlabs/whisper", { token: "hf_...", timeout: 60, hardware: "a10g-small" }); ```
Duplicating a Space for private use
https://gradio.app/guides/getting-started-with-the-js-client
Gradio Clients And Lite - Getting Started With The Js Client Guide
If your app is running somewhere else, just provide the full URL instead, including the "http://" or "https://". Here's an example of making predictions to a Gradio app that is running on a share URL: ```js import { Client } from "@gradio/client"; const app = Client.connect("https://bec81a83-5b5c-471e.gradio.live"); ```
Connecting a general Gradio app
https://gradio.app/guides/getting-started-with-the-js-client
Gradio Clients And Lite - Getting Started With The Js Client Guide
If the Gradio application you are connecting to [requires a username and password](/guides/sharing-your-appauthentication), then provide them as a tuple to the `auth` argument of the `Client` class: ```js import { Client } from "@gradio/client"; Client.connect( space_name, { auth: [username, password] } ) ```
Connecting to a Gradio app with auth
https://gradio.app/guides/getting-started-with-the-js-client
Gradio Clients And Lite - Getting Started With The Js Client Guide
Once you have connected to a Gradio app, you can view the APIs that are available to you by calling the `Client`'s `view_api` method. For the Whisper Space, we can do this: ```js import { Client } from "@gradio/client"; const app = await Client.connect("abidlabs/whisper"); const app_info = await app.view_api(); console.log(app_info); ``` And we will see the following: ```json { "named_endpoints": { "/predict": { "parameters": [ { "label": "text", "component": "Textbox", "type": "string" } ], "returns": [ { "label": "output", "component": "Textbox", "type": "string" } ] } }, "unnamed_endpoints": {} } ``` This shows us that we have 1 API endpoint in this space, and shows us how to use the API endpoint to make a prediction: we should call the `.predict()` method (which we will explore below), providing a parameter `input_audio` of type `string`, which is a url to a file. We should also provide the `api_name='/predict'` argument to the `predict()` method. Although this isn't necessary if a Gradio app has only 1 named endpoint, it does allow us to call different endpoints in a single app if they are available. If an app has unnamed API endpoints, these can also be displayed by running `.view_api(all_endpoints=True)`.
Inspecting the API endpoints
https://gradio.app/guides/getting-started-with-the-js-client
Gradio Clients And Lite - Getting Started With The Js Client Guide
As an alternative to running the `.view_api()` method, you can click on the "Use via API" link in the footer of the Gradio app, which shows us the same information, along with example usage. ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/view-api.png) The View API page also includes an "API Recorder" that lets you interact with the Gradio UI normally and converts your interactions into the corresponding code to run with the JS Client.
The "View API" Page
https://gradio.app/guides/getting-started-with-the-js-client
Gradio Clients And Lite - Getting Started With The Js Client Guide
The simplest way to make a prediction is simply to call the `.predict()` method with the appropriate arguments: ```js import { Client } from "@gradio/client"; const app = await Client.connect("abidlabs/en2fr"); const result = await app.predict("/predict", ["Hello"]); ``` If there are multiple parameters, then you should pass them as an array to `.predict()`, like this: ```js import { Client } from "@gradio/client"; const app = await Client.connect("gradio/calculator"); const result = await app.predict("/predict", [4, "add", 5]); ``` For certain inputs, such as images, you should pass in a `Buffer`, `Blob` or `File` depending on what is most convenient. In node, this would be a `Buffer` or `Blob`; in a browser environment, this would be a `Blob` or `File`. ```js import { Client, handle_file } from "@gradio/client"; const response = await fetch( "https://audio-samples.github.io/samples/mp3/blizzard_unconditional/sample-0.mp3" ); const audio_file = await response.blob(); const app = await Client.connect("abidlabs/whisper"); const result = await app.predict("/predict", [handle_file(audio_file)]); ```
Making a prediction
https://gradio.app/guides/getting-started-with-the-js-client
Gradio Clients And Lite - Getting Started With The Js Client Guide
If the API you are working with can return results over time, or you wish to access information about the status of a job, you can use the iterable interface for more flexibility. This is especially useful for iterative endpoints or generator endpoints that will produce a series of values over time as discrete responses. ```js import { Client } from "@gradio/client"; function log_result(payload) { const { data: [translation] } = payload; console.log(`The translated result is: ${translation}`); } const app = await Client.connect("abidlabs/en2fr"); const job = app.submit("/predict", ["Hello"]); for await (const message of job) { log_result(message); } ```
Using events
https://gradio.app/guides/getting-started-with-the-js-client
Gradio Clients And Lite - Getting Started With The Js Client Guide