text
stringlengths 0
2k
| heading1
stringlengths 4
79
| source_page_url
stringclasses 183
values | source_page_title
stringclasses 183
values |
|---|---|---|---|
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
|
The main Client class for the Python client. This class is used to connect
to a remote Gradio app and call its API endpoints.
|
Description
|
https://gradio.app/docs/python-client/client
|
Python Client - Client Docs
|
from gradio_client import Client
client = Client("abidlabs/whisper-large-v2") connecting to a Hugging Face Space
client.predict("test.mp4", api_name="/predict")
>> What a nice recording! returns the result of the remote API call
client = Client("https://bec81a83-5b5c-471e.gradio.live") connecting to a temporary Gradio share URL
job = client.submit("hello", api_name="/predict") runs the prediction in a background thread
job.result()
>> 49 returns the result of the remote API call (blocking call)
|
Example usage
|
https://gradio.app/docs/python-client/client
|
Python Client - Client Docs
|
Parameters ▼
src: str
either the name of the Hugging Face Space to load, (e.g. "abidlabs/whisper-
large-v2") or the full URL (including "http" or "https") of the hosted Gradio
app to load (e.g. "http://mydomain.com/app" or
"https://bec81a83-5b5c-471e.gradio.live/").
token: str | None
default `= None`
optional Hugging Face token to use to access private Spaces. By default, the
locally saved token is used if there is one. Find your tokens here:
https://huggingface.co/settings/tokens.
max_workers: int
default `= 40`
maximum number of thread workers that can be used to make requests to the
remote Gradio app simultaneously.
verbose: bool
default `= True`
whether the client should print statements to the console.
auth: tuple[str, str] | None
default `= None`
httpx_kwargs: dict[str, Any] | None
default `= None`
additional keyword arguments to pass to `httpx.Client`, `httpx.stream`,
`httpx.get` and `httpx.post`. This can be used to set timeouts, proxies, http
auth, etc.
headers: dict[str, str] | None
default `= None`
additional headers to send to the remote Gradio app on every request. By
default only the HF authorization and user-agent headers are sent. This
parameter will override the default headers if they have the same keys.
download_files: str | Path | Literal[False]
default `= "/tmp/gradio"`
directory where the client should download output files on the local machine
from the remote API. By default, uses the value of the GRADIO_TEMP_DIR
environment variable which, if not set by the user, is a temporary directory
on your machine. If False, the client does not download files and returns a
FileData dataclass object with the filepath on the remote machine instead.
ssl_verify: bool
default `= True`
if False, skips certificate validation which allows the client to connect to
Gradio apps that are using self-signed ce
|
Initialization
|
https://gradio.app/docs/python-client/client
|
Python Client - Client Docs
|
n the remote machine instead.
ssl_verify: bool
default `= True`
if False, skips certificate validation which allows the client to connect to
Gradio apps that are using self-signed certificates.
analytics_enabled: bool
default `= True`
Whether to allow basic telemetry. If None, will use GRADIO_ANALYTICS_ENABLED
environment variable or default to True.
|
Initialization
|
https://gradio.app/docs/python-client/client
|
Python Client - Client Docs
|
Description
Event listeners allow you to respond to user interactions with the UI
components you've defined in a Gradio Blocks app. When a user interacts with
an element, such as changing a slider value or uploading an image, a function
is called.
Supported Event Listeners
The Client component supports the following event listeners. Each event
listener takes the same parameters, which are listed in the Event Parameters
table below.
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 `token` or be logged in via the Hugging Face Hub CLI. <br> The new
Space will be private by default and use the same hardware as the original
Space. This can be changed by using the `private` and `hardware` parameters.
For hardware upgrades (beyond the basic CPU tier), you may be required to
provide billing information on Hugging Face:
<https://huggingface.co/settings/billing> <br>
Event Parameters
Parameters ▼
|
Event Listeners
|
https://gradio.app/docs/python-client/client
|
Python Client - Client Docs
|
grades (beyond the basic CPU tier), you may be required to
provide billing information on Hugging Face:
<https://huggingface.co/settings/billing> <br>
Event Parameters
Parameters ▼
args: <class 'inspect._empty'>
The positional arguments to pass to the remote API endpoint. The order of the
arguments must match the order of the inputs in the Gradio app.
api_name: str | None
default `= None`
The name of the API endpoint to call starting with a leading slash, e.g.
"/predict". Does not need to be provided if the Gradio app has only one named
API endpoint.
fn_index: int | None
default `= None`
As an alternative to api_name, this parameter takes the index of the API
endpoint to call, e.g. 0. Both api_name and fn_index can be provided, but if
they conflict, api_name will take precedence.
headers: dict[str, str] | None
default `= None`
Additional headers to send to the remote Gradio app on this request. This
parameter will overrides the headers provided in the Client constructor if
they have the same keys.
kwargs: <class 'inspect._empty'>
The keyword arguments to pass to the remote API endpoint.
|
Event Listeners
|
https://gradio.app/docs/python-client/client
|
Python Client - Client Docs
|
`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://huggingface.co/proxy/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
|
Gradio features [blocks](https://www.gradio.app/docs/blocks) to easily layout applications. To use this feature, you need to stack or nest layout components and create a hierarchy with them. This isn't difficult to implement and maintain for small projects, but after the project gets more complex, this component hierarchy becomes difficult to maintain and reuse.
In this guide, we are going to explore how we can wrap the layout classes to create more maintainable and easy-to-read applications without sacrificing flexibility.
|
Introduction
|
https://gradio.app/guides/wrapping-layouts
|
Other Tutorials - Wrapping Layouts Guide
|
We are going to follow the implementation from this Huggingface Space example:
<gradio-app
space="gradio/wrapping-layouts">
</gradio-app>
|
Example
|
https://gradio.app/guides/wrapping-layouts
|
Other Tutorials - Wrapping Layouts Guide
|
The wrapping utility has two important classes. The first one is the ```LayoutBase``` class and the other one is the ```Application``` class.
We are going to look at the ```render``` and ```attach_event``` functions of them for brevity. You can look at the full implementation from [the example code](https://huggingface.co/spaces/WoWoWoWololo/wrapping-layouts/blob/main/app.py).
So let's start with the ```LayoutBase``` class.
LayoutBase Class
1. Render Function
Let's look at the ```render``` function in the ```LayoutBase``` class:
```python
other LayoutBase implementations
def render(self) -> None:
with self.main_layout:
for renderable in self.renderables:
renderable.render()
self.main_layout.render()
```
This is a little confusing at first but if you consider the default implementation you can understand it easily.
Let's look at an example:
In the default implementation, this is what we're doing:
```python
with Row():
left_textbox = Textbox(value="left_textbox")
right_textbox = Textbox(value="right_textbox")
```
Now, pay attention to the Textbox variables. These variables' ```render``` parameter is true by default. So as we use the ```with``` syntax and create these variables, they are calling the ```render``` function under the ```with``` syntax.
We know the render function is called in the constructor with the implementation from the ```gradio.blocks.Block``` class:
```python
class Block:
constructor parameters are omitted for brevity
def __init__(self, ...):
other assign functions
if render:
self.render()
```
So our implementation looks like this:
```python
self.main_layout -> Row()
with self.main_layout:
left_textbox.render()
right_textbox.render()
```
What this means is by calling the components' render functions under the ```with``` syntax, we are actually simulating the default implementation.
So now let's consider two nested ```with```s to see ho
|
Implementation
|
https://gradio.app/guides/wrapping-layouts
|
Other Tutorials - Wrapping Layouts Guide
|
at this means is by calling the components' render functions under the ```with``` syntax, we are actually simulating the default implementation.
So now let's consider two nested ```with```s to see how the outer one works. For this, let's expand our example with the ```Tab``` component:
```python
with Tab():
with Row():
first_textbox = Textbox(value="first_textbox")
second_textbox = Textbox(value="second_textbox")
```
Pay attention to the Row and Tab components this time. We have created the Textbox variables above and added them to Row with the ```with``` syntax. Now we need to add the Row component to the Tab component. You can see that the Row component is created with default parameters, so its render parameter is true, that's why the render function is going to be executed under the Tab component's ```with``` syntax.
To mimic this implementation, we need to call the ```render``` function of the ```main_layout``` variable after the ```with``` syntax of the ```main_layout``` variable.
So the implementation looks like this:
```python
with tab_main_layout:
with row_main_layout:
first_textbox.render()
second_textbox.render()
row_main_layout.render()
tab_main_layout.render()
```
The default implementation and our implementation are the same, but we are using the render function ourselves. So it requires a little work.
Now, let's take a look at the ```attach_event``` function.
2. Attach Event Function
The function is left as not implemented because it is specific to the class, so each class has to implement its `attach_event` function.
```python
other LayoutBase implementations
def attach_event(self, block_dict: Dict[str, Block]) -> None:
raise NotImplementedError
```
Check out the ```block_dict``` variable in the ```Application``` class's ```attach_event``` function.
Application Class
1. Render Function
```python
other Application implementations
def _render(self):
|
Implementation
|
https://gradio.app/guides/wrapping-layouts
|
Other Tutorials - Wrapping Layouts Guide
|
ct``` variable in the ```Application``` class's ```attach_event``` function.
Application Class
1. Render Function
```python
other Application implementations
def _render(self):
with self.app:
for child in self.children:
child.render()
self.app.render()
```
From the explanation of the ```LayoutBase``` class's ```render``` function, we can understand the ```child.render``` part.
So let's look at the bottom part, why are we calling the ```app``` variable's ```render``` function? It's important to call this function because if we look at the implementation in the ```gradio.blocks.Blocks``` class, we can see that it is adding the components and event functions into the root component. To put it another way, it is creating and structuring the gradio application.
2. Attach Event Function
Let's see how we can attach events to components:
```python
other Application implementations
def _attach_event(self):
block_dict: Dict[str, Block] = {}
for child in self.children:
block_dict.update(child.global_children_dict)
with self.app:
for child in self.children:
try:
child.attach_event(block_dict=block_dict)
except NotImplementedError:
print(f"{child.name}'s attach_event is not implemented")
```
You can see why the ```global_children_list``` is used in the ```LayoutBase``` class from the example code. With this, all the components in the application are gathered into one dictionary, so the component can access all the components with their names.
The ```with``` syntax is used here again to attach events to components. If we look at the ```__exit__``` function in the ```gradio.blocks.Blocks``` class, we can see that it is calling the ```attach_load_events``` function which is used for setting event triggers to components. So we have to use the ```with``` syntax to trigger the ```_
|
Implementation
|
https://gradio.app/guides/wrapping-layouts
|
Other Tutorials - Wrapping Layouts Guide
|
Blocks``` class, we can see that it is calling the ```attach_load_events``` function which is used for setting event triggers to components. So we have to use the ```with``` syntax to trigger the ```__exit__``` function.
Of course, we can call ```attach_load_events``` without using the ```with``` syntax, but the function needs a ```Context.root_block```, and it is set in the ```__enter__``` function. So we used the ```with``` syntax here rather than calling the function ourselves.
|
Implementation
|
https://gradio.app/guides/wrapping-layouts
|
Other Tutorials - Wrapping Layouts Guide
|
In this guide, we saw
- How we can wrap the layouts
- How components are rendered
- How we can structure our application with wrapped layout classes
Because the classes used in this guide are used for demonstration purposes, they may still not be totally optimized or modular. But that would make the guide much longer!
I hope this guide helps you gain another view of the layout classes and gives you an idea about how you can use them for your needs. See the full implementation of our example [here](https://huggingface.co/spaces/WoWoWoWololo/wrapping-layouts/blob/main/app.py).
|
Conclusion
|
https://gradio.app/guides/wrapping-layouts
|
Other Tutorials - Wrapping Layouts Guide
|
Gradio is a Python library that allows you to quickly create customizable web apps for your machine learning models and data processing pipelines. Gradio apps can be deployed on [Hugging Face Spaces](https://hf.space) for free.
In some cases though, you might want to deploy a Gradio app on your own web server. You might already be using [Nginx](https://www.nginx.com/), a highly performant web server, to serve your website (say `https://www.example.com`), and you want to attach Gradio to a specific subpath on your website (e.g. `https://www.example.com/gradio-demo`).
In this Guide, we will guide you through the process of running a Gradio app behind Nginx on your own web server to achieve this.
**Prerequisites**
1. A Linux web server with [Nginx installed](https://www.nginx.com/blog/setting-up-nginx/) and [Gradio installed](/quickstart)
2. A working Gradio app saved as a python file on your web server
|
Introduction
|
https://gradio.app/guides/running-gradio-on-your-web-server-with-nginx
|
Other Tutorials - Running Gradio On Your Web Server With Nginx Guide
|
1. Start by editing the Nginx configuration file on your web server. By default, this is located at: `/etc/nginx/nginx.conf`
In the `http` block, add the following line to include server block configurations from a separate file:
```bash
include /etc/nginx/sites-enabled/*;
```
2. Create a new file in the `/etc/nginx/sites-available` directory (create the directory if it does not already exist), using a filename that represents your app, for example: `sudo nano /etc/nginx/sites-available/my_gradio_app`
3. Paste the following into your file editor:
```bash
server {
listen 80;
server_name example.com www.example.com; Change this to your domain name
location /gradio-demo/ { Change this if you'd like to server your Gradio app on a different path
proxy_pass http://127.0.0.1:7860/; Change this if your Gradio app will be running on a different port
proxy_buffering off;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
Tip: Setting the `X-Forwarded-Host` and `X-Forwarded-Proto` headers is important as Gradio uses these, in conjunction with the `root_path` parameter discussed below, to construct the public URL that your app is being served on. Gradio uses the public URL to fetch various static assets. If these headers are not set, your Gradio app may load in a broken state.
*Note:* The `$host` variable does not include the host port. If you are serving your Gradio application on a raw IP address and port, you should use the `$http_host` variable instead, in these lines:
```bash
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;
```
|
Editing your Nginx configuration file
|
https://gradio.app/guides/running-gradio-on-your-web-server-with-nginx
|
Other Tutorials - Running Gradio On Your Web Server With Nginx Guide
|
1. Before you launch your Gradio app, you'll need to set the `root_path` to be the same as the subpath that you specified in your nginx configuration. This is necessary for Gradio to run on any subpath besides the root of the domain.
*Note:* Instead of a subpath, you can also provide a complete URL for `root_path` (beginning with `http` or `https`) in which case the `root_path` is treated as an absolute URL instead of a URL suffix (but in this case, you'll need to update the `root_path` if the domain changes).
Here's a simple example of a Gradio app with a custom `root_path` corresponding to the Nginx configuration above.
```python
import gradio as gr
import time
def test(x):
time.sleep(4)
return x
gr.Interface(test, "textbox", "textbox").queue().launch(root_path="/gradio-demo")
```
2. Start a `tmux` session by typing `tmux` and pressing enter (optional)
It's recommended that you run your Gradio app in a `tmux` session so that you can keep it running in the background easily
3. Then, start your Gradio app. Simply type in `python` followed by the name of your Gradio python file. By default, your app will run on `localhost:7860`, but if it starts on a different port, you will need to update the nginx configuration file above.
|
Run your Gradio app on your web server
|
https://gradio.app/guides/running-gradio-on-your-web-server-with-nginx
|
Other Tutorials - Running Gradio On Your Web Server With Nginx Guide
|
1. If you are in a tmux session, exit by typing CTRL+B (or CMD+B), followed by the "D" key.
2. Finally, restart nginx by running `sudo systemctl restart nginx`.
And that's it! If you visit `https://example.com/gradio-demo` on your browser, you should see your Gradio app running there
|
Restart Nginx
|
https://gradio.app/guides/running-gradio-on-your-web-server-with-nginx
|
Other Tutorials - Running Gradio On Your Web Server With Nginx Guide
|
Tabular data science is the most widely used domain of machine learning, with problems ranging from customer segmentation to churn prediction. Throughout various stages of the tabular data science workflow, communicating your work to stakeholders or clients can be cumbersome; which prevents data scientists from focusing on what matters, such as data analysis and model building. Data scientists can end up spending hours building a dashboard that takes in dataframe and returning plots, or returning a prediction or plot of clusters in a dataset. In this guide, we'll go through how to use `gradio` to improve your data science workflows. We will also talk about how to use `gradio` and [skops](https://skops.readthedocs.io/en/stable/) to build interfaces with only one line of code!
Prerequisites
Make sure you have the `gradio` Python package already [installed](/getting_started).
|
Introduction
|
https://gradio.app/guides/using-gradio-for-tabular-workflows
|
Other Tutorials - Using Gradio For Tabular Workflows Guide
|
We will take a look at how we can create a simple UI that predicts failures based on product information.
```python
import gradio as gr
import pandas as pd
import joblib
import datasets
inputs = [gr.Dataframe(row_count = (2, "dynamic"), col_count=(4,"dynamic"), label="Input Data", interactive=1)]
outputs = [gr.Dataframe(row_count = (2, "dynamic"), col_count=(1, "fixed"), label="Predictions", headers=["Failures"])]
model = joblib.load("model.pkl")
we will give our dataframe as example
df = datasets.load_dataset("merve/supersoaker-failures")
df = df["train"].to_pandas()
def infer(input_dataframe):
return pd.DataFrame(model.predict(input_dataframe))
gr.Interface(fn = infer, inputs = inputs, outputs = outputs, examples = [[df.head(2)]]).launch()
```
Let's break down above code.
- `fn`: the inference function that takes input dataframe and returns predictions.
- `inputs`: the component we take our input with. We define our input as dataframe with 2 rows and 4 columns, which initially will look like an empty dataframe with the aforementioned shape. When the `row_count` is set to `dynamic`, you don't have to rely on the dataset you're inputting to pre-defined component.
- `outputs`: The dataframe component that stores outputs. This UI can take single or multiple samples to infer, and returns 0 or 1 for each sample in one column, so we give `row_count` as 2 and `col_count` as 1 above. `headers` is a list made of header names for dataframe.
- `examples`: You can either pass the input by dragging and dropping a CSV file, or a pandas DataFrame through examples, which headers will be automatically taken by the interface.
We will now create an example for a minimal data visualization dashboard. You can find a more comprehensive version in the related Spaces.
<gradio-app space="gradio/tabular-playground"></gradio-app>
```python
import gradio as gr
import pandas as pd
import datasets
import seaborn as sns
import matplotlib.pyplot as plt
df = datasets.load_dataset
|
Let's Create a Simple Interface!
|
https://gradio.app/guides/using-gradio-for-tabular-workflows
|
Other Tutorials - Using Gradio For Tabular Workflows Guide
|
app space="gradio/tabular-playground"></gradio-app>
```python
import gradio as gr
import pandas as pd
import datasets
import seaborn as sns
import matplotlib.pyplot as plt
df = datasets.load_dataset("merve/supersoaker-failures")
df = df["train"].to_pandas()
df.dropna(axis=0, inplace=True)
def plot(df):
plt.scatter(df.measurement_13, df.measurement_15, c = df.loading,alpha=0.5)
plt.savefig("scatter.png")
df['failure'].value_counts().plot(kind='bar')
plt.savefig("bar.png")
sns.heatmap(df.select_dtypes(include="number").corr())
plt.savefig("corr.png")
plots = ["corr.png","scatter.png", "bar.png"]
return plots
inputs = [gr.Dataframe(label="Supersoaker Production Data")]
outputs = [gr.Gallery(label="Profiling Dashboard", columns=(1,3))]
gr.Interface(plot, inputs=inputs, outputs=outputs, examples=[df.head(100)], title="Supersoaker Failures Analysis Dashboard").launch()
```
<gradio-app space="gradio/gradio-analysis-dashboard-minimal"></gradio-app>
We will use the same dataset we used to train our model, but we will make a dashboard to visualize it this time.
- `fn`: The function that will create plots based on data.
- `inputs`: We use the same `Dataframe` component we used above.
- `outputs`: The `Gallery` component is used to keep our visualizations.
- `examples`: We will have the dataset itself as the example.
|
Let's Create a Simple Interface!
|
https://gradio.app/guides/using-gradio-for-tabular-workflows
|
Other Tutorials - Using Gradio For Tabular Workflows Guide
|
`skops` is a library built on top of `huggingface_hub` and `sklearn`. With the recent `gradio` integration of `skops`, you can build tabular data interfaces with one line of code!
```python
import gradio as gr
title and description are optional
title = "Supersoaker Defective Product Prediction"
description = "This model predicts Supersoaker production line failures. Drag and drop any slice from dataset or edit values as you wish in below dataframe component."
gr.load("huggingface/scikit-learn/tabular-playground", title=title, description=description).launch()
```
<gradio-app space="gradio/gradio-skops-integration"></gradio-app>
`sklearn` models pushed to Hugging Face Hub using `skops` include a `config.json` file that contains an example input with column names, the task being solved (that can either be `tabular-classification` or `tabular-regression`). From the task type, `gradio` constructs the `Interface` and consumes column names and the example input to build it. You can [refer to skops documentation on hosting models on Hub](https://skops.readthedocs.io/en/latest/auto_examples/plot_hf_hub.htmlsphx-glr-auto-examples-plot-hf-hub-py) to learn how to push your models to Hub using `skops`.
|
Easily load tabular data interfaces with one line of code using skops
|
https://gradio.app/guides/using-gradio-for-tabular-workflows
|
Other Tutorials - Using Gradio For Tabular Workflows Guide
|
App-level parameters have been moved from `Blocks` to `launch()`
The `gr.Blocks` class constructor previously contained several parameters that applied to your entire Gradio app, specifically:
* `theme`: The theme for your Gradio app
* `css`: Custom CSS code as a string
* `css_paths`: Paths to custom CSS files
* `js`: Custom JavaScript code
* `head`: Custom HTML code to insert in the head of the page
* `head_paths`: Paths to custom HTML files to insert in the head
Since `gr.Blocks` can be nested and are not necessarily unique to a Gradio app, these parameters have now been moved to `Blocks.launch()`, which can only be called once for your entire Gradio app.
**Before (Gradio 5.x):**
```python
import gradio as gr
with gr.Blocks(
theme=gr.themes.Soft(),
css=".my-class { color: red; }",
) as demo:
gr.Textbox(label="Input")
demo.launch()
```
**After (Gradio 6.x):**
```python
import gradio as gr
with gr.Blocks() as demo:
gr.Textbox(label="Input")
demo.launch(
theme=gr.themes.Soft(),
css=".my-class { color: red; }",
)
```
This change makes it clearer that these parameters apply to the entire app and not to individual `Blocks` instances.
`show_api` parameter replaced with `footer_links`
The `show_api` parameter in `launch()` has been replaced with a more flexible `footer_links` parameter that allows you to control which links appear in the footer of your Gradio app.
**In Gradio 5.x:**
- `show_api=True` (default) showed the API documentation link in the footer
- `show_api=False` hid the API documentation link
**In Gradio 6.x:**
- `footer_links` accepts a list of strings: `["api", "gradio", "settings"]`
- You can now control precisely which footer links are shown:
- `"api"`: Shows the API documentation link
- `"gradio"`: Shows the "Built with Gradio" link
- `"settings"`: Shows the settings link
**Before (Gradio 5.x):**
```python
import gradio as gr
with gr.Blocks() as demo:
gr.Textbox(label="Input")
demo.launch(sho
|
App-level Changes
|
https://gradio.app/guides/gradio-6-migration-guide
|
Other Tutorials - Gradio 6 Migration Guide Guide
|
he "Built with Gradio" link
- `"settings"`: Shows the settings link
**Before (Gradio 5.x):**
```python
import gradio as gr
with gr.Blocks() as demo:
gr.Textbox(label="Input")
demo.launch(show_api=False)
```
**After (Gradio 6.x):**
```python
import gradio as gr
with gr.Blocks() as demo:
gr.Textbox(label="Input")
demo.launch(footer_links=["gradio", "settings"])
```
To replicate the old behavior:
- `show_api=True` → `footer_links=["api", "gradio", "settings"]` (or just omit the parameter, as this is the default)
- `show_api=False` → `footer_links=["gradio", "settings"]`
Event listener parameters: `show_api` removed and `api_name=False` no longer supported
In event listeners (such as `.click()`, `.change()`, etc.), the `show_api` parameter has been removed, and `api_name` no longer accepts `False` as a valid value. These have been replaced with a new `api_visibility` parameter that provides more fine-grained control.
**In Gradio 5.x:**
- `show_api=True` (default) showed the endpoint in the API documentation
- `show_api=False` hid the endpoint from API docs but still allowed downstream apps to use it
- `api_name=False` completely disabled the API endpoint (no downstream apps could use it)
**In Gradio 6.x:**
- `api_visibility` accepts one of three string values:
- `"public"`: The endpoint is shown in API docs and accessible to all (equivalent to old `show_api=True`)
- `"undocumented"`: The endpoint is hidden from API docs but still accessible to downstream apps (equivalent to old `show_api=False`)
- `"private"`: The endpoint is completely disabled and inaccessible (equivalent to old `api_name=False`)
**Before (Gradio 5.x):**
```python
import gradio as gr
with gr.Blocks() as demo:
btn = gr.Button("Click me")
output = gr.Textbox()
btn.click(fn=lambda: "Hello", outputs=output, show_api=False)
demo.launch()
```
Or to completely disable the API:
```python
btn.click(fn=lambda: "Hello", outputs=output, api_name=False)
`
|
App-level Changes
|
https://gradio.app/guides/gradio-6-migration-guide
|
Other Tutorials - Gradio 6 Migration Guide Guide
|
btn.click(fn=lambda: "Hello", outputs=output, show_api=False)
demo.launch()
```
Or to completely disable the API:
```python
btn.click(fn=lambda: "Hello", outputs=output, api_name=False)
```
**After (Gradio 6.x):**
```python
import gradio as gr
with gr.Blocks() as demo:
btn = gr.Button("Click me")
output = gr.Textbox()
btn.click(fn=lambda: "Hello", outputs=output, api_visibility="undocumented")
demo.launch()
```
Or to completely disable the API:
```python
btn.click(fn=lambda: "Hello", outputs=output, api_visibility="private")
```
To replicate the old behavior:
- `show_api=True` → `api_visibility="public"` (or just omit the parameter, as this is the default)
- `show_api=False` → `api_visibility="undocumented"`
- `api_name=False` → `api_visibility="private"`
`like_user_message` moved from `.like()` event to constructor
The `like_user_message` parameter has been moved from the `.like()` event listener to the Chatbot constructor.
**Before (Gradio 5.x):**
```python
chatbot = gr.Chatbot()
chatbot.like(print_like_dislike, None, None, like_user_message=True)
```
**After (Gradio 6.x):**
```python
chatbot = gr.Chatbot(like_user_message=True)
chatbot.like(print_like_dislike, None, None)
```
Default API names for `Interface` and `ChatInterface` now use function names
The default API endpoint names for `gr.Interface` and `gr.ChatInterface` have changed to be consistent with how `gr.Blocks` events work and to better support MCP (Model Context Protocol) tools.
**In Gradio 5.x:**
- `gr.Interface` had a default API name of `/predict`
- `gr.ChatInterface` had a default API name of `/chat`
**In Gradio 6.x:**
- Both `gr.Interface` and `gr.ChatInterface` now use the name of the function you pass in as the default API endpoint name
- This makes the API more descriptive and consistent with `gr.Blocks` behavior
E.g. if your Gradio app is:
```python
import gradio as gr
def generate_text(prompt):
return f"Generated: {prompt}"
|
App-level Changes
|
https://gradio.app/guides/gradio-6-migration-guide
|
Other Tutorials - Gradio 6 Migration Guide Guide
|
This makes the API more descriptive and consistent with `gr.Blocks` behavior
E.g. if your Gradio app is:
```python
import gradio as gr
def generate_text(prompt):
return f"Generated: {prompt}"
demo = gr.Interface(fn=generate_text, inputs="text", outputs="text")
demo.launch()
```
Previously, the API endpoint that Gradio generated would be: `/predict`. Now, the API endpoint will be: `/generate_text`
**To maintain the old endpoint names:**
If you need to keep the old endpoint names for backward compatibility (e.g., if you have external services calling these endpoints), you can explicitly set the `api_name` parameter:
```python
demo = gr.Interface(fn=generate_text, inputs="text", outputs="text", api_name="predict")
```
Similarly for `ChatInterface`:
```python
demo = gr.ChatInterface(fn=chat_function, api_name="chat")
```
`gr.Chatbot` and `gr.ChatInterface` tuple format removed
The tuple format for chatbot messages has been removed in Gradio 6.0. You must now use the messages format with dictionaries containing "role" and "content" keys.
**In Gradio 5.x:**
- You could use `type="tuples"` or the default tuple format: `[["user message", "assistant message"], ...]`
- The tuple format was a list of lists where each inner list had two elements: `[user_message, assistant_message]`
**In Gradio 6.x:**
- Only the messages format is supported: `type="messages"`
- Messages must be dictionaries with "role" and "content" keys: `[{"role": "user", "content": "Hello"}, {"role": "assistant", "content": "Hi there!"}]`
**Before (Gradio 5.x):**
```python
import gradio as gr
Using tuple format
chatbot = gr.Chatbot(value=[["Hello", "Hi there!"]])
```
Or with `type="tuples"`:
```python
chatbot = gr.Chatbot(value=[["Hello", "Hi there!"]], type="tuples")
```
**After (Gradio 6.x):**
```python
import gradio as gr
Must use messages format
chatbot = gr.Chatbot(
value=[
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hi the
|
App-level Changes
|
https://gradio.app/guides/gradio-6-migration-guide
|
Other Tutorials - Gradio 6 Migration Guide Guide
|
adio 6.x):**
```python
import gradio as gr
Must use messages format
chatbot = gr.Chatbot(
value=[
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hi there!"}
],
type="messages"
)
```
Similarly for `gr.ChatInterface`, if you were manually setting the chat history:
```python
Before (Gradio 5.x)
demo = gr.ChatInterface(
fn=chat_function,
examples=[["Hello", "Hi there!"]]
)
After (Gradio 6.x)
demo = gr.ChatInterface(
fn=chat_function,
examples=[{"role": "user", "content": "Hello"}, {"role": "assistant", "content": "Hi there!"}]
)
```
**Note:** If you're using `gr.ChatInterface` with a function that returns messages, the function should return messages in the new format. The tuple format is no longer supported.
`gr.ChatInterface` `history` format now uses structured content
The `history` format in `gr.ChatInterface` has been updated to consistently use OpenAI-style structured content format. Content is now always a list of content blocks, even for simple text messages.
**In Gradio 5.x:**
- Content could be a simple string: `{"role": "user", "content": "Hello"}`
- Simple text messages used a string directly
**In Gradio 6.x:**
- Content is always a list of content blocks: `{"role": "user", "content": [{"type": "text", "text": "Hello"}]}`
- This format is consistent with OpenAI's message format and supports multimodal content (text, images, etc.)
**Before (Gradio 5.x):**
```python
history = [
{"role": "user", "content": "What is the capital of France?"},
{"role": "assistant", "content": "Paris"}
]
```
**After (Gradio 6.x):**
```python
history = [
{"role": "user", "content": [{"type": "text", "text": "What is the capital of France?"}]},
{"role": "assistant", "content": [{"type": "text", "text": "Paris"}]}
]
```
**With files:**
When files are uploaded in the chat, they are represented as content blocks with `"type": "file"`. All content blocks (files and text) are gro
|
App-level Changes
|
https://gradio.app/guides/gradio-6-migration-guide
|
Other Tutorials - Gradio 6 Migration Guide Guide
|
type": "text", "text": "Paris"}]}
]
```
**With files:**
When files are uploaded in the chat, they are represented as content blocks with `"type": "file"`. All content blocks (files and text) are grouped together in the same message's content array:
```python
history = [
{
"role": "user",
"content": [
{"type": "file", "file": {"path": "cat1.png"}},
{"type": "file", "file": {"path": "cat2.png"}},
{"type": "text", "text": "What's the difference between these two images?"}
]
}
]
```
This structured format allows for multimodal content (text, images, files, etc.) in chat messages, making it consistent with OpenAI's API format. All files uploaded in a single message are grouped together in the `content` array along with any text content.
`cache_examples` parameter updated and `cache_mode` introduced
The `cache_examples` parameter (used in `Interface`, `ChatInterface`, and `Examples`) no longer accepts the string value `"lazy"`. It now strictly accepts boolean values (`True` or `False`). To control the caching strategy, a new `cache_mode` parameter has been introduced.
**In Gradio 5.x:**
- `cache_examples` accepted `True`, `False`, or `"lazy"`.
**In Gradio 6.x:**
- `cache_examples` only accepts `True` or `False`.
- `cache_mode` accepts `"eager"` (default) or `"lazy"`.
**Before (Gradio 5.x):**
```python
import gradio as gr
demo = gr.Interface(
fn=predict,
inputs="text",
outputs="text",
examples=["Hello", "World"],
cache_examples="lazy"
)
```
**After (Gradio 6.x):**
You must now set `cache_examples=True` and specify the mode separately:
```python
import gradio as gr
demo = gr.Interface(
fn=predict,
inputs="text",
outputs="text",
examples=["Hello", "World"],
cache_examples=True,
cache_mode="lazy"
)
```
If you previously used `cache_examples=True` (which implied eager caching), no changes are required, as `cache_mode` defaults to `"eager"`.
|
App-level Changes
|
https://gradio.app/guides/gradio-6-migration-guide
|
Other Tutorials - Gradio 6 Migration Guide Guide
|
ld"],
cache_examples=True,
cache_mode="lazy"
)
```
If you previously used `cache_examples=True` (which implied eager caching), no changes are required, as `cache_mode` defaults to `"eager"`.
|
App-level Changes
|
https://gradio.app/guides/gradio-6-migration-guide
|
Other Tutorials - Gradio 6 Migration Guide Guide
|
`gr.Video` no longer accepts tuple values for video and subtitles
The tuple format for returning video with subtitles has been deprecated. Instead of returning a tuple `(video_path, subtitle_path)`, you should now use the `gr.Video` component directly with the `subtitles` parameter.
**In Gradio 5.x:**
- You could return a tuple of `(video_path, subtitle_path)` from a function
- The tuple format was `(str | Path, str | Path | None)`
**In Gradio 6.x:**
- Return a `gr.Video` component instance with the `subtitles` parameter
- This provides more flexibility and consistency with other components
**Before (Gradio 5.x):**
```python
import gradio as gr
def generate_video_with_subtitles(input):
video_path = "output.mp4"
subtitle_path = "subtitles.srt"
return (video_path, subtitle_path)
demo = gr.Interface(
fn=generate_video_with_subtitles,
inputs="text",
outputs=gr.Video()
)
demo.launch()
```
**After (Gradio 6.x):**
```python
import gradio as gr
def generate_video_with_subtitles(input):
video_path = "output.mp4"
subtitle_path = "subtitles.srt"
return gr.Video(value=video_path, subtitles=subtitle_path)
demo = gr.Interface(
fn=generate_video_with_subtitles,
inputs="text",
outputs=gr.Video()
)
demo.launch()
```
`gr.HTML` `padding` parameter default changed to `False`
The default value of the `padding` parameter in `gr.HTML` has been changed from `True` to `False` for consistency with `gr.Markdown`.
**In Gradio 5.x:**
- `padding=True` was the default for `gr.HTML`
- HTML components had padding by default
**In Gradio 6.x:**
- `padding=False` is the default for `gr.HTML`
- This matches the default behavior of `gr.Markdown` for consistency
**To maintain the old behavior:**
If you want to keep the padding that was present in Gradio 5.x, explicitly set `padding=True`:
```python
html = gr.HTML("<div>Content</div>", padding=True)
```
`gr.Dataframe` `row_count` and `col_count` parameters restructured
The `r
|
Component-level Changes
|
https://gradio.app/guides/gradio-6-migration-guide
|
Other Tutorials - Gradio 6 Migration Guide Guide
|
present in Gradio 5.x, explicitly set `padding=True`:
```python
html = gr.HTML("<div>Content</div>", padding=True)
```
`gr.Dataframe` `row_count` and `col_count` parameters restructured
The `row_count` and `col_count` parameters in `gr.Dataframe` have been restructured to provide more flexibility and clarity. The tuple format for specifying fixed/dynamic behavior has been replaced with separate parameters for initial counts and limits.
**In Gradio 5.x:**
- `row_count: int | tuple[int, str]` - Could be an int or tuple like `(5, "fixed")` or `(5, "dynamic")`
- `col_count: int | tuple[int, str] | None` - Could be an int or tuple like `(3, "fixed")` or `(3, "dynamic")`
**In Gradio 6.x:**
- `row_count: int | None` - Just the initial number of rows to display
- `row_limits: tuple[int | None, int | None] | None` - Tuple specifying (min_rows, max_rows) constraints
- `column_count: int | None` - The initial number of columns to display
- `column_limits: tuple[int | None, int | None] | None` - Tuple specifying (min_columns, max_columns) constraints
**Before (Gradio 5.x):**
```python
import gradio as gr
Fixed number of rows (users can't add/remove rows)
df = gr.Dataframe(row_count=(5, "fixed"), col_count=(3, "dynamic"))
```
Or with dynamic rows:
```python
Dynamic rows (users can add/remove rows)
df = gr.Dataframe(row_count=(5, "dynamic"), col_count=(3, "fixed"))
```
Or with just integers (defaults to dynamic):
```python
df = gr.Dataframe(row_count=5, col_count=3)
```
**After (Gradio 6.x):**
```python
import gradio as gr
Fixed number of rows (users can't add/remove rows)
df = gr.Dataframe(row_count=5, row_limits=(5, 5), column_count=3, column_limits=None)
```
Or with dynamic rows (users can add/remove rows):
```python
Dynamic rows with no limits
df = gr.Dataframe(row_count=5, row_limits=None, column_count=3, column_limits=None)
```
Or with min/max constraints:
```python
Rows between 3 and 10, columns between 2 and 5
df = gr.Dataframe(row_count=
|
Component-level Changes
|
https://gradio.app/guides/gradio-6-migration-guide
|
Other Tutorials - Gradio 6 Migration Guide Guide
|
r.Dataframe(row_count=5, row_limits=None, column_count=3, column_limits=None)
```
Or with min/max constraints:
```python
Rows between 3 and 10, columns between 2 and 5
df = gr.Dataframe(row_count=5, row_limits=(3, 10), column_count=3, column_limits=(2, 5))
```
**Migration examples:**
- `row_count=(5, "fixed")` → `row_count=5, row_limits=(5, 5)`
- `row_count=(5, "dynamic")` → `row_count=5, row_limits=None`
- `row_count=5` → `row_count=5, row_limits=None` (same behavior)
- `col_count=(3, "fixed")` → `column_count=3, column_limits=(3, 3)`
- `col_count=(3, "dynamic")` → `column_count=3, column_limits=None`
- `col_count=3` → `column_count=3, column_limits=None` (same behavior)
`allow_tags=True` is now the default for `gr.Chatbot`
Due to the rise in LLMs returning HTML, markdown tags, and custom tags (such as `<thinking>` tags), the default value of `allow_tags` in `gr.Chatbot` has changed from `False` to `True` in Gradio 6.
**In Gradio 5.x:**
- `allow_tags=False` was the default
- All HTML and custom tags were sanitized/removed from chatbot messages (unless explicitly allowed)
**In Gradio 6.x:**
- `allow_tags=True` is the default
- All custom tags (non-standard HTML tags) are preserved in chatbot messages
- Standard HTML tags are still sanitized for security unless `sanitize_html=False`
**Before (Gradio 5.x):**
```python
import gradio as gr
chatbot = gr.Chatbot()
```
This would remove all tags from messages, including custom tags like `<thinking>`.
**After (Gradio 6.x):**
```python
import gradio as gr
chatbot = gr.Chatbot()
```
This will now preserve custom tags like `<thinking>` in the messages.
**To maintain the old behavior:**
If you want to continue removing all tags from chatbot messages (the old default behavior), explicitly set `allow_tags=False`:
```python
import gradio as gr
chatbot = gr.Chatbot(allow_tags=False)
```
**Note:** You can also specify a list of specific tags to allow:
```python
chatbot = gr.Chatbot(allow_tags=["thinking",
|
Component-level Changes
|
https://gradio.app/guides/gradio-6-migration-guide
|
Other Tutorials - Gradio 6 Migration Guide Guide
|
e`:
```python
import gradio as gr
chatbot = gr.Chatbot(allow_tags=False)
```
**Note:** You can also specify a list of specific tags to allow:
```python
chatbot = gr.Chatbot(allow_tags=["thinking", "tool_call"])
```
This will only preserve `<thinking>` and `<tool_call>` tags while removing all other custom tags.
Other removed component parameters
Several component parameters have been removed in Gradio 6.0. These parameters were previously deprecated and have now been fully removed.
`gr.Chatbot` removed parameters
**`bubble_full_width`** - This parameter has been removed as it no longer has any effect.
**`resizeable`** - This parameter (with the typo) has been removed. Use `resizable` instead.
**Before (Gradio 5.x):**
```python
chatbot = gr.Chatbot(resizeable=True)
```
**After (Gradio 6.x):**
```python
chatbot = gr.Chatbot(resizable=True)
```
**`show_copy_button`, `show_copy_all_button`, `show_share_button`** - These parameters have been removed. Use the `buttons` parameter instead.
**Before (Gradio 5.x):**
```python
chatbot = gr.Chatbot(show_copy_button=True, show_copy_all_button=True, show_share_button=True)
```
**After (Gradio 6.x):**
```python
chatbot = gr.Chatbot(buttons=["copy", "copy_all", "share"])
```
`gr.Audio` / `WaveformOptions` removed parameters
**`show_controls`** - This parameter in `WaveformOptions` has been removed. Use `show_recording_waveform` instead.
**Before (Gradio 5.x):**
```python
audio = gr.Audio(
waveform_options=gr.WaveformOptions(show_controls=False)
)
```
**After (Gradio 6.x):**
```python
audio = gr.Audio(
waveform_options=gr.WaveformOptions(show_recording_waveform=False)
)
```
**`min_length` and `max_length`** - These parameters have been removed. Use validators instead.
**Before (Gradio 5.x):**
```python
audio = gr.Audio(min_length=1, max_length=10)
```
**After (Gradio 6.x):**
```python
audio = gr.Audio(
validator=lambda audio: gr.validators.is_audio_correct_length(audio, min_length=1
|
Component-level Changes
|
https://gradio.app/guides/gradio-6-migration-guide
|
Other Tutorials - Gradio 6 Migration Guide Guide
|
*
```python
audio = gr.Audio(min_length=1, max_length=10)
```
**After (Gradio 6.x):**
```python
audio = gr.Audio(
validator=lambda audio: gr.validators.is_audio_correct_length(audio, min_length=1, max_length=10)
)
```
**`show_download_button`, `show_share_button`** - These parameters have been removed. Use the `buttons` parameter instead.
**Before (Gradio 5.x):**
```python
audio = gr.Audio(show_download_button=True, show_share_button=True)
```
**After (Gradio 6.x):**
```python
audio = gr.Audio(buttons=["download", "share"])
```
**Note:** For components where `show_share_button` had a default of `None` (which would show the button on Spaces), you can use `buttons=["share"]` to always show it, or omit it from the list to hide it.
`gr.Image` removed parameters
**`mirror_webcam`** - This parameter has been removed. Use `webcam_options` with `gr.WebcamOptions` instead.
**Before (Gradio 5.x):**
```python
image = gr.Image(mirror_webcam=True)
```
**After (Gradio 6.x):**
```python
image = gr.Image(webcam_options=gr.WebcamOptions(mirror=True))
```
**`webcam_constraints`** - This parameter has been removed. Use `webcam_options` with `gr.WebcamOptions` instead.
**Before (Gradio 5.x):**
```python
image = gr.Image(webcam_constraints={"facingMode": "user"})
```
**After (Gradio 6.x):**
```python
image = gr.Image(webcam_options=gr.WebcamOptions(constraints={"facingMode": "user"}))
```
**`show_download_button`, `show_share_button`, `show_fullscreen_button`** - These parameters have been removed. Use the `buttons` parameter instead.
**Before (Gradio 5.x):**
```python
image = gr.Image(show_download_button=True, show_share_button=True, show_fullscreen_button=True)
```
**After (Gradio 6.x):**
```python
image = gr.Image(buttons=["download", "share", "fullscreen"])
```
`gr.Video` removed parameters
**`mirror_webcam`** - This parameter has been removed. Use `webcam_options` with `gr.WebcamOptions` instead.
**Before (Gradio 5.x):**
```python
video = gr.Video(m
|
Component-level Changes
|
https://gradio.app/guides/gradio-6-migration-guide
|
Other Tutorials - Gradio 6 Migration Guide Guide
|
`gr.Video` removed parameters
**`mirror_webcam`** - This parameter has been removed. Use `webcam_options` with `gr.WebcamOptions` instead.
**Before (Gradio 5.x):**
```python
video = gr.Video(mirror_webcam=True)
```
**After (Gradio 6.x):**
```python
video = gr.Video(webcam_options=gr.WebcamOptions(mirror=True))
```
**`webcam_constraints`** - This parameter has been removed. Use `webcam_options` with `gr.WebcamOptions` instead.
**Before (Gradio 5.x):**
```python
video = gr.Video(webcam_constraints={"facingMode": "user"})
```
**After (Gradio 6.x):**
```python
video = gr.Video(webcam_options=gr.WebcamOptions(constraints={"facingMode": "user"}))
```
**`min_length` and `max_length`** - These parameters have been removed. Use validators instead.
**Before (Gradio 5.x):**
```python
video = gr.Video(min_length=1, max_length=10)
```
**After (Gradio 6.x):**
```python
video = gr.Video(
validator=lambda video: gr.validators.is_video_correct_length(video, min_length=1, max_length=10)
)
```
**`show_download_button`, `show_share_button`** - These parameters have been removed. Use the `buttons` parameter instead.
**Before (Gradio 5.x):**
```python
video = gr.Video(show_download_button=True, show_share_button=True)
```
**After (Gradio 6.x):**
```python
video = gr.Video(buttons=["download", "share"])
```
`gr.ImageEditor` removed parameters
**`crop_size`** - This parameter has been removed. Use `canvas_size` instead.
**Before (Gradio 5.x):**
```python
editor = gr.ImageEditor(crop_size=(512, 512))
```
**After (Gradio 6.x):**
```python
editor = gr.ImageEditor(canvas_size=(512, 512))
```
Removed components
**`gr.LogoutButton`** - This component has been removed. Use `gr.LoginButton` instead, which handles both login and logout processes.
**Before (Gradio 5.x):**
```python
logout_btn = gr.LogoutButton()
```
**After (Gradio 6.x):**
```python
login_btn = gr.LoginButton()
```
Native plot components removed parameters
The following parameters have
|
Component-level Changes
|
https://gradio.app/guides/gradio-6-migration-guide
|
Other Tutorials - Gradio 6 Migration Guide Guide
|
5.x):**
```python
logout_btn = gr.LogoutButton()
```
**After (Gradio 6.x):**
```python
login_btn = gr.LoginButton()
```
Native plot components removed parameters
The following parameters have been removed from `gr.LinePlot`, `gr.BarPlot`, and `gr.ScatterPlot`:
- `overlay_point` - This parameter has been removed.
- `width` - This parameter has been removed. Use CSS styling or container width instead.
- `stroke_dash` - This parameter has been removed.
- `interactive` - This parameter has been removed.
- `show_actions_button` - This parameter has been removed.
- `color_legend_title` - This parameter has been removed. Use `color_title` instead.
- `show_fullscreen_button`, `show_export_button` - These parameters have been removed. Use the `buttons` parameter instead.
**Before (Gradio 5.x):**
```python
plot = gr.LinePlot(
value=data,
x="date",
y="downloads",
overlay_point=True,
width=900,
show_fullscreen_button=True,
show_export_button=True
)
```
**After (Gradio 6.x):**
```python
plot = gr.LinePlot(
value=data,
x="date",
y="downloads",
buttons=["fullscreen", "export"]
)
```
**Note:** For `color_legend_title`, use `color_title` instead:
**Before (Gradio 5.x):**
```python
plot = gr.ScatterPlot(color_legend_title="Category")
```
**After (Gradio 6.x):**
```python
plot = gr.ScatterPlot(color_title="Category")
```
`gr.Textbox` removed parameters
**`show_copy_button`** - This parameter has been removed. Use the `buttons` parameter instead.
**Before (Gradio 5.x):**
```python
text = gr.Textbox(show_copy_button=True)
```
**After (Gradio 6.x):**
```python
text = gr.Textbox(buttons=["copy"])
```
`gr.Markdown` removed parameters
**`show_copy_button`** - This parameter has been removed. Use the `buttons` parameter instead.
**Before (Gradio 5.x):**
```python
markdown = gr.Markdown(show_copy_button=True)
```
**After (Gradio 6.x):**
```python
markdown = gr.Markdown(buttons=["copy"])
```
`gr.Dataframe` remove
|
Component-level Changes
|
https://gradio.app/guides/gradio-6-migration-guide
|
Other Tutorials - Gradio 6 Migration Guide Guide
|
stead.
**Before (Gradio 5.x):**
```python
markdown = gr.Markdown(show_copy_button=True)
```
**After (Gradio 6.x):**
```python
markdown = gr.Markdown(buttons=["copy"])
```
`gr.Dataframe` removed parameters
**`show_copy_button`, `show_fullscreen_button`** - These parameters have been removed. Use the `buttons` parameter instead.
**Before (Gradio 5.x):**
```python
df = gr.Dataframe(show_copy_button=True, show_fullscreen_button=True)
```
**After (Gradio 6.x):**
```python
df = gr.Dataframe(buttons=["copy", "fullscreen"])
```
`gr.Slider` removed parameters
**`show_reset_button`** - This parameter has been removed. Use the `buttons` parameter instead.
**Before (Gradio 5.x):**
```python
slider = gr.Slider(show_reset_button=True)
```
**After (Gradio 6.x):**
```python
slider = gr.Slider(buttons=["reset"])
```
|
Component-level Changes
|
https://gradio.app/guides/gradio-6-migration-guide
|
Other Tutorials - Gradio 6 Migration Guide Guide
|
`gradio sketch` command removed
The `gradio sketch` command-line tool has been deprecated and completely removed in Gradio 6. This tool was used to create Gradio apps through a visual interface.
**In Gradio 5.x:**
- You could run `gradio sketch` to launch an interactive GUI for building Gradio apps
- The tool would generate Python code visually
**In Gradio 6.x:**
- The `gradio sketch` command has been removed
- Running `gradio sketch` will raise a `DeprecationWarning`
|
CLI Changes
|
https://gradio.app/guides/gradio-6-migration-guide
|
Other Tutorials - Gradio 6 Migration Guide Guide
|
`hf_token` parameter renamed to `token` in `Client`
The `hf_token` parameter in the `Client` class has been renamed to `token` for consistency and simplicity.
**Before (Gradio 5.x):**
```python
from gradio_client import Client
client = Client("abidlabs/my-private-space", hf_token="hf_...")
```
**After (Gradio 6.x):**
```python
from gradio_client import Client
client = Client("abidlabs/my-private-space", token="hf_...")
```
`deploy_discord` method deprecated
The `deploy_discord` method in the `Client` class has been deprecated and will be removed in Gradio 6.0. This method was used to deploy Gradio apps as Discord bots.
**Before (Gradio 5.x):**
```python
from gradio_client import Client
client = Client("username/space-name")
client.deploy_discord(discord_bot_token="...")
```
**After (Gradio 6.x):**
The `deploy_discord` method is no longer available. Please see the [documentation on creating a Discord bot with Gradio](https://www.gradio.app/guides/creating-a-discord-bot-from-a-gradio-app) for alternative approaches.
`AppError` now subclasses `Exception` instead of `ValueError`
The `AppError` exception class in the Python client now subclasses `Exception` directly instead of `ValueError`. This is a breaking change if you have code that specifically catches `ValueError` to handle `AppError` instances.
**Before (Gradio 5.x):**
```python
from gradio_client import Client
from gradio_client.exceptions import AppError
try:
client = Client("username/space-name")
result = client.predict("/predict", inputs)
except ValueError as e:
This would catch AppError in Gradio 5.x
print(f"Error: {e}")
```
**After (Gradio 6.x):**
```python
from gradio_client import Client
from gradio_client.exceptions import AppError
try:
client = Client("username/space-name")
result = client.predict("/predict", inputs)
except AppError as e:
Explicitly catch AppError
print(f"App error: {e}")
except ValueError as e:
This will no lon
|
Python Client Changes
|
https://gradio.app/guides/gradio-6-migration-guide
|
Other Tutorials - Gradio 6 Migration Guide Guide
|
"username/space-name")
result = client.predict("/predict", inputs)
except AppError as e:
Explicitly catch AppError
print(f"App error: {e}")
except ValueError as e:
This will no longer catch AppError
print(f"Value error: {e}")
```
|
Python Client Changes
|
https://gradio.app/guides/gradio-6-migration-guide
|
Other Tutorials - Gradio 6 Migration Guide Guide
|
In this Guide, we'll walk you through:
- Introduction of ONNX, ONNX model zoo, Gradio, and Hugging Face Spaces
- How to setup a Gradio demo for EfficientNet-Lite4
- How to contribute your own Gradio demos for the ONNX organization on Hugging Face
Here's an [example](https://huggingface.co/proxy/onnx-efficientnet-lite4.hf.space/) of an ONNX model.
|
Introduction
|
https://gradio.app/guides/Gradio-and-ONNX-on-Hugging-Face
|
Other Tutorials - Gradio And Onnx On Hugging Face Guide
|
Open Neural Network Exchange ([ONNX](https://onnx.ai/)) is an open standard format for representing machine learning models. ONNX is supported by a community of partners who have implemented it in many frameworks and tools. For example, if you have trained a model in TensorFlow or PyTorch, you can convert it to ONNX easily, and from there run it on a variety of devices using an engine/compiler like ONNX Runtime.
The [ONNX Model Zoo](https://github.com/onnx/models) is a collection of pre-trained, state-of-the-art models in the ONNX format contributed by community members. Accompanying each model are Jupyter notebooks for model training and running inference with the trained model. The notebooks are written in Python and include links to the training dataset as well as references to the original paper that describes the model architecture.
|
What is the ONNX Model Zoo?
|
https://gradio.app/guides/Gradio-and-ONNX-on-Hugging-Face
|
Other Tutorials - Gradio And Onnx On Hugging Face Guide
|
Gradio
Gradio lets users demo their machine learning models as a web app all in python code. Gradio wraps a python function into a user interface and the demos can be launched inside jupyter notebooks, colab notebooks, as well as embedded in your own website and hosted on Hugging Face Spaces for free.
Get started [here](https://gradio.app/getting_started)
Hugging Face Spaces
Hugging Face Spaces is a free hosting option for Gradio demos. Spaces comes with 3 SDK options: Gradio, Streamlit and Static HTML demos. Spaces can be public or private and the workflow is similar to github repos. There are over 2000+ spaces currently on Hugging Face. Learn more about spaces [here](https://huggingface.co/spaces/launch).
Hugging Face Models
Hugging Face Model Hub also supports ONNX models and ONNX models can be filtered through the [ONNX tag](https://huggingface.co/models?library=onnx&sort=downloads)
|
What are Hugging Face Spaces & Gradio?
|
https://gradio.app/guides/Gradio-and-ONNX-on-Hugging-Face
|
Other Tutorials - Gradio And Onnx On Hugging Face Guide
|
There are a lot of Jupyter notebooks in the ONNX Model Zoo for users to test models. Previously, users needed to download the models themselves and run those notebooks locally for testing. With Hugging Face, the testing process can be much simpler and more user-friendly. Users can easily try certain ONNX Model Zoo model on Hugging Face Spaces and run a quick demo powered by Gradio with ONNX Runtime, all on cloud without downloading anything locally. Note, there are various runtimes for ONNX, e.g., [ONNX Runtime](https://github.com/microsoft/onnxruntime), [MXNet](https://github.com/apache/incubator-mxnet).
|
How did Hugging Face help the ONNX Model Zoo?
|
https://gradio.app/guides/Gradio-and-ONNX-on-Hugging-Face
|
Other Tutorials - Gradio And Onnx On Hugging Face Guide
|
ONNX Runtime is a cross-platform inference and training machine-learning accelerator. It makes live Gradio demos with ONNX Model Zoo model on Hugging Face possible.
ONNX Runtime inference can enable faster customer experiences and lower costs, supporting models from deep learning frameworks such as PyTorch and TensorFlow/Keras as well as classical machine learning libraries such as scikit-learn, LightGBM, XGBoost, etc. ONNX Runtime is compatible with different hardware, drivers, and operating systems, and provides optimal performance by leveraging hardware accelerators where applicable alongside graph optimizations and transforms. For more information please see the [official website](https://onnxruntime.ai/).
|
What is the role of ONNX Runtime?
|
https://gradio.app/guides/Gradio-and-ONNX-on-Hugging-Face
|
Other Tutorials - Gradio And Onnx On Hugging Face Guide
|
EfficientNet-Lite 4 is the largest variant and most accurate of the set of EfficientNet-Lite models. It is an integer-only quantized model that produces the highest accuracy of all of the EfficientNet models. It achieves 80.4% ImageNet top-1 accuracy, while still running in real-time (e.g. 30ms/image) on a Pixel 4 CPU. To learn more read the [model card](https://github.com/onnx/models/tree/main/vision/classification/efficientnet-lite4)
Here we walk through setting up a example demo for EfficientNet-Lite4 using Gradio
First we import our dependencies and download and load the efficientnet-lite4 model from the onnx model zoo. Then load the labels from the labels_map.txt file. We then setup our preprocessing functions, load the model for inference, and setup the inference function. Finally, the inference function is wrapped into a gradio interface for a user to interact with. See the full code below.
```python
import numpy as np
import math
import matplotlib.pyplot as plt
import cv2
import json
import gradio as gr
from huggingface_hub import hf_hub_download
from onnx import hub
import onnxruntime as ort
loads ONNX model from ONNX Model Zoo
model = hub.load("efficientnet-lite4")
loads the labels text file
labels = json.load(open("labels_map.txt", "r"))
sets image file dimensions to 224x224 by resizing and cropping image from center
def pre_process_edgetpu(img, dims):
output_height, output_width, _ = dims
img = resize_with_aspectratio(img, output_height, output_width, inter_pol=cv2.INTER_LINEAR)
img = center_crop(img, output_height, output_width)
img = np.asarray(img, dtype='float32')
converts jpg pixel value from [0 - 255] to float array [-1.0 - 1.0]
img -= [127.0, 127.0, 127.0]
img /= [128.0, 128.0, 128.0]
return img
resizes the image with a proportional scale
def resize_with_aspectratio(img, out_height, out_width, scale=87.5, inter_pol=cv2.INTER_LINEAR):
height, width, _ = img.shape
new_height = int(100. * out_he
|
Setting up a Gradio Demo for EfficientNet-Lite4
|
https://gradio.app/guides/Gradio-and-ONNX-on-Hugging-Face
|
Other Tutorials - Gradio And Onnx On Hugging Face Guide
|
the image with a proportional scale
def resize_with_aspectratio(img, out_height, out_width, scale=87.5, inter_pol=cv2.INTER_LINEAR):
height, width, _ = img.shape
new_height = int(100. * out_height / scale)
new_width = int(100. * out_width / scale)
if height > width:
w = new_width
h = int(new_height * height / width)
else:
h = new_height
w = int(new_width * width / height)
img = cv2.resize(img, (w, h), interpolation=inter_pol)
return img
crops the image around the center based on given height and width
def center_crop(img, out_height, out_width):
height, width, _ = img.shape
left = int((width - out_width) / 2)
right = int((width + out_width) / 2)
top = int((height - out_height) / 2)
bottom = int((height + out_height) / 2)
img = img[top:bottom, left:right]
return img
sess = ort.InferenceSession(model)
def inference(img):
img = cv2.imread(img)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = pre_process_edgetpu(img, (224, 224, 3))
img_batch = np.expand_dims(img, axis=0)
results = sess.run(["Softmax:0"], {"images:0": img_batch})[0]
result = reversed(results[0].argsort()[-5:])
resultdic = {}
for r in result:
resultdic[labels[str(r)]] = float(results[0][r])
return resultdic
title = "EfficientNet-Lite4"
description = "EfficientNet-Lite 4 is the largest variant and most accurate of the set of EfficientNet-Lite model. It is an integer-only quantized model that produces the highest accuracy of all of the EfficientNet models. It achieves 80.4% ImageNet top-1 accuracy, while still running in real-time (e.g. 30ms/image) on a Pixel 4 CPU."
examples = [['catonnx.jpg']]
gr.Interface(inference, gr.Image(type="filepath"), "label", title=title, description=description, examples=examples).launch()
```
|
Setting up a Gradio Demo for EfficientNet-Lite4
|
https://gradio.app/guides/Gradio-and-ONNX-on-Hugging-Face
|
Other Tutorials - Gradio And Onnx On Hugging Face Guide
|
examples=examples).launch()
```
|
Setting up a Gradio Demo for EfficientNet-Lite4
|
https://gradio.app/guides/Gradio-and-ONNX-on-Hugging-Face
|
Other Tutorials - Gradio And Onnx On Hugging Face Guide
|
- Add model to the [onnx model zoo](https://github.com/onnx/models/blob/main/.github/PULL_REQUEST_TEMPLATE.md)
- Create an account on Hugging Face [here](https://huggingface.co/join).
- See list of models left to add to ONNX organization, please refer to the table with the [Models list](https://github.com/onnx/modelsmodels)
- Add Gradio Demo under your username, see this [blog post](https://huggingface.co/blog/gradio-spaces) for setting up Gradio Demo on Hugging Face.
- Request to join ONNX Organization [here](https://huggingface.co/onnx).
- Once approved transfer model from your username to ONNX organization
- Add a badge for model in model table, see examples in [Models list](https://github.com/onnx/modelsmodels)
|
How to contribute Gradio demos on HF spaces using ONNX models
|
https://gradio.app/guides/Gradio-and-ONNX-on-Hugging-Face
|
Other Tutorials - Gradio And Onnx On Hugging Face Guide
|
Let's deploy a Gradio-style "Hello, world" app that lets a user input their name and then responds with a short greeting. We're not going to use this code as-is in our app, but it's useful to see what the initial Gradio version looks like.
```python
import gradio as gr
A simple Gradio interface for a greeting function
def greet(name):
return f"Hello {name}!"
demo = gr.Interface(fn=greet, inputs="text", outputs="text")
demo.launch()
```
To deploy this app on Modal you'll need to
- define your container image,
- wrap the Gradio app in a Modal Function,
- and deploy it using Modal's CLI!
Prerequisite: Install and set up Modal
Before you get started, you'll need to create a Modal account if you don't already have one. Then you can set up your environment by authenticating with those account credentials.
- Sign up at [modal.com](https://www.modal.com?utm_source=partner&utm_medium=github&utm_campaign=livekit).
- Install the Modal client in your local development environment.
```bash
pip install modal
```
- Authenticate your account.
```
modal setup
```
Great, now we can start building our app!
Step 1: Define our `modal.Image`
To start, let's make a new file named `gradio_app.py`, import `modal`, and define our image. Modal `Images` are defined by sequentially calling methods on our `Image` instance.
For this simple app, we'll
- start with the `debian_slim` image,
- choose a Python version (3.12),
- and install the dependencies - only `fastapi` and `gradio`.
```python
import modal
app = modal.App("gradio-app")
web_image = modal.Image.debian_slim(python_version="3.12").uv_pip_install(
"fastapi[standard]",
"gradio",
)
```
Note, that you don't need to install `gradio` or `fastapi` in your local environement - only `modal` is required locally.
Step 2: Wrap the Gradio app in a Modal-deployed FastAPI app
Like many Gradio apps, the example above is run by calling `launch()` on our demo at the end of the script. However, Modal doesn't ru
|
Deploying a simple Gradio app on Modal
|
https://gradio.app/guides/deploying-gradio-with-modal
|
Other Tutorials - Deploying Gradio With Modal Guide
|
.
Step 2: Wrap the Gradio app in a Modal-deployed FastAPI app
Like many Gradio apps, the example above is run by calling `launch()` on our demo at the end of the script. However, Modal doesn't run scripts, it runs functions - serverless functions to be exact.
To get Modal to serve our `demo`, we can leverage Gradio and Modal's support for `fastapi` apps. We do this with the `@modal.asgi_app()` function decorator which deploys the web app returned by the function. And we use the `mount_gradio_app` function to add our Gradio `demo` as a route in the web app.
```python
with web_image.imports():
import gradio as gr
from gradio.routes import mount_gradio_app
from fastapi import FastAPI
@app.function(
image=web_image,
max_containers = 1, we'll come to this later
)
@modal.concurrent(max_inputs=100) allow multiple users at one time
@modal.asgi_app()
def ui():
"""A simple Gradio interface for a greeting function."""
def greet(name):
return f"Hello {name}!"
demo = gr.Interface(fn=greet, inputs="text", outputs="text")
return mount_gradio_app(app=FastAPI(), blocks=demo, path="/")
```
Let's quickly review what's going on here:
- We use the `Image.imports` context manager to define our imports. These will be available when your function runs in the cloud.
- We move our code inside a Python function, `ui`, and decorate it with `@app.function` which wraps it as a Modal serverless Function. We provide the image and other parameters (we'll cover this later) as inputs to the decorator.
- We add the `@modal.concurrent` decorator which allows multiple requests per container to be processed at the same time.
- We add the `@modal.asgi_app` decorator which tells Modal that this particular function is serving an ASGI app (here a `fastapi` app). To use this decorator, your ASGI app needs to be the return value from the function.
Step 3: Deploying on Modal
To deploy the app, just run the following command:
```bash
modal deploy <pat
|
Deploying a simple Gradio app on Modal
|
https://gradio.app/guides/deploying-gradio-with-modal
|
Other Tutorials - Deploying Gradio With Modal Guide
|
app). To use this decorator, your ASGI app needs to be the return value from the function.
Step 3: Deploying on Modal
To deploy the app, just run the following command:
```bash
modal deploy <path-to-file>
```
The first time you run your app, Modal will build and cache the image which, takes about 30 seconds. As long as you don't change the image, subsequent deployments will only take a few seconds.
After the image builds Modal will print the URL to your webapp and to your Modal dashboard. The webapp URL should look something like `https://{workspace}-{environment}--gradio-app-ui.modal.run`. Paste it into your web browser a try out your app!
|
Deploying a simple Gradio app on Modal
|
https://gradio.app/guides/deploying-gradio-with-modal
|
Other Tutorials - Deploying Gradio With Modal Guide
|
Sticky Sessions
Modal Functions are serverless which means that each client request is considered independent. While this facilitates autoscaling, it can also mean that extra care should be taken if your application requires any sort of server-side statefulness.
Gradio relies on a REST API, which is itself stateless. But it does require sticky sessions, meaning that every request from a particular client must be routed to the same container. However, Modal does not make any guarantees in this regard.
A simple way to satisfy this constraint is to set `max_containers = 1` in the `@app.function` decorator and setting the `max_inputs` argument of `@modal.concurrent` to a fairly large number - as we did above. This means that Modal won't spin up more than one container to serve requests to your app which effectively satisfies the sticky session requirement.
Concurrency and Queues
Both Gradio and Modal have concepts of concurrency and queues, and getting the most of out of your compute resources requires understanding how these interact.
Modal queues client requests to each deployed Function and simultaneously executes requests up to the concurrency limit for that Function. If requests come in and the concurrency limit is already satisfied, Modal will spin up a new container - up to the maximum set for the Function. In our case, our Gradio app is represented by one Modal Function, so all requests share one queue and concurrency limit. Therefore Modal constrains the _total_ number of requests running at one time, regardless of what they are doing.
Gradio on the other hand, allows developers to utilize multiple queues each with its own concurrency limit. One or more event listeners can then be assigned to a queue which is useful to manage GPU resources for computationally expensive requests.
Thinking carefully about how these queues and limits interact can help you optimize your app's performance and resource optimization while avoiding unwanted results like
|
Important Considerations
|
https://gradio.app/guides/deploying-gradio-with-modal
|
Other Tutorials - Deploying Gradio With Modal Guide
|
tionally expensive requests.
Thinking carefully about how these queues and limits interact can help you optimize your app's performance and resource optimization while avoiding unwanted results like shared or lost state.
Creating a GPU Function
Another option to manage GPU utilization is to deploy your GPU computations in their own Modal Function and calling this remote Function from inside your Gradio app. This allows you to take full advantage of Modal's serverless autoscaling while routing all of the client HTTP requests to a single Gradio CPU container.
|
Important Considerations
|
https://gradio.app/guides/deploying-gradio-with-modal
|
Other Tutorials - Deploying Gradio With Modal Guide
|
When you demo a machine learning model, you might want to collect data from users who try the model, particularly data points in which the model is not behaving as expected. Capturing these "hard" data points is valuable because it allows you to improve your machine learning model and make it more reliable and robust.
Gradio simplifies the collection of this data by including a **Flag** button with every `Interface`. This allows a user or tester to easily send data back to the machine where the demo is running. In this Guide, we discuss more about how to use the flagging feature, both with `gradio.Interface` as well as with `gradio.Blocks`.
|
Introduction
|
https://gradio.app/guides/using-flagging
|
Other Tutorials - Using Flagging Guide
|
Flagging with Gradio's `Interface` is especially easy. By default, underneath the output components, there is a button marked **Flag**. When a user testing your model sees input with interesting output, they can click the flag button to send the input and output data back to the machine where the demo is running. The sample is saved to a CSV log file (by default). If the demo involves images, audio, video, or other types of files, these are saved separately in a parallel directory and the paths to these files are saved in the CSV file.
There are [four parameters](https://gradio.app/docs/interfaceinitialization) in `gradio.Interface` that control how flagging works. We will go over them in greater detail.
- `flagging_mode`: this parameter can be set to either `"manual"` (default), `"auto"`, or `"never"`.
- `manual`: users will see a button to flag, and samples are only flagged when the button is clicked.
- `auto`: users will not see a button to flag, but every sample will be flagged automatically.
- `never`: users will not see a button to flag, and no sample will be flagged.
- `flagging_options`: this parameter can be either `None` (default) or a list of strings.
- If `None`, then the user simply clicks on the **Flag** button and no additional options are shown.
- If a list of strings are provided, then the user sees several buttons, corresponding to each of the strings that are provided. For example, if the value of this parameter is `["Incorrect", "Ambiguous"]`, then buttons labeled **Flag as Incorrect** and **Flag as Ambiguous** appear. This only applies if `flagging_mode` is `"manual"`.
- The chosen option is then logged along with the input and output.
- `flagging_dir`: this parameter takes a string.
- It represents what to name the directory where flagged data is stored.
- `flagging_callback`: this parameter takes an instance of a subclass of the `FlaggingCallback` class
- Using this parameter allows you to write custom code that gets run whe
|
The **Flag** button in `gradio.Interface`
|
https://gradio.app/guides/using-flagging
|
Other Tutorials - Using Flagging Guide
|
flagged data is stored.
- `flagging_callback`: this parameter takes an instance of a subclass of the `FlaggingCallback` class
- Using this parameter allows you to write custom code that gets run when the flag button is clicked
- By default, this is set to an instance of `gr.JSONLogger`
|
The **Flag** button in `gradio.Interface`
|
https://gradio.app/guides/using-flagging
|
Other Tutorials - Using Flagging Guide
|
Within the directory provided by the `flagging_dir` argument, a JSON file will log the flagged data.
Here's an example: The code below creates the calculator interface embedded below it:
```python
import gradio as gr
def calculator(num1, operation, num2):
if operation == "add":
return num1 + num2
elif operation == "subtract":
return num1 - num2
elif operation == "multiply":
return num1 * num2
elif operation == "divide":
return num1 / num2
iface = gr.Interface(
calculator,
["number", gr.Radio(["add", "subtract", "multiply", "divide"]), "number"],
"number",
flagging_mode="manual"
)
iface.launch()
```
<gradio-app space="gradio/calculator-flagging-basic"></gradio-app>
When you click the flag button above, the directory where the interface was launched will include a new flagged subfolder, with a csv file inside it. This csv file includes all the data that was flagged.
```directory
+-- flagged/
| +-- logs.csv
```
_flagged/logs.csv_
```csv
num1,operation,num2,Output,timestamp
5,add,7,12,2022-01-31 11:40:51.093412
6,subtract,1.5,4.5,2022-01-31 03:25:32.023542
```
If the interface involves file data, such as for Image and Audio components, folders will be created to store those flagged data as well. For example an `image` input to `image` output interface will create the following structure.
```directory
+-- flagged/
| +-- logs.csv
| +-- image/
| | +-- 0.png
| | +-- 1.png
| +-- Output/
| | +-- 0.png
| | +-- 1.png
```
_flagged/logs.csv_
```csv
im,Output timestamp
im/0.png,Output/0.png,2022-02-04 19:49:58.026963
im/1.png,Output/1.png,2022-02-02 10:40:51.093412
```
If you wish for the user to provide a reason for flagging, you can pass a list of strings to the `flagging_options` argument of Interface. Users will have to select one of these choices when flagging, and the option will be saved as an additional column to the CSV.
If we go back to the calculator example, the fo
|
What happens to flagged data?
|
https://gradio.app/guides/using-flagging
|
Other Tutorials - Using Flagging Guide
|
` argument of Interface. Users will have to select one of these choices when flagging, and the option will be saved as an additional column to the CSV.
If we go back to the calculator example, the following code will create the interface embedded below it.
```python
iface = gr.Interface(
calculator,
["number", gr.Radio(["add", "subtract", "multiply", "divide"]), "number"],
"number",
flagging_mode="manual",
flagging_options=["wrong sign", "off by one", "other"]
)
iface.launch()
```
<gradio-app space="gradio/calculator-flagging-options"></gradio-app>
When users click the flag button, the csv file will now include a column indicating the selected option.
_flagged/logs.csv_
```csv
num1,operation,num2,Output,flag,timestamp
5,add,7,-12,wrong sign,2022-02-04 11:40:51.093412
6,subtract,1.5,3.5,off by one,2022-02-04 11:42:32.062512
```
|
What happens to flagged data?
|
https://gradio.app/guides/using-flagging
|
Other Tutorials - Using Flagging Guide
|
What about if you are using `gradio.Blocks`? On one hand, you have even more flexibility
with Blocks -- you can write whatever Python code you want to run when a button is clicked,
and assign that using the built-in events in Blocks.
At the same time, you might want to use an existing `FlaggingCallback` to avoid writing extra code.
This requires two steps:
1. You have to run your callback's `.setup()` somewhere in the code prior to the
first time you flag data
2. When the flagging button is clicked, then you trigger the callback's `.flag()` method,
making sure to collect the arguments correctly and disabling the typical preprocessing.
Here is an example with an image sepia filter Blocks demo that lets you flag
data using the default `CSVLogger`:
$code_blocks_flag
$demo_blocks_flag
|
Flagging with Blocks
|
https://gradio.app/guides/using-flagging
|
Other Tutorials - Using Flagging Guide
|
Important Note: please make sure your users understand when the data they submit is being saved, and what you plan on doing with it. This is especially important when you use `flagging_mode=auto` (when all of the data submitted through the demo is being flagged)
That's all! Happy building :)
|
Privacy
|
https://gradio.app/guides/using-flagging
|
Other Tutorials - Using Flagging Guide
|
Encoder functions to send audio as base64-encoded data and images as base64-encoded JPEG.
```python
import base64
import numpy as np
from io import BytesIO
from PIL import Image
def encode_audio(data: np.ndarray) -> dict:
"""Encode audio data (int16 mono) for Gemini."""
return {
"mime_type": "audio/pcm",
"data": base64.b64encode(data.tobytes()).decode("UTF-8"),
}
def encode_image(data: np.ndarray) -> dict:
with BytesIO() as output_bytes:
pil_image = Image.fromarray(data)
pil_image.save(output_bytes, "JPEG")
bytes_data = output_bytes.getvalue()
base64_str = str(base64.b64encode(bytes_data), "utf-8")
return {"mime_type": "image/jpeg", "data": base64_str}
```
|
1) Encoders for audio and images
|
https://gradio.app/guides/create-immersive-demo
|
Other Tutorials - Create Immersive Demo Guide
|
This handler:
- Opens a Gemini Live session on startup
- Receives streaming audio from Gemini and yields it back to the client
- Sends microphone audio as it arrives
- Sends a video frame at most once per second (to avoid flooding the API)
- Optionally sends an uploaded image (`gr.Image`) alongside the webcam frame
```python
import asyncio
import os
import time
import numpy as np
import websockets
from dotenv import load_dotenv
from google import genai
from fastrtc import AsyncAudioVideoStreamHandler, wait_for_item, WebRTCError
load_dotenv()
class GeminiHandler(AsyncAudioVideoStreamHandler):
def __init__(self) -> None:
super().__init__(
"mono",
output_sample_rate=24000,
input_sample_rate=16000,
)
self.audio_queue = asyncio.Queue()
self.video_queue = asyncio.Queue()
self.session = None
self.last_frame_time = 0.0
self.quit = asyncio.Event()
def copy(self) -> "GeminiHandler":
return GeminiHandler()
async def start_up(self):
await self.wait_for_args()
api_key = self.latest_args[3]
hf_token = self.latest_args[4]
if hf_token is None or hf_token == "":
raise WebRTCError("HF Token is required")
os.environ["HF_TOKEN"] = hf_token
client = genai.Client(
api_key=api_key, http_options={"api_version": "v1alpha"}
)
config = {"response_modalities": ["AUDIO"], "system_instruction": "You are an art critic that will critique the artwork passed in as an image to the user. Critique the artwork in a funny and lighthearted way. Be concise and to the point. Be friendly and engaging. Be helpful and informative. Be funny and lighthearted."}
async with client.aio.live.connect(
model="gemini-2.0-flash-exp",
config=config,
) as session:
self.session = session
while not self.quit.is_set():
turn = self.session.receiv
|
2) Implement the Gemini audio-video handler
|
https://gradio.app/guides/create-immersive-demo
|
Other Tutorials - Create Immersive Demo Guide
|
model="gemini-2.0-flash-exp",
config=config,
) as session:
self.session = session
while not self.quit.is_set():
turn = self.session.receive()
try:
async for response in turn:
if data := response.data:
audio = np.frombuffer(data, dtype=np.int16).reshape(1, -1)
self.audio_queue.put_nowait(audio)
except websockets.exceptions.ConnectionClosedOK:
print("connection closed")
break
Video: receive and (optionally) send frames to Gemini
async def video_receive(self, frame: np.ndarray):
self.video_queue.put_nowait(frame)
if self.session and (time.time() - self.last_frame_time > 1.0):
self.last_frame_time = time.time()
await self.session.send(input=encode_image(frame))
If there is an uploaded image passed alongside the WebRTC component,
it will be available in latest_args[2]
if self.latest_args[2] is not None:
await self.session.send(input=encode_image(self.latest_args[2]))
async def video_emit(self) -> np.ndarray:
frame = await wait_for_item(self.video_queue, 0.01)
if frame is not None:
return frame
Fallback while waiting for first frame
return np.zeros((100, 100, 3), dtype=np.uint8)
Audio: forward microphone audio to Gemini
async def receive(self, frame: tuple[int, np.ndarray]) -> None:
_, array = frame
array = array.squeeze() (num_samples,)
audio_message = encode_audio(array)
if self.session:
await self.session.send(input=audio_message)
Audio: emit Gemini’s audio back to the client
async def emit(self):
array = await wait_for_item(self.audio_queue, 0.01)
if array is not None:
return (self.output_sam
|
2) Implement the Gemini audio-video handler
|
https://gradio.app/guides/create-immersive-demo
|
Other Tutorials - Create Immersive Demo Guide
|
Audio: emit Gemini’s audio back to the client
async def emit(self):
array = await wait_for_item(self.audio_queue, 0.01)
if array is not None:
return (self.output_sample_rate, array)
return array
async def shutdown(self) -> None:
if self.session:
self.quit.set()
await self.session.close()
self.quit.clear()
```
|
2) Implement the Gemini audio-video handler
|
https://gradio.app/guides/create-immersive-demo
|
Other Tutorials - Create Immersive Demo Guide
|
We’ll add an optional `gr.Image` input alongside the `WebRTC` component. The handler will access this in `self.latest_args[1]` when sending frames to Gemini.
```python
import gradio as gr
from fastrtc import Stream, WebRTC, get_hf_turn_credentials
stream = Stream(
handler=GeminiHandler(),
modality="audio-video",
mode="send-receive",
server_rtc_configuration=get_hf_turn_credentials(ttl=600*10000),
rtc_configuration=get_hf_turn_credentials(),
additional_inputs=[
gr.Markdown(
"🎨 Art Critic\n\n"
"Provide an image of your artwork or hold it up to the webcam, and Gemini will critique it for you."
"To get a Gemini API key, please visit the [Gemini API Key](https://aistudio.google.com/apikey) page."
"To get an HF Token, please visit the [HF Token](https://huggingface.co/settings/tokens) page."
),
gr.Image(label="Artwork", value="mona_lisa.jpg", type="numpy", sources=["upload", "clipboard"]),
gr.Textbox(label="Gemini API Key", type="password"),
gr.Textbox(label="HF Token", type="password"),
],
ui_args={
"icon": "https://www.gstatic.com/lamda/images/gemini_favicon_f069958c85030456e93de685481c559f160ea06b.png",
"pulse_color": "rgb(255, 255, 255)",
"icon_button_color": "rgb(255, 255, 255)",
"title": "Gemini Audio Video Chat",
},
time_limit=90,
concurrency_limit=5,
)
if __name__ == "__main__":
stream.ui.launch()
```
References
- Gemini Audio Video Chat reference code: [Hugging Face Space](https://huggingface.co/spaces/gradio/gemini-audio-video/blob/main/app.py)
- FastRTC docs: `https://fastrtc.org`
- Audio + video user guide: `https://fastrtc.org/userguide/audio-video/`
- Gradio component integration: `https://fastrtc.org/userguide/gradio/`
- Cookbook (live demos + code): `https://fastrtc.org/cookbook/`
|
3) Setup Stream and Gradio UI
|
https://gradio.app/guides/create-immersive-demo
|
Other Tutorials - Create Immersive Demo Guide
|
Building a dashboard from a public Google Sheet is very easy, thanks to the [`pandas` library](https://pandas.pydata.org/):
1\. Get the URL of the Google Sheets that you want to use. To do this, simply go to the Google Sheets, click on the "Share" button in the top-right corner, and then click on the "Get shareable link" button. This will give you a URL that looks something like this:
```html
https://docs.google.com/spreadsheets/d/1UoKzzRzOCt-FXLLqDKLbryEKEgllGAQUEJ5qtmmQwpU/editgid=0
```
2\. Now, let's modify this URL and then use it to read the data from the Google Sheets into a Pandas DataFrame. (In the code below, replace the `URL` variable with the URL of your public Google Sheet):
```python
import pandas as pd
URL = "https://docs.google.com/spreadsheets/d/1UoKzzRzOCt-FXLLqDKLbryEKEgllGAQUEJ5qtmmQwpU/editgid=0"
csv_url = URL.replace('/editgid=', '/export?format=csv&gid=')
def get_data():
return pd.read_csv(csv_url)
```
3\. The data query is a function, which means that it's easy to display it real-time using the `gr.DataFrame` component, or plot it real-time using the `gr.LinePlot` component (of course, depending on the data, a different plot may be appropriate). To do this, just pass the function into the respective components, and set the `every` parameter based on how frequently (in seconds) you would like the component to refresh. Here's the Gradio code:
```python
import gradio as gr
with gr.Blocks() as demo:
gr.Markdown("📈 Real-Time Line Plot")
with gr.Row():
with gr.Column():
gr.DataFrame(get_data, every=gr.Timer(5))
with gr.Column():
gr.LinePlot(get_data, every=gr.Timer(5), x="Date", y="Sales", y_title="Sales ($ millions)", overlay_point=True, width=500, height=500)
demo.queue().launch() Run the demo with queuing enabled
```
And that's it! You have a dashboard that refreshes every 5 seconds, pulling the data from your Google Sheet.
|
Public Google Sheets
|
https://gradio.app/guides/creating-a-realtime-dashboard-from-google-sheets
|
Other Tutorials - Creating A Realtime Dashboard From Google Sheets Guide
|
For private Google Sheets, the process requires a little more work, but not that much! The key difference is that now, you must authenticate yourself to authorize access to the private Google Sheets.
Authentication
To authenticate yourself, obtain credentials from Google Cloud. Here's [how to set up google cloud credentials](https://developers.google.com/workspace/guides/create-credentials):
1\. First, log in to your Google Cloud account and go to the Google Cloud Console (https://console.cloud.google.com/)
2\. In the Cloud Console, click on the hamburger menu in the top-left corner and select "APIs & Services" from the menu. If you do not have an existing project, you will need to create one.
3\. Then, click the "+ Enabled APIs & services" button, which allows you to enable specific services for your project. Search for "Google Sheets API", click on it, and click the "Enable" button. If you see the "Manage" button, then Google Sheets is already enabled, and you're all set.
4\. In the APIs & Services menu, click on the "Credentials" tab and then click on the "Create credentials" button.
5\. In the "Create credentials" dialog, select "Service account key" as the type of credentials to create, and give it a name. **Note down the email of the service account**
6\. After selecting the service account, select the "JSON" key type and then click on the "Create" button. This will download the JSON key file containing your credentials to your computer. It will look something like this:
```json
{
"type": "service_account",
"project_id": "your project",
"private_key_id": "your private key id",
"private_key": "private key",
"client_email": "email",
"client_id": "client id",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/email_id"
}
```
|
Private Google Sheets
|
https://gradio.app/guides/creating-a-realtime-dashboard-from-google-sheets
|
Other Tutorials - Creating A Realtime Dashboard From Google Sheets Guide
|
google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/email_id"
}
```
Querying
Once you have the credentials `.json` file, you can use the following steps to query your Google Sheet:
1\. Click on the "Share" button in the top-right corner of the Google Sheet. Share the Google Sheets with the email address of the service from Step 5 of authentication subsection (this step is important!). Then click on the "Get shareable link" button. This will give you a URL that looks something like this:
```html
https://docs.google.com/spreadsheets/d/1UoKzzRzOCt-FXLLqDKLbryEKEgllGAQUEJ5qtmmQwpU/editgid=0
```
2\. Install the [`gspread` library](https://docs.gspread.org/en/v5.7.0/), which makes it easy to work with the [Google Sheets API](https://developers.google.com/sheets/api/guides/concepts) in Python by running in the terminal: `pip install gspread`
3\. Write a function to load the data from the Google Sheet, like this (replace the `URL` variable with the URL of your private Google Sheet):
```python
import gspread
import pandas as pd
Authenticate with Google and get the sheet
URL = 'https://docs.google.com/spreadsheets/d/1_91Vps76SKOdDQ8cFxZQdgjTJiz23375sAT7vPvaj4k/editgid=0'
gc = gspread.service_account("path/to/key.json")
sh = gc.open_by_url(URL)
worksheet = sh.sheet1
def get_data():
values = worksheet.get_all_values()
df = pd.DataFrame(values[1:], columns=values[0])
return df
```
4\. The data query is a function, which means that it's easy to display it real-time using the `gr.DataFrame` component, or plot it real-time using the `gr.LinePlot` component (of course, depending on the data, a different plot may be appropriate). To do this, we just pass the function into the respective components, and set the `every` parameter based on how frequently (in seconds) we would like the component to refresh. Here's the Gradio cod
|
Private Google Sheets
|
https://gradio.app/guides/creating-a-realtime-dashboard-from-google-sheets
|
Other Tutorials - Creating A Realtime Dashboard From Google Sheets Guide
|
. To do this, we just pass the function into the respective components, and set the `every` parameter based on how frequently (in seconds) we would like the component to refresh. Here's the Gradio code:
```python
import gradio as gr
with gr.Blocks() as demo:
gr.Markdown("📈 Real-Time Line Plot")
with gr.Row():
with gr.Column():
gr.DataFrame(get_data, every=gr.Timer(5))
with gr.Column():
gr.LinePlot(get_data, every=gr.Timer(5), x="Date", y="Sales", y_title="Sales ($ millions)", overlay_point=True, width=500, height=500)
demo.queue().launch() Run the demo with queuing enabled
```
You now have a Dashboard that refreshes every 5 seconds, pulling the data from your Google Sheet.
|
Private Google Sheets
|
https://gradio.app/guides/creating-a-realtime-dashboard-from-google-sheets
|
Other Tutorials - Creating A Realtime Dashboard From Google Sheets Guide
|
And that's all there is to it! With just a few lines of code, you can use `gradio` and other libraries to read data from a public or private Google Sheet and then display and plot the data in a real-time dashboard.
|
Conclusion
|
https://gradio.app/guides/creating-a-realtime-dashboard-from-google-sheets
|
Other Tutorials - Creating A Realtime Dashboard From Google Sheets Guide
|
Data visualization is a crucial aspect of data analysis and machine learning. The Gradio `DataFrame` component is a popular way to display tabular data within a web application.
But what if you want to stylize the table of data? What if you want to add background colors, partially highlight cells, or change the display precision of numbers? This Guide is for you!
Let's dive in!
**Prerequisites**: We'll be using the `gradio.Blocks` class in our examples.
You can [read the Guide to Blocks first](https://gradio.app/blocks-and-event-listeners) if you are not already familiar with it. Also please make sure you are using the **latest version** version of Gradio: `pip install --upgrade gradio`.
|
Introduction
|
https://gradio.app/guides/styling-the-gradio-dataframe
|
Other Tutorials - Styling The Gradio Dataframe Guide
|
The Gradio `DataFrame` component now supports values of the type `Styler` from the `pandas` class. This allows us to reuse the rich existing API and documentation of the `Styler` class instead of inventing a new style format on our own. Here's a complete example of how it looks:
```python
import pandas as pd
import gradio as gr
Creating a sample dataframe
df = pd.DataFrame({
"A" : [14, 4, 5, 4, 1],
"B" : [5, 2, 54, 3, 2],
"C" : [20, 20, 7, 3, 8],
"D" : [14, 3, 6, 2, 6],
"E" : [23, 45, 64, 32, 23]
})
Applying style to highlight the maximum value in each row
styler = df.style.highlight_max(color = 'lightgreen', axis = 0)
Displaying the styled dataframe in Gradio
with gr.Blocks() as demo:
gr.DataFrame(styler)
demo.launch()
```
The Styler class can be used to apply conditional formatting and styling to dataframes, making them more visually appealing and interpretable. You can highlight certain values, apply gradients, or even use custom CSS to style the DataFrame. The Styler object is applied to a DataFrame and it returns a new object with the relevant styling properties, which can then be previewed directly, or rendered dynamically in a Gradio interface.
To read more about the Styler object, read the official `pandas` documentation at: https://pandas.pydata.org/docs/user_guide/style.html
Below, we'll explore a few examples:
Highlighting Cells
Ok, so let's revisit the previous example. We start by creating a `pd.DataFrame` object and then highlight the highest value in each row with a light green color:
```python
import pandas as pd
Creating a sample dataframe
df = pd.DataFrame({
"A" : [14, 4, 5, 4, 1],
"B" : [5, 2, 54, 3, 2],
"C" : [20, 20, 7, 3, 8],
"D" : [14, 3, 6, 2, 6],
"E" : [23, 45, 64, 32, 23]
})
Applying style to highlight the maximum value in each row
styler = df.style.highlight_max(color = 'lightgreen', axis = 0)
```
Now, we simply pass this object into the Gradio `DataFra
|
The Pandas `Styler`
|
https://gradio.app/guides/styling-the-gradio-dataframe
|
Other Tutorials - Styling The Gradio Dataframe Guide
|
, 32, 23]
})
Applying style to highlight the maximum value in each row
styler = df.style.highlight_max(color = 'lightgreen', axis = 0)
```
Now, we simply pass this object into the Gradio `DataFrame` and we can visualize our colorful table of data in 4 lines of python:
```python
import gradio as gr
with gr.Blocks() as demo:
gr.Dataframe(styler)
demo.launch()
```
Here's how it looks:

Font Colors
Apart from highlighting cells, you might want to color specific text within the cells. Here's how you can change text colors for certain columns:
```python
import pandas as pd
import gradio as gr
Creating a sample dataframe
df = pd.DataFrame({
"A" : [14, 4, 5, 4, 1],
"B" : [5, 2, 54, 3, 2],
"C" : [20, 20, 7, 3, 8],
"D" : [14, 3, 6, 2, 6],
"E" : [23, 45, 64, 32, 23]
})
Function to apply text color
def highlight_cols(x):
df = x.copy()
df.loc[:, :] = 'color: purple'
df[['B', 'C', 'E']] = 'color: green'
return df
Applying the style function
s = df.style.apply(highlight_cols, axis = None)
Displaying the styled dataframe in Gradio
with gr.Blocks() as demo:
gr.DataFrame(s)
demo.launch()
```
In this script, we define a custom function highlight_cols that changes the text color to purple for all cells, but overrides this for columns B, C, and E with green. Here's how it looks:

Display Precision
Sometimes, the data you are dealing with might have long floating numbers, and you may want to display only a fixed number of decimals for simplicity. The pandas Styler object allows you to format the precision of numbers displayed. Here's how you can do this:
```python
import pandas as pd
import gradio as gr
Creating a sample dataframe with floating numbers
df = pd.DataFrame({
"A" : [14.12345, 4.
|
The Pandas `Styler`
|
https://gradio.app/guides/styling-the-gradio-dataframe
|
Other Tutorials - Styling The Gradio Dataframe Guide
|
on of numbers displayed. Here's how you can do this:
```python
import pandas as pd
import gradio as gr
Creating a sample dataframe with floating numbers
df = pd.DataFrame({
"A" : [14.12345, 4.23456, 5.34567, 4.45678, 1.56789],
"B" : [5.67891, 2.78912, 54.89123, 3.91234, 2.12345],
... other columns
})
Setting the precision of numbers to 2 decimal places
s = df.style.format("{:.2f}")
Displaying the styled dataframe in Gradio
with gr.Blocks() as demo:
gr.DataFrame(s)
demo.launch()
```
In this script, the format method of the Styler object is used to set the precision of numbers to two decimal places. Much cleaner now:

|
The Pandas `Styler`
|
https://gradio.app/guides/styling-the-gradio-dataframe
|
Other Tutorials - Styling The Gradio Dataframe Guide
|
So far, we've been restricting ourselves to styling that is supported by the Pandas `Styler` class. But what if you want to create custom styles like partially highlighting cells based on their values:

This isn't possible with `Styler`, but you can do this by creating your own **`styling`** array, which is a 2D array the same size and shape as your data. Each element in this list should be a CSS style string (e.g. `"background-color: green"`) that applies to the `<td>` element containing the cell value (or an empty string if no custom CSS should be applied). Similarly, you can create a **`display_value`** array which controls the value that is displayed in each cell (which can be different the underlying value which is the one that is used for searching/sorting).
Here's the complete code for how to can use custom styling with `gr.Dataframe` as in the screenshot above:
$code_dataframe_custom_styling
|
Custom Styling
|
https://gradio.app/guides/styling-the-gradio-dataframe
|
Other Tutorials - Styling The Gradio Dataframe Guide
|
One thing to keep in mind is that the gradio `DataFrame` component only accepts custom styling objects when it is non-interactive (i.e. in "static" mode). If the `DataFrame` component is interactive, then the styling information is ignored and instead the raw table values are shown instead.
The `DataFrame` component is by default non-interactive, unless it is used as an input to an event. In which case, you can force the component to be non-interactive by setting the `interactive` prop like this:
```python
c = gr.DataFrame(styler, interactive=False)
```
|
Note about Interactivity
|
https://gradio.app/guides/styling-the-gradio-dataframe
|
Other Tutorials - Styling The Gradio Dataframe Guide
|
This is just a taste of what's possible using the `gradio.DataFrame` component with the `Styler` class from `pandas`. Try it out and let us know what you think!
|
Conclusion 🎉
|
https://gradio.app/guides/styling-the-gradio-dataframe
|
Other Tutorials - Styling The Gradio Dataframe Guide
|
It seems that cryptocurrencies, [NFTs](https://www.nytimes.com/interactive/2022/03/18/technology/nft-guide.html), and the web3 movement are all the rage these days! Digital assets are being listed on marketplaces for astounding amounts of money, and just about every celebrity is debuting their own NFT collection. While your crypto assets [may be taxable, such as in Canada](https://www.canada.ca/en/revenue-agency/programs/about-canada-revenue-agency-cra/compliance/digital-currency/cryptocurrency-guide.html), today we'll explore some fun and tax-free ways to generate your own assortment of procedurally generated [CryptoPunks](https://www.larvalabs.com/cryptopunks).
Generative Adversarial Networks, often known just as _GANs_, are a specific class of deep-learning models that are designed to learn from an input dataset to create (_generate!_) new material that is convincingly similar to elements of the original training set. Famously, the website [thispersondoesnotexist.com](https://thispersondoesnotexist.com/) went viral with lifelike, yet synthetic, images of people generated with a model called StyleGAN2. GANs have gained traction in the machine learning world, and are now being used to generate all sorts of images, text, and even [music](https://salu133445.github.io/musegan/)!
Today we'll briefly look at the high-level intuition behind GANs, and then we'll build a small demo around a pre-trained GAN to see what all the fuss is about. Here's a [peek](https://huggingface.co/proxy/nimaboscarino-cryptopunks.hf.space) at what we're going to be putting together.
Prerequisites
Make sure you have the `gradio` Python package already [installed](/getting_started). To use the pretrained model, also install `torch` and `torchvision`.
|
Introduction
|
https://gradio.app/guides/create-your-own-friends-with-a-gan
|
Other Tutorials - Create Your Own Friends With A Gan Guide
|
Originally proposed in [Goodfellow et al. 2014](https://arxiv.org/abs/1406.2661), GANs are made up of neural networks which compete with the intention of outsmarting each other. One network, known as the _generator_, is responsible for generating images. The other network, the _discriminator_, receives an image at a time from the generator along with a **real** image from the training data set. The discriminator then has to guess: which image is the fake?
The generator is constantly training to create images which are trickier for the discriminator to identify, while the discriminator raises the bar for the generator every time it correctly detects a fake. As the networks engage in this competitive (_adversarial!_) relationship, the images that get generated improve to the point where they become indistinguishable to human eyes!
For a more in-depth look at GANs, you can take a look at [this excellent post on Analytics Vidhya](https://www.analyticsvidhya.com/blog/2021/06/a-detailed-explanation-of-gan-with-implementation-using-tensorflow-and-keras/) or this [PyTorch tutorial](https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html). For now, though, we'll dive into a demo!
|
GANs: a very brief introduction
|
https://gradio.app/guides/create-your-own-friends-with-a-gan
|
Other Tutorials - Create Your Own Friends With A Gan Guide
|
To generate new images with a GAN, you only need the generator model. There are many different architectures that the generator could use, but for this demo we'll use a pretrained GAN generator model with the following architecture:
```python
from torch import nn
class Generator(nn.Module):
Refer to the link below for explanations about nc, nz, and ngf
https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.htmlinputs
def __init__(self, nc=4, nz=100, ngf=64):
super(Generator, self).__init__()
self.network = nn.Sequential(
nn.ConvTranspose2d(nz, ngf * 4, 3, 1, 0, bias=False),
nn.BatchNorm2d(ngf * 4),
nn.ReLU(True),
nn.ConvTranspose2d(ngf * 4, ngf * 2, 3, 2, 1, bias=False),
nn.BatchNorm2d(ngf * 2),
nn.ReLU(True),
nn.ConvTranspose2d(ngf * 2, ngf, 4, 2, 0, bias=False),
nn.BatchNorm2d(ngf),
nn.ReLU(True),
nn.ConvTranspose2d(ngf, nc, 4, 2, 1, bias=False),
nn.Tanh(),
)
def forward(self, input):
output = self.network(input)
return output
```
We're taking the generator from [this repo by @teddykoker](https://github.com/teddykoker/cryptopunks-gan/blob/main/train.pyL90), where you can also see the original discriminator model structure.
After instantiating the model, we'll load in the weights from the Hugging Face Hub, stored at [nateraw/cryptopunks-gan](https://huggingface.co/nateraw/cryptopunks-gan):
```python
from huggingface_hub import hf_hub_download
import torch
model = Generator()
weights_path = hf_hub_download('nateraw/cryptopunks-gan', 'generator.pth')
model.load_state_dict(torch.load(weights_path, map_location=torch.device('cpu'))) Use 'cuda' if you have a GPU available
```
|
Step 1 — Create the Generator model
|
https://gradio.app/guides/create-your-own-friends-with-a-gan
|
Other Tutorials - Create Your Own Friends With A Gan Guide
|
The `predict` function is the key to making Gradio work! Whatever inputs we choose through the Gradio interface will get passed through our `predict` function, which should operate on the inputs and generate outputs that we can display with Gradio output components. For GANs it's common to pass random noise into our model as the input, so we'll generate a tensor of random numbers and pass that through the model. We can then use `torchvision`'s `save_image` function to save the output of the model as a `png` file, and return the file name:
```python
from torchvision.utils import save_image
def predict(seed):
num_punks = 4
torch.manual_seed(seed)
z = torch.randn(num_punks, 100, 1, 1)
punks = model(z)
save_image(punks, "punks.png", normalize=True)
return 'punks.png'
```
We're giving our `predict` function a `seed` parameter, so that we can fix the random tensor generation with a seed. We'll then be able to reproduce punks if we want to see them again by passing in the same seed.
_Note!_ Our model needs an input tensor of dimensions 100x1x1 to do a single inference, or (BatchSize)x100x1x1 for generating a batch of images. In this demo we'll start by generating 4 punks at a time.
|
Step 2 — Defining a `predict` function
|
https://gradio.app/guides/create-your-own-friends-with-a-gan
|
Other Tutorials - Create Your Own Friends With A Gan Guide
|
At this point you can even run the code you have with `predict(<SOME_NUMBER>)`, and you'll find your freshly generated punks in your file system at `./punks.png`. To make a truly interactive demo, though, we'll build out a simple interface with Gradio. Our goals here are to:
- Set a slider input so users can choose the "seed" value
- Use an image component for our output to showcase the generated punks
- Use our `predict()` to take the seed and generate the images
With `gr.Interface()`, we can define all of that with a single function call:
```python
import gradio as gr
gr.Interface(
predict,
inputs=[
gr.Slider(0, 1000, label='Seed', default=42),
],
outputs="image",
).launch()
```
|
Step 3 — Creating a Gradio interface
|
https://gradio.app/guides/create-your-own-friends-with-a-gan
|
Other Tutorials - Create Your Own Friends With A Gan Guide
|
Generating 4 punks at a time is a good start, but maybe we'd like to control how many we want to make each time. Adding more inputs to our Gradio interface is as simple as adding another item to the `inputs` list that we pass to `gr.Interface`:
```python
gr.Interface(
predict,
inputs=[
gr.Slider(0, 1000, label='Seed', default=42),
gr.Slider(4, 64, label='Number of Punks', step=1, default=10), Adding another slider!
],
outputs="image",
).launch()
```
The new input will be passed to our `predict()` function, so we have to make some changes to that function to accept a new parameter:
```python
def predict(seed, num_punks):
torch.manual_seed(seed)
z = torch.randn(num_punks, 100, 1, 1)
punks = model(z)
save_image(punks, "punks.png", normalize=True)
return 'punks.png'
```
When you relaunch your interface, you should see a second slider that'll let you control the number of punks!
|
Step 4 — Even more punks!
|
https://gradio.app/guides/create-your-own-friends-with-a-gan
|
Other Tutorials - Create Your Own Friends With A Gan Guide
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.