text stringlengths 0 2k | heading1 stringlengths 3 79 | source_page_url stringclasses 190
values | source_page_title stringclasses 190
values |
|---|---|---|---|
...] | None
default `= None`
A unique key for this event listener to be used in @gr.render(). If set, this
value identifies an event as identical across re-renders when the key is
identical.
validator: Callable | None
default `= None`
Optional validation function to run before the main function. If... | Event Listeners | https://gradio.app/docs/gradio/barplot | Gradio - Barplot Docs |
Creates an image component that can be used to upload images (as an input)
or display images (as an output).
| Description | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
**Using Image as an input component.**
How Image will pass its value to your function:
Type: `np.ndarray | PIL.Image.Image | str | None`
Passes the uploaded image as a `numpy.array`, `PIL.Image` or `str` filepath
depending on `type`.
Example Code
import gradio as gr
def pred... | Behavior | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
Parameters ▼
value: str | PIL.Image.Image | np.ndarray | Callable | None
default `= None`
A `PIL.Image`, `numpy.array`, `pathlib.Path`, or `str` filepath or URL for the
default value that Image component is going to take. If a function is
provided, the function will be called each time the app loads t... | Initialization | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
erred
from the image file type (e.g. "RGBA" for a .png image, "RGB" in most other
cases).
sources: list[Literal['upload', 'webcam', 'clipboard']] | Literal['upload', 'webcam', 'clipboard'] | None
default `= None`
List of sources for the image. "upload" creates a box where user can drop an
image file, ... | Initialization | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
o calculate `value` if `value` is a
function (has no effect otherwise). `value` is recalculated any time the
inputs change.
show_label: bool | None
default `= None`
if True, will display label.
buttons: list[Literal['download', 'share', 'fullscreen'] | Button] | None
default `= None`
... | Initialization | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
rovided, this is inferred based on whether the
component is used as an input or output.
visible: bool | Literal['hidden']
default `= True`
If False, component will be hidden. If "hidden", component will be visually
hidden and not take up space in the layout but still exist in the DOM
s... | Initialization | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
es
provided during constructor.
webcam_options: WebcamOptions | None
default `= None`
placeholder: str | None
default `= None`
Custom text for the upload area. Overrides default upload messages when
provided. Accepts new lines and `` to designate a heading.
watermark: ... | Initialization | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
Shortcuts
gradio.Image
Interface String Shortcut `"image"`
Initialization Uses default values
| Shortcuts | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
The `type` parameter controls the format of the data passed to your Python
function. Choosing the right type avoids unnecessary conversions in your code:
`type`| Your function receives| Shape / Format| Best for
---|---|---|---
`"numpy"` (default)| `numpy.ndarray`| `(height, width, 3)`, dtype `uint8`,
values 0–255|... | Understanding Image Types | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
The `gr.Image` component can process or display any image format that is
[supported by the PIL
library](https://pillow.readthedocs.io/en/stable/handbook/image-file-
formats.html), including animated GIFs. In addition, it also supports the SVG
image format.
When the `gr.Image` component is used as an input component, t... | `GIF` and `SVG` Image Formats | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
sepia_filterfake_diffusion
| Demos | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
Description
Event listeners allow you to respond to user interactions with the UI
components you've defined in a Gradio Blocks app. When a user interacts with
an element, such as changing a slider value or uploading an image, a function
is called.
Supported Event Listeners
The Image component supports the following ... | Event Listeners | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
corresponds to one
input component, and the function should return a single value or a tuple of
values, with each element in the tuple corresponding to one output component.
inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default `= None`
List o... | Event Listeners | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
animation at all
show_progress_on: Component | list[Component] | None
default `= None`
Component or list of components to show the progress animation on. If None,
will show the progress animation on all of the output components.
queue: bool
default `= True`
If True, will place the r... | Event Listeners | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
n (or generators that are iterating) will be cancelled, but
functions that are currently running will be allowed to finish.
trigger_mode: Literal['once', 'multiple', 'always_last'] | None
default `= None`
If "once" (default for all events except `.change()`) would not allow any
submissions while an ev... | Event Listeners | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
dio client libraries), or "undocumented" (hidden
from API docs but callable by clients and via gr.load). If fn is None,
api_visibility will automatically be set to "private".
time_limit: int | None
default `= None`
stream_every: float
default `= 0.5`
key: int | str | tu... | Event Listeners | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
Helper Classes | https://gradio.app/docs/gradio/image | Gradio - Image Docs | |
gradio.WebcamOptions(···)
Description
A dataclass for specifying options for the webcam tool in the ImageEditor
component. An instance of this class can be passed to the `webcam_options`
parameter of `gr.ImageEditor`.
Initialization
Parameters ▼
mirror: bool
default `= True`
If True, the webcam wi... | Webcam Options | https://gradio.app/docs/gradio/image | Gradio - Image Docs |
The gr.DeletedFileData class is a subclass of gr.EventData that
specifically carries information about the `.delete()` event. When
gr.DeletedFileData is added as a type hint to an argument of an event listener
method, a gr.DeletedFileData object will automatically be passed as the value
of that argument. The attributes... | Description | https://gradio.app/docs/gradio/deletedfiledata | Gradio - Deletedfiledata Docs |
import gradio as gr
def test(delete_data: gr.DeletedFileData):
return delete_data.file.path
with gr.Blocks() as demo:
files = gr.File(file_count="multiple")
deleted_file = gr.File()
files.delete(test, None, deleted_file)
demo.launch()
| Example Usage | https://gradio.app/docs/gradio/deletedfiledata | Gradio - Deletedfiledata Docs |
Parameters ▼
file: FileData
The file that was deleted, as a FileData object. The str path to the file can
be retrieved with the .path attribute.
| Attributes | https://gradio.app/docs/gradio/deletedfiledata | Gradio - Deletedfiledata Docs |
file_component_events
| Demos | https://gradio.app/docs/gradio/deletedfiledata | Gradio - Deletedfiledata Docs |
An MCP (Model Control Protocol) server is a standardized way to expose tools so that they can be used by LLMs. A tool can provide an LLM functionality that it does not have natively, such as the ability to generate images or calculate the prime factors of a number.
| What is an MCP Server? | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
LLMs are famously not great at counting the number of letters in a word (e.g. the number of "r"-s in "strawberry"). But what if we equip them with a tool to help? Let's start by writing a simple Gradio app that counts the number of letters in a word or phrase:
$code_letter_counter
Notice that we have: (1) included a ... | Example: Counting Letters in a Word | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
1. **Tool Conversion**: Each API endpoint in your Gradio app is automatically converted into an MCP tool with a corresponding name, description, and input schema. To view the tools and schemas, visit http://your-server:port/gradio_api/mcp/schema or go to the "View API" link in the footer of your Gradio app, and then cl... | Key features of the Gradio <> MCP Integration | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
p: To minimize latency and increase throughput by as much as 10 times, set queue=False in the event handlers of your Gradio app. However, this disables progress notifications so its recommended that long running events set queue=True
| Key features of the Gradio <> MCP Integration | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
If there's an existing Space that you'd like to use an MCP server, you'll need to do three things:
1. First, [duplicate the Space](https://huggingface.co/docs/hub/en/spaces-more-ways-to-createduplicating-a-space) if it is not your own Space. This will allow you to make changes to the app. If the Space requires a GPU, ... | Converting an Existing Space | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
You can use either a public Space or a private Space as an MCP server. If you'd like to use a private Space as an MCP server (or a ZeroGPU Space with your own quota), then you will need to provide your [Hugging Face token](https://huggingface.co/settings/token) when you make your request. To do this, simply add it as a... | Private Spaces | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
You may wish to authenticate users more precisely or let them provide other kinds of credentials or tokens in order to provide a custom experience for different users.
Gradio allows you to access the underlying `starlette.Request` that has made the tool call, which means that you can access headers, originating IP ad... | Authentication and Credentials | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
the headers you need to supply when connecting to the server! See the image below:
```python
import gradio as gr
def make_api_request_on_behalf_of_user(prompt: str, x_api_token: gr.Header):
"""Make a request to everyone's favorite API.
Args:
prompt: The prompt to send to the API.
Returns:
... | Authentication and Credentials | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
Gradio automatically sets the tool name based on the name of your function, and the description from the docstring of your function. But you may want to change how the description appears to your LLM. You can do this by using the `api_description` parameter in `Interface`, `ChatInterface`, or any event listener. This p... | Modifying Tool Descriptions | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
In addition to tools (which execute functions generally and are the default for any function exposed through the Gradio MCP integration), MCP supports two other important primitives: **resources** (for exposing data) and **prompts** (for defining reusable templates). Gradio provides decorators to easily create MCP serv... | MCP Resources and Prompts | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
So far, all of our MCP tools, resources, or prompts have corresponded to event listeners in the UI. This works well for functions that directly update the UI, but may not work if you wish to expose a "pure logic" function that should return raw data (e.g. a JSON object) without directly causing a UI update.
In order t... | Adding MCP-Only Functions | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
In some cases, you may decide not to use Gradio's built-in integration and instead manually create an FastMCP Server that calls a Gradio app. This approach is useful when you want to:
- Store state / identify users between calls instead of treating every tool call completely independently
- Start the Gradio app MCP se... | Gradio with FastMCP | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
return result
@mcp.tool()
async def run_dia_tts(prompt: str, space_id: str = "ysharma/Dia-1.6B") -> str:
"""Text-to-Speech Synthesis.
Args:
prompt: Text prompt describing the conversation between speakers S1, S2
space_id: HuggingFace Space ID to use
"""
client = get_client(space_... | Gradio with FastMCP | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
use your Gradio-powered tools to accomplish these tasks.
| Gradio with FastMCP | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
The MCP protocol is still in its infancy and you might see issues connecting to an MCP Server that you've built. We generally recommend using the [MCP Inspector Tool](https://github.com/modelcontextprotocol/inspector) to try connecting and debugging your MCP Server.
Here are some things that may help:
**1. Ensure tha... | Troubleshooting your MCP Servers | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
= 3
while divisor * divisor <= n_int:
while n_int % divisor == 0:
factors.append(divisor)
n_int //= divisor
divisor += 2
if n_int > 1:
factors.append(n_int)
return factors
```
**3. Ensure that your MCP Client Supports Streamable HTTP**
Some MCP Clients do ... | Troubleshooting your MCP Servers | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
The Model Context Protocol (MCP) standardizes how applications provide context to LLMs. It allows Claude to interact with external tools, like image generators, file systems, or APIs, etc.
| What is MCP? | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
- Python 3.10+
- An Anthropic API key
- Basic understanding of Python programming
| Prerequisites | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
First, install the required packages:
```bash
pip install gradio anthropic mcp
```
Create a `.env` file in your project directory and add your Anthropic API key:
```
ANTHROPIC_API_KEY=your_api_key_here
```
| Setup | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
The server provides tools that Claude can use. In this example, we'll create a server that generates images through [a HuggingFace space](https://huggingface.co/spaces/ysharma/SanaSprint).
Create a file named `gradio_mcp_server.py`:
```python
from mcp.server.fastmcp import FastMCP
import json
import sys
import io
imp... | Part 1: Building the MCP Server | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
"message": f"Error generating image: {str(e)}"
})
if __name__ == "__main__":
mcp.run(transport='stdio')
```
What this server does:
1. It creates an MCP server that exposes a `generate_image` tool
2. The tool connects to the SanaSprint model hosted on HuggingFace Spaces
3. It handles the asynchronous na... | Part 1: Building the MCP Server | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
Now let's create a Gradio chat interface as MCP Client that connects Claude to our MCP server.
Create a file named `app.py`:
```python
import asyncio
import os
import json
from typing import List, Dict, Any, Union
from contextlib import AsyncExitStack
import gradio as gr
from gradio.components.chatbot import ChatMes... | Part 2: Building the MCP Client with Gradio | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
iption,
"input_schema": tool.inputSchema
} for tool in response.tools]
tool_names = [tool["name"] for tool in self.tools]
return f"Connected to MCP server. Available tools: {', '.join(tool_names)}"
def process_message(self, message: str, history: List[Union[Dict[str... | Part 2: Building the MCP Client with Gradio | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
ntent": content.text
})
elif content.type == 'tool_use':
tool_name = content.name
tool_args = content.input
result_messages.append({
"role": "assistant",
"content": f"I'l... | Part 2: Building the MCP Client with Gradio | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
})
result_content = result.content
if isinstance(result_content, list):
result_content = "\n".join(str(item) for item in result_content)
try:
result_json = json.loads(result_content)
... | Part 2: Building the MCP Client with Gradio | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
"parent_id": f"result_{tool_name}",
"id": f"raw_result_{tool_name}",
"title": "Raw Output"
}
})
claude_messages.append({"role": "user", "content": f"Tool result for {tool_name}: {result_... | Part 2: Building the MCP Client with Gradio | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
w(equal_height=True):
msg = gr.Textbox(
label="Your Question",
placeholder="Ask about weather or alerts (e.g., What's the weather in New York?)",
scale=4
)
clear_btn = gr.Button("Clear Chat", scale=1)
connect_btn.click(... | Part 2: Building the MCP Client with Gradio | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
To run your MCP application:
- Start a terminal window and run the MCP Client:
```bash
python app.py
```
- Open the Gradio interface at the URL shown (typically http://127.0.0.1:7860)
- In the Gradio interface, you'll see a field for the MCP Server path. It should default to `gradio_mcp_server.py`.
- Click "C... | Running the Application | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
Now you can chat with Claude and it will be able to generate images based on your descriptions.
Try prompts like:
- "Can you generate an image of a mountain landscape at sunset?"
- "Create an image of a cool tabby cat"
- "Generate a picture of a panda wearing sunglasses"
Claude will recognize these as image generatio... | Example Usage | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
Here's the high-level flow of what happens during a chat session:
1. Your prompt enters the Gradio interface
2. The client forwards your prompt to Claude
3. Claude analyzes the prompt and decides to use the `generate_image` tool
4. The client sends the tool call to the MCP server
5. The server calls the external image... | How it Works | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
Now that you have a working MCP system, here are some ideas to extend it:
- Add more tools to your server
- Improve error handling
- Add private Huggingface Spaces with authentication for secure tool access
- Create custom tools that connect to your own APIs or services
- Implement streaming responses for better user... | Next Steps | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
Congratulations! You've successfully built an MCP Client and Server that allows Claude to generate images based on text prompts. This is just the beginning of what you can do with Gradio and MCP. This guide enables you to build complex AI applications that can use Claude or any other powerful LLM to interact with virtu... | Conclusion | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
As of version 5.36.0, Gradio now comes with a built-in MCP server that can upload files to a running Gradio application. In the `View API` page of the server, you should see the following code snippet if any of the tools require file inputs:
<img src="https://huggingface.co/datasets/freddyaboulton/bucket/resolve/main/... | Using the File Upload MCP Server | https://gradio.app/guides/file-upload-mcp | Mcp - File Upload Mcp Guide |
In this guide, we've covered how you can connect to the Upload File MCP Server so that your agent can upload files before using Gradio MCP servers. Remember to set the `<UPLOAD_DIRECTORY>` as small as possible to prevent unintended file uploads!
| Conclusion | https://gradio.app/guides/file-upload-mcp | Mcp - File Upload Mcp Guide |
If you're using LLMs in your workflow, adding this server will augment them with just the right context on gradio - which makes your experience a lot faster and smoother.
<video src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/mcp-docs.mp4" style="width:100%" controls p... | Why an MCP Server? | https://gradio.app/guides/using-docs-mcp | Mcp - Using Docs Mcp Guide |
For clients that support streamable HTTP (e.g. Cursor, Windsurf, Cline), simply add the following configuration to your MCP config:
```json
{
"mcpServers": {
"gradio": {
"url": "https://gradio-docs-mcp.hf.space/gradio_api/mcp/"
}
}
}
```
We've included step-by-step instructions for Cursor below, but... | Installing in the Clients | https://gradio.app/guides/using-docs-mcp | Mcp - Using Docs Mcp Guide |
There are currently only two tools in the server: `gradio_docs_mcp_load_gradio_docs` and `gradio_docs_mcp_search_gradio_docs`.
1. `gradio_docs_mcp_load_gradio_docs`: This tool takes no arguments and will load an /llms.txt style summary of Gradio's latest, full documentation. Very useful context the LLM can parse befo... | Tools | https://gradio.app/guides/using-docs-mcp | Mcp - Using Docs Mcp Guide |
When you are building a Gradio demo, particularly out of Blocks, you may find it cumbersome to keep re-running your code to test your changes.
To make it faster and more convenient to write your code, we've made it easier to "reload" your Gradio apps instantly when you are developing in a **Python IDE** (like VS Code,... | Why Hot Reloading? | https://gradio.app/guides/developing-faster-with-reload-mode | Other Tutorials - Developing Faster With Reload Mode Guide |
If you are building Gradio Blocks using a Python IDE, your file of code (let's name it `run.py`) might look something like this:
```python
import gradio as gr
with gr.Blocks() as demo:
gr.Markdown("Greetings from Gradio!")
inp = gr.Textbox(placeholder="What is your name?")
out = gr.Textbox()
inp.chan... | Python IDE Reload 🔥 | https://gradio.app/guides/developing-faster-with-reload-mode | Other Tutorials - Developing Faster With Reload Mode Guide |
emo as the 2nd parameter in your code. So if your `run.py` file looked like this:
```python
import gradio as gr
with gr.Blocks() as my_demo:
gr.Markdown("Greetings from Gradio!")
inp = gr.Textbox(placeholder="What is your name?")
out = gr.Textbox()
inp.change(fn=lambda x: f"Welcome, {x}!",
... | Python IDE Reload 🔥 | https://gradio.app/guides/developing-faster-with-reload-mode | Other Tutorials - Developing Faster With Reload Mode Guide |
second.
As a small aside, this auto-reloading happens if you change your `run.py` source code or the Gradio source code. Meaning that this can be useful if you decide to [contribute to Gradio itself](https://github.com/gradio-app/gradio/blob/main/CONTRIBUTING.md) ✅
| Python IDE Reload 🔥 | https://gradio.app/guides/developing-faster-with-reload-mode | Other Tutorials - Developing Faster With Reload Mode Guide |
By default, reload mode will re-run your entire script for every change you make.
But there are some cases where this is not desirable.
For example, loading a machine learning model should probably only happen once to save time. There are also some Python libraries that use C or Rust extensions that throw errors when t... | Controlling the Reload 🎛️ | https://gradio.app/guides/developing-faster-with-reload-mode | Other Tutorials - Developing Faster With Reload Mode Guide |
You can also enable Gradio's **Vibe Mode**, which, which provides an in-browser chat that can be used to write or edit your Gradio app using natural language. To enable this, simply run use the `--vibe` flag with Gradio, e.g. `gradio --vibe app.py`.
Vibe Mode lets you describe commands using natural language and have ... | Vibe Mode | https://gradio.app/guides/developing-faster-with-reload-mode | Other Tutorials - Developing Faster With Reload Mode Guide |
What about if you use Jupyter Notebooks (or Colab Notebooks, etc.) to develop code? We got something for you too!
We've developed a **magic command** that will create and run a Blocks demo for you. To use this, load the gradio extension at the top of your notebook:
`%load_ext gradio`
Then, in the cell that you are d... | Jupyter Notebook Magic 🔮 | https://gradio.app/guides/developing-faster-with-reload-mode | Other Tutorials - Developing Faster With Reload Mode Guide |
Now that you know how to develop quickly using Gradio, start building your own!
If you are looking for inspiration, try exploring demos other people have built with Gradio, [browse public Hugging Face Spaces](http://hf.space/) 🤗
| Next Steps | https://gradio.app/guides/developing-faster-with-reload-mode | Other Tutorials - Developing Faster With Reload Mode 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 li... | 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 cred... | 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\. Cl... | 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()... | 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 |
Let's go through a simple example to understand how to containerize a Gradio app using Docker.
Step 1: Create Your Gradio App
First, we need a simple Gradio app. Let's create a Python file named `app.py` with the following content:
```python
import gradio as gr
def greet(name):
return f"Hello {name}!"
iface = ... | How to Dockerize a Gradio App | https://gradio.app/guides/deploying-gradio-with-docker | Other Tutorials - Deploying Gradio With Docker Guide |
When running Gradio applications in Docker, there are a few important things to keep in mind:
Running the Gradio app on `"0.0.0.0"` and exposing port 7860
In the Docker environment, setting `GRADIO_SERVER_NAME="0.0.0.0"` as an environment variable (or directly in your Gradio app's `launch()` function) is crucial for ... | Important Considerations | https://gradio.app/guides/deploying-gradio-with-docker | Other Tutorials - Deploying Gradio With Docker 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/pc... | 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
``... | 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.dat... | 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.qui... | 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-vid... | 3) Setup Stream and Gradio UI | https://gradio.app/guides/create-immersive-demo | Other Tutorials - Create Immersive Demo Guide |
In this Guide, we'll walk you through:
- Introduction of Gradio, and Hugging Face Spaces, and Wandb
- How to setup a Gradio demo using the Wandb integration for JoJoGAN
- How to contribute your own Gradio demos after tracking your experiments on wandb to the Wandb organization on Hugging Face
| Introduction | https://gradio.app/guides/Gradio-and-Wandb-Integration | Other Tutorials - Gradio And Wandb Integration Guide |
Weights and Biases (W&B) allows data scientists and machine learning scientists to track their machine learning experiments at every stage, from training to production. Any metric can be aggregated over samples and shown in panels in a customizable and searchable dashboard, like below:
<img alt="Screen Shot 2022-08-01... | What is Wandb? | https://gradio.app/guides/Gradio-and-Wandb-Integration | Other Tutorials - Gradio And Wandb Integration Guide |
Gradio
Gradio lets users demo their machine learning models as a web app, all in a few lines of Python. Gradio wraps any Python function (such as a machine learning model's inference function) into a user interface and the demos can be launched inside jupyter notebooks, colab notebooks, as well as embedded in your own... | What are Hugging Face Spaces & Gradio? | https://gradio.app/guides/Gradio-and-Wandb-Integration | Other Tutorials - Gradio And Wandb Integration Guide |
Now, let's walk you through how to do this on your own. We'll make the assumption that you're new to W&B and Gradio for the purposes of this tutorial.
Let's get started!
1. Create a W&B account
Follow [these quick instructions](https://app.wandb.ai/login) to create your free account if you don’t have one already.... | Setting up a Gradio Demo for JoJoGAN | https://gradio.app/guides/Gradio-and-Wandb-Integration | Other Tutorials - Gradio And Wandb Integration Guide |
: storage)
discriminator.load_state_dict(ckpt["d"], strict=False)
reset generator
del generator
generator = deepcopy(original_generator)
g_optim = optim.Adam(generator.parameters(), lr=2e-3, betas=(0, 0.99))
Which layers to swap for generating a family of plausible real images -> fake image
if p... | Setting up a Gradio Demo for JoJoGAN | https://gradio.app/guides/Gradio-and-Wandb-Integration | Other Tutorials - Gradio And Wandb Integration Guide |
ave, Download, and Load Model
Here's how to save and download your model.
```python
from PIL import Image
import torch
torch.backends.cudnn.benchmark = True
from torchvision import transforms, utils
from util import *
import math
import random
import numpy as np
from torch import nn,... | Setting up a Gradio Demo for JoJoGAN | https://gradio.app/guides/Gradio-and-Wandb-Integration | Other Tutorials - Gradio And Wandb Integration Guide |
.5, 0.5)),
]
)
def inference(img):
img.save('out.jpg')
aligned_face = align_face('out.jpg')
my_w = e4e_projection(aligned_face, "out.pt", device).unsqueeze(0)
with torch.no_grad():
my_sample = generator(my_w, input_is_latent=True)
npimage = my_sampl... | Setting up a Gradio Demo for JoJoGAN | https://gradio.app/guides/Gradio-and-Wandb-Integration | Other Tutorials - Gradio And Wandb Integration Guide |
``python
import gradio as gr
def wandb_report(url):
iframe = f'<iframe src={url} style="border:none;height:1024px;width:100%">'
return gr.HTML(iframe)
with gr.Blocks() as demo:
report_url = 'https://wandb.ai/_scott/pytorch-sweeps-demo/reports/loss-22-10-07-16-00-17---VmlldzoyNzU2Nz... | Setting up a Gradio Demo for JoJoGAN | https://gradio.app/guides/Gradio-and-Wandb-Integration | Other Tutorials - Gradio And Wandb Integration Guide |
We hope you enjoyed this brief demo of embedding a Gradio demo to a W&B report! Thanks for making it to the end. To recap:
- Only one single reference image is needed for fine-tuning JoJoGAN which usually takes about 1 minute on a GPU in colab. After training, style can be applied to any input image. Read more in the ... | Conclusion | https://gradio.app/guides/Gradio-and-Wandb-Integration | Other Tutorials - Gradio And Wandb Integration Guide |
- Create an account on Hugging Face [here](https://huggingface.co/join).
- Add Gradio Demo under your username, see this [course](https://huggingface.co/course/chapter9/4?fw=pt) for setting up Gradio Demo on Hugging Face.
- Request to join wandb organization [here](https://huggingface.co/wandb).
- Once approved transfe... | How to contribute Gradio demos on HF spaces on the Wandb organization | https://gradio.app/guides/Gradio-and-Wandb-Integration | Other Tutorials - Gradio And Wandb Integration 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 focusin... | 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.Data... | 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... | 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 mo... | 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 |
Image classification is a central task in computer vision. Building better classifiers to classify what object is present in a picture is an active area of research, as it has applications stretching from facial recognition to manufacturing quality control.
State-of-the-art image classifiers are based on the _transfor... | Introduction | https://gradio.app/guides/image-classification-with-vision-transformers | Other Tutorials - Image Classification With Vision Transformers Guide |
First, we will need an image classification model. For this tutorial, we will use a model from the [Hugging Face Model Hub](https://huggingface.co/models?pipeline_tag=image-classification). The Hub contains thousands of models covering dozens of different machine learning tasks.
Expand the Tasks category on the left s... | Step 1 — Choosing a Vision Image Classification Model | https://gradio.app/guides/image-classification-with-vision-transformers | Other Tutorials - Image Classification With Vision Transformers Guide |
When using a model from the Hugging Face Hub, we do not need to define the input or output components for the demo. Similarly, we do not need to be concerned with the details of preprocessing or postprocessing.
All of these are automatically inferred from the model tags.
Besides the import statement, it only takes a s... | Step 2 — Loading the Vision Transformer Model with Gradio | https://gradio.app/guides/image-classification-with-vision-transformers | Other Tutorials - Image Classification With Vision Transformers Guide |
In this guide we will demonstrate some of the ways you can use Gradio with Comet. We will cover the basics of using Comet with Gradio and show you some of the ways that you can leverage Gradio's advanced features such as [Embedding with iFrames](https://www.gradio.app/guides/sharing-your-app/embedding-with-iframes) and... | Introduction | https://gradio.app/guides/Gradio-and-Comet | Other Tutorials - Gradio And Comet Guide |
[Comet](https://www.comet.com?utm_source=gradio&utm_medium=referral&utm_campaign=gradio-integration&utm_content=gradio-docs) is an MLOps Platform that is designed to help Data Scientists and Teams build better models faster! Comet provides tooling to Track, Explain, Manage, and Monitor your models in a single place! It... | What is Comet? | https://gradio.app/guides/Gradio-and-Comet | Other Tutorials - Gradio And Comet Guide |
First, install the dependencies needed to run these examples
```shell
pip install comet_ml torch torchvision transformers gradio shap requests Pillow
```
Next, you will need to [sign up for a Comet Account](https://www.comet.com/signup?utm_source=gradio&utm_medium=referral&utm_campaign=gradio-integration&utm_content=... | Setup | https://gradio.app/guides/Gradio-and-Comet | Other Tutorials - Gradio And Comet Guide |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.