text
stringlengths
0
2k
heading1
stringlengths
3
79
source_page_url
stringclasses
189 values
source_page_title
stringclasses
189 values
When a user closes their browser tab, Gradio will automatically delete any `gr.State` variables associated with that user session after 60 minutes. If the user connects again within those 60 minutes, no state will be deleted. You can control the deletion behavior further with the following two parameters of `gr.State`...
Automatic deletion of `gr.State`
https://gradio.app/guides/resource-cleanup
Additional Features - Resource Cleanup Guide
Your Gradio application will save uploaded and generated files to a special directory called the cache directory. Gradio uses a hashing scheme to ensure that duplicate files are not saved to the cache but over time the size of the cache will grow (especially if your app goes viral 😉). Gradio can periodically clean up...
Automatic cache cleanup via `delete_cache`
https://gradio.app/guides/resource-cleanup
Additional Features - Resource Cleanup Guide
Additionally, Gradio now includes a `Blocks.unload()` event, allowing you to run arbitrary cleanup functions when users disconnect (this does not have a 60 minute delay). Unlike other gradio events, this event does not accept inputs or outptus. You can think of the `unload` event as the opposite of the `load` event.
The `unload` event
https://gradio.app/guides/resource-cleanup
Additional Features - Resource Cleanup Guide
The following demo uses all of these features. When a user visits the page, a special unique directory is created for that user. As the user interacts with the app, images are saved to disk in that special directory. When the user closes the page, the images created in that session are deleted via the `unload` event. T...
Putting it all together
https://gradio.app/guides/resource-cleanup
Additional Features - Resource Cleanup Guide
The simplest possible Workflow app: ```python import gradio as gr gr.Workflow().launch() ``` Open the app, drag Spaces, models, and datasets from the sidebar onto the canvas, connect their ports, and hit **Run**. As you edit the workflow, a `workflow.json` file will automatically be created next to the Python script...
Quickstart
https://gradio.app/guides/workflows
Additional Features - Workflows Guide
Pass your own Python functions via `bind=` and they appear as callable nodes on the canvas. Gradio inspects the function signature to auto-generate input/output ports. ```python import gradio as gr def summarize(text: str) -> str: return text[:200] gr.Workflow(bind=[summarize]).launch() ``` Use a dict to give n...
Binding Python functions
https://gradio.app/guides/workflows
Additional Features - Workflows Guide
For pipelines you want to ship with a fixed topology, declare edges programmatically: ```python import gradio as gr def clean(text: str) -> str: return text.strip().lower() def tag(text: str) -> str: return f"[processed] {text}" gr.Workflow( bind=[clean, tag], edges=[("clean", "tag")], ).launch() ``...
Defining edges in code
https://gradio.app/guides/workflows
Additional Features - Workflows Guide
Pass a `graph=` path to load a saved workflow topology. The canvas reads from the file on each page load and autosaves back to it when you make edits. ```python gr.Workflow(graph="workflow.json").launch() ``` If the file doesn't exist yet, it's created on the first authorized edit. `bind=` does not automatically add ...
Loading from a JSON file
https://gradio.app/guides/workflows
Additional Features - Workflows Guide
A workflow is a JSON file with three node collections: ```json { "schema_version": "2", "name": "My Pipeline", "references": [ { "id": "ref_prompt", "label": "Prompt", "role": "reference", "asset_type": "text", "inputs": [{"id": "in", "label": "Text", "type": "text"}], "outputs": [{"...
Workflow JSON format
https://gradio.app/guides/workflows
Additional Features - Workflows Guide
s` | Outputs — the results being created | Operator kinds | `kind` | What it calls | |---|---| | `"space"` | A Gradio Space on the Hub via `gradio_client`; set `space_id` and `endpoint` | | `"model"` | A Hugging Face model via `InferenceClient`; set `model_id` and a supported `endpoint` such as `text_to_image`. `pipe...
Workflow JSON format
https://gradio.app/guides/workflows
Additional Features - Workflows Guide
Ports are typed so the canvas can validate connections. Supported types: `image` · `audio` · `video` · `text` · `number` · `boolean` · `gallery` · `file` · `json` · `model3d` · `any` `any` is a compatibility fallback that can connect to every port type. `file` and `any` usually come from API schema inference and are ...
Port types
https://gradio.app/guides/workflows
Additional Features - Workflows Guide
One reference can feed multiple operators simultaneously. When you run the workflow in the interactive canvas, operators at the same dependency depth run in parallel: ```python workflow.json excerpt — one product photo → 4 FLUX Kontext branches "edges": [ {"from_node_id": "ref_product", ..., "to_node_id": "op_kontex...
Fan-out pipelines
https://gradio.app/guides/workflows
Additional Features - Workflows Guide
A Workflow app is a standard Gradio app — deploy it to Hugging Face Spaces exactly like any other, by uploading the code to a Space, or by simply running in your terminal: ``` gradio deploy ``` Set `hf_oauth: true` [in your Space](https://huggingface.co/docs/hub/en/spaces-oauth) so the owner can authenticate for edit...
Deploying to Spaces
https://gradio.app/guides/workflows
Additional Features - Workflows Guide
Every Workflow app is a Gradio app, meaning that it exposes its connected pipelines through the standard Gradio REST API. Each disconnected pipeline containing one or more output (subject) nodes gets one endpoint. Its name is derived from the first subject's label — for example, a pipeline whose first subject is labell...
API access
https://gradio.app/guides/workflows
Additional Features - Workflows Guide
- **1. Static files**. You can designate static files or directories using the `gr.set_static_paths` function. Static files are not be copied to the Gradio cache (see below) and will be served directly from your computer. This can help save disk space and reduce the time your app takes to launch but be mindful of poss...
Files Gradio allows users to access
https://gradio.app/guides/file-access
Additional Features - File Access Guide
First, it's important to understand why Gradio has a cache at all. Gradio copies files to a cache directory before returning them to the frontend. This prevents files from being overwritten by one user while they are still needed by another user of your application. For example, if your prediction function returns a vi...
The Gradio cache
https://gradio.app/guides/file-access
Additional Features - File Access Guide
d by a user to your Gradio app (e.g. through the `File` or `Image` input components). Tip: If at any time Gradio blocks a file that you would like it to process, add its path to the `allowed_paths` parameter.
The Gradio cache
https://gradio.app/guides/file-access
Additional Features - File Access Guide
While running, Gradio apps will NOT ALLOW users to access: - **Files that you explicitly block via the `blocked_paths` parameter in `launch()`**. You can pass in a list of additional directories or exact filepaths to the `blocked_paths` parameter in `launch()`. This parameter takes precedence over the files that Gradi...
The files Gradio will not allow others to access
https://gradio.app/guides/file-access
Additional Features - File Access Guide
Sharing your Gradio application will also allow users to upload files to your computer or server. You can set a maximum file size for uploads to prevent abuse and to preserve disk space. You can do this with the `max_file_size` parameter of `.launch`. For example, the following two code snippets limit file uploads to 5...
Uploading Files
https://gradio.app/guides/file-access
Additional Features - File Access Guide
* Set a `max_file_size` for your application. * Do not return arbitrary user input from a function that is connected to a file-based output component (`gr.Image`, `gr.File`, etc.). For example, the following interface would allow anyone to move an arbitrary file in your local directory to the cache: `gr.Interface(lambd...
Best Practices
https://gradio.app/guides/file-access
Additional Features - File Access Guide
Both `gr.set_static_paths` and the `allowed_paths` parameter in launch expect absolute paths. Below is a minimal example to display a local `.png` image file in an HTML block. ```txt ├── assets │ └── logo.png └── app.py ``` For the example directory structure, `logo.png` and any other files in the `assets` folder ca...
Example: Accessing local files
https://gradio.app/guides/file-access
Additional Features - File Access Guide
By default, Gradio automatically generates a navigation bar for multipage apps that displays all your pages with "Home" as the title for the main page. You can customize the navbar behavior using the `gr.Navbar` component. Per-Page Navbar Configuration You can have different navbar configurations for each page of you...
Customizing the Navbar
https://gradio.app/guides/multipage-apps
Additional Features - Multipage Apps Guide
Let's create a demo where a user can choose a filter to apply to their webcam stream. Users can choose from an edge-detection filter, a cartoon filter, or simply flipping the stream vertically. $code_streaming_filter $demo_streaming_filter You will notice that if you change the filter value it will immediately take e...
A Realistic Image Demo
https://gradio.app/guides/streaming-inputs
Additional Features - Streaming Inputs Guide
For some image streaming demos, like the one above, we don't need to display separate input and output components. Our app would look cleaner if we could just display the modified output stream. We can do so by just specifying the input image component as the output of the stream event. $code_streaming_filter_unified...
Unified Image Demos
https://gradio.app/guides/streaming-inputs
Additional Features - Streaming Inputs Guide
Your streaming function should be stateless. It should take the current input and return its corresponding output. However, there are cases where you may want to keep track of past inputs or outputs. For example, you may want to keep a buffer of the previous `k` inputs to improve the accuracy of your transcription demo...
Keeping track of past inputs or outputs
https://gradio.app/guides/streaming-inputs
Additional Features - Streaming Inputs Guide
For an end-to-end example of streaming from the webcam, see the object detection from webcam [guide](/main/guides/object-detection-from-webcam-with-webrtc).
End-to-End Examples
https://gradio.app/guides/streaming-inputs
Additional Features - Streaming Inputs Guide
**API endpoint names** When you create a Gradio application, the API endpoint names are automatically generated based on the function names. You can change this by using the `api_name` parameter in `gr.Interface` or `gr.ChatInterface`. If you are using Gradio `Blocks`, you can name each event listener, like this: ```...
Configuring the API Page
https://gradio.app/guides/view-api-page
Additional Features - View Api Page Guide
**Adding API endpoints** You can also add new API routes to your Gradio application that do not correspond to events in your UI. For example, in this Gradio application, we add a new route that adds numbers and slices a list: ```py import gradio as gr with gr.Blocks() as demo: with gr.Row(): input = gr...
Configuring the API Page
https://gradio.app/guides/view-api-page
Additional Features - View Api Page Guide
This API page not only lists all of the endpoints that can be used to query the Gradio app, but also shows the usage of both [the Gradio Python client](https://gradio.app/guides/getting-started-with-the-python-client/), and [the Gradio JavaScript client](https://gradio.app/guides/getting-started-with-the-js-client/). ...
The Clients
https://gradio.app/guides/view-api-page
Additional Features - View Api Page Guide
Instead of reading through the view API page, you can also use Gradio's built-in API recorder to generate the relevant code snippet. Simply click on the "API Recorder" button, use your Gradio app via the UI as you would normally, and then the API Recorder will generate the code using the Clients to recreate your all of...
The API Recorder 🪄
https://gradio.app/guides/view-api-page
Additional Features - View Api Page Guide
Next to the "Use via API" link, the footer has a **Runs** link, which opens a page at `<your-gradio-app-url>/gradio_api/runs` listing the runs made from this browser, grouped by endpoint. Each run shows its inputs, its outputs, how long the function took, and whether it succeeded. Clicking **Load run** puts a saved run...
Run History
https://gradio.app/guides/view-api-page
Additional Features - View Api Page Guide
hose code you would rather not edit. Runs made through the clients Calls made with the JavaScript client are recorded in the same way whenever that client runs in a browser, which is how a `gr.Server` app builds up a run history despite having no UI of its own. Pass `record_history: false` to opt a single client out:...
Run History
https://gradio.app/guides/view-api-page
Additional Features - View Api Page Guide
The API page also includes instructions on how to use the Gradio app as an Model Context Protocol (MCP) server, which is a standardized way to expose functions as tools so that they can be used by LLMs. ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/view-api-mcp.png) ...
MCP Server
https://gradio.app/guides/view-api-page
Additional Features - View Api Page Guide
You can access the complete OpenAPI (formerly Swagger) specification of your Gradio app's API at the endpoint `<your-gradio-app-url>/gradio_api/openapi.json`. The OpenAPI specification is a standardized, language-agnostic interface description for REST APIs that enables both humans and computers to discover and underst...
OpenAPI Specification
https://gradio.app/guides/view-api-page
Additional Features - View Api Page Guide
1. `GRADIO_SERVER_PORT` - **Description**: Specifies the port on which the Gradio app will run. - **Default**: `7860` - **Example**: ```bash export GRADIO_SERVER_PORT=8000 ``` 2. `GRADIO_SERVER_NAME` - **Description**: Defines the host name for the Gradio server. To make Gradio accessible from any IP address, ...
Key Environment Variables
https://gradio.app/guides/environment-variables
Additional Features - Environment Variables Guide
r the Gradio application. Useful if running Gradio [behind a reverse proxy](/guides/running-gradio-on-your-web-server-with-nginx). - **Default**: `""` - **Example**: ```sh export GRADIO_ROOT_PATH="/myapp" ``` 9. `GRADIO_SHARE` - **Description**: Enables or disables sharing the Gradio app. - **Default**: `"False...
Key Environment Variables
https://gradio.app/guides/environment-variables
Additional Features - Environment Variables Guide
the application will trust the `X-Forwarded-For` header from these IP addresses to determine the original IP address of the user making the request. This means that if you use the `gr.Request` [object's](https://www.gradio.app/docs/gradio/request) `client.host` property, it will correctly get the user's IP address ins...
Key Environment Variables
https://gradio.app/guides/environment-variables
Additional Features - Environment Variables Guide
e()`, `gr.ChatInterface()` or in `gr.Examples()`, Gradio will run your prediction function and save the results to disk. By default, this is in the `.gradio/cached_examples//` subdirectory within your app's working directory. You can customize the location of cached example files created by Gradio by setting the enviro...
Key Environment Variables
https://gradio.app/guides/environment-variables
Additional Features - Environment Variables Guide
e"` - **Options**: `"True"`, `"False"` - **Example**: ```sh export GRADIO_RESET_EXAMPLES_CACHE="True" ``` 20. `GRADIO_CHAT_FLAGGING_MODE` - **Description**: Controls whether users can flag messages in `gr.ChatInterface` applications. Similar to `GRADIO_FLAGGING_MODE` but specifically for chat interfaces. - **De...
Key Environment Variables
https://gradio.app/guides/environment-variables
Additional Features - Environment Variables Guide
*Options**: `"True"`, `"False"` - **Example**: ```sh export GRADIO_MCP_SERVER="True" ``` 24. `GRADIO_NUM_WORKERS` - **Description**: Number of multiple workers to launch in the background to offload traffic for file I/O and static assets from the main Gradio server. Only works when SSR mode is set. - **Default...
Key Environment Variables
https://gradio.app/guides/environment-variables
Additional Features - Environment Variables Guide
To set environment variables in your terminal, use the `export` command followed by the variable name and its value. For example: ```sh export GRADIO_SERVER_PORT=8000 ``` If you're using a `.env` file to manage your environment variables, you can add them like this: ```sh GRADIO_SERVER_PORT=8000 GRADIO_SERVER_NAME="...
How to Set Environment Variables
https://gradio.app/guides/environment-variables
Additional Features - Environment Variables Guide
Gradio can stream audio and video directly from your generator function. This lets your user hear your audio or see your video nearly as soon as it's `yielded` by your function. All you have to do is 1. Set `streaming=True` in your `gr.Audio` or `gr.Video` output component. 2. Write a python generator that yields the...
Streaming Media
https://gradio.app/guides/streaming-outputs
Additional Features - Streaming Outputs Guide
For an end-to-end example of streaming media, see the object detection from video [guide](/main/guides/object-detection-from-video) or the streaming AI-generated audio with [transformers](https://huggingface.co/docs/transformers/index) [guide](/main/guides/streaming-ai-generated-audio).
End-to-End Examples
https://gradio.app/guides/streaming-outputs
Additional Features - Streaming Outputs Guide
To add custom buttons to a component, pass a list of `gr.Button()` instances to the `buttons` parameter: ```python import gradio as gr refresh_btn = gr.Button("Refresh", variant="secondary", size="sm") clear_btn = gr.Button("Clear", variant="secondary", size="sm") textbox = gr.Textbox( value="Sample text", l...
Basic Usage
https://gradio.app/guides/custom-buttons
Additional Features - Custom Buttons Guide
Custom buttons work just like regular `gr.Button` components. You can connect them to Python functions or JavaScript functions using the `.click()` method: Python Functions ```python def refresh_data(): import random return f"Refreshed: {random.randint(1000, 9999)}" refresh_btn.click(refresh_data, outputs=te...
Connecting Button Events
https://gradio.app/guides/custom-buttons
Additional Features - Custom Buttons Guide
Here's a complete example showing custom buttons with both Python and JavaScript functions: $code_textbox_custom_buttons
Complete Example
https://gradio.app/guides/custom-buttons
Additional Features - Custom Buttons Guide
- Custom buttons appear in the component's toolbar, typically in the top-right corner - Only the `value` of the Button is used, other attributes like `icon` are not used. - Buttons are rendered in the order they appear in the `buttons` list - Built-in buttons (like "copy", "download") can be hidden by omitting them fro...
Notes
https://gradio.app/guides/custom-buttons
Additional Features - Custom Buttons Guide
By default, each event listener has its own queue, which handles one request at a time. This can be configured via two arguments: - `concurrency_limit`: This sets the maximum number of concurrent executions for an event listener. By default, the limit is 1 unless configured otherwise in `Blocks.queue()`. You can also ...
Configuring the Queue
https://gradio.app/guides/queuing
Additional Features - Queuing Guide
identified by `"gpu_queue"`. The queue can handle up to 2 concurrent requests at a time, as defined by the `concurrency_limit`. Notes - To ensure unlimited concurrency for an event listener, set `concurrency_limit=None`. This is useful if your function is calling e.g. an external API which handles the rate limiting...
Configuring the Queue
https://gradio.app/guides/queuing
Additional Features - Queuing Guide
Client side functions are ideal for updating component properties (like visibility, placeholders, interactive state, or styling). Here's a basic example: ```py import gradio as gr with gr.Blocks() as demo: with gr.Row() as row: btn = gr.Button("Hide this row") This function runs in the browser ...
When to Use Client Side Functions
https://gradio.app/guides/client-side-functions
Additional Features - Client Side Functions Guide
Client side functions have some important restrictions: * They can only update component properties (not values) * They cannot take any inputs Here are some functions that will work with `js=True`: ```py Simple property updates lambda: gr.Textbox(lines=4) Multiple component updates lambda: [gr.Textbox(lines=4), gr.B...
Limitations
https://gradio.app/guides/client-side-functions
Additional Features - Client Side Functions Guide
Here's a more complete example showing how client side functions can improve the user experience: $code_todo_list_js
Complete Example
https://gradio.app/guides/client-side-functions
Additional Features - Client Side Functions Guide
When you set `js=True`, Gradio: 1. Transpiles your Python function to JavaScript 2. Runs the function directly in the browser 3. Still sends the request to the server (for consistency and to handle any side effects) This provides immediate visual feedback while ensuring your application state remains consistent.
Behind the Scenes
https://gradio.app/guides/client-side-functions
Additional Features - Client Side Functions Guide
Gradio demos can be easily shared publicly by setting `share=True` in the `launch()` method. Like this: ```python import gradio as gr def greet(name): return "Hello " + name + "!" demo = gr.Interface(fn=greet, inputs="textbox", outputs="textbox") demo.launch(share=True) Share your demo with just 1 extra parame...
Sharing Demos
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
If you'd like to have a permanent link to your Gradio demo on the internet, use Hugging Face Spaces. [Hugging Face Spaces](http://huggingface.co/spaces/) provides the infrastructure to permanently host your machine learning model for free! After you have [created a free Hugging Face account](https://huggingface.co/joi...
Hosting on HF Spaces
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
You can add a button to your Gradio app that creates a unique URL you can use to share your app and all components **as they currently are** with others. This is useful for sharing unique and interesting generations from your application , or for saving a snapshot of your app at a particular point in time. To add a de...
Sharing Deep Links
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
Once you have hosted your app on Hugging Face Spaces (or on your own server), you may want to embed the demo on a different website, such as your blog or your portfolio. Embedding an interactive demo allows people to try out the machine learning model that you have built, without needing to download or install anything...
Embedding Hosted Spaces
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
=> { let v = obj.info.version; content = document.querySelector('.prose'); content.innerHTML = content.innerHTML.replaceAll("{GRADIO_VERSION}", v); }); </script> You can see examples of how web components look <a href="https://www.gradio.app">on the Gradio landing page</a>. You can also customize the appe...
Embedding Hosted Spaces
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
ple of how to use these attributes to create a Gradio app that does not lazy load and has an initial height of 0px. ```html <gradio-app space="gradio/Echocardiogram-Segmentation" eager="true" initial_height="0px" ></gradio-app> ``` Here's another example of how to use the `render` event. An event listener is used ...
Embedding Hosted Spaces
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
You can use almost any Gradio app as an API! In the footer of a Gradio app [like this one](https://huggingface.co/spaces/gradio/hello_world), you'll see a "Use via API" link. ![Use via API](https://github.com/gradio-app/gradio/blob/main/guides/assets/use_via_api.png?raw=true) This is a page that lists the endpoints t...
API Page
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
When a user makes a prediction to your app, you may need the underlying network request, in order to get the request headers (e.g. for advanced authentication), log the client's IP address, getting the query parameters, or for other reasons. Gradio supports this in a similar manner to FastAPI: simply add a function par...
Accessing the Network Request Directly
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
In some cases, you might have an existing FastAPI app, and you'd like to add a path for a Gradio demo. You can easily do this with `gradio.mount_gradio_app()`. Here's a complete example: $code_custom_path Note that this approach also allows you run your Gradio apps on custom paths (`http://localhost:8000/gradio` in ...
Mounting Within Another FastAPI App
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
Password-protected app You may wish to put an authentication page in front of your app to limit who can open your app. With the `auth=` keyword argument in the `launch()` method, you can provide a tuple with a username and password, or a list of acceptable username/password tuples; Here's an example that provides pass...
Authentication
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
Let's update the previous example to include a log out button: ```python import gradio as gr def update_message(request: gr.Request): return f"Welcome, {request.username}" with gr.Blocks() as demo: m = gr.Markdown() logout_button = gr.Button("Logout", link="/logout") demo.load(update_message, None, ...
Authentication
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
e. If you want to perform actions on behalf of the user (e.g. list user's private repos, create repo, etc.), you can retrieve the user token by adding a parameter of type `gr.OAuthToken`. You must define which scopes you will use in your Space metadata (see [documentation](https://huggingface.co/docs/hub/spaces-oauthsc...
Authentication
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
erence is that the `gr.OAuthProfile` or `gr.OAuthToken` will be `None` in the corresponding functions. OAuth (with external providers) It is also possible to authenticate with external OAuth providers (e.g. Google OAuth) in your Gradio apps. To do this, first mount your Gradio app within a FastAPI app ([as discussed...
Authentication
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
entials on the [Google Developer Console](https://console.cloud.google.com/project)): ```python import os from authlib.integrations.starlette_client import OAuth, OAuthError from fastapi import FastAPI, Depends, Request from starlette.config import Config from starlette.responses import RedirectResponse from starlette...
Authentication
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
direct_uri = urlunparse(urlparse(str(redirect_uri))._replace(scheme='https')) return await oauth.google.authorize_redirect(request, redirect_uri) @app.route('/auth') async def auth(request: Request): try: access_token = await oauth.google.authorize_access_token(request) except OAuthError: r...
Authentication
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
Gradio apps can function as MCP (Model Context Protocol) servers, allowing LLMs to use your app's functions as tools. By simply setting `mcp_server=True` in the `.launch()` method, Gradio automatically converts your app's functions into MCP tools that can be called by MCP clients like Claude Desktop, Cursor, or Cline. ...
MCP Servers
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
When publishing your app publicly, and making it available via API or via MCP server, you might want to set rate limits to prevent users from abusing your app. You can identify users using their IP address (using the `gr.Request` object [as discussed above](accessing-the-network-request-directly)) or, if they are logge...
Rate Limits
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
By default, Gradio collects certain analytics to help us better understand the usage of the `gradio` library. This includes the following information: * What environment the Gradio app is running on (e.g. Colab Notebook, Hugging Face Spaces) * What input/output components are being used in the Gradio app * Whether the...
Analytics
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App Guide
[Progressive Web Apps (PWAs)](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps) are web applications that are regular web pages or websites, but can appear to the user like installable platform-specific applications. Gradio apps can be easily served as PWAs by setting the `pwa=True` parameter in the `...
Progressive Web App (PWA)
https://gradio.app/guides/sharing-your-app
Additional Features - Sharing Your App 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 w...
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 t...
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.duplic...
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 P...
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 pag...
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 se...
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'...
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...
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", res...
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 th...
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 Fal...
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 = clie...
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. Whe...
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 TypeSc...
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 y...
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://huggin...
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://hug...
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(); co...
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 pag...
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 sh...
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 response...
Using events
https://gradio.app/guides/getting-started-with-the-js-client
Gradio Clients And Lite - Getting Started With The Js Client Guide
The event interface also allows you to get the status of the running job by instantiating the client with the `events` options passing `status` and `data` as an array: ```ts import { Client } from "@gradio/client"; const app = await Client.connect("abidlabs/en2fr", { events: ["status", "data"] }); ``` This ensures...
Status
https://gradio.app/guides/getting-started-with-the-js-client
Gradio Clients And Lite - Getting Started With The Js Client Guide
The job instance also has a `.cancel()` method that cancels jobs that have been queued but not started. For example, if you run: ```js import { Client } from "@gradio/client"; const app = await Client.connect("abidlabs/en2fr"); const job_one = app.submit("/predict", ["Hello"]); const job_two = app.submit("/predict", ...
Cancelling Jobs
https://gradio.app/guides/getting-started-with-the-js-client
Gradio Clients And Lite - Getting Started With The Js Client Guide