
EllieKini/Herta
Audio-to-Audio
•
Updated
text
stringlengths 0
2k
| heading1
stringlengths 4
79
| source_page_url
stringclasses 178
values | source_page_title
stringclasses 178
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 | None
default `= None`
optional Hugging Face token to use to access private Spaces. By default, the
locally saved token is used if there is one. Find your tokens here:
https://huggingface.co/settings/tokens.
max_workers: int
default `= 40`
maximum number of thread workers that can be used to make requests to the
remote Gradio app simultaneously.
verbose: bool
default `= True`
whether the client should print statements to the console.
auth: tuple[str, str] | None
default `= None`
httpx_kwargs: dict[str, Any] | None
default `= None`
additional keyword arguments to pass to `httpx.Client`, `httpx.stream`,
`httpx.get` and `httpx.post`. This can be used to set timeouts, proxies, http
auth, etc.
headers: dict[str, str] | None
default `= None`
additional headers to send to the remote Gradio app on every request. By
default only the HF authorization and user-agent headers are sent. This
parameter will override the default headers if they have the same keys.
download_files: str | Path | Literal[False]
default `= "/tmp/gradio"`
directory where the client should download output files on the local machine
from the remote API. By default, uses the value of the GRADIO_TEMP_DIR
environment variable which, if not set by the user, is a temporary directory
on your machine. If False, the client does not download files and returns a
FileData dataclass object with the filepath on the remote machine instead.
ssl_verify: bool
default `= True`
if False, skips certificate validation which allows the client to connect to
Gradio apps that are using self-signed
|
Initialization
|
https://gradio.app/docs/python-client/client
|
Python Client - Client Docs
|
h 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.
headers: dict[str, str] | None
default `= None`
Additional headers to send to the remote Gradio app on this request. This
parameter will overrides the headers provided in the Client constructor if
they have the same keys.
kwargs: <class 'inspect._empty'>
The keyword arguments to pass to the remote API endpoint.
|
Event Listeners
|
https://gradio.app/docs/python-client/client
|
Python Client - Client Docs
|
**Stream From a Gradio app in 5 lines**
Use the `submit` method to get a job you can iterate over.
In python:
from gradio_client import Client
client = Client("gradio/llm_stream")
for result in client.submit("What's the best UI framework in Python?"):
print(result)
In typescript:
import { Client } from "@gradio/client";
const client = await Client.connect("gradio/llm_stream")
const job = client.submit("/predict", {"text": "What's the best UI framework in Python?"})
for await (const msg of job) console.log(msg.data)
**Use the same keyword arguments as the app**
In the examples below, the upstream app has a function with parameters called
`message`, `system_prompt`, and `tokens`. We can see that the client `predict`
call uses the same arguments.
In python:
from gradio_client import Client
client = Client("http://127.0.0.1:7860/")
result = client.predict(
message="Hello!!",
system_prompt="You are helpful AI.",
tokens=10,
api_name="/chat"
)
print(result)
In typescript:
import { Client } from "@gradio/client";
const client = await Client.connect("http://127.0.0.1:7860/");
const result = await client.predict("/chat", {
message: "Hello!!",
system_prompt: "Hello!!",
tokens: 10,
});
console.log(result.data);
**Better Error Messages**
If something goes wrong in the upstream app, the client will raise the same
exception as the app provided that `show_error=True` in the original app's
`launch()` function, or it's a `gr.Error` exception.
|
Ergonomic API 💆
|
https://gradio.app/docs/python-client/version-1-release
|
Python Client - Version 1 Release Docs
|
Anything you can do in the UI, you can do with the client:
* 🔐Authentication
* 🛑 Job Cancelling
* ℹ️ Access Queue Position and API
* 📕 View the API information
Here's an example showing how to display the queue position of a pending job:
from gradio_client import Client
client = Client("gradio/diffusion_model")
job = client.submit("A cute cat")
while not job.done():
status = job.status()
print(f"Current in position {status.rank} out of {status.queue_size}")
|
Transparent Design 🪟
|
https://gradio.app/docs/python-client/version-1-release
|
Python Client - Version 1 Release Docs
|
The client can run from pretty much any python and javascript environment
(node, deno, the browser, Service Workers).
Here's an example using the client from a Flask server using gevent:
from gevent import monkey
monkey.patch_all()
from gradio_client import Client
from flask import Flask, send_file
import time
app = Flask(__name__)
imageclient = Client("gradio/diffusion_model")
@app.route("/gen")
def gen():
result = imageclient.predict(
"A cute cat",
api_name="/predict"
)
return send_file(result)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
|
Portable Design ⛺️
|
https://gradio.app/docs/python-client/version-1-release
|
Python Client - Version 1 Release Docs
|
Changes
**Python**
* The `serialize` argument of the `Client` class was removed and has no effect.
* The `upload_files` argument of the `Client` was removed.
* All filepaths must be wrapped in the `handle_file` method. For example, `caption = client.predict(handle_file('./dog.jpg'))`.
* The `output_dir` argument was removed. It is not specified in the `download_files` argument.
**Javascript**
The client has been redesigned entirely. It was refactored from a function
into a class. An instance can now be constructed by awaiting the `connect`
method.
const app = await Client.connect("gradio/whisper")
The app variable has the same methods as the python class (`submit`,
`predict`, `view_api`, `duplicate`).
|
v1.0 Migration Guide and Breaking
|
https://gradio.app/docs/python-client/version-1-release
|
Python Client - Version 1 Release Docs
|
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.

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 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
|
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
|
A Gradio request object that can be used to access the request headers,
cookies, query parameters and other information about the request from within
the prediction function. The class is a thin wrapper around the
fastapi.Request class. Attributes of this class include: `headers`, `client`,
`query_params`, `session_hash`, and `path_params`. If auth is enabled, the
`username` attribute can be used to get the logged in user. In some
environments, the dict-like attributes (e.g. `requests.headers`,
`requests.query_params`) of this class are automatically converted to
dictionaries, so we recommend converting them to dictionaries before accessing
attributes for consistent behavior in different environments.
|
Description
|
https://gradio.app/docs/gradio/request
|
Gradio - Request Docs
|
import gradio as gr
def echo(text, request: gr.Request):
if request:
print("Request headers dictionary:", request.headers)
print("IP address:", request.client.host)
print("Query parameters:", dict(request.query_params))
print("Session hash:", request.session_hash)
return text
io = gr.Interface(echo, "textbox", "textbox").launch()
|
Example Usage
|
https://gradio.app/docs/gradio/request
|
Gradio - Request Docs
|
Parameters ▼
request: fastapi.Request | None
default `= None`
A fastapi.Request
username: str | None
default `= None`
The username of the logged in user (if auth is enabled)
session_hash: str | None
default `= None`
The session hash of the current session. It is unique for each page load.
|
Initialization
|
https://gradio.app/docs/gradio/request
|
Gradio - Request Docs
|
request_ip_headers
Open in 🎢 ↗ import gradio as gr def predict(text, request: gr.Request):
headers = request.headers host = request.client.host user_agent =
request.headers["user-agent"] return { "ip": host, "user_agent": user_agent,
"headers": headers, } gr.Interface(predict, "text", "json").launch()
import gradio as gr
def predict(text, request: gr.Request):
headers = request.headers
host = request.client.host
user_agent = request.headers["user-agent"]
return {
"ip": host,
"user_agent": user_agent,
"headers": headers,
}
gr.Interface(predict, "text", "json").launch()
|
Demos
|
https://gradio.app/docs/gradio/request
|
Gradio - Request Docs
|
Creates a file explorer component that allows users to browse files on the
machine hosting the Gradio app. As an input component, it also allows users to
select files to be used as input to a function, while as an output component,
it displays selected files.
|
Description
|
https://gradio.app/docs/gradio/fileexplorer
|
Gradio - Fileexplorer Docs
|
**As input component** : Passes the selected file or directory as a `str`
path (relative to `root`) or `list[str}` depending on `file_count`
Your function should accept one of these types:
def predict(
value: list[str] | str | None
)
...
**As output component** : Expects function to return a `str` path to a
file, or `list[str]` consisting of paths to files.
Your function should return one of these types:
def predict(···) -> str | list[str] | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/fileexplorer
|
Gradio - Fileexplorer Docs
|
Parameters ▼
glob: str
default `= "**/*"`
The glob-style pattern used to select which files to display, e.g. "*" to
match all files, "*.png" to match all .png files, "**/*.txt" to match any .txt
file in any subdirectory, etc. The default value matches all files and folders
recursively. See the Python glob documentation at
https://docs.python.org/3/library/glob.html for more information.
value: str | list[str] | Callable | None
default `= None`
The file (or list of files, depending on the `file_count` parameter) to show
as "selected" when the component is first loaded. If a callable is provided,
it will be called when the app loads to set the initial value of the
component. If not provided, no files are shown as selected.
file_count: Literal['single', 'multiple']
default `= "multiple"`
Whether to allow single or multiple files to be selected. If "single", the
component will return a single absolute file path as a string. If "multiple",
the component will return a list of absolute file paths as a list of strings.
root_dir: str | Path
default `= "."`
Path to root directory to select files from. If not provided, defaults to
current working directory.
ignore_glob: str | None
default `= None`
The glob-style, case-sensitive pattern that will be used to exclude files from
the list. For example, "*.py" will exclude all .py files from the list. See
the Python glob documentation at https://docs.python.org/3/library/glob.html
for more information.
label: str | I18nData | None
default `= None`
the label for this component. Appears above the component and is also used as
the header if there are a table of examples for this component. If None and
used in a `gr.Interface`, the label will be the name of the parameter this
component is assigned to.
every: Timer | float | None
default `= None`
Continously calls `value` to recalculate it if `value` is a function
|
Initialization
|
https://gradio.app/docs/gradio/fileexplorer
|
Gradio - Fileexplorer Docs
|
bel will be the name of the parameter this
component is assigned to.
every: Timer | float | None
default `= None`
Continously calls `value` to recalculate it if `value` is a function (has no
effect otherwise). Can provide a Timer whose tick resets `value`, or a float
that provides the regular interval for the reset Timer.
inputs: Component | list[Component] | set[Component] | None
default `= None`
Components that are used as inputs to calculate `value` if `value` is a
function (has no effect otherwise). `value` is recalculated any time the
inputs change.
show_label: bool | None
default `= None`
if True, will display label.
container: bool
default `= True`
If True, will place the component in a container - providing some extra
padding around the border.
scale: int | None
default `= None`
relative size compared to adjacent Components. For example if Components A and
B are in a Row, and A has scale=2, and B has scale=1, A will be twice as wide
as B. Should be an integer. scale applies in Rows, and to top-level Components
in Blocks where fill_height=True.
min_width: int
default `= 160`
minimum pixel width, will wrap if not sufficient screen space to satisfy this
value. If a certain scale value results in this Component being narrower than
min_width, the min_width parameter will be respected first.
height: int | str | None
default `= None`
The maximum height of the file component, specified in pixels if a number is
passed, or in CSS units if a string is passed. If more files are uploaded than
can fit in the height, a scrollbar will appear.
max_height: int | str | None
default `= 500`
min_height: int | str | None
default `= None`
interactive: bool | None
default `= None`
if True, will allow users to select file(s); if False, will only display
files. If not provided, this is inferred based on wheth
|
Initialization
|
https://gradio.app/docs/gradio/fileexplorer
|
Gradio - Fileexplorer Docs
|
lt `= None`
interactive: bool | None
default `= None`
if True, will allow users to select file(s); if False, will only display
files. If not provided, this is inferred based on whether the component is
used as an input or output.
visible: bool
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/fileexplorer
|
Gradio - Fileexplorer Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.FileExplorer` | "fileexplorer" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/fileexplorer
|
Gradio - Fileexplorer Docs
|
Description
Event listeners allow you to respond to user interactions with the UI
components you've defined in a Gradio Blocks app. When a user interacts with
an element, such as changing a slider value or uploading an image, a function
is called.
Supported Event Listeners
The FileExplorer component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
Listener | Description
---|---
`FileExplorer.change(fn, ···)` |
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.
api_description: str | None | Literal[False]
d
|
Event Listeners
|
https://gradio.app/docs/gradio/fileexplorer
|
Gradio - Fileexplorer Docs
|
nt 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.
api_description: str | None | Literal[False]
default `= None`
Description of the API endpoint. Can be a string, None, or False. If set to a
string, the endpoint will be exposed in the API docs with the given
description. If None, the function's docstring will be used as the API
endpoint description. If False, then no description will be displayed in the
API docs.
scroll_to_output: bool
default `= False`
If True, will scroll to output component on completion
show_progress: Literal['full', 'minimal', 'hidden']
default `= "full"`
how to show the progress animation while event is running: "full" shows a
spinner which covers the output component area as well as a runtime display in
the upper right corner, "minimal" only shows the runtime display, "hidden"
shows no progress animation at all
show_progress_on: Component | list[Component] | None
default `= None`
Component or list of components to show the progress animation on. If None,
will show the progress animation on all of the output components.
queue: bool
default `= True`
If True, will place the request on the queue, if the queue has been enabled.
If False, will not put this event on the queue, even if the queue has been
enabled. If None, will use the queue setting of the gradio app.
batch: bool
default `= False`
If True, then the function should process a batch of inputs, meaning that it
should accept a list of input values for each parameter. 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 togeth
|
Event Listeners
|
https://gradio.app/docs/gradio/fileexplorer
|
Gradio - Fileexplorer Docs
|
en 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 number of
th
|
Event Listeners
|
https://gradio.app/docs/gradio/fileexplorer
|
Gradio - Fileexplorer Docs
|
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/fileexplorer
|
Gradio - Fileexplorer Docs
|
dict() -> new empty dictionary dict(mapping) -> new dictionary initialized
from a mapping object's (key, value) pairs dict(iterable) -> new dictionary
initialized as if via: d = `` for k, v in iterable: d[k] = v dict(__kwargs) -
> new dictionary initialized with the name=value pairs in the keyword argument
list. For example: dict(one=1, two=2)
|
Description
|
https://gradio.app/docs/gradio/dependency
|
Gradio - Dependency Docs
|
Blocks is Gradio's low-level API that allows you to create more custom web
applications and demos than Interfaces (yet still entirely in Python).
Compared to the Interface class, Blocks offers more flexibility and control
over: (1) the layout of components (2) the events that trigger the execution
of functions (3) data flows (e.g. inputs can trigger outputs, which can
trigger the next level of outputs). Blocks also offers ways to group together
related demos such as with tabs.
The basic usage of Blocks is as follows: create a Blocks object, then use it
as a context (with the "with" statement), and then define layouts, components,
or events within the Blocks context. Finally, call the launch() method to
launch the demo.
|
Description
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
import gradio as gr
def update(name):
return f"Welcome to Gradio, {name}!"
with gr.Blocks() as demo:
gr.Markdown("Start typing below and then click **Run** to see the output.")
with gr.Row():
inp = gr.Textbox(placeholder="What is your name?")
out = gr.Textbox()
btn = gr.Button("Run")
btn.click(fn=update, inputs=inp, outputs=out)
demo.launch()
|
Example Usage
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
Parameters ▼
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.
mode: str
default `= "blocks"`
A human-friendly name for the kind of Blocks or Interface being created. Used
internally for analytics.
title: str | I18nData
default `= "Gradio"`
The tab title to display when this is opened in a browser window.
css: str | None
default `= None`
Custom css as a code string. This css will be included in the demo webpage.
css_paths: str | Path | list[str | Path] | None
default `= None`
Custom css as a pathlib.Path to a css file or a list of such paths. This css
files will be read, concatenated, and included in the demo webpage. If the
`css` parameter is also set, the css from `css` will be included first.
js: str | Literal[True] | None
default `= None`
Custom js as a code string. The custom js should be 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 code 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.
head_paths: str | Path | list[str | Path] | None
default `= None`
Custom html code as a pathlib.Path to a html file or a list of such paths.
This html files will be read, concatenated, and included in the head of the
demo webpage. If the `head`
|
Initialization
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
e
default `= None`
Custom html code as a pathlib.Path to a html file or a list of such paths.
This html files will be read, concatenated, and included in the head of the
demo webpage. If the `head` parameter is also set, the html from `head` will
be included first.
fill_height: bool
default `= False`
Whether to vertically expand top-level child components to the height of the
window. If True, expansion occurs when the scale value of the child components
>= 1.
fill_width: bool
default `= False`
Whether to horizontally expand to fill container fully. If False, centers and
constrains app to a maximum width. Only applies if this is the outermost
`Blocks` in your Gradio app.
delete_cache: tuple[int, int] | None
default `= None`
A tuple corresponding [frequency, age] both expressed in number of seconds.
Every `frequency` seconds, the temporary files created by this Blocks instance
will be deleted if more than `age` seconds have passed since the file was
created. For example, setting this to (86400, 86400) will delete temporary
files every day. The cache will be deleted entirely when the server restarts.
If None, no cache deletion will occur.
|
Initialization
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
blocks_helloblocks_flipperblocks_kinematics
Open in 🎢 ↗ import gradio as gr def welcome(name): return f"Welcome to Gradio,
{name}!" with gr.Blocks() as demo: gr.Markdown( """ Hello World! Start
typing below to see the output. """) inp = gr.Textbox(placeholder="What is
your name?") out = gr.Textbox() inp.change(welcome, inp, out) if __name__ ==
"__main__": demo.launch()
import gradio as gr
def welcome(name):
return f"Welcome to Gradio, {name}!"
with gr.Blocks() as demo:
gr.Markdown(
"""
Hello World!
Start typing below to see the output.
""")
inp = gr.Textbox(placeholder="What is your name?")
out = gr.Textbox()
inp.change(welcome, inp, out)
if __name__ == "__main__":
demo.launch()
Open in 🎢 ↗ import numpy as np import gradio as gr def flip_text(x): return
x[::-1] def flip_image(x): return np.fliplr(x) with gr.Blocks() as demo:
gr.Markdown("Flip text or image files using this demo.") with gr.Tab("Flip
Text"): text_input = gr.Textbox() text_output = gr.Textbox() text_button =
gr.Button("Flip") with gr.Tab("Flip Image"): with gr.Row(): image_input =
gr.Image() image_output = gr.Image() image_button = gr.Button("Flip") with
gr.Accordion("Open for More!", open=False): gr.Markdown("Look at me...")
temp_slider = gr.Slider( 0, 1, value=0.1, step=0.1, interactive=True,
label="Slide me", ) text_button.click(flip_text, inputs=text_input,
outputs=text_output) image_button.click(flip_image, inputs=image_input,
outputs=image_output) if __name__ == "__main__": demo.launch()
import numpy as np
import gradio as gr
def flip_text(x):
return x[::-1]
def flip_image(x):
return np.fliplr(x)
with gr.Blocks() as demo:
gr.Markdown("Flip text or image files using this demo.")
with gr.Tab("Flip Text"):
text_input = gr.Textbox()
text_output = gr.Textbox()
|
Demos
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
gr.Blocks() as demo:
gr.Markdown("Flip text or image files using this demo.")
with gr.Tab("Flip Text"):
text_input = gr.Textbox()
text_output = gr.Textbox()
text_button = gr.Button("Flip")
with gr.Tab("Flip Image"):
with gr.Row():
image_input = gr.Image()
image_output = gr.Image()
image_button = gr.Button("Flip")
with gr.Accordion("Open for More!", open=False):
gr.Markdown("Look at me...")
temp_slider = gr.Slider(
0, 1,
value=0.1,
step=0.1,
interactive=True,
label="Slide me",
)
text_button.click(flip_text, inputs=text_input, outputs=text_output)
image_button.click(flip_image, inputs=image_input, outputs=image_output)
if __name__ == "__main__":
demo.launch()
Open in 🎢 ↗ import pandas as pd import numpy as np import gradio as gr def
plot(v, a): g = 9.81 theta = a / 180 * 3.14 tmax = ((2 * v) * np.sin(theta)) /
g timemat = tmax * np.linspace(0, 1, 40) x = (v * timemat) * np.cos(theta) y =
((v * timemat) * np.sin(theta)) - ((0.5 * g) * (timemat**2)) df =
pd.DataFrame({"x": x, "y": y}) return df demo = gr.Blocks() with demo:
gr.Markdown( r"Let's do some kinematics! Choose the speed and angle to see the
trajectory. Remember that the range $R = v_0^2 \cdot \frac{\sin(2\theta)}{g}$"
) with gr.Row(): speed = gr.Slider(1, 30, 25, label="Speed") angle =
gr.Slider(0, 90, 45, label="Angle") output = gr.LinePlot( x="x", y="y",
overlay_point=True, tooltip=["x", "y"], x_lim=[0, 100], y_lim=[0, 60],
width=350, height=300, ) btn = gr.Button(value="Run") btn.click(plot, [speed,
angle], output) if __name__ == "__main__": demo.launch()
import pandas as pd
import numpy as np
import gradio as gr
def plot(v, a):
g = 9.81
theta = a / 180 * 3.14
|
Demos
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
_name__ == "__main__": demo.launch()
import pandas as pd
import numpy as np
import gradio as gr
def plot(v, a):
g = 9.81
theta = a / 180 * 3.14
tmax = ((2 * v) * np.sin(theta)) / g
timemat = tmax * np.linspace(0, 1, 40)
x = (v * timemat) * np.cos(theta)
y = ((v * timemat) * np.sin(theta)) - ((0.5 * g) * (timemat**2))
df = pd.DataFrame({"x": x, "y": y})
return df
demo = gr.Blocks()
with demo:
gr.Markdown(
r"Let's do some kinematics! Choose the speed and angle to see the trajectory. Remember that the range $R = v_0^2 \cdot \frac{\sin(2\theta)}{g}$"
)
with gr.Row():
speed = gr.Slider(1, 30, 25, label="Speed")
angle = gr.Slider(0, 90, 45, label="Angle")
output = gr.LinePlot(
x="x",
y="y",
overlay_point=True,
tooltip=["x", "y"],
x_lim=[0, 100],
y_lim=[0, 60],
width=350,
height=300,
)
btn = gr.Button(value="Run")
btn.click(plot, [speed, angle], output)
if __name__ == "__main__":
demo.launch()
|
Demos
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
Methods
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
|
%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)
gradio.Blocks.launch(···)
Description
%20Copyright%202022%20Fonticons,%20Inc.%20
|
launch
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
-!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\(Commercial%20License\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)
Launches a simple web server that serves the demo. Can also be used to create
a public link used by anyone to access the demo from their browser by setting
share=True.
Example Usage
%20Copyright%202022%20Fonticons,%20
|
launch
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
3e%3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\(Commercial%20License\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)
import gradio as gr
def reverse(text):
return text[::-1]
with gr.Blocks() as demo:
button = gr.Button(value="Reverse")
button.click(reverse, gr.Textbox(), gr.Textbox())
demo.launch(share=True, auth=("username", "password"))
Parameters ▼
inline: bool | None
default `= None`
whether to display in the gradio app inline in an iframe. Defaults to True in
python notebooks; False otherwise.
inbrowser: bool
default
|
launch
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
inline: bool | None
default `= None`
whether to display in the gradio app inline in an iframe. Defaults to True in
python notebooks; False otherwise.
inbrowser: bool
default `= False`
whether to automatically launch the gradio app in a new tab on the default
browser.
share: bool | None
default `= None`
whether to create a publicly shareable link for the gradio app. Creates an SSH
tunnel to make your UI accessible from anywhere. If not provided, it is set to
False by default every time, except when running in Google Colab. When
localhost is not accessible (e.g. Google Colab), setting share=False is not
supported. Can be set by environment variable GRADIO_SHARE=True.
debug: bool
default `= False`
if True, blocks the main thread from running. If running in Google Colab, this
is needed to print the errors in the cell output.
max_threads: int
default `= 40`
the maximum number of total threads that the Gradio app can generate in
parallel. The default is inherited from the starlette library (currently 40).
auth: Callable[[str, str], bool] | tuple[str, str] | list[tuple[str, str]] | None
default `= None`
If provided, username and password (or list of username-password tuples)
required to access app. Can also provide function that takes username and
password and returns True if valid login.
auth_message: str | None
default `= None`
If provided, HTML message provided on login page.
prevent_thread_lock: bool
default `= False`
By default, the gradio app blocks the main thread while the server is running.
If set to True, the gradio app will not block and the gradio server will
terminate as soon as the script finishes.
show_error: bool
default `= False`
If True, any errors in the gradio app will be displayed in an alert modal and
printed in the browser console log. They will also be displayed in the alert
modal of downstream apps
|
launch
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
default `= False`
If True, any errors in the gradio app will be displayed in an alert modal and
printed in the browser console log. They will also be displayed in the alert
modal of downstream apps that gr.load() this app.
server_name: str | None
default `= None`
to make app accessible on local network, set this to "0.0.0.0". Can be set by
environment variable GRADIO_SERVER_NAME. If None, will use "127.0.0.1".
server_port: int | None
default `= None`
will start gradio app on this port (if available). Can be set by environment
variable GRADIO_SERVER_PORT. If None, will search for an available port
starting at 7860.
height: int
default `= 500`
The height in pixels of the iframe element containing the gradio app (used if
inline=True)
width: int | str
default `= "100%"`
The width in pixels of the iframe element containing the gradio app (used if
inline=True)
favicon_path: str | Path | None
default `= None`
If a path to a file (.png, .gif, or .ico) is provided, it will be used as the
favicon for the web page.
ssl_keyfile: str | None
default `= None`
If a path to a file is provided, will use this as the private key file to
create a local server running on https.
ssl_certfile: str | None
default `= None`
If a path to a file is provided, will use this as the signed certificate for
https. Needs to be provided if ssl_keyfile is provided.
ssl_keyfile_password: str | None
default `= None`
If a password is provided, will use this with the ssl certificate for https.
ssl_verify: bool
default `= True`
If False, skips certificate validation which allows self-signed certificates
to be used.
quiet: bool
default `= False`
If True, suppresses most print statements.
show_api: bool
default `= True`
If True, shows the api docs in the footer of the app. Default True.
allowed_pa
|
launch
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
t `= False`
If True, suppresses most print statements.
show_api: bool
default `= True`
If True, shows the api docs in the footer of the app. Default True.
allowed_paths: list[str] | None
default `= None`
List of complete filepaths or parent directories that gradio is allowed to
serve. Must be absolute paths. Warning: if you provide directories, any files
in these directories or their subdirectories are accessible to all users of
your app. Can be set by comma separated environment variable
GRADIO_ALLOWED_PATHS. These files are generally assumed to be secure and will
be displayed in the browser when possible.
blocked_paths: list[str] | None
default `= None`
List of complete filepaths or parent directories that gradio is not allowed to
serve (i.e. users of your app are not allowed to access). Must be absolute
paths. Warning: takes precedence over `allowed_paths` and all other
directories exposed by Gradio by default. Can be set by comma separated
environment variable GRADIO_BLOCKED_PATHS.
root_path: str | None
default `= None`
The root path (or "mount point") of the application, if it's not served from
the root ("/") of the domain. Often used when the application is behind a
reverse proxy that forwards requests to the application. For example, if the
application is served at "https://example.com/myapp", the `root_path` should
be set to "/myapp". A full URL beginning with http:// or https:// can be
provided, which will be used as the root path in its entirety. Can be set by
environment variable GRADIO_ROOT_PATH. Defaults to "".
app_kwargs: dict[str, Any] | None
default `= None`
Additional keyword arguments to pass to the underlying FastAPI app as a
dictionary of parameter keys and argument values. For example, `{"docs_url":
"/docs"}`
state_session_capacity: int
default `= 10000`
The maximum number of sessions whose information to store in memory. If the
number of
|
launch
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
ument values. For example, `{"docs_url":
"/docs"}`
state_session_capacity: int
default `= 10000`
The maximum number of sessions whose information to store in memory. If the
number of sessions exceeds this number, the oldest sessions will be removed.
Reduce capacity to reduce memory usage when using gradio.State or returning
updated components from functions. Defaults to 10000.
share_server_address: str | None
default `= None`
Use this to specify a custom FRP server and port for sharing Gradio apps (only
applies if share=True). If not provided, will use the default FRP server at
https://gradio.live. See https://github.com/huggingface/frp for more
information.
share_server_protocol: Literal['http', 'https'] | None
default `= None`
Use this to specify the protocol to use for the share links. Defaults to
"https", unless a custom share_server_address is provided, in which case it
defaults to "http". If you are using a custom share_server_address and want to
use https, you must set this to "https".
share_server_tls_certificate: str | None
default `= None`
The path to a TLS certificate file to use when connecting to a custom share
server. This parameter is not used with the default FRP server at
https://gradio.live. Otherwise, you must provide a valid TLS certificate file
(e.g. a "cert.pem") relative to the current working directory, or the
connection will not use TLS encryption, which is insecure.
auth_dependency: Callable[[fastapi.Request], str | None] | None
default `= None`
A function that takes a FastAPI request and returns a string user ID or None.
If the function returns None for a specific request, that user is not
authorized to access the app (they will see a 401 Unauthorized response). To
be used with external authentication systems like OAuth. Cannot be used with
`auth`.
max_file_size: str | int | None
default `= None`
The maximum file size in bytes that c
|
launch
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
ponse). To
be used with external authentication systems like OAuth. Cannot be used with
`auth`.
max_file_size: str | int | None
default `= None`
The maximum file size in bytes that can be uploaded. Can be a string of the
form "<value><unit>", where value is any positive integer and unit is one of
"b", "kb", "mb", "gb", "tb". If None, no limit is set.
enable_monitoring: bool | None
default `= None`
Enables traffic monitoring of the app through the /monitoring endpoint. By
default is None, which enables this endpoint. If explicitly True, will also
print the monitoring URL to the console. If False, will disable monitoring
altogether.
strict_cors: bool
default `= True`
If True, prevents external domains from making requests to a Gradio server
running on localhost. If False, allows requests to localhost that originate
from localhost but also, crucially, from "null". This parameter should
normally be True to prevent CSRF attacks but may need to be False when
embedding a *locally-running Gradio app* using web components.
node_server_name: str | None
default `= None`
node_port: int | None
default `= None`
ssr_mode: bool | None
default `= None`
If True, the Gradio app will be rendered using server-side rendering mode,
which is typically more performant and provides better SEO, but this requires
Node 20+ to be installed on the system. If False, the app will be rendered
using client-side rendering mode. If None, will use GRADIO_SSR_MODE
environment variable or default to False.
pwa: bool | None
default `= None`
If True, the Gradio app will be set up as an installable PWA (Progressive Web
App). If set to None (default behavior), then the PWA feature will be enabled
if this Gradio app is launched on Spaces, but not otherwise.
mcp_server: bool | None
default `= None`
If True, the Gradio app will be set up as an MCP server and documented
fun
|
launch
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
abled
if this Gradio app is launched on Spaces, but not otherwise.
mcp_server: bool | None
default `= None`
If True, the Gradio app will be set up as an MCP server and documented
functions will be added as MCP tools. If None (default behavior), then the
GRADIO_MCP_SERVER environment variable will be used to determine if the MCP
server should be enabled (which is "True" on Hugging Face Spaces).
i18n: I18n | None
default `= None`
An I18n instance containing custom translations, which are used to translate
strings in our components (e.g. the labels of components or Markdown strings).
This feature can only be used to translate static text in the frontend, not
values in the backend.
|
launch
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)
gradio.Blocks.queue(···)
Description
%20Copyright%202022%20Fonticons,%20Inc.%20-
|
queue
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\(Commercial%20License\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)
By enabling the queue you can control when users know their position in the
queue, and set a limit on maximum number of events allowed.
Example Usage
%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%2
|
queue
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\(Commercial%20License\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)
with gr.Blocks() as demo:
button = gr.Button(label="Generate Image")
button.click(fn=image_generator, inputs=gr.Textbox(), outputs=gr.Image())
demo.queue(max_size=10)
demo.launch()
Parameters ▼
status_update_rate: float | Literal['auto']
default `= "auto"`
If "auto", Queue will send status estimations to all clients whenever a job is
finished. Otherwise Queue will send status at regular intervals set by this
parameter as the number of seconds.
api_open:
|
queue
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
will send status estimations to all clients whenever a job is
finished. Otherwise Queue will send status at regular intervals set by this
parameter as the number of seconds.
api_open: bool | None
default `= None`
If True, the REST routes of the backend will be open, allowing requests made
directly to those endpoints to skip the queue.
max_size: int | None
default `= None`
The maximum number of events the queue will store at any given moment. If the
queue is full, new events will not be added and a user will receive a message
saying that the queue is full. If None, the queue size will be unlimited.
default_concurrency_limit: int | None | Literal['not_set']
default `= "not_set"`
The default value of `concurrency_limit` to use for event listeners that don't
specify a value. Can be set by environment variable
GRADIO_DEFAULT_CONCURRENCY_LIMIT. Defaults to 1 if not set otherwise.
|
queue
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)
gradio.Blocks.integrate(···)
Description
%20Copyright%202022%20Fonticons,%20Inc.
|
integrate
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\(Commercial%20License\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)
A catch-all method for integrating with other libraries. This method should be
run after launch()
Parameters ▼
comet_ml: <class 'inspect._empty'>
default `= None`
If a comet_ml Experiment object is provided, will integrate with the
experiment and appear on Comet dashboard
wandb: ModuleType | None
default `= None`
If the wandb module is provided, will integrate with it and appear on WandB
dashboard
mlflow: ModuleType | None
default `= None`
If
|
integrate
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
wandb: ModuleType | None
default `= None`
If the wandb module is provided, will integrate with it and appear on WandB
dashboard
mlflow: ModuleType | None
default `= None`
If the mlflow module is provided, will integrate with the experiment and
appear on ML Flow dashboard
|
integrate
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)
gradio.Blocks.load(block, ···)
Description
%20Copyright%202022%20Fonticons,%20In
|
load
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
%3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\(Commercial%20License\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)
This listener is triggered when the Blocks initially loads in the browser.
Parameters ▼
block: Block | None
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 o
|
load
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
ction 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.
api_description: str | None | Literal[False]
default `= None`
Description of the API endpoint. Can be a string, None, or False. If set to a
string, the endpoint will be exposed in the API docs with the given
description. If None, the function's docstring will be used as the API
endpoint description. If False, then no description will be displayed in the
API docs.
scroll_to_output: bool
default `= False`
If True, will scroll to output component on completion
show_progress: Literal['full', 'minimal', 'hidden']
default `= "full"`
how to show the progress animation while event is running: "full" shows a
spinner which covers the output component area as well as a runtime display in
the upper right corner, "minimal" only shows the runtime displa
|
load
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
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=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. F
|
load
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
r 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 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 au
|
load
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
()" 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.
|
load
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)
gradio.Blocks.unload(fn, ···)
Description
%20Copyright%202022%20Fonticons,%20Inc
|
unload
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
3c!--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\(Commercial%20License\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)
This listener is triggered when the user closes or refreshes the tab, ending
the user session. It is useful for cleaning up resources when the app is
closed.
Example Usage
%20Copyright%202022%20Fonticons,%20Inc.%2
|
unload
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
--!%20Font%20Awesome%20Pro%206.0.0%20by%20@fontawesome%20-%20https://fontawesome.com%20License%20-%20https://fontawesome.com/license%20\(Commercial%20License\)%20Copyright%202022%20Fonticons,%20Inc.%20--%3e%3cpath%20d='M172.5%20131.1C228.1%2075.51%20320.5%2075.51%20376.1%20131.1C426.1%20181.1%20433.5%20260.8%20392.4%20318.3L391.3%20319.9C381%20334.2%20361%20337.6%20346.7%20327.3C332.3%20317%20328.9%20297%20339.2%20282.7L340.3%20281.1C363.2%20249%20359.6%20205.1%20331.7%20177.2C300.3%20145.8%20249.2%20145.8%20217.7%20177.2L105.5%20289.5C73.99%20320.1%2073.99%20372%20105.5%20403.5C133.3%20431.4%20177.3%20435%20209.3%20412.1L210.9%20410.1C225.3%20400.7%20245.3%20404%20255.5%20418.4C265.8%20432.8%20262.5%20452.8%20248.1%20463.1L246.5%20464.2C188.1%20505.3%20110.2%20498.7%2060.21%20448.8C3.741%20392.3%203.741%20300.7%2060.21%20244.3L172.5%20131.1zM467.5%20380C411%20436.5%20319.5%20436.5%20263%20380C213%20330%20206.5%20251.2%20247.6%20193.7L248.7%20192.1C258.1%20177.8%20278.1%20174.4%20293.3%20184.7C307.7%20194.1%20311.1%20214.1%20300.8%20229.3L299.7%20230.9C276.8%20262.1%20280.4%20306.9%20308.3%20334.8C339.7%20366.2%20390.8%20366.2%20422.3%20334.8L534.5%20222.5C566%20191%20566%20139.1%20534.5%20108.5C506.7%2080.63%20462.7%2076.99%20430.7%2099.9L429.1%20101C414.7%20111.3%20394.7%20107.1%20384.5%2093.58C374.2%2079.2%20377.5%2059.21%20391.9%2048.94L393.5%2047.82C451%206.731%20529.8%2013.25%20579.8%2063.24C636.3%20119.7%20636.3%20211.3%20579.8%20267.7L467.5%20380z'/%3e%3c/svg%3e)
import gradio as gr
with gr.Blocks() as demo:
gr.Markdown("When you close the tab, hello will be printed to the console")
demo.unload(lambda: print("hello"))
demo.launch()
Parameters ▼
fn: Callable[..., Any]
Callable function to run to clear resources. The function should not take any
arguments and the output is not used.
|
unload
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
ources. The function should not take any
arguments and the output is not used.
|
unload
|
https://gradio.app/docs/gradio/blocks
|
Gradio - Blocks Docs
|
The gr.DeletedFileData class is a subclass of gr.EventData that
specifically carries information about the `.delete()` event. When
gr.DeletedFileData is added as a type hint to an argument of an event listener
method, a gr.DeletedFileData 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/deletedfiledata
|
Gradio - Deletedfiledata Docs
|
import gradio as gr
def test(delete_data: gr.DeletedFileData):
return delete_data.file.path
with gr.Blocks() as demo:
files = gr.File(file_count="multiple")
deleted_file = gr.File()
files.delete(test, None, deleted_file)
demo.launch()
|
Example Usage
|
https://gradio.app/docs/gradio/deletedfiledata
|
Gradio - Deletedfiledata Docs
|
Parameters ▼
file: FileData
The file that was deleted, as a FileData object. The str path to the file can
be retrieved with the .path attribute.
|
Attributes
|
https://gradio.app/docs/gradio/deletedfiledata
|
Gradio - Deletedfiledata Docs
|
file_component_events
Open in 🎢 ↗ import gradio as gr def delete_file(n: int, file:
gr.DeletedFileData): return [file.file.path, n + 1] with gr.Blocks() as demo:
with gr.Row(): with gr.Column(): file_component = gr.File(label="Upload Single
File", file_count="single") with gr.Column(): output_file_1 = gr.File(
label="Upload Single File Output", file_count="single" ) num_load_btn_1 =
gr.Number(label="Load Upload Single File", value=0) file_component.upload(
lambda s, n: (s, n + 1), [file_component, num_load_btn_1], [output_file_1,
num_load_btn_1], ) with gr.Row(): with gr.Column(): file_component_multiple =
gr.File( label="Upload Multiple Files", file_count="multiple" ) with
gr.Column(): output_file_2 = gr.File( label="Upload Multiple Files Output",
file_count="multiple" ) num_load_btn_2 = gr.Number(label="Load Upload
Multiple Files", value=0) file_component_multiple.upload( lambda s, n: (s, n +
1), [file_component_multiple, num_load_btn_2], [output_file_2,
num_load_btn_2], ) with gr.Row(): with gr.Column(): file_component_specific =
gr.File( label="Upload Multiple Files Image/Video", file_count="multiple",
file_types=["image", "video"], ) with gr.Column(): output_file_3 = gr.File(
label="Upload Multiple Files Output Image/Video", file_count="multiple" )
num_load_btn_3 = gr.Number( label="Load Upload Multiple Files Image/Video",
value=0 ) file_component_specific.upload( lambda s, n: (s, n + 1),
[file_component_specific, num_load_btn_3], [output_file_3, num_load_btn_3], )
with gr.Row(): with gr.Column(): file_component_pdf = gr.File(label="Upload
PDF File", file_types=[".pdf"]) with gr.Column(): output_file_4 =
gr.File(label="Upload PDF File Output") num_load_btn_4 = gr.Number(label="
Load Upload PDF File", value=0) file_component_pdf.upload( lambda s, n: (s, n
+ 1), [file_component_pdf, num_load_btn_4], [output_file_4, num_load_btn_4], )
with gr.Row(): with gr.Column(): file_component_invalid = gr.File(
label="Upload File with Invalid file_types", file_types=
|
Demos
|
https://gradio.app/docs/gradio/deletedfiledata
|
Gradio - Deletedfiledata Docs
|
1), [file_component_pdf, num_load_btn_4], [output_file_4, num_load_btn_4], )
with gr.Row(): with gr.Column(): file_component_invalid = gr.File(
label="Upload File with Invalid file_types", file_types=["invalid file_type"],
) with gr.Column(): output_file_5 = gr.File(label="Upload File with Invalid
file_types Output") num_load_btn_5 = gr.Number( label="Load Upload File with
Invalid file_types", value=0 ) file_component_invalid.upload( lambda s, n: (s,
n + 1), [file_component_invalid, num_load_btn_5], [output_file_5,
num_load_btn_5], ) with gr.Row(): with gr.Column(): del_file_input =
gr.File(label="Delete File", file_count="multiple") with gr.Column():
del_file_data = gr.Textbox(label="Delete file data") num_load_btn_6 =
gr.Number(label="Deleted File", value=0) del_file_input.delete( delete_file,
[num_load_btn_6], [del_file_data, num_load_btn_6], ) f =
gr.File(label="Upload many File", file_count="multiple")
f.delete(delete_file) f.delete(delete_file, inputs=None, outputs=None) if
__name__ == "__main__": demo.launch()
import gradio as gr
def delete_file(n: int, file: gr.DeletedFileData):
return [file.file.path, n + 1]
with gr.Blocks() as demo:
with gr.Row():
with gr.Column():
file_component = gr.File(label="Upload Single File", file_count="single")
with gr.Column():
output_file_1 = gr.File(
label="Upload Single File Output", file_count="single"
)
num_load_btn_1 = gr.Number(label="Load Upload Single File", value=0)
file_component.upload(
lambda s, n: (s, n + 1),
[file_component, num_load_btn_1],
[output_file_1, num_load_btn_1],
)
with gr.Row():
with gr.Column():
file_component_multiple = gr.File(
label="Upload Multiple Files", file_count="multiple"
|
Demos
|
https://gradio.app/docs/gradio/deletedfiledata
|
Gradio - Deletedfiledata Docs
|
1],
)
with gr.Row():
with gr.Column():
file_component_multiple = gr.File(
label="Upload Multiple Files", file_count="multiple"
)
with gr.Column():
output_file_2 = gr.File(
label="Upload Multiple Files Output", file_count="multiple"
)
num_load_btn_2 = gr.Number(label="Load Upload Multiple Files", value=0)
file_component_multiple.upload(
lambda s, n: (s, n + 1),
[file_component_multiple, num_load_btn_2],
[output_file_2, num_load_btn_2],
)
with gr.Row():
with gr.Column():
file_component_specific = gr.File(
label="Upload Multiple Files Image/Video",
file_count="multiple",
file_types=["image", "video"],
)
with gr.Column():
output_file_3 = gr.File(
label="Upload Multiple Files Output Image/Video", file_count="multiple"
)
num_load_btn_3 = gr.Number(
label="Load Upload Multiple Files Image/Video", value=0
)
file_component_specific.upload(
lambda s, n: (s, n + 1),
[file_component_specific, num_load_btn_3],
[output_file_3, num_load_btn_3],
)
with gr.Row():
with gr.Column():
file_component_pdf = gr.File(label="Upload PDF File", file_types=[".pdf"])
with gr.Column():
output_file_4 = gr.File(label="Upload PDF File Output")
num_load_btn_4 = gr.Number(label="Load Upload PDF File", value=0)
file_component_pdf.upload(
lambda s, n: (s, n + 1),
[file_component_pdf, num_load_bt
|
Demos
|
https://gradio.app/docs/gradio/deletedfiledata
|
Gradio - Deletedfiledata Docs
|
_btn_4 = gr.Number(label="Load Upload PDF File", value=0)
file_component_pdf.upload(
lambda s, n: (s, n + 1),
[file_component_pdf, num_load_btn_4],
[output_file_4, num_load_btn_4],
)
with gr.Row():
with gr.Column():
file_component_invalid = gr.File(
label="Upload File with Invalid file_types",
file_types=["invalid file_type"],
)
with gr.Column():
output_file_5 = gr.File(label="Upload File with Invalid file_types Output")
num_load_btn_5 = gr.Number(
label="Load Upload File with Invalid file_types", value=0
)
file_component_invalid.upload(
lambda s, n: (s, n + 1),
[file_component_invalid, num_load_btn_5],
[output_file_5, num_load_btn_5],
)
with gr.Row():
with gr.Column():
del_file_input = gr.File(label="Delete File", file_count="multiple")
with gr.Column():
del_file_data = gr.Textbox(label="Delete file data")
num_load_btn_6 = gr.Number(label="Deleted File", value=0)
del_file_input.delete(
delete_file,
[num_load_btn_6],
[del_file_data, num_load_btn_6],
)
f = gr.File(label="Upload many File", file_count="multiple")
f.delete(delete_file)
f.delete(delete_file, inputs=None, outputs=None)
if __name__ == "__main__":
demo.launch()
|
Demos
|
https://gradio.app/docs/gradio/deletedfiledata
|
Gradio - Deletedfiledata Docs
|
Creates a line plot component to display data from a pandas DataFrame.
|
Description
|
https://gradio.app/docs/gradio/lineplot
|
Gradio - Lineplot Docs
|
**As input component** : The data to display in a line plot.
Your function should accept one of these types:
def predict(
value: AltairPlotData | None
)
...
**As output component** : Expects a pandas DataFrame containing the data to
display in the line plot. The DataFrame should contain at least two columns,
one for the x-axis (corresponding to this component's `x` argument) and one
for the y-axis (corresponding to `y`).
Your function should return one of these types:
def predict(···) -> pd.DataFrame | dict | None
...
return value
|
Behavior
|
https://gradio.app/docs/gradio/lineplot
|
Gradio - Lineplot Docs
|
Parameters ▼
value: pd.DataFrame | Callable | None
default `= None`
The pandas dataframe containing the data to display in the plot.
x: str | None
default `= None`
Column corresponding to the x axis. Column can be numeric, datetime, or
string/category.
y: str | None
default `= None`
Column corresponding to the y axis. Column must be numeric.
color: str | None
default `= None`
Column corresponding to series, visualized by color. Column must be
string/category.
title: str | None
default `= None`
The title to display on top of the chart.
x_title: str | None
default `= None`
The title given to the x axis. By default, uses the value of the x parameter.
y_title: str | None
default `= None`
The title given to the y axis. By default, uses the value of the y parameter.
color_title: str | None
default `= None`
The title given to the color legend. By default, uses the value of color
parameter.
x_bin: str | float | None
default `= None`
Grouping used to cluster x values. If x column is numeric, should be number to
bin the x values. If x column is datetime, should be string such as "1h",
"15m", "10s", using "s", "m", "h", "d" suffixes.
y_aggregate: Literal['sum', 'mean', 'median', 'min', 'max', 'count'] | None
default `= None`
Aggregation function used to aggregate y values, used if x_bin is provided or
x is a string/category. Must be one of "sum", "mean", "median", "min", "max".
color_map: dict[str, str] | None
default `= None`
Mapping of series to color names or codes. For example, {"success": "green",
"fail": "FF8888"}.
x_lim: list[float] | None
default `= None`
A tuple or list containing the limits for the x-axis, specified as [x_min,
x_max]. If x column is datetime type, x_lim should be timestamps.
y_lim: list[float | None]
default `= None`
A
|
Initialization
|
https://gradio.app/docs/gradio/lineplot
|
Gradio - Lineplot Docs
|
ple or list containing the limits for the x-axis, specified as [x_min,
x_max]. If x column is datetime type, x_lim should be timestamps.
y_lim: list[float | None]
default `= None`
A tuple of list containing the limits for the y-axis, specified as [y_min,
y_max]. To fix only one of these values, set the other to None, e.g. [0, None]
to scale from 0 to the maximum to value.
x_label_angle: float
default `= 0`
The angle of the x-axis labels in degrees offset clockwise.
y_label_angle: float
default `= 0`
The angle of the y-axis labels in degrees offset clockwise.
x_axis_labels_visible: bool
default `= True`
Whether the x-axis labels should be visible. Can be hidden when many x-axis
labels are present.
caption: str | I18nData | None
default `= None`
The (optional) caption to display below the plot.
sort: Literal['x', 'y', '-x', '-y'] | list[str] | None
default `= None`
The sorting order of the x values, if x column is type string/category. Can be
"x", "y", "-x", "-y", or list of strings that represent the order of the
categories.
tooltip: Literal['axis', 'none', 'all'] | list[str]
default `= "axis"`
The tooltip to display when hovering on a point. "axis" shows the values for
the axis columns, "all" shows all column values, and "none" shows no tooltips.
Can also provide a list of strings representing columns to show in the
tooltip, which will be displayed along with axis values.
height: int | None
default `= None`
The height of the plot in pixels.
label: str | I18nData | None
default `= None`
The (optional) label to display on the top left corner of the plot.
show_label: bool | None
default `= None`
Whether the label should be displayed.
container: bool
default `= True`
If True, will place the component in a container - providing some extra
padding around the border.
|
Initialization
|
https://gradio.app/docs/gradio/lineplot
|
Gradio - Lineplot Docs
|
Whether the label should be displayed.
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.
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.
visible: bool
default `= True`
Whether the plot should be visible.
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.
|
Initialization
|
https://gradio.app/docs/gradio/lineplot
|
Gradio - Lineplot Docs
|
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.
show_fullscreen_button: bool
default `= False`
If True, will show a button to make plot visible in fullscreen mode.
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/lineplot
|
Gradio - Lineplot Docs
|
Class | Interface String Shortcut | Initialization
---|---|---
`gradio.LinePlot` | "lineplot" | Uses default values
|
Shortcuts
|
https://gradio.app/docs/gradio/lineplot
|
Gradio - Lineplot Docs
|
No dataset card yet