text
stringlengths
0
2k
heading1
stringlengths
4
79
source_page_url
stringclasses
176 values
source_page_title
stringclasses
176 values
`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
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/"). hf_token: str | Literal[False] | None default `= False` optional Hugging Face token to use to access private Spaces. By default, no token is sent to the server. Set `hf_token=None` to use the locally saved token if there is one (warning: only provide a token if you are loading a trusted private Space as the token can be read by the Space you are loading). 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
Initialization
https://gradio.app/docs/python-client/client
Python Client - Client Docs
IR 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 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. Listener | Description ---|--- `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 `hf_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> `Client.deploy_discord(fn, ···)` | Deploy
Event Listeners
https://gradio.app/docs/python-client/client
Python Client - Client Docs
dware upgrades (beyond the basic CPU tier), you may be required to provide billing information on Hugging Face: https://huggingface.co/settings/billing <br> `Client.deploy_discord(fn, ···)` | Deploy the upstream app as a discord bot. Currently only supports gr.ChatInterface. 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. 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
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. Listener | Description ---|--- `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
**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
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. Simply calling Space B from Space A with the python client will quickly exhaust your rate limit, as all the requests to the ZeroGPU space will have the same token. So in order to avoid this, we need to extract the token of the user using Space A before we call Space B programmatically. 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
When a user presses enter in the textbox, we will extract their token from the `X-IP-Token` header of the incoming request. We will use this header when constructing the gradio client. The following hypothetical text-to-image application shows how this is done. 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 with gr.Blocks() as demo: image = gr.Image() prompt = gr.Textbox(max_lines=1) prompt.submit(text_to_image, [prompt], [image]) demo.launch()
Avoiding Rate Limits
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. ![](https://huggingface.co/datasets/huggingface/documentation- images/resolve/main/gradio-guides/view-api.png) The View API page also includes an “API Recorder” that lets you interact with the Gradio UI normally and converts your interactions into the corresponding code to run with the Python Client.
The “View API” Page
https://gradio.app/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
A TabbedInterface is created by providing a list of Interfaces or Blocks, each of which gets rendered in a separate tab. Only the components from the Interface/Blocks will be rendered in the tab. Certain high-level attributes of the Blocks (e.g. custom `css`, `js`, and `head` attributes) will not be loaded.
Description
https://gradio.app/docs/gradio/tabbedinterface
Gradio - Tabbedinterface Docs
Parameters ▼ interface_list: list[Blocks] A list of Interfaces (or Blocks) to be rendered in the tabs. tab_names: list[str] | None default `= None` A list of tab names. If None, the tab names will be "Tab 1", "Tab 2", etc. title: str | None default `= None` The tab title to display when this demo is opened in a browser window. theme: Theme | str | None default `= None` A Theme object or a string representing a theme. If a string, will look for a built-in theme with that name (e.g. "soft" or "default"), or will attempt to load a theme from the Hugging Face Hub (e.g. "gradio/monochrome"). If None, will use the Default theme. analytics_enabled: bool | None default `= None` Whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED environment variable or default to True. css: str | None default `= None` Custom css as a string or path to a css file. This css will be included in the demo webpage. js: str | Literal[True] | None default `= None` Custom js as a string or path to a js file. The custom js should in the form of a single js function. This function will automatically be executed when the page loads. For more flexibility, use the head parameter to insert js inside <script> tags. head: str | None default `= None` Custom html to insert into the head of the demo webpage. This can be used to add custom meta tags, multiple scripts, stylesheets, etc. to the page.
Initialization
https://gradio.app/docs/gradio/tabbedinterface
Gradio - Tabbedinterface Docs
tabbed_interface_lite Open in 🎢 ↗ import gradio as gr hello_world = gr.Interface(lambda name: "Hello " + name, "text", "text") bye_world = gr.Interface(lambda name: "Bye " + name, "text", "text") chat = gr.ChatInterface(lambda *args: "Hello " + args[0]) demo = gr.TabbedInterface([hello_world, bye_world, chat], ["Hello World", "Bye World", "Chat"]) if __name__ == "__main__": demo.launch() import gradio as gr hello_world = gr.Interface(lambda name: "Hello " + name, "text", "text") bye_world = gr.Interface(lambda name: "Bye " + name, "text", "text") chat = gr.ChatInterface(lambda *args: "Hello " + args[0]) demo = gr.TabbedInterface([hello_world, bye_world, chat], ["Hello World", "Bye World", "Chat"]) if __name__ == "__main__": demo.launch()
Demos
https://gradio.app/docs/gradio/tabbedinterface
Gradio - Tabbedinterface Docs
Creates a gallery or table to display data samples. This component is primarily designed for internal use to display examples. However, it can also be used directly to display a dataset and let users select examples.
Description
https://gradio.app/docs/gradio/dataset
Gradio - Dataset Docs
**As input component** : Passes the selected sample either as a `list` of data corresponding to each input component (if `type` is "value") or as an `int` index (if `type` is "index"), or as a `tuple` of the index and the data (if `type` is "tuple"). Your function should accept one of these types: def predict( value: int | list | None ) ... **As output component** : Expects an `int` index or `list` of sample data. Returns the index of the sample in the dataset or `None` if the sample is not found. Your function should return one of these types: def predict(···) -> list[list] ... return value
Behavior
https://gradio.app/docs/gradio/dataset
Gradio - Dataset Docs
Parameters ▼ label: str | I18nData | None default `= None` the label for this component, appears above the component. show_label: bool default `= True` If True, the label will be shown above the component. components: list[Component] | list[str] | None default `= None` Which component types to show in this dataset widget, can be passed in as a list of string names or Components instances. The following components are supported in a Dataset: Audio, Checkbox, CheckboxGroup, ColorPicker, Dataframe, Dropdown, File, HTML, Image, Markdown, Model3D, Number, Radio, Slider, Textbox, TimeSeries, Video component_props: list[dict[str, Any]] | None default `= None` samples: list[list[Any]] | None default `= None` a nested list of samples. Each sublist within the outer list represents a data sample, and each element within the sublist represents an value for each component headers: list[str] | None default `= None` Column headers in the Dataset widget, should be the same len as components. If not provided, inferred from component labels type: Literal['values', 'index', 'tuple'] default `= "values"` "values" if clicking on a sample should pass the value of the sample, "index" if it should pass the index of the sample, or "tuple" if it should pass both the index and the value of the sample. layout: Literal['gallery', 'table'] | None default `= None` "gallery" if the dataset should be displayed as a gallery with each sample in a clickable card, or "table" if it should be displayed as a table with each sample in a row. By default, "gallery" is used if there is a single component, and "table" is used if there are more than one component. If there are more than one component, the layout can only be "table". samples_per_page: int default `= 10` how many examples to show per page. visible: bool default `= True`
Initialization
https://gradio.app/docs/gradio/dataset
Gradio - Dataset Docs
re more than one component, the layout can only be "table". samples_per_page: int default `= 10` how many examples to show per page. visible: bool default `= True` If False, component will be hidden. 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. 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.
Initialization
https://gradio.app/docs/gradio/dataset
Gradio - Dataset Docs
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. proxy_url: str | None default `= None` The URL of the external Space used to load this component. Set automatically when using `gr.load()`. This should not be set manually. sample_labels: list[str] | None default `= None` A list of labels for each sample. If provided, the length of this list should be the same as the number of samples, and these labels will be used in the UI instead of rendering the sample values.
Initialization
https://gradio.app/docs/gradio/dataset
Gradio - Dataset Docs
Class | Interface String Shortcut | Initialization ---|---|--- `gradio.Dataset` | "dataset" | Uses default values
Shortcuts
https://gradio.app/docs/gradio/dataset
Gradio - Dataset Docs
**Updating a Dataset** In this example, we display a text dataset using `gr.Dataset` and then update it when the user clicks a button: import gradio as gr philosophy_quotes = [ ["I think therefore I am."], ["The unexamined life is not worth living."] ] startup_quotes = [ ["Ideas are easy. Implementation is hard"], ["Make mistakes faster."] ] def show_startup_quotes(): return gr.Dataset(samples=startup_quotes) with gr.Blocks() as demo: textbox = gr.Textbox() dataset = gr.Dataset(components=[textbox], samples=philosophy_quotes) button = gr.Button() button.click(show_startup_quotes, None, dataset) demo.launch()
Examples
https://gradio.app/docs/gradio/dataset
Gradio - Dataset 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 Dataset component supports the following event listeners. Each event listener takes the same parameters, which are listed in the Event Parameters table below. Listener | Description ---|--- `Dataset.click(fn, ···)` | Triggered when the Dataset is clicked. `Dataset.select(fn, ···)` | Event listener for when the user selects or deselects the Dataset. Uses event data gradio.SelectData to carry `value` referring to the label of the Dataset, and `selected` to refer to state of the Dataset. See EventData documentation on how to use this event data 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_name: str | None | Literal[False] default `= None` defines how the endpoint appears in the API docs. Can be a string, None, or False. If set to a string, the endpoint will be exposed in the API doc
Event Listeners
https://gradio.app/docs/gradio/dataset
Gradio - Dataset Docs
_name: str | None | Literal[False] default `= None` defines how the endpoint appears in the API docs. Can be a string, None, or False. 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. If False, the endpoint will not be exposed in the API docs and downstream apps (including those that `gr.load` this app) will not be able to use this event. 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. 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=Tru
Event Listeners
https://gradio.app/docs/gradio/dataset
Gradio - Dataset Docs
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 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 us
Event Listeners
https://gradio.app/docs/gradio/dataset
Gradio - Dataset Docs
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. show_api: bool default `= True` whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False. time_limit: int | None default `= None` stream_every: float default `= 0.5` like_user_message: bool default `= False` 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.
Event Listeners
https://gradio.app/docs/gradio/dataset
Gradio - Dataset Docs
The gr.DownloadData class is a subclass of gr.EventData that specifically carries information about the `.download()` event. When gr.DownloadData is added as a type hint to an argument of an event listener method, a gr.DownloadData 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/downloaddata
Gradio - Downloaddata Docs
import gradio as gr def on_download(download_data: gr.DownloadData): return f"Downloaded file: {download_data.file.path}" with gr.Blocks() as demo: files = gr.File() textbox = gr.Textbox() files.download(on_download, None, textbox) demo.launch()
Example Usage
https://gradio.app/docs/gradio/downloaddata
Gradio - Downloaddata Docs
Parameters ▼ file: FileData The file that was downloaded, as a FileData object.
Attributes
https://gradio.app/docs/gradio/downloaddata
Gradio - Downloaddata Docs
Creates a textarea for user to enter string input or display string output.
Description
https://gradio.app/docs/gradio/textbox
Gradio - Textbox Docs
**As input component** : Passes text value as a `str` into the function. Your function should accept one of these types: def predict( value: str | None ) ... **As output component** : Expects a `str` returned from function and sets textarea value to it. Your function should return one of these types: def predict(···) -> str | None ... return value
Behavior
https://gradio.app/docs/gradio/textbox
Gradio - Textbox Docs
Parameters ▼ value: str | I18nData | Callable | None default `= None` text to show in textbox. If a function is provided, the function will be called each time the app loads to set the initial value of this component. type: Literal['text', 'password', 'email'] default `= "text"` The type of textbox. One of: 'text' (which allows users to enter any text), 'password' (which masks text entered by the user), 'email' (which suggests email input to the browser). For "password" and "email" types, `lines` must be 1 and `max_lines` must be None or 1. lines: int default `= 1` minimum number of line rows to provide in textarea. max_lines: int | None default `= None` maximum number of line rows to provide in textarea. Must be at least `lines`. If not provided, the maximum number of lines is max(lines, 20) for "text" type, and 1 for "password" and "email" types. placeholder: str | I18nData | None default `= None` placeholder hint to provide behind textarea. label: str | I18nData | None default `= None` the label for this component, displayed above the component if `show_label` is `True` 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 corresponds to. info: str | I18nData | None default `= None` additional component description, appears below the label in smaller font. Supports markdown / HTML syntax. 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`
Initialization
https://gradio.app/docs/gradio/textbox
Gradio - Textbox Docs
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 the label. If False, the copy button is hidden as well as well as the 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. interactive: bool | None default `= None` if True, will be rendered as an editable textbox; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. visible: bool default `= True` If False, component will be hidden. 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. autofocus: bool default `= False` If True, will focus on the textbox when the page loads. Use this carefully, as it can cause usability issues for sighted and non-sighted users. autoscroll: bool default `= True` If True, will automatically scroll to the bottom of the textb
Initialization
https://gradio.app/docs/gradio/textbox
Gradio - Textbox Docs
se this carefully, as it can cause usability issues for sighted and non-sighted users. 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. 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. text_align: Literal['left', 'right'] | None default `= None` How to align the text in the textbox, can be: "left", "right", or None (default). If None, the alignment is left if `rtl` is False, or right if `rtl` is True. Can only be changed if `type` is "text". rtl: bool default `= False` If True and `type` is "text", sets the direction of the text to right-to-left (cursor appears on the left of the text). Default is False, which renders cursor on the right. show_copy_button: bool default `= False` If Tru
Initialization
https://gradio.app/docs/gradio/textbox
Gradio - Textbox Docs
direction of the text to right-to-left (cursor appears on the left of the text). Default is False, which renders cursor on the right. show_copy_button: bool default `= False` If True, includes a copy button to copy the text in the textbox. Only applies if show_label is True. max_length: int | None default `= None` maximum number of characters (including newlines) allowed in the textbox. If None, there is no maximum length. submit_btn: str | bool | None default `= False` If False, will not show a submit button. If True, will show a submit button with an icon. If a string, will use that string as the submit button text. When the submit button is shown, the border of the textbox will be removed, which is useful for creating a chat interface. stop_btn: str | bool | None default `= False`
Initialization
https://gradio.app/docs/gradio/textbox
Gradio - Textbox Docs
Class | Interface String Shortcut | Initialization ---|---|--- `gradio.Textbox` | "textbox" | Uses default values `gradio.TextArea` | "textarea" | Uses lines=7
Shortcuts
https://gradio.app/docs/gradio/textbox
Gradio - Textbox Docs
hello_worlddiff_textssentence_builder Open in 🎢 ↗ import gradio as gr def greet(name): return "Hello " + name + "!" demo = gr.Interface(fn=greet, inputs="textbox", outputs="textbox") if __name__ == "__main__": demo.launch() import gradio as gr def greet(name): return "Hello " + name + "!" demo = gr.Interface(fn=greet, inputs="textbox", outputs="textbox") if __name__ == "__main__": demo.launch() Open in 🎢 ↗ from difflib import Differ import gradio as gr def diff_texts(text1, text2): d = Differ() return [ (token[2:], token[0] if token[0] != " " else None) for token in d.compare(text1, text2) ] demo = gr.Interface( diff_texts, [ gr.Textbox( label="Text 1", info="Initial text", lines=3, value="The quick brown fox jumped over the lazy dogs.", ), gr.Textbox( label="Text 2", info="Text to compare", lines=3, value="The fast brown fox jumps over lazy dogs.", ), ], gr.HighlightedText( label="Diff", combine_adjacent=True, show_legend=True, color_map={"+": "red", "-": "green"}), theme=gr.themes.Base() ) if __name__ == "__main__": demo.launch() from difflib import Differ import gradio as gr def diff_texts(text1, text2): d = Differ() return [ (token[2:], token[0] if token[0] != " " else None) for token in d.compare(text1, text2) ] demo = gr.Interface( diff_texts, [ gr.Textbox( label="Text 1", info="Initial text", lines=3, value="The quick brown fox jumped over the lazy dogs.", ), gr.Textbox( label="Text 2", info="Text to compare", lines=3, value="The fast brown fox jumps over lazy dogs.", ), ], gr.HighlightedText( label="Diff", combine_adjacent=True, show_legend=True,
Demos
https://gradio.app/docs/gradio/textbox
Gradio - Textbox Docs
value="The fast brown fox jumps over lazy dogs.", ), ], gr.HighlightedText( label="Diff", combine_adjacent=True, show_legend=True, color_map={"+": "red", "-": "green"}), theme=gr.themes.Base() ) if __name__ == "__main__": demo.launch() Open in 🎢 ↗ import gradio as gr def sentence_builder(quantity, animal, countries, place, activity_list, morning): return f"""The {quantity} {animal}s from {" and ".join(countries)} went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}""" demo = gr.Interface( sentence_builder, [ gr.Slider(2, 20, value=4, label="Count", info="Choose between 2 and 20"), gr.Dropdown( ["cat", "dog", "bird"], label="Animal", info="Will add more animals later!" ), gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="Countries", info="Where are they from?"), gr.Radio(["park", "zoo", "road"], label="Location", info="Where did they go?"), gr.Dropdown( ["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True, label="Activity", info="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl." ), gr.Checkbox(label="Morning", info="Did they do it in the morning?"), ], "text", examples=[ [2, "cat", ["Japan", "Pakistan"], "park", ["ate", "swam"], True], [4, "dog", ["Japan"], "zoo", ["ate", "swam"], False], [10, "bird", ["USA", "Pakistan"], "road", ["ran"], False], [8, "cat", ["Pakistan"], "zoo", ["ate"], True], ] ) if __name__ == "__main__": demo.launch() import gradio as gr def sentence_builder(quantity, animal, countries, place, activity_list, morning): return f"""The {quantity} {animal}s from {" and ".join(countries)} went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}""" demo = gr.Interface(
Demos
https://gradio.app/docs/gradio/textbox
Gradio - Textbox Docs
f"""The {quantity} {animal}s from {" and ".join(countries)} went to the {place} where they {" and ".join(activity_list)} until the {"morning" if morning else "night"}""" demo = gr.Interface( sentence_builder, [ gr.Slider(2, 20, value=4, label="Count", info="Choose between 2 and 20"), gr.Dropdown( ["cat", "dog", "bird"], label="Animal", info="Will add more animals later!" ), gr.CheckboxGroup(["USA", "Japan", "Pakistan"], label="Countries", info="Where are they from?"), gr.Radio(["park", "zoo", "road"], label="Location", info="Where did they go?"), gr.Dropdown( ["ran", "swam", "ate", "slept"], value=["swam", "slept"], multiselect=True, label="Activity", info="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, nisl eget ultricies aliquam, nunc nisl aliquet nunc, eget aliquam nisl nunc vel nisl." ), gr.Checkbox(label="Morning", info="Did they do it in the morning?"), ], "text", examples=[ [2, "cat", ["Japan", "Pakistan"], "park", ["ate", "swam"], True], [4, "dog", ["Japan"], "zoo", ["ate", "swam"], False], [10, "bird", ["USA", "Pakistan"], "road", ["ran"], False], [8, "cat", ["Pakistan"], "zoo", ["ate"], True], ] ) if __name__ == "__main__": demo.launch()
Demos
https://gradio.app/docs/gradio/textbox
Gradio - Textbox 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 Textbox component supports the following event listeners. Each event listener takes the same parameters, which are listed in the Event Parameters table below. Listener | Description ---|--- `Textbox.change(fn, ···)` | Triggered when the value of the Textbox 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. `Textbox.input(fn, ···)` | This listener is triggered when the user changes the value of the Textbox. `Textbox.select(fn, ···)` | Event listener for when the user selects or deselects the Textbox. Uses event data gradio.SelectData to carry `value` referring to the label of the Textbox, and `selected` to refer to state of the Textbox. See EventData documentation on how to use this event data `Textbox.submit(fn, ···)` | This listener is triggered when the user presses the Enter key while the Textbox is focused. `Textbox.focus(fn, ···)` | This listener is triggered when the Textbox is focused. `Textbox.blur(fn, ···)` | This listener is triggered when the Textbox is unfocused/blurred. `Textbox.stop(fn, ···)` | This listener is triggered when the user reaches the end of the media playing in the Textbox. `Textbox.copy(fn, ···)` | This listener is triggered when the user copies content from the Textbox. Uses event data gradio.CopyData to carry information about the copied content. See EventData documentation on how to use this event data Event Parameters Parameters ▼ fn: Callable | None | Literal['decorator'] default `= "decorator"` the function to cal
Event Listeners
https://gradio.app/docs/gradio/textbox
Gradio - Textbox Docs
EventData documentation on how to use this event data 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_name: str | None | Literal[False] default `= None` defines how the endpoint appears in the API docs. Can be a string, None, or False. 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. If False, the endpoint will not be exposed in the API docs and downstream apps (including those that `gr.load` this app) will not be able to use this event. 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] | Non
Event Listeners
https://gradio.app/docs/gradio/textbox
Gradio - Textbox Docs
s 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. 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 curren
Event Listeners
https://gradio.app/docs/gradio/textbox
Gradio - Textbox Docs
ck_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 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. show_api: bool default `= True` whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False. time_limit: int | None default `= None` stream_every
Event Listeners
https://gradio.app/docs/gradio/textbox
Gradio - Textbox Docs
nstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False. time_limit: int | None default `= None` stream_every: float default `= 0.5` like_user_message: bool default `= False` 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.
Event Listeners
https://gradio.app/docs/gradio/textbox
Gradio - Textbox Docs
Displays an interactive table of parameters and their descriptions and default values with syntax highlighting. For each parameter, the user should provide a type (e.g. a `str`), a human-readable description, and a default value. As this component does not accept user input, it is rarely used as an input component. Internally, this component is used to display the parameters of components in the Custom Component Gallery (https://www.gradio.app/custom- components/gallery).
Description
https://gradio.app/docs/gradio/paramviewer
Gradio - Paramviewer Docs
**As input component** : (Rarely used) passes value as a `dict[str, dict]`. The key in the outer dictionary is the parameter name, while the inner dictionary has keys "type", "description", and "default" for each parameter. Your function should accept one of these types: def predict( value: dict[str, Parameter] ) ... **As output component** : Expects value as a `dict[str, dict]`. The key in the outer dictionary is the parameter name, while the inner dictionary has keys "type", "description", and "default" for each parameter. Your function should return one of these types: def predict(···) -> dict[str, Parameter] ... return value
Behavior
https://gradio.app/docs/gradio/paramviewer
Gradio - Paramviewer Docs
Parameters ▼ value: dict[str, Parameter] | None default `= None` A dictionary of dictionaries. The key in the outer dictionary is the parameter name, while the inner dictionary has keys "type", "description", and "default" for each parameter. Markdown links are supported in "description". language: Literal['python', 'typescript'] default `= "python"` The language to display the code in. One of "python" or "typescript". linkify: list[str] | None default `= None` A list of strings to linkify. If any of these strings is found in the description, it will be rendered as a link. 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. 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
Initialization
https://gradio.app/docs/gradio/paramviewer
Gradio - Paramviewer Docs
er() 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. header: str | None default `= "Parameters"` The header to display above the table of parameters, also includes a toggle button that closes/opens all details at once. If None, no header will be displayed. anchor_links: bool | str default `= False` If True, creates anchor links for each parameter that can be used to link directly to that parameter. If a string, creates anchor links with the given string as the prefix to prevent conflicts with other ParamViewer components.
Initialization
https://gradio.app/docs/gradio/paramviewer
Gradio - Paramviewer Docs
Class | Interface String Shortcut | Initialization ---|---|--- `gradio.ParamViewer` | "paramviewer" | Uses default values
Shortcuts
https://gradio.app/docs/gradio/paramviewer
Gradio - Paramviewer 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 ParamViewer component supports the following event listeners. Each event listener takes the same parameters, which are listed in the Event Parameters table below. Listener | Description ---|--- `ParamViewer.change(fn, ···)` | Triggered when the value of the ParamViewer 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. `ParamViewer.upload(fn, ···)` | This listener is triggered when the user uploads a file into the ParamViewer. 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_name: str | None | Literal[False] default `= None` defines how the endpoint appears in the API docs. Can be a string, None, o
Event Listeners
https://gradio.app/docs/gradio/paramviewer
Gradio - Paramviewer Docs
on returns no outputs, this should be an empty list. api_name: str | None | Literal[False] default `= None` defines how the endpoint appears in the API docs. Can be a string, None, or False. 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. If False, the endpoint will not be exposed in the API docs and downstream apps (including those that `gr.load` this app) will not be able to use this event. 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. 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 bat
Event Listeners
https://gradio.app/docs/gradio/paramviewer
Gradio - Paramviewer Docs
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 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 num
Event Listeners
https://gradio.app/docs/gradio/paramviewer
Gradio - Paramviewer Docs
t: 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. show_api: bool default `= True` whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False. time_limit: int | None default `= None` stream_every: float default `= 0.5` like_user_message: bool default `= False` 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.
Event Listeners
https://gradio.app/docs/gradio/paramviewer
Gradio - Paramviewer Docs
Creates a color picker for user to select a color as string input. Can be used as an input to pass a color value to a function or as an output to display a color value.
Description
https://gradio.app/docs/gradio/colorpicker
Gradio - Colorpicker Docs
**As input component** : Passes selected color value as a hex `str` into the function. Your function should accept one of these types: def predict( value: str | None ) ... **As output component** : Expects a hex `str` returned from function and sets color picker value to it. Your function should return one of these types: def predict(···) -> str | None ... return value
Behavior
https://gradio.app/docs/gradio/colorpicker
Gradio - Colorpicker Docs
Parameters ▼ value: str | Callable | None default `= None` default color hex code to provide in color picker. 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, displayed above the component if `show_label` is `True` 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 corresponds to. info: str | I18nData | None default `= None` additional component description, appears below the label in smaller font. Supports markdown / HTML syntax. 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 cer
Initialization
https://gradio.app/docs/gradio/colorpicker
Gradio - Colorpicker Docs
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 be rendered as an editable color picker; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. visible: bool default `= True` If False, component will be hidden. 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.
Initialization
https://gradio.app/docs/gradio/colorpicker
Gradio - Colorpicker Docs
if they have been changed by the user or an event listener) instead of re-rendered based on the values provided during constructor.
Initialization
https://gradio.app/docs/gradio/colorpicker
Gradio - Colorpicker Docs
Class | Interface String Shortcut | Initialization ---|---|--- `gradio.ColorPicker` | "colorpicker" | Uses default values
Shortcuts
https://gradio.app/docs/gradio/colorpicker
Gradio - Colorpicker Docs
color_picker Open in 🎢 ↗ import gradio as gr import numpy as np from PIL import Image, ImageColor def change_color(icon, color): """ Function that given an icon in .png format changes its color Args: icon: Icon whose color needs to be changed. color: Chosen color with which to edit the input icon. Returns: edited_image: Edited icon. """ img = icon.convert("LA") img = img.convert("RGBA") image_np = np.array(icon) _, _, _, alpha = image_np.T mask = alpha > 0 image_np[..., :-1][mask.T] = ImageColor.getcolor(color, "RGB") edited_image = Image.fromarray(image_np) return edited_image inputs = [ gr.Image(label="icon", type="pil", image_mode="RGBA"), gr.ColorPicker(label="color"), ] outputs = gr.Image(label="colored icon") demo = gr.Interface( fn=change_color, inputs=inputs, outputs=outputs ) if __name__ == "__main__": demo.launch() import gradio as gr import numpy as np from PIL import Image, ImageColor def change_color(icon, color): """ Function that given an icon in .png format changes its color Args: icon: Icon whose color needs to be changed. color: Chosen color with which to edit the input icon. Returns: edited_image: Edited icon. """ img = icon.convert("LA") img = img.convert("RGBA") image_np = np.array(icon) _, _, _, alpha = image_np.T mask = alpha > 0 image_np[..., :-1][mask.T] = ImageColor.getcolor(color, "RGB") edited_image = Image.fromarray(image_np) return edited_image inputs = [ gr.Image(label="icon", type="pil", image_mode="RGBA"), gr.ColorPicker(label="color"), ] outputs = gr.Image(label="colored icon") demo = gr.Interface( fn=change_color, inputs=inputs, outputs=outputs ) if __name__ == "__main__": demo.launch()
Demos
https://gradio.app/docs/gradio/colorpicker
Gradio - Colorpicker 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 ColorPicker component supports the following event listeners. Each event listener takes the same parameters, which are listed in the Event Parameters table below. Listener | Description ---|--- `ColorPicker.change(fn, ···)` | Triggered when the value of the ColorPicker 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. `ColorPicker.input(fn, ···)` | This listener is triggered when the user changes the value of the ColorPicker. `ColorPicker.submit(fn, ···)` | This listener is triggered when the user presses the Enter key while the ColorPicker is focused. `ColorPicker.focus(fn, ···)` | This listener is triggered when the ColorPicker is focused. `ColorPicker.blur(fn, ···)` | This listener is triggered when the ColorPicker is unfocused/blurred. 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 | Bloc
Event Listeners
https://gradio.app/docs/gradio/colorpicker
Gradio - Colorpicker Docs
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 | Literal[False] default `= None` defines how the endpoint appears in the API docs. Can be a string, None, or False. 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. If False, the endpoint will not be exposed in the API docs and downstream apps (including those that `gr.load` this app) will not be able to use this event. 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. The
Event Listeners
https://gradio.app/docs/gradio/colorpicker
Gradio - Colorpicker Docs
he 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 method a
Event Listeners
https://gradio.app/docs/gradio/colorpicker
Gradio - Colorpicker Docs
ubmission 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. show_api: bool default `= True` whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False. time_limit: int | None default `= None` stream_every: float default `= 0.5` like_user_message: bool default `= False` 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.
Event Listeners
https://gradio.app/docs/gradio/colorpicker
Gradio - Colorpicker Docs
Creates a textarea for users to enter string input or display string output and also allows for the uploading of multimedia files.
Description
https://gradio.app/docs/gradio/multimodaltextbox
Gradio - Multimodaltextbox Docs
**As input component** : Passes text value and list of file(s) as a `dict` into the function. Your function should accept one of these types: def predict( value: MultimodalValue | None ) ... **As output component** : Expects a `dict` with "text" and "files", both optional. The files array is a list of file paths or URLs. Your function should return one of these types: def predict(···) -> MultimodalValue | None ... return value
Behavior
https://gradio.app/docs/gradio/multimodaltextbox
Gradio - Multimodaltextbox Docs
Parameters ▼ value: str | dict[str, str | list] | Callable | None default `= None` Default value to show in MultimodalTextbox. A string value, or a dictionary of the form {"text": "sample text", "files": [{path: "files/file.jpg", orig_name: "file.jpg", url: "http://image_url.jpg", size: 100}]}. If a function is provided, the function will be called each time the app loads to set the initial value of this component. sources: list[Literal['upload', 'microphone']] | Literal['upload', 'microphone'] | None default `= None` A list of sources permitted. "upload" creates a button where users can click to upload or drop files, "microphone" creates a microphone input. If None, defaults to ["upload"]. file_types: list[str] | None default `= None` List of file extensions or types of files to be uploaded (e.g. ['image', '.json', '.mp4']). "file" allows any file to be uploaded, "image" allows only image files to be uploaded, "audio" allows only audio files to be uploaded, "video" allows only video files to be uploaded, "text" allows only text files to be uploaded. file_count: Literal['single', 'multiple', 'directory'] default `= "single"` if single, allows user to upload one file. If "multiple", user uploads multiple files. If "directory", user uploads all files in selected directory. Return type will be list for each file in case of "multiple" or "directory". lines: int default `= 1` minimum number of line rows to provide in textarea. max_lines: int default `= 20` maximum number of line rows to provide in textarea. placeholder: str | None default `= None` placeholder hint to provide behind textarea. label: str | I18nData | None default `= None` the label for this component, displayed above the component if `show_label` is `True` and is also used as the header if there are a table of examples for this component. If None and used in a `gr.
Initialization
https://gradio.app/docs/gradio/multimodaltextbox
Gradio - Multimodaltextbox Docs
e` the label for this component, displayed above the component if `show_label` is `True` 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 corresponds to. info: str | I18nData | None default `= None` additional component description, appears below the label in smaller font. Supports markdown / HTML syntax. 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. interactive: bool | None default `= None` if True, will be rendered as an editable textbox; if False, editing will be disabled. If not provided, this is inferred based on
Initialization
https://gradio.app/docs/gradio/multimodaltextbox
Gradio - Multimodaltextbox Docs
cted first. interactive: bool | None default `= None` if True, will be rendered as an editable textbox; if False, editing will be disabled. If not provided, this is inferred based on whether the component is used as an input or output. visible: bool default `= True` If False, component will be hidden. 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. autofocus: bool default `= False` If True, will focus on the textbox when the page loads. Use this carefully, as it can cause usability issues for sighted and non-sighted users. 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. 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
Initialization
https://gradio.app/docs/gradio/multimodaltextbox
Gradio - Multimodaltextbox Docs
er() 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. text_align: Literal['left', 'right'] | None default `= None` How to align the text in the textbox, can be: "left", "right", or None (default). If None, the alignment is left if `rtl` is False, or right if `rtl` is True. Can only be changed if `type` is "text". rtl: bool default `= False` If True and `type` is "text", sets the direction of the text to right-to-left (cursor appears on the left of the text). Default is False, which renders cursor on the right. submit_btn: str | bool | None default `= True` If False, will not show a submit button. If a string, will use that string as the submit button text. stop_btn: str | bool | None default `= False` If True, will show a stop button (useful for streaming demos). If a string, will use that string as the stop button text. max_plain_text_length: int default `= 1000` Maximum length of plain text in the textbox. If the text exceeds this length, the text will be pasted as a file. Default is 1000.
Initialization
https://gradio.app/docs/gradio/multimodaltextbox
Gradio - Multimodaltextbox Docs
Class | Interface String Shortcut | Initialization ---|---|--- `gradio.MultimodalTextbox` | "multimodaltextbox" | Uses default values
Shortcuts
https://gradio.app/docs/gradio/multimodaltextbox
Gradio - Multimodaltextbox Docs
chatbot_multimodal Open in 🎢 ↗ import gradio as gr import time Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text. def print_like_dislike(x: gr.LikeData): print(x.index, x.value, x.liked) def add_message(history, message): for x in message["files"]: history.append({"role": "user", "content": {"path": x}}) if message["text"] is not None: history.append({"role": "user", "content": message["text"]}) return history, gr.MultimodalTextbox(value=None, interactive=False) def bot(history: list): response = "**That's cool!**" history.append({"role": "assistant", "content": ""}) for character in response: history[-1]["content"] += character time.sleep(0.05) yield history with gr.Blocks() as demo: chatbot = gr.Chatbot(elem_id="chatbot", bubble_full_width=False, type="messages") chat_input = gr.MultimodalTextbox( interactive=True, file_count="multiple", placeholder="Enter message or upload file...", show_label=False, sources=["microphone", "upload"], ) chat_msg = chat_input.submit( add_message, [chatbot, chat_input], [chatbot, chat_input] ) bot_msg = chat_msg.then(bot, chatbot, chatbot, api_name="bot_response") bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input]) chatbot.like(print_like_dislike, None, None, like_user_message=True) if __name__ == "__main__": demo.launch() import gradio as gr import time Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text. def print_like_dislike(x: gr.LikeData): print(x.index, x.value, x.liked) def add_message(history, message): for x in message["files"]: history.append({"role": "user", "content": {"path": x}}) if message["text"] is not None: history.append({"role": "user", "content": message["text"]}) return history, gr.MultimodalTextbox(valu
Demos
https://gradio.app/docs/gradio/multimodaltextbox
Gradio - Multimodaltextbox Docs
le": "user", "content": {"path": x}}) if message["text"] is not None: history.append({"role": "user", "content": message["text"]}) return history, gr.MultimodalTextbox(value=None, interactive=False) def bot(history: list): response = "**That's cool!**" history.append({"role": "assistant", "content": ""}) for character in response: history[-1]["content"] += character time.sleep(0.05) yield history with gr.Blocks() as demo: chatbot = gr.Chatbot(elem_id="chatbot", bubble_full_width=False, type="messages") chat_input = gr.MultimodalTextbox( interactive=True, file_count="multiple", placeholder="Enter message or upload file...", show_label=False, sources=["microphone", "upload"], ) chat_msg = chat_input.submit( add_message, [chatbot, chat_input], [chatbot, chat_input] ) bot_msg = chat_msg.then(bot, chatbot, chatbot, api_name="bot_response") bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input]) chatbot.like(print_like_dislike, None, None, like_user_message=True) if __name__ == "__main__": demo.launch()
Demos
https://gradio.app/docs/gradio/multimodaltextbox
Gradio - Multimodaltextbox 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 MultimodalTextbox component supports the following event listeners. Each event listener takes the same parameters, which are listed in the Event Parameters table below. Listener | Description ---|--- `MultimodalTextbox.change(fn, ···)` | Triggered when the value of the MultimodalTextbox 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. `MultimodalTextbox.input(fn, ···)` | This listener is triggered when the user changes the value of the MultimodalTextbox. `MultimodalTextbox.select(fn, ···)` | Event listener for when the user selects or deselects the MultimodalTextbox. Uses event data gradio.SelectData to carry `value` referring to the label of the MultimodalTextbox, and `selected` to refer to state of the MultimodalTextbox. See EventData documentation on how to use this event data `MultimodalTextbox.submit(fn, ···)` | This listener is triggered when the user presses the Enter key while the MultimodalTextbox is focused. `MultimodalTextbox.focus(fn, ···)` | This listener is triggered when the MultimodalTextbox is focused. `MultimodalTextbox.blur(fn, ···)` | This listener is triggered when the MultimodalTextbox is unfocused/blurred. `MultimodalTextbox.stop(fn, ···)` | This listener is triggered when the user reaches the end of the media playing in the MultimodalTextbox. 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 pred
Event Listeners
https://gradio.app/docs/gradio/multimodaltextbox
Gradio - Multimodaltextbox Docs
t 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_name: str | None | Literal[False] default `= None` defines how the endpoint appears in the API docs. Can be a string, None, or False. 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. If False, the endpoint will not be exposed in the API docs and downstream apps (including those that `gr.load` this app) will not be able to use this event. 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 prog
Event Listeners
https://gradio.app/docs/gradio/multimodaltextbox
Gradio - Multimodaltextbox Docs
he 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. 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:
Event Listeners
https://gradio.app/docs/gradio/multimodaltextbox
Gradio - Multimodaltextbox Docs
.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 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. show_api: bool default `= True` whether to show this event in the "view API" page of the Gradio app, or in the ".view_api()" method of the Gradio clients. Unlike setting api_name to False, setting show_api to False will still allow downstream apps as well as the Clients to use this event. If fn is None, show_api will automatically be set to False. time_limit: int | None default `= None` stream_every: float default `= 0.5` like_user_message: bool def
Event Listeners
https://gradio.app/docs/gradio/multimodaltextbox
Gradio - Multimodaltextbox Docs
show_api will automatically be set to False. time_limit: int | None default `= None` stream_every: float default `= 0.5` like_user_message: bool default `= False` 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.
Event Listeners
https://gradio.app/docs/gradio/multimodaltextbox
Gradio - Multimodaltextbox Docs