EllieKini/Herta
Audio-to-Audio • Updated
text stringlengths 0 2k | heading1 stringlengths 3 79 | source_page_url stringclasses 185
values | source_page_title stringclasses 185
values |
|---|---|---|---|
The main Client class for the Python client. This class is used to connect
to a remote Gradio app and call its API endpoints.
| Description | https://gradio.app/docs/python-client/client | Python Client - Client Docs |
from gradio_client import Client
client = Client("abidlabs/whisper-large-v2") connecting to a Hugging Face Space
client.predict("test.mp4", api_name="/predict")
>> What a nice recording! returns the result of the remote API call
client = Client("https://bec81a83-5b5c-471e.gradio.live") connecting to a temporary Gradio share URL
job = client.submit("hello", api_name="/predict") runs the prediction in a background thread
job.result()
>> 49 returns the result of the remote API call (blocking call)
| Example usage | https://gradio.app/docs/python-client/client | Python Client - Client Docs |
Parameters ▼
src: str
either the name of the Hugging Face Space to load, (e.g. "abidlabs/whisper-
large-v2") or the full URL (including "http" or "https") of the hosted Gradio
app to load (e.g. "http://mydomain.com/app" or
"https://bec81a83-5b5c-471e.gradio.live/").
token: str | None
default `= None`
optional Hugging Face token to use to access private Spaces. By default, the
locally saved token is used if there is one. Find your tokens here:
https://huggingface.co/settings/tokens.
max_workers: int
default `= 40`
maximum number of thread workers that can be used to make requests to the
remote Gradio app simultaneously.
verbose: bool
default `= True`
whether the client should print statements to the console.
auth: tuple[str, str] | None
default `= None`
httpx_kwargs: dict[str, Any] | None
default `= None`
additional keyword arguments to pass to `httpx.Client`, `httpx.stream`,
`httpx.get` and `httpx.post`. This can be used to set timeouts, proxies, http
auth, etc.
headers: dict[str, str] | None
default `= None`
additional headers to send to the remote Gradio app on every request. By
default only the HF authorization and user-agent headers are sent. This
parameter will override the default headers if they have the same keys.
download_files: str | Path | Literal[False]
default `= "/tmp/gradio"`
directory where the client should download output files on the local machine
from the remote API. By default, uses the value of the GRADIO_TEMP_DIR
environment variable which, if not set by the user, is a temporary directory
on your machine. If False, the client does not download files and returns a
FileData dataclass object with the filepath on the remote machine instead.
ssl_verify: bool
default `= True`
if False, skips certificate validation which allows the client to connect to
Gradio apps that are using self-signed ce | Initialization | https://gradio.app/docs/python-client/client | Python Client - Client Docs |
n the remote machine instead.
ssl_verify: bool
default `= True`
if False, skips certificate validation which allows the client to connect to
Gradio apps that are using self-signed certificates.
analytics_enabled: bool
default `= True`
Whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED
environment variable or default to True.
| Initialization | https://gradio.app/docs/python-client/client | Python Client - Client Docs |
Description
Event listeners allow you to respond to user interactions with the UI
components you've defined in a Gradio Blocks app. When a user interacts with
an element, such as changing a slider value or uploading an image, a function
is called.
Supported Event Listeners
The Client component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listeners
Client.predict(fn, ···)
Calls the Gradio API and returns the result (this is a blocking call).
Arguments can be provided as positional arguments or as keyword arguments
(latter is recommended). <br>
Client.submit(fn, ···)
Creates and returns a Job object which calls the Gradio API in a background
thread. The job can be used to retrieve the status and result of the remote
API call. Arguments can be provided as positional arguments or as keyword
arguments (latter is recommended). <br>
Client.view_api(fn, ···)
Prints the usage info for the API. If the Gradio app has multiple API
endpoints, the usage info for each endpoint will be printed separately. If
return_format="dict" the info is returned in dictionary format, as shown in
the example below. <br>
Client.duplicate(fn, ···)
Duplicates a Hugging Face Space under your account and returns a Client object
for the new Space. No duplication is created if the Space already exists in
your account (to override this, provide a new name for the new Space using
`to_id`). To use this method, you must provide an `token` or be logged in via
the Hugging Face Hub CLI. <br> The new Space will be private by default and
use the same hardware as the original Space. This can be changed by using the
`private` and `hardware` parameters. For hardware upgrades (beyond the basic
CPU tier), you may be required to provide billing information on Hugging Face:
<https://huggingface.co/settings/billing> <br>
Event Parameters
Par | Event Listeners | https://gradio.app/docs/python-client/client | Python Client - Client Docs |
eters. For hardware upgrades (beyond the basic
CPU tier), you may be required to provide billing information on Hugging Face:
<https://huggingface.co/settings/billing> <br>
Event Parameters
Parameters ▼
args: <class 'inspect._empty'>
The positional arguments to pass to the remote API endpoint. The order of the
arguments must match the order of the inputs in the Gradio app.
api_name: str | None
default `= None`
The name of the API endpoint to call starting with a leading slash, e.g.
"/predict". Does not need to be provided if the Gradio app has only one named
API endpoint.
fn_index: int | None
default `= None`
As an alternative to api_name, this parameter takes the index of the API
endpoint to call, e.g. 0. Both api_name and fn_index can be provided, but if
they conflict, api_name will take precedence.
headers: dict[str, str] | None
default `= None`
Additional headers to send to the remote Gradio app on this request. This
parameter will overrides the headers provided in the Client constructor if
they have the same keys.
kwargs: <class 'inspect._empty'>
The keyword arguments to pass to the remote API endpoint.
| Event Listeners | https://gradio.app/docs/python-client/client | Python Client - Client Docs |
**Stream From a Gradio app in 5 lines**
Use the `submit` method to get a job you can iterate over.
In python:
from gradio_client import Client
client = Client("gradio/llm_stream")
for result in client.submit("What's the best UI framework in Python?"):
print(result)
In typescript:
import { Client } from "@gradio/client";
const client = await Client.connect("gradio/llm_stream")
const job = client.submit("/predict", {"text": "What's the best UI framework in Python?"})
for await (const msg of job) console.log(msg.data)
**Use the same keyword arguments as the app**
In the examples below, the upstream app has a function with parameters called
`message`, `system_prompt`, and `tokens`. We can see that the client `predict`
call uses the same arguments.
In python:
from gradio_client import Client
client = Client("http://127.0.0.1:7860/")
result = client.predict(
message="Hello!!",
system_prompt="You are helpful AI.",
tokens=10,
api_name="/chat"
)
print(result)
In typescript:
import { Client } from "@gradio/client";
const client = await Client.connect("http://127.0.0.1:7860/");
const result = await client.predict("/chat", {
message: "Hello!!",
system_prompt: "Hello!!",
tokens: 10,
});
console.log(result.data);
**Better Error Messages**
If something goes wrong in the upstream app, the client will raise the same
exception as the app provided that `show_error=True` in the original app's
`launch()` function, or it's a `gr.Error` exception.
| Ergonomic API 💆 | https://gradio.app/docs/python-client/version-1-release | Python Client - Version 1 Release Docs |
Anything you can do in the UI, you can do with the client:
* 🔐Authentication
* 🛑 Job Cancelling
* ℹ️ Access Queue Position and API
* 📕 View the API information
Here's an example showing how to display the queue position of a pending job:
from gradio_client import Client
client = Client("gradio/diffusion_model")
job = client.submit("A cute cat")
while not job.done():
status = job.status()
print(f"Current in position {status.rank} out of {status.queue_size}")
| Transparent Design 🪟 | https://gradio.app/docs/python-client/version-1-release | Python Client - Version 1 Release Docs |
The client can run from pretty much any python and javascript environment
(node, deno, the browser, Service Workers).
Here's an example using the client from a Flask server using gevent:
from gevent import monkey
monkey.patch_all()
from gradio_client import Client
from flask import Flask, send_file
import time
app = Flask(__name__)
imageclient = Client("gradio/diffusion_model")
@app.route("/gen")
def gen():
result = imageclient.predict(
"A cute cat",
api_name="/predict"
)
return send_file(result)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
| Portable Design ⛺️ | https://gradio.app/docs/python-client/version-1-release | Python Client - Version 1 Release Docs |
Changes
**Python**
* The `serialize` argument of the `Client` class was removed and has no effect.
* The `upload_files` argument of the `Client` was removed.
* All filepaths must be wrapped in the `handle_file` method. For example, `caption = client.predict(handle_file('./dog.jpg'))`.
* The `output_dir` argument was removed. It is not specified in the `download_files` argument.
**Javascript**
The client has been redesigned entirely. It was refactored from a function
into a class. An instance can now be constructed by awaiting the `connect`
method.
const app = await Client.connect("gradio/whisper")
The app variable has the same methods as the python class (`submit`,
`predict`, `view_api`, `duplicate`).
| v1.0 Migration Guide and Breaking | https://gradio.app/docs/python-client/version-1-release | Python Client - Version 1 Release Docs |
A Job is a wrapper over the Future class that represents a prediction call
that has been submitted by the Gradio client. This class is not meant to be
instantiated directly, but rather is created by the Client.submit() method.
A Job object includes methods to get the status of the prediction call, as
well to get the outputs of the prediction call. Job objects are also iterable,
and can be used in a loop to get the outputs of prediction calls as they
become available for generator endpoints.
| Description | https://gradio.app/docs/python-client/job | Python Client - Job Docs |
Parameters ▼
future: Future
The future object that represents the prediction call, created by the
Client.submit() method
communicator: Communicator | None
default `= None`
The communicator object that is used to communicate between the client and the
background thread running the job
verbose: bool
default `= True`
Whether to print any status-related messages to the console
space_id: str | None
default `= None`
The space ID corresponding to the Client object that created this Job object
| Initialization | https://gradio.app/docs/python-client/job | Python Client - Job Docs |
Description
Event listeners allow you to respond to user interactions with the UI
components you've defined in a Gradio Blocks app. When a user interacts with
an element, such as changing a slider value or uploading an image, a function
is called.
Supported Event Listeners
The Job component supports the following event listeners. Each event listener
takes the same parameters, which are listed in the Event Parameters table
below.
Listeners
Job.result(fn, ···)
Return the result of the call that the future represents. Raises
CancelledError: If the future was cancelled, TimeoutError: If the future
didn't finish executing before the given timeout, and Exception: If the call
raised then that exception will be raised. <br>
Job.outputs(fn, ···)
Returns a list containing the latest outputs from the Job. <br> If the
endpoint has multiple output components, the list will contain a tuple of
results. Otherwise, it will contain the results without storing them in
tuples. <br> For endpoints that are queued, this list will contain the final
job output even if that endpoint does not use a generator function. <br>
Job.status(fn, ···)
Returns the latest status update from the Job in the form of a StatusUpdate
object, which contains the following fields: code, rank, queue_size, success,
time, eta, and progress_data. <br> progress_data is a list of updates emitted
by the gr.Progress() tracker of the event handler. Each element of the list
has the following fields: index, length, unit, progress, desc. If the event
handler does not have a gr.Progress() tracker, the progress_data field will be
None. <br>
Event Parameters
Parameters ▼
timeout: float | None
default `= None`
The number of seconds to wait for the result if the future isn't done. If
None, then there is no limit on the wait time.
| Event Listeners | https://gradio.app/docs/python-client/job | Python Client - Job Docs |
ZeroGPU
ZeroGPU spaces are rate-limited to ensure that a single user does not hog all
of the available GPUs. The limit is controlled by a special token that the
Hugging Face Hub infrastructure adds to all incoming requests to Spaces. This
token is a request header called `X-IP-Token` and its value changes depending
on the user who makes a request to the ZeroGPU space.
Let’s say you want to create a space (Space A) that uses a ZeroGPU space
(Space B) programmatically. Normally, calling Space B from Space A with the
Gradio Python client would quickly exhaust Space B’s rate limit, as all the
requests to the ZeroGPU space would be missing the `X-IP-Token` request header
and would therefore be treated as unauthenticated.
In order to avoid this, we need to extract the `X-IP-Token` of the user using
Space A before we call Space B programmatically. Where possible, specifically
in the case of functions that are passed into event listeners directly, Gradio
automatically extracts the `X-IP-Token` from the incoming request and passes
it into the Gradio Client. But if the Client is instantiated outside of such a
function, then you may need to pass in the token manually.
How to do this will be explained in the following section.
| Explaining Rate Limits for | https://gradio.app/docs/python-client/using-zero-gpu-spaces | Python Client - Using Zero Gpu Spaces Docs |
Token
In the following hypothetical example, when a user presses enter in the
textbox, the `generate()` function is called, which calls a second function,
`text_to_image()`. Because the Gradio Client is being instantiated indirectly,
in `text_to_image()`, we will need to extract their token from the `X-IP-
Token` header of the incoming request. We will use this header when
constructing the gradio client.
import gradio as gr
from gradio_client import Client
def text_to_image(prompt, request: gr.Request):
x_ip_token = request.headers['x-ip-token']
client = Client("hysts/SDXL", headers={"x-ip-token": x_ip_token})
img = client.predict(prompt, api_name="/predict")
return img
def generate(prompt, request: gr.Request):
prompt = prompt[:300]
return text_to_image(prompt, request)
with gr.Blocks() as demo:
image = gr.Image()
prompt = gr.Textbox(max_lines=1)
prompt.submit(generate, [prompt], [image])
demo.launch()
| Avoiding Rate Limits by Manually Passing an IP | https://gradio.app/docs/python-client/using-zero-gpu-spaces | Python Client - Using Zero Gpu Spaces Docs |
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.9 or higher** :
$ pip install --upgrade gradio_client
| Installation | https://gradio.app/docs/python-client/introduction | Python Client - Introduction Docs |
Spaces
Start by connecting instantiating a `Client` object and connecting it to a
Gradio app that is running on Hugging Face Spaces.
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
`hf_token` parameter. You can get your HF token here:
<https://huggingface.co/settings/tokens>
from gradio_client import Client
client = Client("abidlabs/my-private-space", hf_token="...")
| Connecting to a Gradio App on Hugging Face | https://gradio.app/docs/python-client/introduction | Python Client - Introduction Docs |
use
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):
import os
from gradio_client import Client, file
HF_TOKEN = os.environ.get("HF_TOKEN")
client = Client.duplicate("abidlabs/whisper", hf_token=HF_TOKEN)
client.predict(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 | https://gradio.app/docs/python-client/introduction | Python Client - Introduction Docs |
app
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:
from gradio_client import Client
client = Client("https://bec81a83-5b5c-471e.gradio.live")
| Connecting a general Gradio | https://gradio.app/docs/python-client/introduction | Python Client - Introduction Docs |
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:
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/docs/python-client/introduction | Python Client - Introduction Docs |
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.

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/docs/python-client/introduction | Python Client - Introduction Docs |
The simplest way to make a prediction is simply to call the `.predict()`
function with the appropriate arguments:
from gradio_client import Client
client = Client("abidlabs/en2fr", api_name='/predict')
client.predict("Hello")
>> Bonjour
If there are multiple parameters, then you should pass them as separate
arguments to `.predict()`, like this:
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:
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.
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:
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.file()`. This takes care of
uploading the file to the Gradio server and ensures that the file is
preprocessed correctly:
from gradio_client import Client, file
client = Client("abidlabs/whisper")
client.predict(
| Making a prediction | https://gradio.app/docs/python-client/introduction | Python Client - Introduction Docs |
to the Gradio server and ensures that the file is
preprocessed correctly:
from gradio_client import Client, file
client = Client("abidlabs/whisper")
client.predict(
audio=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/docs/python-client/introduction | Python Client - Introduction Docs |
Oe 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:
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/docs/python-client/introduction | Python Client - Introduction Docs |
Alternatively, one can add one or more callbacks to perform actions after the
job has completed running, like this:
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/docs/python-client/introduction | Python Client - Introduction Docs |
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).
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/docs/python-client/introduction | Python Client - Introduction Docs |
The `Job` class also has a `.cancel()` instance method that cancels jobs that
have been queued but not started. For example, if you run:
client = Client("abidlabs/whisper")
job1 = client.submit(file("audio_sample1.wav"))
job2 = client.submit(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/docs/python-client/introduction | Python Client - Introduction Docs |
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()`:
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:
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.
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/docs/python-client/introduction | Python Client - Introduction Docs |
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:
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:
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/docs/python-client/introduction | Python Client - Introduction Docs |
`gradio-rs` is a Gradio Client in Rust built by
[@JacobLinCool](https://github.com/JacobLinCool). You can find the repo
[here](https://github.com/JacobLinCool/gradio-rs), and more in depth API
documentation [here](https://docs.rs/gradio/latest/gradio/).
| Introduction | https://gradio.app/docs/third-party-clients/rust-client | Third Party Clients - Rust Client Docs |
Here is an example of using BS-RoFormer model to separate vocals and
background music from an audio file.
use gradio::{PredictionInput, Client, ClientOptions};
[tokio::main]
async fn main() {
if std::env::args().len() < 2 {
println!("Please provide an audio file path as an argument");
std::process::exit(1);
}
let args: Vec<String> = std::env::args().collect();
let file_path = &args[1];
println!("File: {}", file_path);
let client = Client::new("JacobLinCool/vocal-separation", ClientOptions::default())
.await
.unwrap();
let output = client
.predict(
"/separate",
vec![
PredictionInput::from_file(file_path),
PredictionInput::from_value("BS-RoFormer"),
],
)
.await
.unwrap();
println!(
"Vocals: {}",
output[0].clone().as_file().unwrap().url.unwrap()
);
println!(
"Background: {}",
output[1].clone().as_file().unwrap().url.unwrap()
);
}
You can find more examples [here](https://github.com/JacobLinCool/gradio-
rs/tree/main/examples).
| Usage | https://gradio.app/docs/third-party-clients/rust-client | Third Party Clients - Rust Client Docs |
cargo install gradio
gr --help
Take [stabilityai/stable-
diffusion-3-medium](https://huggingface.co/spaces/stabilityai/stable-
diffusion-3-medium) HF Space as an example:
> gr list stabilityai/stable-diffusion-3-medium
API Spec for stabilityai/stable-diffusion-3-medium:
/infer
Parameters:
prompt ( str )
negative_prompt ( str )
seed ( float ) numeric value between 0 and 2147483647
randomize_seed ( bool )
width ( float ) numeric value between 256 and 1344
height ( float ) numeric value between 256 and 1344
guidance_scale ( float ) numeric value between 0.0 and 10.0
num_inference_steps ( float ) numeric value between 1 and 50
Returns:
Result ( filepath )
Seed ( float ) numeric value between 0 and 2147483647
> gr run stabilityai/stable-diffusion-3-medium infer 'Rusty text "AI & CLI" on the snow.' '' 0 true 1024 1024 5 28
Result: https://stabilityai-stable-diffusion-3-medium.hf.space/file=/tmp/gradio/5735ca7775e05f8d56d929d8f57b099a675c0a01/image.webp
Seed: 486085626
For file input, simply use the file path as the argument:
gr run hf-audio/whisper-large-v3 predict 'test-audio.wav' 'transcribe'
output: " Did you know you can try the coolest model on your command line?"
| Command Line Interface | https://gradio.app/docs/third-party-clients/rust-client | Third Party Clients - Rust Client Docs |
Gradio applications support programmatic requests from many environments:
* The [Python Client](/docs/python-client): `gradio-client` allows you to make requests from Python environments.
* The [JavaScript Client](/docs/js-client): `@gradio/client` allows you to make requests in TypeScript from the browser or server-side.
* You can also query gradio apps [directly from cURL](/guides/querying-gradio-apps-with-curl).
| Gradio Clients | https://gradio.app/docs/third-party-clients/introduction | Third Party Clients - Introduction Docs |
We also encourage the development and use of third party clients built by
the community:
* [Rust Client](/docs/third-party-clients/rust-client): `gradio-rs` built by [@JacobLinCool](https://github.com/JacobLinCool) allows you to make requests in Rust.
* [Powershell Client](https://github.com/rrg92/powershai): `powershai` built by [@rrg92](https://github.com/rrg92) allows you to make requests to Gradio apps directly from Powershell. See [here for documentation](https://github.com/rrg92/powershai/blob/main/docs/en-US/providers/HUGGING-FACE.md)
| Community Clients | https://gradio.app/docs/third-party-clients/introduction | Third Party Clients - Introduction Docs |
Load a chat interface from an OpenAI API chat compatible endpoint.
| Description | https://gradio.app/docs/gradio/load_chat | Gradio - Load_Chat Docs |
import gradio as gr
demo = gr.load_chat("http://localhost:11434/v1", model="deepseek-r1")
demo.launch()
| Example Usage | https://gradio.app/docs/gradio/load_chat | Gradio - Load_Chat Docs |
Parameters ▼
base_url: str
The base URL of the endpoint, e.g. "http://localhost:11434/v1/"
model: str
The name of the model you are loading, e.g. "llama3.2"
token: str | None
default `= None`
The API token or a placeholder string if you are using a local model, e.g.
"ollama"
file_types: Literal['text_encoded', 'image'] | list[Literal['text_encoded', 'image']] | None
default `= "text_encoded"`
The file types allowed to be uploaded by the user. "text_encoded" allows
uploading any text-encoded file (which is simply appended to the prompt), and
"image" adds image upload support. Set to None to disable file uploads.
system_message: str | None
default `= None`
The system message to use for the conversation, if any.
streaming: bool
default `= True`
Whether the response should be streamed.
kwargs: <class 'inspect._empty'>
Additional keyword arguments to pass into ChatInterface for customization.
[Creating a Chatbot Fast](../../guides/creating-a-chatbot-fast)
| Initialization | https://gradio.app/docs/gradio/load_chat | Gradio - Load_Chat Docs |
Set the static paths to be served by the gradio app.
Static files are are served directly from the file system instead of being
copied. They are served to users with The Content-Disposition HTTP header set
to "inline" when sending these files to users. This indicates that the file
should be displayed directly in the browser window if possible. This function
is useful when you want to serve files that you know will not be modified
during the lifetime of the gradio app (like files used in gr.Examples). By
setting static paths, your app will launch faster and it will consume less
disk space. Calling this function will set the static paths for all gradio
applications defined in the same interpreter session until it is called again
or the session ends.
| Description | https://gradio.app/docs/gradio/set_static_paths | Gradio - Set_Static_Paths Docs |
import gradio as gr
Paths can be a list of strings or pathlib.Path objects
corresponding to filenames or directories.
gr.set_static_paths(paths=["test/test_files/"])
The example files and the default value of the input
will not be copied to the gradio cache and will be served directly.
demo = gr.Interface(
lambda s: s.rotate(45),
gr.Image(value="test/test_files/cheetah1.jpg", type="pil"),
gr.Image(),
examples=["test/test_files/bus.png"],
)
demo.launch()
| Example Usage | https://gradio.app/docs/gradio/set_static_paths | Gradio - Set_Static_Paths Docs |
Parameters ▼
paths: str | pathlib.Path | list[str | pathlib.Path]
filepath or list of filepaths or directory names to be served by the gradio
app. If it is a directory name, ALL files located within that directory will
be considered static and not moved to the gradio cache. This also means that
ALL files in that directory will be accessible over the network.
[File Access](../../guides/file-access)
| Initialization | https://gradio.app/docs/gradio/set_static_paths | Gradio - Set_Static_Paths Docs |
A Gradio request object that can be used to access the request headers,
cookies, query parameters and other information about the request from within
the prediction function. The class is a thin wrapper around the
fastapi.Request class. Attributes of this class include: `headers`, `client`,
`query_params`, `session_hash`, and `path_params`. If auth is enabled, the
`username` attribute can be used to get the logged in user. In some
environments, the dict-like attributes (e.g. `requests.headers`,
`requests.query_params`) of this class are automatically converted to
dictionaries, so we recommend converting them to dictionaries before accessing
attributes for consistent behavior in different environments.
| Description | https://gradio.app/docs/gradio/request | Gradio - Request Docs |
import gradio as gr
def echo(text, request: gr.Request):
if request:
print("Request headers dictionary:", request.headers)
print("IP address:", request.client.host)
print("Query parameters:", dict(request.query_params))
print("Session hash:", request.session_hash)
return text
io = gr.Interface(echo, "textbox", "textbox").launch()
| Example Usage | https://gradio.app/docs/gradio/request | Gradio - Request Docs |
Parameters ▼
request: fastapi.Request | None
default `= None`
A fastapi.Request
username: str | None
default `= None`
The username of the logged in user (if auth is enabled)
session_hash: str | None
default `= None`
The session hash of the current session. It is unique for each page load.
| Initialization | https://gradio.app/docs/gradio/request | Gradio - Request Docs |
request_ip_headers
| Demos | https://gradio.app/docs/gradio/request | Gradio - Request Docs |
Creates a file explorer component that allows users to browse files on the
machine hosting the Gradio app. As an input component, it also allows users to
select files to be used as input to a function, while as an output component,
it displays selected files.
| Description | https://gradio.app/docs/gradio/fileexplorer | Gradio - Fileexplorer Docs |
**Using FileExplorer as an input component.**
How FileExplorer will pass its value to your function:
Type: `list[str] | str | None`
Passes the selected file or directory as a `str` path (relative to `root`) or
`list[str}` depending on `file_count`
Example Code
import gradio as gr
def predict(
value: list[str] | str | None
):
process value from the FileExplorer component
return "prediction"
interface = gr.Interface(predict, gr.FileExplorer(), gr.Textbox())
interface.launch()
**Using FileExplorer as an output component**
How FileExplorer expects you to return a value:
Type: `str | list[str] | None`
Expects function to return a `str` path to a file, or `list[str]` consisting
of paths to files.
Example Code
import gradio as gr
def predict(text) -> str | list[str] | None
process value to return to the FileExplorer component
return value
interface = gr.Interface(predict, gr.Textbox(), gr.FileExplorer())
interface.launch()
| Behavior | https://gradio.app/docs/gradio/fileexplorer | Gradio - Fileexplorer Docs |
Parameters ▼
glob: str
default `= "**/*"`
The glob-style pattern used to select which files to display, e.g. "*" to
match all files, "*.png" to match all .png files, "**/*.txt" to match any .txt
file in any subdirectory, etc. The default value matches all files and folders
recursively. See the Python glob documentation at
https://docs.python.org/3/library/glob.html for more information.
value: str | list[str] | Callable | None
default `= None`
The file (or list of files, depending on the `file_count` parameter) to show
as "selected" when the component is first loaded. If a callable is provided,
it will be called when the app loads to set the initial value of the
component. If not provided, no files are shown as selected.
file_count: Literal['single', 'multiple']
default `= "multiple"`
Whether to allow single or multiple files to be selected. If "single", the
component will return a single absolute file path as a string. If "multiple",
the component will return a list of absolute file paths as a list of strings.
root_dir: str | Path
default `= "."`
Path to root directory to select files from. If not provided, defaults to
current working directory. Raises ValueError if the directory does not exist.
ignore_glob: str | None
default `= None`
The glob-style, case-sensitive pattern that will be used to exclude files from
the list. For example, "*.py" will exclude all .py files from the list. See
the Python glob documentation at https://docs.python.org/3/library/glob.html
for more information.
label: str | I18nData | None
default `= None`
the label for this component. Appears above the component and is also used as
the header if there are a table of examples for this component. If None and
used in a `gr.Interface`, the label will be the name of the parameter this
component is assigned to.
every: Timer | float | None
default `= None`
Continously calls | Initialization | https://gradio.app/docs/gradio/fileexplorer | Gradio - Fileexplorer Docs |
onent. If None and
used in a `gr.Interface`, the label will be the name of the parameter this
component is assigned to.
every: Timer | float | None
default `= None`
Continously calls `value` to recalculate it if `value` is a function (has no
effect otherwise). Can provide a Timer whose tick resets `value`, or a float
that provides the regular interval for the reset Timer.
inputs: Component | list[Component] | set[Component] | None
default `= None`
Components that are used as inputs to calculate `value` if `value` is a
function (has no effect otherwise). `value` is recalculated any time the
inputs change.
show_label: bool | None
default `= None`
if True, will display label.
container: bool
default `= True`
If True, will place the component in a container - providing some extra
padding around the border.
scale: int | None
default `= None`
relative size compared to adjacent Components. For example if Components A and
B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide
as B. Should be an integer. scale applies in Rows, and to top-level Components
in Blocks where fill_height=True.
min_width: int
default `= 160`
minimum pixel width, will wrap if not sufficient screen space to satisfy this
value. If a certain scale value results in this Component being narrower than
min_width, the min_width parameter will be respected first.
height: int | str | None
default `= None`
The maximum height of the file component, specified in pixels if a number is
passed, or in CSS units if a string is passed. If more files are uploaded than
can fit in the height, a scrollbar will appear.
max_height: int | str | None
default `= 500`
min_height: int | str | None
default `= None`
interactive: bool | None
default `= None`
if True, will allow users to select file(s); if False, will only display
file | Initialization | https://gradio.app/docs/gradio/fileexplorer | Gradio - Fileexplorer Docs |
min_height: int | str | None
default `= None`
interactive: bool | None
default `= None`
if True, will allow users to select file(s); if False, will only display
files. If not provided, this is inferred based on whether the component is
used as an input or output.
visible: bool | Literal['hidden']
default `= True`
If False, component will be hidden. If "hidden", component will be visually
hidden and not take up space in the layout but still exist in the DOM
elem_id: str | None
default `= None`
An optional string that is assigned as the id of this component in the HTML
DOM. Can be used for targeting CSS styles.
elem_classes: list[str] | str | None
default `= None`
An optional list of strings that are assigned as the classes of this component
in the HTML DOM. Can be used for targeting CSS styles.
render: bool
default `= True`
If False, component will not render be rendered in the Blocks context. Should
be used if the intention is to assign event listeners now but render the
component later.
key: int | str | tuple[int | str, ...] | None
default `= None`
in a gr.render, Components with the same key across re-renders are treated as
the same component, not a new component. Properties set in 'preserved_by_key'
are not reset across a re-render.
preserved_by_key: list[str] | str | None
default `= "value"`
A list of parameters from this component's constructor. Inside a gr.render()
function, if a component is re-rendered with the same key, these (and only
these) parameters will be preserved in the UI (if they have been changed by
the user or an event listener) instead of re-rendered based on the values
provided during constructor.
buttons: list[Button] | None
default `= None`
A list of gr.Button() instances to show in the top right corner of the
component. Custom buttons will appear in the toolbar with their configured | Initialization | https://gradio.app/docs/gradio/fileexplorer | Gradio - Fileexplorer Docs |
buttons: list[Button] | None
default `= None`
A list of gr.Button() instances to show in the top right corner of the
component. Custom buttons will appear in the toolbar with their configured
icon and/or label, and clicking them will trigger any .click() events
registered on the button.
| Initialization | https://gradio.app/docs/gradio/fileexplorer | Gradio - Fileexplorer Docs |
Shortcuts
gradio.FileExplorer
Interface String Shortcut `"fileexplorer"`
Initialization Uses default values
| Shortcuts | https://gradio.app/docs/gradio/fileexplorer | Gradio - Fileexplorer Docs |
Description
Event listeners allow you to respond to user interactions with the UI
components you've defined in a Gradio Blocks app. When a user interacts with
an element, such as changing a slider value or uploading an image, a function
is called.
Supported Event Listeners
The FileExplorer component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listeners
FileExplorer.change(fn, ···)
Triggered when the value of the FileExplorer changes either because of user
input (e.g. a user types in a textbox) OR because of a function update (e.g.
an image receives a value from the output of an event trigger). See `.input()`
for a listener that is only triggered by user input.
FileExplorer.input(fn, ···)
This listener is triggered when the user changes the value of the
FileExplorer.
FileExplorer.select(fn, ···)
Event listener for when the user selects or deselects the FileExplorer. Uses
event data gradio.SelectData to carry `value` referring to the label of the
FileExplorer, and `selected` to refer to state of the FileExplorer. See
<https://www.gradio.app/main/docs/gradio/eventdata> for more details.
Event Parameters
Parameters ▼
fn: Callable | None | Literal['decorator']
default `= "decorator"`
the function to call when this event is triggered. Often a machine learning
model's prediction function. Each parameter of the function corresponds to one
input component, and the function should return a single value or a tuple of
values, with each element in the tuple corresponding to one output component.
inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as inputs. If the function takes no inputs,
this should be an empty list.
outputs: Component | BlockContext | list[Comp | Event Listeners | https://gradio.app/docs/gradio/fileexplorer | Gradio - Fileexplorer Docs |
text] | None
default `= None`
List of gradio.components to use as inputs. If the function takes no inputs,
this should be an empty list.
outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as outputs. If the function returns no
outputs, this should be an empty list.
api_name: str | None
default `= None`
defines how the endpoint appears in the API docs. Can be a string or None. If
set to a string, the endpoint will be exposed in the API docs with the given
name. If None (default), the name of the function will be used as the API
endpoint.
api_description: str | None | Literal[False]
default `= None`
Description of the API endpoint. Can be a string, None, or False. If set to a
string, the endpoint will be exposed in the API docs with the given
description. If None, the function's docstring will be used as the API
endpoint description. If False, then no description will be displayed in the
API docs.
scroll_to_output: bool
default `= False`
If True, will scroll to output component on completion
show_progress: Literal['full', 'minimal', 'hidden']
default `= "full"`
how to show the progress animation while event is running: "full" shows a
spinner which covers the output component area as well as a runtime display in
the upper right corner, "minimal" only shows the runtime display, "hidden"
shows no progress animation at all
show_progress_on: Component | list[Component] | None
default `= None`
Component or list of components to show the progress animation on. If None,
will show the progress animation on all of the output components.
queue: bool
default `= True`
If True, will place the request on the queue, if the queue has been enabled.
If False, will not put this event on the queue, even if the queue has been
enabled. If None, will use the queu | Event Listeners | https://gradio.app/docs/gradio/fileexplorer | Gradio - Fileexplorer Docs |
lt `= True`
If True, will place the request on the queue, if the queue has been enabled.
If False, will not put this event on the queue, even if the queue has been
enabled. If None, will use the queue setting of the gradio app.
batch: bool
default `= False`
If True, then the function should process a batch of inputs, meaning that it
should accept a list of input values for each parameter. The lists should be
of equal length (and be up to length `max_batch_size`). The function is then
*required* to return a tuple of lists (even if there is only 1 output
component), with each list in the tuple corresponding to one output component.
max_batch_size: int
default `= 4`
Maximum number of inputs to batch together if this is called from the queue
(only relevant if batch=True)
preprocess: bool
default `= True`
If False, will not run preprocessing of component data before running 'fn'
(e.g. leaving it as a base64 string if this method is called with the `Image`
component).
postprocess: bool
default `= True`
If False, will not run postprocessing of component data before returning 'fn'
output to the browser.
cancels: dict[str, Any] | list[dict[str, Any]] | None
default `= None`
A list of other events to cancel when this listener is triggered. For example,
setting cancels=[click_event] will cancel the click_event, where click_event
is the return value of another components .click method. Functions that have
not yet run (or generators that are iterating) will be cancelled, but
functions that are currently running will be allowed to finish.
trigger_mode: Literal['once', 'multiple', 'always_last'] | None
default `= None`
If "once" (default for all events except `.change()`) would not allow any
submissions while an event is pending. If set to "multiple", unlimited
submissions are allowed while pending, and "always_last" (default for
`.change()` and `.key_up()` events) would al | Event Listeners | https://gradio.app/docs/gradio/fileexplorer | Gradio - Fileexplorer Docs |
not allow any
submissions while an event is pending. If set to "multiple", unlimited
submissions are allowed while pending, and "always_last" (default for
`.change()` and `.key_up()` events) would allow a second submission after the
pending event is complete.
js: str | Literal[True] | None
default `= None`
Optional frontend js method to run before running 'fn'. Input arguments for js
method are values of 'inputs' and 'outputs', return should be a list of values
for output components.
concurrency_limit: int | None | Literal['default']
default `= "default"`
If set, this is the maximum number of this event that can be running
simultaneously. Can be set to None to mean no concurrency_limit (any number of
this event can be running simultaneously). Set to "default" to use the default
concurrency limit (defined by the `default_concurrency_limit` parameter in
`Blocks.queue()`, which itself is 1 by default).
concurrency_id: str | None
default `= None`
If set, this is the id of the concurrency group. Events with the same
concurrency_id will be limited by the lowest set concurrency_limit.
api_visibility: Literal['public', 'private', 'undocumented']
default `= "public"`
controls the visibility and accessibility of this endpoint. Can be "public"
(shown in API docs and callable by clients), "private" (hidden from API docs
and not callable by the Gradio client libraries), or "undocumented" (hidden
from API docs but callable by clients and via gr.load). If fn is None,
api_visibility will automatically be set to "private".
time_limit: int | None
default `= None`
stream_every: float
default `= 0.5`
key: int | str | tuple[int | str, ...] | None
default `= None`
A unique key for this event listener to be used in @gr.render(). If set, this
value identifies an event as identical across re-renders when the key is
identical.
validator: Callable | None | Event Listeners | https://gradio.app/docs/gradio/fileexplorer | Gradio - Fileexplorer Docs |
ique key for this event listener to be used in @gr.render(). If set, this
value identifies an event as identical across re-renders when the key is
identical.
validator: Callable | None
default `= None`
Optional validation function to run before the main function. If provided,
this function will be executed first with queue=False, and only if it
completes successfully will the main function be called. The validator
receives the same inputs as the main function and should return a
`gr.validate()` for each input value.
| Event Listeners | https://gradio.app/docs/gradio/fileexplorer | Gradio - Fileexplorer Docs |
Creates a chatbot that displays user-submitted messages and responses.
Supports a subset of Markdown including bold, italics, code, tables. Also
supports audio/video/image files, which are displayed in the Chatbot, and
other kinds of files which are displayed as links. This component is usually
used as an output component.
| Description | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs |
The Chatbot component accepts a list of messages, where each message is a
dictionary with `role` and `content` keys. This format is compatible with the
message format expected by most LLM APIs (OpenAI, Claude, HuggingChat, etc.),
making it easy to pipe model outputs directly into the component.
The `role` key should be either `'user'` or `'assistant'`, and the `content`
key can be a string (rendered as markdown/HTML) or a Gradio component (useful
for displaying files, images, plots, and other media).
As an example:
import gradio as gr
history = [
{"role": "assistant", "content": "I am happy to provide you that report and plot."},
{"role": "assistant", "content": gr.Plot(value=make_plot_from_file('quaterly_sales.txt'))}
]
with gr.Blocks() as demo:
gr.Chatbot(history)
demo.launch()
For convenience, you can use the `ChatMessage` dataclass so that your text
editor can give you autocomplete hints and typechecks.
import gradio as gr
history = [
gr.ChatMessage(role="assistant", content="How can I help you?"),
gr.ChatMessage(role="user", content="Can you make me a plot of quarterly sales?"),
gr.ChatMessage(role="assistant", content="I am happy to provide you that report and plot.")
]
with gr.Blocks() as demo:
gr.Chatbot(history)
demo.launch()
| Behavior | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs |
Parameters ▼
value: list[MessageDict | Message] | Callable | None
default `= None`
Default list of messages to show in chatbot, where each message is of the
format {"role": "user", "content": "Help me."}. Role can be one of "user",
"assistant", or "system". Content should be either text, or media passed as a
Gradio component, e.g. {"content": gr.Image("lion.jpg")}. If a function is
provided, the function will be called each time the app loads to set the
initial value of this component.
label: str | I18nData | None
default `= None`
the label for this component. Appears above the component and is also used as
the header if there are a table of examples for this component. If None and
used in a `gr.Interface`, the label will be the name of the parameter this
component is assigned to.
every: Timer | float | None
default `= None`
Continously calls `value` to recalculate it if `value` is a function (has no
effect otherwise). Can provide a Timer whose tick resets `value`, or a float
that provides the regular interval for the reset Timer.
inputs: Component | list[Component] | set[Component] | None
default `= None`
Components that are used as inputs to calculate `value` if `value` is a
function (has no effect otherwise). `value` is recalculated any time the
inputs change.
show_label: bool | None
default `= None`
if True, will display label.
container: bool
default `= True`
If True, will place the component in a container - providing some extra
padding around the border.
scale: int | None
default `= None`
relative size compared to adjacent Components. For example if Components A and
B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide
as B. Should be an integer. scale applies in Rows, and to top-level Components
in Blocks where fill_height=True.
min_width: int
default `= 160`
minimum pixel width, will wrap if | Initialization | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs |
ide
as B. Should be an integer. scale applies in Rows, and to top-level Components
in Blocks where fill_height=True.
min_width: int
default `= 160`
minimum pixel width, will wrap if not sufficient screen space to satisfy this
value. If a certain scale value results in this Component being narrower than
min_width, the min_width parameter will be respected first.
visible: bool | Literal['hidden']
default `= True`
If False, component will be hidden. If "hidden", component will be visually
hidden and not take up space in the layout but still exist in the DOM
elem_id: str | None
default `= None`
An optional string that is assigned as the id of this component in the HTML
DOM. Can be used for targeting CSS styles.
elem_classes: list[str] | str | None
default `= None`
An optional list of strings that are assigned as the classes of this component
in the HTML DOM. Can be used for targeting CSS styles.
autoscroll: bool
default `= True`
If True, will automatically scroll to the bottom of the textbox when the value
changes, unless the user scrolls up. If False, will not scroll to the bottom
of the textbox when the value changes.
render: bool
default `= True`
If False, component will not render be rendered in the Blocks context. Should
be used if the intention is to assign event listeners now but render the
component later.
key: int | str | tuple[int | str, ...] | None
default `= None`
in a gr.render, Components with the same key across re-renders are treated as
the same component, not a new component. Properties set in 'preserved_by_key'
are not reset across a re-render.
preserved_by_key: list[str] | str | None
default `= "value"`
A list of parameters from this component's constructor. Inside a gr.render()
function, if a component is re-rendered with the same key, these (and only
these) parameters will be preserved in the UI (if they hav | Initialization | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs |
parameters from this component's constructor. Inside a gr.render()
function, if a component is re-rendered with the same key, these (and only
these) parameters will be preserved in the UI (if they have been changed by
the user or an event listener) instead of re-rendered based on the values
provided during constructor.
height: int | str | None
default `= 400`
The height of the component, specified in pixels if a number is passed, or in
CSS units if a string is passed. If messages exceed the height, the component
will scroll.
resizable: bool
default `= False`
If True, the user of the Gradio app can resize the chatbot by dragging the
bottom right corner.
max_height: int | str | None
default `= None`
The maximum height of the component, specified in pixels if a number is
passed, or in CSS units if a string is passed. If messages exceed the height,
the component will scroll. If messages are shorter than the height, the
component will shrink to fit the content. Will not have any effect if `height`
is set and is smaller than `max_height`.
min_height: int | str | None
default `= None`
The minimum height of the component, specified in pixels if a number is
passed, or in CSS units if a string is passed. If messages exceed the height,
the component will expand to fit the content. Will not have any effect if
`height` is set and is larger than `min_height`.
editable: Literal['user', 'all'] | None
default `= None`
Allows user to edit messages in the chatbot. If set to "user", allows editing
of user messages. If set to "all", allows editing of assistant messages as
well.
latex_delimiters: list[dict[str, str | bool]] | None
default `= None`
A list of dicts of the form {"left": open delimiter (str), "right": close
delimiter (str), "display": whether to display in newline (bool)} that will be
used to render LaTeX expressions. If not provided, `latex_delimiters` is set
to `[{ " | Initialization | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs |
pen delimiter (str), "right": close
delimiter (str), "display": whether to display in newline (bool)} that will be
used to render LaTeX expressions. If not provided, `latex_delimiters` is set
to `[{ "left": "$$", "right": "$$", "display": True }]`, so only expressions
enclosed in $$ delimiters will be rendered as LaTeX, and in a new line. Pass
in an empty list to disable LaTeX rendering. For more information, see the
[KaTeX documentation](https://katex.org/docs/autorender.html).
rtl: bool
default `= False`
If True, sets the direction of the rendered text to right-to-left. Default is
False, which renders text left-to-right.
buttons: list[Literal['share', 'copy', 'copy_all'] | Button] | None
default `= None`
A list of buttons to show in the top right corner of the component. Valid
options are "share", "copy", "copy_all", or a gr.Button() instance. The
"share" button allows the user to share outputs to Hugging Face Spaces
Discussions. The "copy" button makes a copy button appear next to each
individual chatbot message. The "copy_all" button appears at the component
level and allows the user to copy all chatbot messages. Custom gr.Button()
instances will appear in the toolbar with their configured icon and/or label,
and clicking them will trigger any .click() events registered on the button.
By default, "share" and "copy_all" buttons are shown.
watermark: str | None
default `= None`
If provided, this text will be appended to the end of messages copied from the
chatbot, after a blank line. Useful for indicating that the message is
generated by an AI model.
avatar_images: tuple[str | Path | None, str | Path | None] | None
default `= None`
Tuple of two avatar image paths or URLs for user and bot (in that order). Pass
None for either the user or bot image to skip. Must be within the working
directory of the Gradio app or an external URL.
sanitize_html: bool
default `= True`
If False, w | Initialization | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs |
rder). Pass
None for either the user or bot image to skip. Must be within the working
directory of the Gradio app or an external URL.
sanitize_html: bool
default `= True`
If False, will disable HTML sanitization for chatbot messages. This is not
recommended, as it can lead to security vulnerabilities.
render_markdown: bool
default `= True`
If False, will disable Markdown rendering for chatbot messages.
feedback_options: list[str] | tuple[str, ...] | None
default `= ('Like', 'Dislike')`
A list of strings representing the feedback options that will be displayed to
the user. The exact case-sensitive strings "Like" and "Dislike" will render as
thumb icons, but any other choices will appear under a separate flag icon.
feedback_value: list[str | None] | None
default `= None`
A list of strings representing the feedback state for entire chat. Only works
when type="messages". Each entry in the list corresponds to that assistant
message, in order, and the value is the feedback given (e.g. "Like",
"Dislike", or any custom feedback option) or None if no feedback was given for
that message.
line_breaks: bool
default `= True`
If True (default), will enable Github-flavored Markdown line breaks in chatbot
messages. If False, single new lines will be ignored. Only applies if
`render_markdown` is True.
layout: Literal['panel', 'bubble'] | None
default `= None`
If "panel", will display the chatbot in a llm style layout. If "bubble", will
display the chatbot with message bubbles, with the user and bot messages on
alterating sides. Will default to "bubble".
placeholder: str | None
default `= None`
a placeholder message to display in the chatbot when it is empty. Centered
vertically and horizontally in the Chatbot. Supports Markdown and HTML. If
None, no placeholder is displayed.
examples: list[ExampleMessage] | None
default `= None`
A list of ex | Initialization | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs |
ered
vertically and horizontally in the Chatbot. Supports Markdown and HTML. If
None, no placeholder is displayed.
examples: list[ExampleMessage] | None
default `= None`
A list of example messages to display in the chatbot before any user/assistant
messages are shown. Each example should be a dictionary with an optional
"text" key representing the message that should be populated in the Chatbot
when clicked, an optional "files" key, whose value should be a list of files
to populate in the Chatbot, an optional "icon" key, whose value should be a
filepath or URL to an image to display in the example box, and an optional
"display_text" key, whose value should be the text to display in the example
box. If "display_text" is not provided, the value of "text" will be displayed.
allow_file_downloads: bool
default `= True`
If True, will show a download button for chatbot messages that contain media.
Defaults to True.
group_consecutive_messages: bool
default `= True`
If True, will display consecutive messages from the same role in the same
bubble. If False, will display each message in a separate bubble. Defaults to
True.
allow_tags: list[str] | bool
default `= True`
If a list of tags is provided, these tags will be preserved in the output
chatbot messages, even if `sanitize_html` is `True`. For example, if this list
is ["thinking"], the tags `<thinking>` and `</thinking>` will not be removed.
If True, all custom tags (non-standard HTML tags) will be preserved. If False,
no tags will be preserved. Default value is 'True'.
reasoning_tags: list[tuple[str, str]] | None
default `= None`
If provided, a list of tuples of (open_tag, close_tag) strings. Any text
between these tags will be extracted and displayed in a separate collapsible
message with metadata={"title": "Reasoning"}. For example, [("<thinking>",
"</thinking>")] will extract content between <thinking> and </thinking> tags.
Each th | Initialization | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs |
and displayed in a separate collapsible
message with metadata={"title": "Reasoning"}. For example, [("<thinking>",
"</thinking>")] will extract content between <thinking> and </thinking> tags.
Each thinking block will be displayed as a separate collapsible message before
the main response. If None (default), no automatic extraction is performed.
like_user_message: bool
default `= False`
If True, will show like/dislike buttons for user messages as well. Defaults to
False.
| Initialization | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs |
Shortcuts
gradio.Chatbot
Interface String Shortcut `"chatbot"`
Initialization Uses default values
| Shortcuts | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs |
**Displaying Thoughts/Tool Usage**
You can provide additional metadata regarding any tools used to generate the
response. This is useful for displaying the thought process of LLM agents. For
example,
def generate_response(history):
history.append(
ChatMessage(role="assistant",
content="The weather API says it is 20 degrees Celcius in New York.",
metadata={"title": "🛠️ Used tool Weather API"})
)
return history
Would be displayed as following:

You can also specify metadata with a plain python dictionary,
def generate_response(history):
history.append(
dict(role="assistant",
content="The weather API says it is 20 degrees Celcius in New York.",
metadata={"title": "🛠️ Used tool Weather API"})
)
return history
**Using Gradio Components Inside`gr.Chatbot`**
The `Chatbot` component supports using many of the core Gradio components
(such as `gr.Image`, `gr.Plot`, `gr.Audio`, and `gr.HTML`) inside of the
chatbot. Simply include one of these components as the `content` of a message.
Here’s an example:
import gradio as gr
def load():
return [
{"role": "user", "content": "Can you show me some media?"},
{"role": "assistant", "content": "Here's an audio clip:"},
{"role": "assistant", "content": gr.Audio("https://github.com/gradio-app/gradio/raw/main/gradio/media_assets/audio/audio_sample.wav")},
{"role": "assistant", "content": "And here's a video:"},
{"role": "assistant", "content": gr.Video("https://github.com/gradio-app/gradio/raw/main/gradio/media_assets/videos/world.mp4")}
]
with gr.Blocks() as demo:
chatbot = gr.Chatbot()
button = gr.Button("Load | Examples | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs |
deo("https://github.com/gradio-app/gradio/raw/main/gradio/media_assets/videos/world.mp4")}
]
with gr.Blocks() as demo:
chatbot = gr.Chatbot()
button = gr.Button("Load audio and video")
button.click(load, None, chatbot)
demo.launch()
| Examples | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs |
chatbot_simplechatbot_streamingchatbot_with_toolschatbot_core_components
| Demos | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs |
Description
Event listeners allow you to respond to user interactions with the UI
components you've defined in a Gradio Blocks app. When a user interacts with
an element, such as changing a slider value or uploading an image, a function
is called.
Supported Event Listeners
The Chatbot component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listeners
Chatbot.change(fn, ···)
Triggered when the value of the Chatbot changes either because of user input
(e.g. a user types in a textbox) OR because of a function update (e.g. an
image receives a value from the output of an event trigger). See `.input()`
for a listener that is only triggered by user input.
Chatbot.select(fn, ···)
Event listener for when the user selects or deselects the Chatbot. Uses event
data gradio.SelectData to carry `value` referring to the label of the Chatbot,
and `selected` to refer to state of the Chatbot. See
<https://www.gradio.app/main/docs/gradio/eventdata> for more details.
Chatbot.like(fn, ···)
This listener is triggered when the user likes/dislikes from within the
Chatbot. This event has EventData of type gradio.LikeData that carries
information, accessible through LikeData.index and LikeData.value. See
EventData documentation on how to use this event data.
Chatbot.retry(fn, ···)
This listener is triggered when the user clicks the retry button in the
chatbot message.
Chatbot.undo(fn, ···)
This listener is triggered when the user clicks the undo button in the chatbot
message.
Chatbot.example_select(fn, ···)
This listener is triggered when the user clicks on an example from within the
Chatbot. This event has SelectData of type gradio.SelectData that carries
information, accessible through SelectData.index and SelectData.value. See
SelectData documentation on how to use this event data.
| Event Listeners | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs |
s event has SelectData of type gradio.SelectData that carries
information, accessible through SelectData.index and SelectData.value. See
SelectData documentation on how to use this event data.
Chatbot.option_select(fn, ···)
This listener is triggered when the user clicks on an option from within the
Chatbot. This event has SelectData of type gradio.SelectData that carries
information, accessible through SelectData.index and SelectData.value. See
SelectData documentation on how to use this event data.
Chatbot.clear(fn, ···)
This listener is triggered when the user clears the Chatbot using the clear
button for the component.
Chatbot.copy(fn, ···)
This listener is triggered when the user copies content from the Chatbot. Uses
event data gradio.CopyData to carry information about the copied content. See
EventData documentation on how to use this event data
Chatbot.edit(fn, ···)
This listener is triggered when the user edits the Chatbot (e.g. image) using
the built-in editor.
Event Parameters
Parameters ▼
fn: Callable | None | Literal['decorator']
default `= "decorator"`
the function to call when this event is triggered. Often a machine learning
model's prediction function. Each parameter of the function corresponds to one
input component, and the function should return a single value or a tuple of
values, with each element in the tuple corresponding to one output component.
inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as inputs. If the function takes no inputs,
this should be an empty list.
outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as outputs. If the function returns no
outputs, this should be an empty list.
api_ | Event Listeners | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs |
ckContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as outputs. If the function returns no
outputs, this should be an empty list.
api_name: str | None
default `= None`
defines how the endpoint appears in the API docs. Can be a string or None. If
set to a string, the endpoint will be exposed in the API docs with the given
name. If None (default), the name of the function will be used as the API
endpoint.
api_description: str | None | Literal[False]
default `= None`
Description of the API endpoint. Can be a string, None, or False. If set to a
string, the endpoint will be exposed in the API docs with the given
description. If None, the function's docstring will be used as the API
endpoint description. If False, then no description will be displayed in the
API docs.
scroll_to_output: bool
default `= False`
If True, will scroll to output component on completion
show_progress: Literal['full', 'minimal', 'hidden']
default `= "full"`
how to show the progress animation while event is running: "full" shows a
spinner which covers the output component area as well as a runtime display in
the upper right corner, "minimal" only shows the runtime display, "hidden"
shows no progress animation at all
show_progress_on: Component | list[Component] | None
default `= None`
Component or list of components to show the progress animation on. If None,
will show the progress animation on all of the output components.
queue: bool
default `= True`
If True, will place the request on the queue, if the queue has been enabled.
If False, will not put this event on the queue, even if the queue has been
enabled. If None, will use the queue setting of the gradio app.
batch: bool
default `= False`
If True, then the function should process a batch of inputs, meaning that it
should accept a list of input values for each parameter. | Event Listeners | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs |
f the gradio app.
batch: bool
default `= False`
If True, then the function should process a batch of inputs, meaning that it
should accept a list of input values for each parameter. The lists should be
of equal length (and be up to length `max_batch_size`). The function is then
*required* to return a tuple of lists (even if there is only 1 output
component), with each list in the tuple corresponding to one output component.
max_batch_size: int
default `= 4`
Maximum number of inputs to batch together if this is called from the queue
(only relevant if batch=True)
preprocess: bool
default `= True`
If False, will not run preprocessing of component data before running 'fn'
(e.g. leaving it as a base64 string if this method is called with the `Image`
component).
postprocess: bool
default `= True`
If False, will not run postprocessing of component data before returning 'fn'
output to the browser.
cancels: dict[str, Any] | list[dict[str, Any]] | None
default `= None`
A list of other events to cancel when this listener is triggered. For example,
setting cancels=[click_event] will cancel the click_event, where click_event
is the return value of another components .click method. Functions that have
not yet run (or generators that are iterating) will be cancelled, but
functions that are currently running will be allowed to finish.
trigger_mode: Literal['once', 'multiple', 'always_last'] | None
default `= None`
If "once" (default for all events except `.change()`) would not allow any
submissions while an event is pending. If set to "multiple", unlimited
submissions are allowed while pending, and "always_last" (default for
`.change()` and `.key_up()` events) would allow a second submission after the
pending event is complete.
js: str | Literal[True] | None
default `= None`
Optional frontend js method to run before running 'fn'. Input arguments for js
metho | Event Listeners | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs |
d submission after the
pending event is complete.
js: str | Literal[True] | None
default `= None`
Optional frontend js method to run before running 'fn'. Input arguments for js
method are values of 'inputs' and 'outputs', return should be a list of values
for output components.
concurrency_limit: int | None | Literal['default']
default `= "default"`
If set, this is the maximum number of this event that can be running
simultaneously. Can be set to None to mean no concurrency_limit (any number of
this event can be running simultaneously). Set to "default" to use the default
concurrency limit (defined by the `default_concurrency_limit` parameter in
`Blocks.queue()`, which itself is 1 by default).
concurrency_id: str | None
default `= None`
If set, this is the id of the concurrency group. Events with the same
concurrency_id will be limited by the lowest set concurrency_limit.
api_visibility: Literal['public', 'private', 'undocumented']
default `= "public"`
controls the visibility and accessibility of this endpoint. Can be "public"
(shown in API docs and callable by clients), "private" (hidden from API docs
and not callable by the Gradio client libraries), or "undocumented" (hidden
from API docs but callable by clients and via gr.load). If fn is None,
api_visibility will automatically be set to "private".
time_limit: int | None
default `= None`
stream_every: float
default `= 0.5`
key: int | str | tuple[int | str, ...] | None
default `= None`
A unique key for this event listener to be used in @gr.render(). If set, this
value identifies an event as identical across re-renders when the key is
identical.
validator: Callable | None
default `= None`
Optional validation function to run before the main function. If provided,
this function will be executed first with queue=False, and only if it
completes successfully will the main function | Event Listeners | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs |
= None`
Optional validation function to run before the main function. If provided,
this function will be executed first with queue=False, and only if it
completes successfully will the main function be called. The validator
receives the same inputs as the main function and should return a
`gr.validate()` for each input value.
| Event Listeners | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs |
Helper Classes | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs | |
gradio.ChatMessage(···)
Description
A dataclass that represents a message in the Chatbot component (with
type="messages"). The only required field is `content`. The value of
`gr.Chatbot` is a list of these dataclasses.
Parameters ▼
content: MessageContent | list[MessageContent]
The content of the message. Can be a string, a file dict, a gradio component,
or a list of these types to group these messages together.
role: Literal['user', 'assistant', 'system']
default `= "assistant"`
The role of the message, which determines the alignment of the message in the
chatbot. Can be "user", "assistant", or "system". Defaults to "assistant".
metadata: MetadataDict
default `= _HAS_DEFAULT_FACTORY_CLASS()`
The metadata of the message, which is used to display intermediate thoughts /
tool usage. Should be a dictionary with the following keys: "title" (required
to display the thought), and optionally: "id" and "parent_id" (to nest
thoughts), "duration" (to display the duration of the thought), "status" (to
display the status of the thought).
options: list[OptionDict]
default `= _HAS_DEFAULT_FACTORY_CLASS()`
The options of the message. A list of Option objects, which are dictionaries
with the following keys: "label" (the text to display in the option), and
optionally "value" (the value to return when the option is selected if
different from the label).
| ChatMessage | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs |
A typed dictionary to represent metadata for a message in the Chatbot
component. An instance of this dictionary is used for the `metadata` field in
a ChatMessage when the chat message should be displayed as a thought.
Keys ▼
title: str
The title of the 'thought' message. Only required field.
id: int | str
The ID of the message. Only used for nested thoughts. Nested thoughts can be
nested by setting the parent_id to the id of the parent thought.
parent_id: int | str
The ID of the parent message. Only used for nested thoughts.
log: str
A string message to display next to the thought title in a subdued font.
duration: float
The duration of the message in seconds. Appears next to the thought title in a
subdued font inside a parentheses.
status: Literal['pending', 'done']
if set to `'pending'`, a spinner appears next to the thought title and the
accordion is initialized open. If `status` is `'done'`, the thought accordion
is initialized closed. If `status` is not provided, the thought accordion is
initialized open and no spinner is displayed.
| MetadataDict | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs |
A typed dictionary to represent an option in a ChatMessage. A list of these
dictionaries is used for the `options` field in a ChatMessage.
Keys ▼
value: str
The value to return when the option is selected.
label: str
The text to display in the option, if different from the value.
[Chatbot Specific Events](../../guides/chatbot-specific-
events/)[Conversational Chatbot](../../guides/conversational-
chatbot/)[Creating A Chatbot Fast](../../guides/creating-a-chatbot-
fast/)[Creating A Custom Chatbot With Blocks](../../guides/creating-a-custom-
chatbot-with-blocks/)[Agents And Tool Usage](../../guides/agents-and-tool-
usage/)
| OptionDict | https://gradio.app/docs/gradio/chatbot | Gradio - Chatbot Docs |
The gr.KeyUpData class is a subclass of gr.EventData that specifically
carries information about the `.key_up()` event. When gr.KeyUpData is added as
a type hint to an argument of an event listener method, a gr.KeyUpData object
will automatically be passed as the value of that argument. The attributes of
this object contains information about the event that triggered the listener.
| Description | https://gradio.app/docs/gradio/keyupdata | Gradio - Keyupdata Docs |
import gradio as gr
def test(value, key_up_data: gr.KeyUpData):
return {
"component value": value,
"input value": key_up_data.input_value,
"key": key_up_data.key
}
with gr.Blocks() as demo:
d = gr.Dropdown(["abc", "def"], allow_custom_value=True)
t = gr.JSON()
d.key_up(test, d, t)
demo.launch()
| Example Usage | https://gradio.app/docs/gradio/keyupdata | Gradio - Keyupdata Docs |
Parameters ▼
key: str
The key that was pressed.
input_value: str
The displayed value in the input textbox after the key was pressed. This may
be different than the `value` attribute of the component itself, as the
`value` attribute of some components (e.g. Dropdown) are not updated until the
user presses Enter.
| Attributes | https://gradio.app/docs/gradio/keyupdata | Gradio - Keyupdata Docs |
dropdown_key_up
| Demos | https://gradio.app/docs/gradio/keyupdata | Gradio - Keyupdata Docs |
The gr.CopyData class is a subclass of gr.EventData that specifically
carries information about the `.copy()` event. When gr.CopyData is added as a
type hint to an argument of an event listener method, a gr.CopyData object
will automatically be passed as the value of that argument. The attributes of
this object contains information about the event that triggered the listener.
| Description | https://gradio.app/docs/gradio/copydata | Gradio - Copydata Docs |
import gradio as gr
def on_copy(copy_data: gr.CopyData):
return f"Copied text: {copy_data.value}"
with gr.Blocks() as demo:
textbox = gr.Textbox("Hello World!")
copied = gr.Textbox()
textbox.copy(on_copy, None, copied)
demo.launch()
| Example Usage | https://gradio.app/docs/gradio/copydata | Gradio - Copydata Docs |
Parameters ▼
value: Any
The value that was copied.
| Attributes | https://gradio.app/docs/gradio/copydata | Gradio - Copydata Docs |
Creates an image component that can be used to upload images (as an input)
or display images (as an output).
| Description | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
**Using Image as an input component.**
How Image will pass its value to your function:
Type: `np.ndarray | PIL.Image.Image | str | None`
Passes the uploaded image as a `numpy.array`, `PIL.Image` or `str` filepath
depending on `type`.
Example Code
import gradio as gr
def predict(
value: np.ndarray | PIL.Image.Image | str | None
):
process value from the Image component
return "prediction"
interface = gr.Interface(predict, gr.Image(), gr.Textbox())
interface.launch()
**Using Image as an output component**
How Image expects you to return a value:
Type: `np.ndarray | PIL.Image.Image | str | Path | None`
Expects a `numpy.array`, `PIL.Image`, or `str` or `pathlib.Path` filepath to
an image which is displayed.
Example Code
import gradio as gr
def predict(text) -> np.ndarray | PIL.Image.Image | str | Path | None
process value to return to the Image component
return value
interface = gr.Interface(predict, gr.Textbox(), gr.Image())
interface.launch()
| Behavior | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
Parameters ▼
value: str | PIL.Image.Image | np.ndarray | Callable | None
default `= None`
A `PIL.Image`, `numpy.array`, `pathlib.Path`, or `str` filepath or URL for the
default value that Image component is going to take. If a function is
provided, the function will be called each time the app loads to set the
initial value of this component.
format: str
default `= "webp"`
File format (e.g. "png" or "gif"). Used to save image if it does not already
have a valid format (e.g. if the image is being returned to the frontend as a
numpy array or PIL Image). The format should be supported by the PIL library.
Applies both when this component is used as an input or output. This parameter
has no effect on SVG files.
height: int | str | None
default `= None`
The height of the component, specified in pixels if a number is passed, or in
CSS units if a string is passed. This has no effect on the preprocessed image
file or numpy array, but will affect the displayed image.
width: int | str | None
default `= None`
The width of the component, specified in pixels if a number is passed, or in
CSS units if a string is passed. This has no effect on the preprocessed image
file or numpy array, but will affect the displayed image.
image_mode: Literal['1', 'L', 'P', 'RGB', 'RGBA', 'CMYK', 'YCbCr', 'LAB', 'HSV', 'I', 'F'] | None
default `= "RGB"`
The pixel format and color depth that the image should be loaded and
preprocessed as. "RGB" will load the image as a color image, or "L" as black-
and-white. See https://pillow.readthedocs.io/en/stable/handbook/concepts.html
for other supported image modes and their meaning. This parameter has no
effect on SVG or GIF files. If set to None, the image_mode will be inferred
from the image file type (e.g. "RGBA" for a .png image, "RGB" in most other
cases).
sources: list[Literal['upload', 'webcam', 'clipboard']] | Literal['upload', 'webcam', 'clipboa | Initialization | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
erred
from the image file type (e.g. "RGBA" for a .png image, "RGB" in most other
cases).
sources: list[Literal['upload', 'webcam', 'clipboard']] | Literal['upload', 'webcam', 'clipboard'] | None
default `= None`
List of sources for the image. "upload" creates a box where user can drop an
image file, "webcam" allows user to take snapshot from their webcam,
"clipboard" allows users to paste an image from the clipboard. If None,
defaults to ["upload", "webcam", "clipboard"] if streaming is False, otherwise
defaults to ["webcam"].
type: Literal['numpy', 'pil', 'filepath']
default `= "numpy"`
The format the image is converted before being passed into the prediction
function. "numpy" converts the image to a numpy array with shape (height,
width, 3) and values from 0 to 255, "pil" converts the image to a PIL image
object, "filepath" passes a str path to a temporary file containing the image.
To support animated GIFs in input, the `type` should be set to "filepath" or
"pil". To support SVGs, the `type` should be set to "filepath".
label: str | I18nData | None
default `= None`
the label for this component. Appears above the component and is also used as
the header if there are a table of examples for this component. If None and
used in a `gr.Interface`, the label will be the name of the parameter this
component is assigned to.
every: Timer | float | None
default `= None`
Continously calls `value` to recalculate it if `value` is a function (has no
effect otherwise). Can provide a Timer whose tick resets `value`, or a float
that provides the regular interval for the reset Timer.
inputs: Component | list[Component] | set[Component] | None
default `= None`
Components that are used as inputs to calculate `value` if `value` is a
function (has no effect otherwise). `value` is recalculated any time the
inputs change.
show_label: bool | None
default `= None`
if True, will disp | Initialization | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
calculate `value` if `value` is a
function (has no effect otherwise). `value` is recalculated any time the
inputs change.
show_label: bool | None
default `= None`
if True, will display label.
buttons: list[Literal['download', 'share', 'fullscreen'] | Button] | None
default `= None`
A list of buttons to show in the corner of the component. Valid options are
"download", "share", "fullscreen", or a gr.Button() instance. The "download"
button allows the user to download the image. The "share" button allows the
user to share to Hugging Face Spaces Discussions. The "fullscreen" button
allows the user to view in fullscreen mode. Custom gr.Button() instances will
appear in the toolbar with their configured icon and/or label, and clicking
them will trigger any .click() events registered on the button. by default,
all of the built-in buttons are shown.
container: bool
default `= True`
If True, will place the component in a container - providing some extra
padding around the border.
scale: int | None
default `= None`
relative size compared to adjacent Components. For example if Components A and
B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide
as B. Should be an integer. scale applies in Rows, and to top-level Components
in Blocks where fill_height=True.
min_width: int
default `= 160`
minimum pixel width, will wrap if not sufficient screen space to satisfy this
value. If a certain scale value results in this Component being narrower than
min_width, the min_width parameter will be respected first.
interactive: bool | None
default `= None`
if True, will allow users to upload and edit an image; if False, can only be
used to display images. If not provided, this is inferred based on whether the
component is used as an input or output.
visible: bool | Literal['hidden']
default `= True`
If False, component will be hidden. If "hidd | Initialization | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
ovided, this is inferred based on whether the
component is used as an input or output.
visible: bool | Literal['hidden']
default `= True`
If False, component will be hidden. If "hidden", component will be visually
hidden and not take up space in the layout but still exist in the DOM
streaming: bool
default `= False`
If True when used in a `live` interface, will automatically stream webcam
feed. Only valid is source is 'webcam'. If the component is an output
component, will automatically convert images to base64.
elem_id: str | None
default `= None`
An optional string that is assigned as the id of this component in the HTML
DOM. Can be used for targeting CSS styles.
elem_classes: list[str] | str | None
default `= None`
An optional list of strings that are assigned as the classes of this component
in the HTML DOM. Can be used for targeting CSS styles.
render: bool
default `= True`
If False, component will not render be rendered in the Blocks context. Should
be used if the intention is to assign event listeners now but render the
component later.
key: int | str | tuple[int | str, ...] | None
default `= None`
in a gr.render, Components with the same key across re-renders are treated as
the same component, not a new component. Properties set in 'preserved_by_key'
are not reset across a re-render.
preserved_by_key: list[str] | str | None
default `= "value"`
A list of parameters from this component's constructor. Inside a gr.render()
function, if a component is re-rendered with the same key, these (and only
these) parameters will be preserved in the UI (if they have been changed by
the user or an event listener) instead of re-rendered based on the values
provided during constructor.
webcam_options: WebcamOptions | None
default `= None`
placeholder: str | None
default `= None`
Custom text for the upload area. Overri | Initialization | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
s
provided during constructor.
webcam_options: WebcamOptions | None
default `= None`
placeholder: str | None
default `= None`
Custom text for the upload area. Overrides default upload messages when
provided. Accepts new lines and `` to designate a heading.
watermark: WatermarkOptions | None
default `= None`
If provided and this component is used to display a `value` image, the
`watermark` image will be displayed on the bottom right of the `value` image,
10 pixels from the bottom and 10 pixels from the right. The watermark image
will not be resized. Supports `PIL.Image`, `numpy.array`, `pathlib.Path`, and
`str` filepaths. SVGs and GIFs are not supported as `watermark` images nor can
they be watermarked.
| Initialization | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
Shortcuts
gradio.Image
Interface String Shortcut `"image"`
Initialization Uses default values
| Shortcuts | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
The `type` parameter controls the format of the data passed to your Python
function. Choosing the right type avoids unnecessary conversions in your code:
`type`| Your function receives| Shape / Format| Best for
---|---|---|---
`"numpy"` (default)| `numpy.ndarray`| `(height, width, 3)`, dtype `uint8`,
values 0–255| ML models (PyTorch, TensorFlow, scikit-learn)
`"pil"`| `PIL.Image.Image`| PIL Image object| Image processing with Pillow
`"filepath"`| `str`| Path to a temporary file on disk| Large images, GIFs,
SVGs, or when you need to read the file yourself
import gradio as gr
For a model that expects a numpy array:
def predict(img):
img is a numpy array with shape (H, W, 3)
return model(img)
demo = gr.Interface(fn=predict, inputs=gr.Image(type="numpy"), outputs="label")
For a pipeline that works with file paths:
def process(path):
path is a string like "/tmp/gradio/abcdef.webp"
return my_pipeline(path)
demo = gr.Interface(fn=process, inputs=gr.Image(type="filepath"), outputs="image")
If you need grayscale input, set `image_mode="L"` — the array shape becomes
`(height, width)` instead of `(height, width, 3)`.
| Understanding Image Types | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
The `gr.Image` component can process or display any image format that is
[supported by the PIL
library](https://pillow.readthedocs.io/en/stable/handbook/image-file-
formats.html), including animated GIFs. In addition, it also supports the SVG
image format.
When the `gr.Image` component is used as an input component, the image is
converted into a `str` filepath, a `PIL.Image` object, or a `numpy.array`,
depending on the `type` parameter. However, animated GIF and SVG images are
treated differently:
* Animated `GIF` images can only be converted to `str` filepaths or `PIL.Image` objects. If they are converted to a `numpy.array` (which is the default behavior), only the first frame will be used. So if your demo expects an input `GIF` image, make sure to set the `type` parameter accordingly, e.g.
import gradio as gr
demo = gr.Interface(
fn=lambda x:x,
inputs=gr.Image(type="filepath"),
outputs=gr.Image()
)
demo.launch()
* For `SVG` images, the `type` parameter is ignored altogether and the image is always returned as an image filepath. This is because `SVG` images cannot be processed as `PIL.Image` or `numpy.array` objects.
| `GIF` and `SVG` Image Formats | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
sepia_filterfake_diffusion
| Demos | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
Description
Event listeners allow you to respond to user interactions with the UI
components you've defined in a Gradio Blocks app. When a user interacts with
an element, such as changing a slider value or uploading an image, a function
is called.
Supported Event Listeners
The Image component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listeners
Image.clear(fn, ···)
This listener is triggered when the user clears the Image using the clear
button for the component.
Image.change(fn, ···)
Triggered when the value of the Image changes either because of user input
(e.g. a user types in a textbox) OR because of a function update (e.g. an
image receives a value from the output of an event trigger). See `.input()`
for a listener that is only triggered by user input.
Image.stream(fn, ···)
This listener is triggered when the user streams the Image.
Image.select(fn, ···)
Event listener for when the user selects or deselects the Image. Uses event
data gradio.SelectData to carry `value` referring to the label of the Image,
and `selected` to refer to state of the Image. See
<https://www.gradio.app/main/docs/gradio/eventdata> for more details.
Image.upload(fn, ···)
This listener is triggered when the user uploads a file into the Image.
Image.input(fn, ···)
This listener is triggered when the user changes the value of the Image.
Event Parameters
Parameters ▼
fn: Callable | None | Literal['decorator']
default `= "decorator"`
the function to call when this event is triggered. Often a machine learning
model's prediction function. Each parameter of the function corresponds to one
input component, and the function should return a single value or a tuple of
values, with each element in the tuple corresponding to one output component.
inputs: Co | Event Listeners | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
corresponds to one
input component, and the function should return a single value or a tuple of
values, with each element in the tuple corresponding to one output component.
inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as inputs. If the function takes no inputs,
this should be an empty list.
outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List of gradio.components to use as outputs. If the function returns no
outputs, this should be an empty list.
api_name: str | None
default `= None`
defines how the endpoint appears in the API docs. Can be a string or None. If
set to a string, the endpoint will be exposed in the API docs with the given
name. If None (default), the name of the function will be used as the API
endpoint.
api_description: str | None | Literal[False]
default `= None`
Description of the API endpoint. Can be a string, None, or False. If set to a
string, the endpoint will be exposed in the API docs with the given
description. If None, the function's docstring will be used as the API
endpoint description. If False, then no description will be displayed in the
API docs.
scroll_to_output: bool
default `= False`
If True, will scroll to output component on completion
show_progress: Literal['full', 'minimal', 'hidden']
default `= "full"`
how to show the progress animation while event is running: "full" shows a
spinner which covers the output component area as well as a runtime display in
the upper right corner, "minimal" only shows the runtime display, "hidden"
shows no progress animation at all
show_progress_on: Component | list[Component] | None
default `= None`
Component or list of components to show the progress animation on. If None,
will show the prog | Event Listeners | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
animation at all
show_progress_on: Component | list[Component] | None
default `= None`
Component or list of components to show the progress animation on. If None,
will show the progress animation on all of the output components.
queue: bool
default `= True`
If True, will place the request on the queue, if the queue has been enabled.
If False, will not put this event on the queue, even if the queue has been
enabled. If None, will use the queue setting of the gradio app.
batch: bool
default `= False`
If True, then the function should process a batch of inputs, meaning that it
should accept a list of input values for each parameter. The lists should be
of equal length (and be up to length `max_batch_size`). The function is then
*required* to return a tuple of lists (even if there is only 1 output
component), with each list in the tuple corresponding to one output component.
max_batch_size: int
default `= 4`
Maximum number of inputs to batch together if this is called from the queue
(only relevant if batch=True)
preprocess: bool
default `= True`
If False, will not run preprocessing of component data before running 'fn'
(e.g. leaving it as a base64 string if this method is called with the `Image`
component).
postprocess: bool
default `= True`
If False, will not run postprocessing of component data before returning 'fn'
output to the browser.
cancels: dict[str, Any] | list[dict[str, Any]] | None
default `= None`
A list of other events to cancel when this listener is triggered. For example,
setting cancels=[click_event] will cancel the click_event, where click_event
is the return value of another components .click method. Functions that have
not yet run (or generators that are iterating) will be cancelled, but
functions that are currently running will be allowed to finish.
trigger_mode: Literal['once', 'multiple', 'always_last'] | N | Event Listeners | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
No dataset card yet