text stringlengths 0 2k | heading1 stringlengths 4 79 | source_page_url stringclasses 183 values | source_page_title stringclasses 183 values |
|---|---|---|---|
ggingface.co/spaces/gradio/chatbot_streaming): A streaming chatbot demo built with `gr.Chatbot` and Blocks.
- [gradio/chatbot_examples](https://huggingface.co/spaces/gradio/chatbot_examples): A chatbot that presents new visitors with a list of multimodal examples they can use to start the conversation.
| Adding Markdown, Images, Audio, or Videos | https://gradio.app/guides/creating-a-custom-chatbot-with-blocks | Chatbots - Creating A Custom Chatbot With Blocks Guide |
Let's start by using `llama-index` on top of `openai` to build a RAG chatbot on any text or PDF files that you can demo and share in less than 30 lines of code. You'll need to have an OpenAI key for this example (keep reading for the free, open-source equivalent!)
$code_llm_llamaindex
| Llama Index | https://gradio.app/guides/chatinterface-examples | Chatbots - Chatinterface Examples Guide |
Here's an example using `langchain` on top of `openai` to build a general-purpose chatbot. As before, you'll need to have an OpenAI key for this example.
$code_llm_langchain
Tip: For quick prototyping, the community-maintained <a href='https://github.com/AK391/langchain-gradio'>langchain-gradio repo</a> makes it even easier to build chatbots on top of LangChain.
| LangChain | https://gradio.app/guides/chatinterface-examples | Chatbots - Chatinterface Examples Guide |
Of course, we could also use the `openai` library directy. Here a similar example to the LangChain , but this time with streaming as well:
Tip: For quick prototyping, the <a href='https://github.com/gradio-app/openai-gradio'>openai-gradio library</a> makes it even easier to build chatbots on top of OpenAI models.
| OpenAI | https://gradio.app/guides/chatinterface-examples | Chatbots - Chatinterface Examples Guide |
Of course, in many cases you want to run a chatbot locally. Here's the equivalent example using the SmolLM2-135M-Instruct model using the Hugging Face `transformers` library.
$code_llm_hf_transformers
| Hugging Face `transformers` | https://gradio.app/guides/chatinterface-examples | Chatbots - Chatinterface Examples Guide |
The SambaNova Cloud API provides access to full-precision open-source models, such as the Llama family. Here's an example of how to build a Gradio app around the SambaNova API
$code_llm_sambanova
Tip: For quick prototyping, the <a href='https://github.com/gradio-app/sambanova-gradio'>sambanova-gradio library</a> makes it even easier to build chatbots on top of SambaNova models.
| SambaNova | https://gradio.app/guides/chatinterface-examples | Chatbots - Chatinterface Examples Guide |
The Hyperbolic AI API provides access to many open-source models, such as the Llama family. Here's an example of how to build a Gradio app around the Hyperbolic
$code_llm_hyperbolic
Tip: For quick prototyping, the <a href='https://github.com/HyperbolicLabs/hyperbolic-gradio'>hyperbolic-gradio library</a> makes it even easier to build chatbots on top of Hyperbolic models.
| Hyperbolic | https://gradio.app/guides/chatinterface-examples | Chatbots - Chatinterface Examples Guide |
Anthropic's Claude model can also be used via API. Here's a simple 20 questions-style game built on top of the Anthropic API:
$code_llm_claude
| Anthropic's Claude | https://gradio.app/guides/chatinterface-examples | Chatbots - Chatinterface Examples Guide |
The Discord bot will listen to messages mentioning it in channels. When it receives a message (which can include text as well as files), it will send it to your Gradio app via Gradio's built-in API. Your bot will reply with the response it receives from the API.
Because Gradio's API is very flexible, you can create Discord bots that support text, images, audio, streaming, chat history, and a wide variety of other features very easily.

| How does it work? | https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app | Chatbots - Creating A Discord Bot From A Gradio App Guide |
* Install the latest version of `gradio` and the `discord.py` libraries:
```
pip install --upgrade gradio discord.py~=2.0
```
* Have a running Gradio app. This app can be running locally or on Hugging Face Spaces. In this example, we will be using the [Gradio Playground Space](https://huggingface.co/spaces/abidlabs/gradio-playground-bot), which takes in an image and/or text and generates the code to generate the corresponding Gradio app.
Now, we are ready to get started!
1. Create a Discord application
First, go to the [Discord apps dashboard](https://discord.com/developers/applications). Look for the "New Application" button and click it. Give your application a name, and then click "Create".

On the resulting screen, you will see basic information about your application. Under the Settings section, click on the "Bot" option. You can update your bot's username if you would like.
Then click on the "Reset Token" button. A new token will be generated. Copy it as we will need it for the next step.
Scroll down to the section that says "Privileged Gateway Intents". Your bot will need certain permissions to work correctly. In this tutorial, we will only be using the "Message Content Intent" so click the toggle to enable this intent. Save the changes.

2. Write a Discord bot
Let's start by writing a very simple Discord bot, just to make sure that everything is working. Write the following Python code in a file called `bot.py`, pasting the discord bot token from the previous step:
```python
bot.py
import discord
TOKEN = PASTE YOUR DISCORD BOT TOKEN HERE
client = discord.Client()
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
client.run(TOKEN)
```
Now, run this file: `python bot.py`, w | Prerequisites | https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app | Chatbots - Creating A Discord Bot From A Gradio App Guide |
CORD BOT TOKEN HERE
client = discord.Client()
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
client.run(TOKEN)
```
Now, run this file: `python bot.py`, which should run and print a message like:
```text
We have logged in as GradioPlaygroundBot1451
```
If that is working, we are ready to add Gradio-specific code. We will be using the [Gradio Python Client](https://www.gradio.app/guides/getting-started-with-the-python-client) to query the Gradio Playground Space mentioned above. Here's the updated `bot.py` file:
```python
import discord
from gradio_client import Client, handle_file
import httpx
import os
TOKEN = PASTE YOUR DISCORD BOT TOKEN HERE
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
gradio_client = Client("abidlabs/gradio-playground-bot")
def download_image(attachment):
response = httpx.get(attachment.url)
image_path = f"./images/{attachment.filename}"
os.makedirs("./images", exist_ok=True)
with open(image_path, "wb") as f:
f.write(response.content)
return image_path
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.event
async def on_message(message):
Ignore messages from the bot itself
if message.author == client.user:
return
Check if the bot is mentioned in the message and reply
if client.user in message.mentions:
Extract the message content without the bot mention
clean_message = message.content.replace(f"<@{client.user.id}>", "").strip()
Handle images (only the first image is used)
files = []
if message.attachments:
for attachment in message.attachments:
if any(attachment.filename.lower().endswith(ext) for ext in ['png', 'jpg', 'jpeg', 'gif', 'webp']):
image_path = download_image(attachment)
files.append(handle_file(image_path)) | Prerequisites | https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app | Chatbots - Creating A Discord Bot From A Gradio App Guide |
.filename.lower().endswith(ext) for ext in ['png', 'jpg', 'jpeg', 'gif', 'webp']):
image_path = download_image(attachment)
files.append(handle_file(image_path))
break
Stream the responses to the channel
for response in gradio_client.submit(
message={"text": clean_message, "files": files},
):
await message.channel.send(response[-1])
client.run(TOKEN)
```
3. Add the bot to your Discord Server
Now we are ready to install the bot on our server. Go back to the [Discord apps dashboard](https://discord.com/developers/applications). Under the Settings section, click on the "OAuth2" option. Scroll down to the "OAuth2 URL Generator" box and select the "bot" checkbox:

Then in "Bot Permissions" box that pops up underneath, enable the following permissions:

Copy the generated URL that appears underneath, which should look something like:
```text
https://discord.com/oauth2/authorize?client_id=1319011745452265575&permissions=377957238784&integration_type=0&scope=bot
```
Paste it into your browser, which should allow you to add the Discord bot to any Discord server that you manage.
4. That's it!
Now you can mention your bot from any channel in your Discord server, optionally attach an image, and it will respond with generated Gradio app code!
The bot will:
1. Listen for mentions
2. Process any attached images
3. Send the text and images to your Gradio app
4. Stream the responses back to the Discord channel
This is just a basic example - you can extend it to handle more types of files, add error handling, or integrate with different Gradio apps.

If you build a Discord bot from a Gradio app, feel free to share it on X and tag [the Gradio account](https://x.com/Gradio), and we are happy to help you amplify! | Prerequisites | https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app | Chatbots - Creating A Discord Bot From A Gradio App Guide |
The Slack bot will listen to messages mentioning it in channels. When it receives a message (which can include text as well as files), it will send it to your Gradio app via Gradio's built-in API. Your bot will reply with the response it receives from the API.
Because Gradio's API is very flexible, you can create Slack bots that support text, images, audio, streaming, chat history, and a wide variety of other features very easily.

| How does it work? | https://gradio.app/guides/creating-a-slack-bot-from-a-gradio-app | Chatbots - Creating A Slack Bot From A Gradio App Guide |
* Install the latest version of `gradio` and the `slack-bolt` library:
```bash
pip install --upgrade gradio slack-bolt~=1.0
```
* Have a running Gradio app. This app can be running locally or on Hugging Face Spaces. In this example, we will be using the [Gradio Playground Space](https://huggingface.co/spaces/abidlabs/gradio-playground-bot), which takes in an image and/or text and generates the code to generate the corresponding Gradio app.
Now, we are ready to get started!
1. Create a Slack App
1. Go to [api.slack.com/apps](https://api.slack.com/apps) and click "Create New App"
2. Choose "From scratch" and give your app a name
3. Select the workspace where you want to develop your app
4. Under "OAuth & Permissions", scroll to "Scopes" and add these Bot Token Scopes:
- `app_mentions:read`
- `chat:write`
- `files:read`
- `files:write`
5. In the same "OAuth & Permissions" page, scroll back up and click the button to install the app to your workspace.
6. Note the "Bot User OAuth Token" (starts with `xoxb-`) that appears as we'll need it later
7. Click on "Socket Mode" in the menu bar. When the page loads, click the toggle to "Enable Socket Mode"
8. Give your token a name, such as `socket-token` and copy the token that is generated (starts with `xapp-`) as we'll need it later.
9. Finally, go to the "Event Subscription" option in the menu bar. Click the toggle to "Enable Events" and subscribe to the `app_mention` bot event.
2. Write a Slack bot
Let's start by writing a very simple Slack bot, just to make sure that everything is working. Write the following Python code in a file called `bot.py`, pasting the two tokens from step 6 and step 8 in the previous section.
```py
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
SLACK_BOT_TOKEN = PASTE YOUR SLACK BOT TOKEN HERE
SLACK_APP_TOKEN = PASTE YOUR SLACK APP TOKEN HERE
app = App(token=SLACK_BOT_TOKEN)
@app.event("app_mention")
def handle_app_mention_ev | Prerequisites | https://gradio.app/guides/creating-a-slack-bot-from-a-gradio-app | Chatbots - Creating A Slack Bot From A Gradio App Guide |
eHandler
SLACK_BOT_TOKEN = PASTE YOUR SLACK BOT TOKEN HERE
SLACK_APP_TOKEN = PASTE YOUR SLACK APP TOKEN HERE
app = App(token=SLACK_BOT_TOKEN)
@app.event("app_mention")
def handle_app_mention_events(body, say):
user_id = body["event"]["user"]
say(f"Hi <@{user_id}>! You mentioned me and said: {body['event']['text']}")
if __name__ == "__main__":
handler = SocketModeHandler(app, SLACK_APP_TOKEN)
handler.start()
```
If that is working, we are ready to add Gradio-specific code. We will be using the [Gradio Python Client](https://www.gradio.app/guides/getting-started-with-the-python-client) to query the Gradio Playground Space mentioned above. Here's the updated `bot.py` file:
```python
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
SLACK_BOT_TOKEN = PASTE YOUR SLACK BOT TOKEN HERE
SLACK_APP_TOKEN = PASTE YOUR SLACK APP TOKEN HERE
app = App(token=SLACK_BOT_TOKEN)
gradio_client = Client("abidlabs/gradio-playground-bot")
def download_image(url, filename):
headers = {"Authorization": f"Bearer {SLACK_BOT_TOKEN}"}
response = httpx.get(url, headers=headers)
image_path = f"./images/{filename}"
os.makedirs("./images", exist_ok=True)
with open(image_path, "wb") as f:
f.write(response.content)
return image_path
def slackify_message(message):
Replace markdown links with slack format and remove code language specifier after triple backticks
pattern = r'\[(.*?)\]\((.*?)\)'
cleaned = re.sub(pattern, r'<\2|\1>', message)
cleaned = re.sub(r'```\w+\n', '```', cleaned)
return cleaned.strip()
@app.event("app_mention")
def handle_app_mention_events(body, say):
Extract the message content without the bot mention
text = body["event"]["text"]
bot_user_id = body["authorizations"][0]["user_id"]
clean_message = text.replace(f"<@{bot_user_id}>", "").strip()
Handle images if present
files = []
if "files" in body["event"]:
for | Prerequisites | https://gradio.app/guides/creating-a-slack-bot-from-a-gradio-app | Chatbots - Creating A Slack Bot From A Gradio App Guide |
= body["authorizations"][0]["user_id"]
clean_message = text.replace(f"<@{bot_user_id}>", "").strip()
Handle images if present
files = []
if "files" in body["event"]:
for file in body["event"]["files"]:
if file["filetype"] in ["png", "jpg", "jpeg", "gif", "webp"]:
image_path = download_image(file["url_private_download"], file["name"])
files.append(handle_file(image_path))
break
Submit to Gradio and send responses back to Slack
for response in gradio_client.submit(
message={"text": clean_message, "files": files},
):
cleaned_response = slackify_message(response[-1])
say(cleaned_response)
if __name__ == "__main__":
handler = SocketModeHandler(app, SLACK_APP_TOKEN)
handler.start()
```
3. Add the bot to your Slack Workplace
Now, create a new channel or navigate to an existing channel in your Slack workspace where you want to use the bot. Click the "+" button next to "Channels" in your Slack sidebar and follow the prompts to create a new channel.
Finally, invite your bot to the channel:
1. In your new channel, type `/invite @YourBotName`
2. Select your bot from the dropdown
3. Click "Invite to Channel"
4. That's it!
Now you can mention your bot in any channel it's in, optionally attach an image, and it will respond with generated Gradio app code!
The bot will:
1. Listen for mentions
2. Process any attached images
3. Send the text and images to your Gradio app
4. Stream the responses back to the Slack channel
This is just a basic example - you can extend it to handle more types of files, add error handling, or integrate with different Gradio apps!

If you build a Slack bot from a Gradio app, feel free to share it on X and tag [the Gradio account](https://x.com/Gr | Prerequisites | https://gradio.app/guides/creating-a-slack-bot-from-a-gradio-app | Chatbots - Creating A Slack Bot From A Gradio App Guide |
/main/gradio-guides/Screen%20Recording%202024-12-19%20at%203.30.00%E2%80%AFPM.gif)
If you build a Slack bot from a Gradio app, feel free to share it on X and tag [the Gradio account](https://x.com/Gradio), and we are happy to help you amplify! | Prerequisites | https://gradio.app/guides/creating-a-slack-bot-from-a-gradio-app | Chatbots - Creating A Slack Bot From A Gradio App Guide |
Let's create a demo where a user can choose a filter to apply to their webcam stream. Users can choose from an edge-detection filter, a cartoon filter, or simply flipping the stream vertically.
$code_streaming_filter
$demo_streaming_filter
You will notice that if you change the filter value it will immediately take effect in the output stream. That is an important difference of stream events in comparison to other Gradio events. The input values of the stream can be changed while the stream is being processed.
Tip: We set the "streaming" parameter of the image output component to be "True". Doing so lets the server automatically convert our output images into base64 format, a format that is efficient for streaming.
| A Realistic Image Demo | https://gradio.app/guides/streaming-inputs | Additional Features - Streaming Inputs Guide |
For some image streaming demos, like the one above, we don't need to display separate input and output components. Our app would look cleaner if we could just display the modified output stream.
We can do so by just specifying the input image component as the output of the stream event.
$code_streaming_filter_unified
$demo_streaming_filter_unified
| Unified Image Demos | https://gradio.app/guides/streaming-inputs | Additional Features - Streaming Inputs Guide |
Your streaming function should be stateless. It should take the current input and return its corresponding output. However, there are cases where you may want to keep track of past inputs or outputs. For example, you may want to keep a buffer of the previous `k` inputs to improve the accuracy of your transcription demo. You can do this with Gradio's `gr.State()` component.
Let's showcase this with a sample demo:
```python
def transcribe_handler(current_audio, state, transcript):
next_text = transcribe(current_audio, history=state)
state.append(current_audio)
state = state[-3:]
return state, transcript + next_text
with gr.Blocks() as demo:
with gr.Row():
with gr.Column():
mic = gr.Audio(sources="microphone")
state = gr.State(value=[])
with gr.Column():
transcript = gr.Textbox(label="Transcript")
mic.stream(transcribe_handler, [mic, state, transcript], [state, transcript],
time_limit=10, stream_every=1)
demo.launch()
```
| Keeping track of past inputs or outputs | https://gradio.app/guides/streaming-inputs | Additional Features - Streaming Inputs Guide |
For an end-to-end example of streaming from the webcam, see the object detection from webcam [guide](/main/guides/object-detection-from-webcam-with-webrtc). | End-to-End Examples | https://gradio.app/guides/streaming-inputs | Additional Features - Streaming Inputs Guide |
To add custom buttons to a component, pass a list of `gr.Button()` instances to the `buttons` parameter:
```python
import gradio as gr
refresh_btn = gr.Button("Refresh", variant="secondary", size="sm")
clear_btn = gr.Button("Clear", variant="secondary", size="sm")
textbox = gr.Textbox(
value="Sample text",
label="Text Input",
buttons=[refresh_btn, clear_btn]
)
```
You can also mix built-in buttons (as strings) with custom buttons:
```python
code = gr.Code(
value="print('Hello')",
language="python",
buttons=["copy", "download", refresh_btn, export_btn]
)
```
| Basic Usage | https://gradio.app/guides/custom-buttons | Additional Features - Custom Buttons Guide |
Custom buttons work just like regular `gr.Button` components. You can connect them to Python functions or JavaScript functions using the `.click()` method:
Python Functions
```python
def refresh_data():
import random
return f"Refreshed: {random.randint(1000, 9999)}"
refresh_btn.click(refresh_data, outputs=textbox)
```
JavaScript Functions
```python
clear_btn.click(
None,
inputs=[],
outputs=textbox,
js="() => ''"
)
```
Combined Python and JavaScript
You can use the same button for both Python and JavaScript logic:
```python
alert_btn.click(
None,
inputs=textbox,
outputs=[],
js="(text) => { alert('Text: ' + text); return []; }"
)
```
| Connecting Button Events | https://gradio.app/guides/custom-buttons | Additional Features - Custom Buttons Guide |
Here's a complete example showing custom buttons with both Python and JavaScript functions:
$code_textbox_custom_buttons
| Complete Example | https://gradio.app/guides/custom-buttons | Additional Features - Custom Buttons Guide |
- Custom buttons appear in the component's toolbar, typically in the top-right corner
- Only the `value` of the Button is used, other attributes like `icon` are not used.
- Buttons are rendered in the order they appear in the `buttons` list
- Built-in buttons (like "copy", "download") can be hidden by omitting them from the list
- Custom buttons work with component events in the same way as as regular buttons
| Notes | https://gradio.app/guides/custom-buttons | Additional Features - Custom Buttons Guide |
Gradio can stream audio and video directly from your generator function.
This lets your user hear your audio or see your video nearly as soon as it's `yielded` by your function.
All you have to do is
1. Set `streaming=True` in your `gr.Audio` or `gr.Video` output component.
2. Write a python generator that yields the next "chunk" of audio or video.
3. Set `autoplay=True` so that the media starts playing automatically.
For audio, the next "chunk" can be either an `.mp3` or `.wav` file or a `bytes` sequence of audio.
For video, the next "chunk" has to be either `.mp4` file or a file with `h.264` codec with a `.ts` extension.
For smooth playback, make sure chunks are consistent lengths and larger than 1 second.
We'll finish with some simple examples illustrating these points.
Streaming Audio
```python
import gradio as gr
from time import sleep
def keep_repeating(audio_file):
for _ in range(10):
sleep(0.5)
yield audio_file
gr.Interface(keep_repeating,
gr.Audio(sources=["microphone"], type="filepath"),
gr.Audio(streaming=True, autoplay=True)
).launch()
```
Streaming Video
```python
import gradio as gr
from time import sleep
def keep_repeating(video_file):
for _ in range(10):
sleep(0.5)
yield video_file
gr.Interface(keep_repeating,
gr.Video(sources=["webcam"], format="mp4"),
gr.Video(streaming=True, autoplay=True)
).launch()
```
| Streaming Media | https://gradio.app/guides/streaming-outputs | Additional Features - Streaming Outputs Guide |
For an end-to-end example of streaming media, see the object detection from video [guide](/main/guides/object-detection-from-video) or the streaming AI-generated audio with [transformers](https://huggingface.co/docs/transformers/index) [guide](/main/guides/streaming-ai-generated-audio). | End-to-End Examples | https://gradio.app/guides/streaming-outputs | Additional Features - Streaming Outputs Guide |
**API endpoint names**
When you create a Gradio application, the API endpoint names are automatically generated based on the function names. You can change this by using the `api_name` parameter in `gr.Interface` or `gr.ChatInterface`. If you are using Gradio `Blocks`, you can name each event listener, like this:
```python
btn.click(add, [num1, num2], output, api_name="addition")
```
**Controlling API endpoint visibility**
When building a complex Gradio app, you might want to control how API endpoints appear or behave. Use the `api_visibility` parameter in any `Blocks` event listener to control this:
- `"public"` (default): The endpoint is shown in API docs and accessible to all
- `"undocumented"`: The endpoint is hidden from API docs but still accessible to downstream apps
- `"private"`: The endpoint is completely disabled and inaccessible
To hide an API endpoint from the documentation while still allowing programmatic access:
```python
btn.click(add, [num1, num2], output, api_visibility="undocumented")
```
**Disabling API endpoints**
If you want to disable an API endpoint altogether so that no one can access it programmatically, set `api_visibility="private"`:
```python
btn.click(add, [num1, num2], output, api_visibility="private")
```
Note: setting `api_visibility="private"` also means that downstream apps will not be able to load your Gradio app using `gr.load()` as this function uses the Gradio API under the hood.
**Adding API endpoints**
You can also add new API routes to your Gradio application that do not correspond to events in your UI.
For example, in this Gradio application, we add a new route that adds numbers and slices a list:
```py
import gradio as gr
with gr.Blocks() as demo:
with gr.Row():
input = gr.Textbox()
button = gr.Button("Submit")
output = gr.Textbox()
def fn(a: int, b: int, c: list[str]) -> tuple[int, str]:
return a + b, c[a:b]
gr.api(fn, api_name="add_and_slice")
_, url, _ = demo.laun | Configuring the API Page | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
gr.Button("Submit")
output = gr.Textbox()
def fn(a: int, b: int, c: list[str]) -> tuple[int, str]:
return a + b, c[a:b]
gr.api(fn, api_name="add_and_slice")
_, url, _ = demo.launch()
```
This will create a new route `/add_and_slice` which will show up in the "view API" page. It can be programmatically called by the Python or JS Clients (discussed below) like this:
```py
from gradio_client import Client
client = Client(url)
result = client.predict(
a=3,
b=5,
c=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
api_name="/add_and_slice"
)
print(result)
```
| Configuring the API Page | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
This API page not only lists all of the endpoints that can be used to query the Gradio app, but also shows the usage of both [the Gradio Python client](https://gradio.app/guides/getting-started-with-the-python-client/), and [the Gradio JavaScript client](https://gradio.app/guides/getting-started-with-the-js-client/).
For each endpoint, Gradio automatically generates a complete code snippet with the parameters and their types, as well as example inputs, allowing you to immediately test an endpoint. Here's an example showing an image file input and `str` output:

| The Clients | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
Instead of reading through the view API page, you can also use Gradio's built-in API recorder to generate the relevant code snippet. Simply click on the "API Recorder" button, use your Gradio app via the UI as you would normally, and then the API Recorder will generate the code using the Clients to recreate your all of your interactions programmatically.

| The API Recorder πͺ | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
The API page also includes instructions on how to use the Gradio app as an Model Context Protocol (MCP) server, which is a standardized way to expose functions as tools so that they can be used by LLMs.

For the MCP sever, each tool, its description, and its parameters are listed, along with instructions on how to integrate with popular MCP Clients. Read more about Gradio's [MCP integration here](https://www.gradio.app/guides/building-mcp-server-with-gradio).
| MCP Server | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
You can access the complete OpenAPI (formerly Swagger) specification of your Gradio app's API at the endpoint `<your-gradio-app-url>/gradio_api/openapi.json`. The OpenAPI specification is a standardized, language-agnostic interface description for REST APIs that enables both humans and computers to discover and understand the capabilities of your service.
| OpenAPI Specification | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
When a user closes their browser tab, Gradio will automatically delete any `gr.State` variables associated with that user session after 60 minutes. If the user connects again within those 60 minutes, no state will be deleted.
You can control the deletion behavior further with the following two parameters of `gr.State`:
1. `delete_callback` - An arbitrary function that will be called when the variable is deleted. This function must take the state value as input. This function is useful for deleting variables from GPU memory.
2. `time_to_live` - The number of seconds the state should be stored for after it is created or updated. This will delete variables before the session is closed, so it's useful for clearing state for potentially long running sessions.
| Automatic deletion of `gr.State` | https://gradio.app/guides/resource-cleanup | Additional Features - Resource Cleanup Guide |
Your Gradio application will save uploaded and generated files to a special directory called the cache directory. Gradio uses a hashing scheme to ensure that duplicate files are not saved to the cache but over time the size of the cache will grow (especially if your app goes viral π).
Gradio can periodically clean up the cache for you if you specify the `delete_cache` parameter of `gr.Blocks()`, `gr.Interface()`, or `gr.ChatInterface()`.
This parameter is a tuple of the form `[frequency, age]` both expressed in number of seconds.
Every `frequency` seconds, the temporary files created by this Blocks instance will be deleted if more than `age` seconds have passed since the file was created.
For example, setting this to (86400, 86400) will delete temporary files every day if they are older than a day old.
Additionally, the cache will be deleted entirely when the server restarts.
| Automatic cache cleanup via `delete_cache` | https://gradio.app/guides/resource-cleanup | Additional Features - Resource Cleanup Guide |
Additionally, Gradio now includes a `Blocks.unload()` event, allowing you to run arbitrary cleanup functions when users disconnect (this does not have a 60 minute delay).
Unlike other gradio events, this event does not accept inputs or outptus.
You can think of the `unload` event as the opposite of the `load` event.
| The `unload` event | https://gradio.app/guides/resource-cleanup | Additional Features - Resource Cleanup Guide |
The following demo uses all of these features. When a user visits the page, a special unique directory is created for that user.
As the user interacts with the app, images are saved to disk in that special directory.
When the user closes the page, the images created in that session are deleted via the `unload` event.
The state and files in the cache are cleaned up automatically as well.
$code_state_cleanup
$demo_state_cleanup | Putting it all together | https://gradio.app/guides/resource-cleanup | Additional Features - Resource Cleanup Guide |
By default, Gradio automatically generates a navigation bar for multipage apps that displays all your pages with "Home" as the title for the main page. You can customize the navbar behavior using the `gr.Navbar` component.
Per-Page Navbar Configuration
You can have different navbar configurations for each page of your app:
```python
import gradio as gr
with gr.Blocks() as demo:
Navbar for the main page
navbar = gr.Navbar(
visible=True,
main_page_name="Dashboard",
value=[("About", "https://example.com/about")]
)
gr.Textbox(label="Main page content")
with demo.route("Settings"):
Different navbar for the Settings page
navbar = gr.Navbar(
visible=True,
main_page_name="Home",
value=[("Documentation", "https://docs.example.com")]
)
gr.Textbox(label="Settings page")
demo.launch()
```
**Important Notes:**
- You can have one `gr.Navbar` component per page. Each page's navbar configuration is independent.
- The `main_page_name` parameter customizes the title of the home page link in the navbar.
- The `value` parameter allows you to add additional links to the navbar, which can be internal pages or external URLs.
- If no `gr.Navbar` component is present on a page, the default navbar behavior is used (visible with "Home" as the home page title).
- You can update the navbar properties using standard Gradio event handling, just like with any other component.
Here's an example that demonstrates the last point:
$code_navbar_customization
| Customizing the Navbar | https://gradio.app/guides/multipage-apps | Additional Features - Multipage Apps Guide |
You can initialize the `I18n` class with multiple language dictionaries to add custom translations:
```python
import gradio as gr
Create an I18n instance with translations for multiple languages
i18n = gr.I18n(
en={"greeting": "Hello, welcome to my app!", "submit": "Submit"},
es={"greeting": "Β‘Hola, bienvenido a mi aplicaciΓ³n!", "submit": "Enviar"},
fr={"greeting": "Bonjour, bienvenue dans mon application!", "submit": "Soumettre"}
)
with gr.Blocks() as demo:
Use the i18n method to translate the greeting
gr.Markdown(i18n("greeting"))
with gr.Row():
input_text = gr.Textbox(label="Input")
output_text = gr.Textbox(label="Output")
submit_btn = gr.Button(i18n("submit"))
Pass the i18n instance to the launch method
demo.launch(i18n=i18n)
```
| Setting Up Translations | https://gradio.app/guides/internationalization | Additional Features - Internationalization Guide |
When you use the `i18n` instance with a translation key, Gradio will show the corresponding translation to users based on their browser's language settings or the language they've selected in your app.
If a translation isn't available for the user's locale, the system will fall back to English (if available) or display the key itself.
| How It Works | https://gradio.app/guides/internationalization | Additional Features - Internationalization Guide |
Locale codes should follow the BCP 47 format (e.g., 'en', 'en-US', 'zh-CN'). The `I18n` class will warn you if you use an invalid locale code.
| Valid Locale Codes | https://gradio.app/guides/internationalization | Additional Features - Internationalization Guide |
The following component properties typically support internationalization:
- `description`
- `info`
- `title`
- `placeholder`
- `value`
- `label`
Note that support may vary depending on the component, and some properties might have exceptions where internationalization is not applicable. You can check this by referring to the typehint for the parameter and if it contains `I18nData`, then it supports internationalization. | Supported Component Properties | https://gradio.app/guides/internationalization | Additional Features - Internationalization Guide |
1. `GRADIO_SERVER_PORT`
- **Description**: Specifies the port on which the Gradio app will run.
- **Default**: `7860`
- **Example**:
```bash
export GRADIO_SERVER_PORT=8000
```
2. `GRADIO_SERVER_NAME`
- **Description**: Defines the host name for the Gradio server. To make Gradio accessible from any IP address, set this to `"0.0.0.0"`
- **Default**: `"127.0.0.1"`
- **Example**:
```bash
export GRADIO_SERVER_NAME="0.0.0.0"
```
3. `GRADIO_NUM_PORTS`
- **Description**: Defines the number of ports to try when starting the Gradio server.
- **Default**: `100`
- **Example**:
```bash
export GRADIO_NUM_PORTS=200
```
4. `GRADIO_ANALYTICS_ENABLED`
- **Description**: Whether Gradio should provide
- **Default**: `"True"`
- **Options**: `"True"`, `"False"`
- **Example**:
```sh
export GRADIO_ANALYTICS_ENABLED="True"
```
5. `GRADIO_DEBUG`
- **Description**: Enables or disables debug mode in Gradio. If debug mode is enabled, the main thread does not terminate allowing error messages to be printed in environments such as Google Colab.
- **Default**: `0`
- **Example**:
```sh
export GRADIO_DEBUG=1
```
6. `GRADIO_FLAGGING_MODE`
- **Description**: Controls whether users can flag inputs/outputs in the Gradio interface. See [the Guide on flagging](/guides/using-flagging) for more details.
- **Default**: `"manual"`
- **Options**: `"never"`, `"manual"`, `"auto"`
- **Example**:
```sh
export GRADIO_FLAGGING_MODE="never"
```
7. `GRADIO_TEMP_DIR`
- **Description**: Specifies the directory where temporary files created by Gradio are stored.
- **Default**: System default temporary directory
- **Example**:
```sh
export GRADIO_TEMP_DIR="/path/to/temp"
```
8. `GRADIO_ROOT_PATH`
- **Description**: Sets the root path for the Gradio application. Useful if running Gradio [behind a reverse proxy](/guides/running-gradio-on-your-web-server-with-nginx).
- **Default**: `""`
- **Example**:
```sh
export GRADIO_ROOT_PATH= | Key Environment Variables | https://gradio.app/guides/environment-variables | Additional Features - Environment Variables Guide |
r the Gradio application. Useful if running Gradio [behind a reverse proxy](/guides/running-gradio-on-your-web-server-with-nginx).
- **Default**: `""`
- **Example**:
```sh
export GRADIO_ROOT_PATH="/myapp"
```
9. `GRADIO_SHARE`
- **Description**: Enables or disables sharing the Gradio app.
- **Default**: `"False"`
- **Options**: `"True"`, `"False"`
- **Example**:
```sh
export GRADIO_SHARE="True"
```
10. `GRADIO_ALLOWED_PATHS`
- **Description**: Sets a list of complete filepaths or parent directories that gradio is allowed to serve. Must be absolute paths. Warning: if you provide directories, any files in these directories or their subdirectories are accessible to all users of your app. Multiple items can be specified by separating items with commas.
- **Default**: `""`
- **Example**:
```sh
export GRADIO_ALLOWED_PATHS="/mnt/sda1,/mnt/sda2"
```
11. `GRADIO_BLOCKED_PATHS`
- **Description**: Sets a list of complete filepaths or parent directories that gradio is not allowed to serve (i.e. users of your app are not allowed to access). Must be absolute paths. Warning: takes precedence over `allowed_paths` and all other directories exposed by Gradio by default. Multiple items can be specified by separating items with commas.
- **Default**: `""`
- **Example**:
```sh
export GRADIO_BLOCKED_PATHS="/users/x/gradio_app/admin,/users/x/gradio_app/keys"
```
12. `FORWARDED_ALLOW_IPS`
- **Description**: This is not a Gradio-specific environment variable, but rather one used in server configurations, specifically `uvicorn` which is used by Gradio internally. This environment variable is useful when deploying applications behind a reverse proxy. It defines a list of IP addresses that are trusted to forward traffic to your application. When set, the application will trust the `X-Forwarded-For` header from these IP addresses to determine the original IP address of the user making the request. This means that if you use the `gr.Request` [objec | Key Environment Variables | https://gradio.app/guides/environment-variables | Additional Features - Environment Variables Guide |
the application will trust the `X-Forwarded-For` header from these IP addresses to determine the original IP address of the user making the request. This means that if you use the `gr.Request` [object's](https://www.gradio.app/docs/gradio/request) `client.host` property, it will correctly get the user's IP address instead of the IP address of the reverse proxy server. Note that only trusted IP addresses (i.e. the IP addresses of your reverse proxy servers) should be added, as any server with these IP addresses can modify the `X-Forwarded-For` header and spoof the client's IP address.
- **Default**: `"127.0.0.1"`
- **Example**:
```sh
export FORWARDED_ALLOW_IPS="127.0.0.1,192.168.1.100"
```
13. `GRADIO_CACHE_EXAMPLES`
- **Description**: Whether or not to cache examples by default in `gr.Interface()`, `gr.ChatInterface()` or in `gr.Examples()` when no explicit argument is passed for the `cache_examples` parameter. You can set this environment variable to either the string "true" or "false".
- **Default**: `"false"`
- **Example**:
```sh
export GRADIO_CACHE_EXAMPLES="true"
```
14. `GRADIO_CACHE_MODE`
- **Description**: How to cache examples. Only applies if `cache_examples` is set to `True` either via enviornment variable or by an explicit parameter, AND no no explicit argument is passed for the `cache_mode` parameter in `gr.Interface()`, `gr.ChatInterface()` or in `gr.Examples()`. Can be set to either the strings "lazy" or "eager." If "lazy", examples are cached after their first use for all users of the app. If "eager", all examples are cached at app launch.
- **Default**: `"eager"`
- **Example**:
```sh
export GRADIO_CACHE_MODE="lazy"
```
15. `GRADIO_EXAMPLES_CACHE`
- **Description**: If you set `cache_examples=True` in `gr.Interface()`, `gr.ChatInterface()` or in `gr.Examples()`, Gradio will run your prediction function and save the results to disk. By default, this is in the `.gradio/cached_examples//` subdirectory within your | Key Environment Variables | https://gradio.app/guides/environment-variables | Additional Features - Environment Variables Guide |
e()`, `gr.ChatInterface()` or in `gr.Examples()`, Gradio will run your prediction function and save the results to disk. By default, this is in the `.gradio/cached_examples//` subdirectory within your app's working directory. You can customize the location of cached example files created by Gradio by setting the environment variable `GRADIO_EXAMPLES_CACHE` to an absolute path or a path relative to your working directory.
- **Default**: `".gradio/cached_examples/"`
- **Example**:
```sh
export GRADIO_EXAMPLES_CACHE="custom_cached_examples/"
```
16. `GRADIO_SSR_MODE`
- **Description**: Controls whether server-side rendering (SSR) is enabled. When enabled, the initial HTML is rendered on the server rather than the client, which can improve initial page load performance and SEO.
- **Default**: `"False"` (except on Hugging Face Spaces, where this environment variable sets it to `True`)
- **Options**: `"True"`, `"False"`
- **Example**:
```sh
export GRADIO_SSR_MODE="True"
```
17. `GRADIO_NODE_SERVER_NAME`
- **Description**: Defines the host name for the Gradio node server. (Only applies if `ssr_mode` is set to `True`.)
- **Default**: `GRADIO_SERVER_NAME` if it is set, otherwise `"127.0.0.1"`
- **Example**:
```sh
export GRADIO_NODE_SERVER_NAME="0.0.0.0"
```
18. `GRADIO_NODE_NUM_PORTS`
- **Description**: Defines the number of ports to try when starting the Gradio node server. (Only applies if `ssr_mode` is set to `True`.)
- **Default**: `100`
- **Example**:
```sh
export GRADIO_NODE_NUM_PORTS=200
```
19. `GRADIO_RESET_EXAMPLES_CACHE`
- **Description**: If set to "True", Gradio will delete and recreate the examples cache directory when the app starts instead of reusing the cached example if they already exist.
- **Default**: `"False"`
- **Options**: `"True"`, `"False"`
- **Example**:
```sh
export GRADIO_RESET_EXAMPLES_CACHE="True"
```
20. `GRADIO_CHAT_FLAGGING_MODE`
- **Description**: Controls whether users can flag | Key Environment Variables | https://gradio.app/guides/environment-variables | Additional Features - Environment Variables Guide |
e"`
- **Options**: `"True"`, `"False"`
- **Example**:
```sh
export GRADIO_RESET_EXAMPLES_CACHE="True"
```
20. `GRADIO_CHAT_FLAGGING_MODE`
- **Description**: Controls whether users can flag messages in `gr.ChatInterface` applications. Similar to `GRADIO_FLAGGING_MODE` but specifically for chat interfaces.
- **Default**: `"never"`
- **Options**: `"never"`, `"manual"`
- **Example**:
```sh
export GRADIO_CHAT_FLAGGING_MODE="manual"
```
21. `GRADIO_WATCH_DIRS`
- **Description**: Specifies directories to watch for file changes when running Gradio in development mode. When files in these directories change, the Gradio app will automatically reload. Multiple directories can be specified by separating them with commas. This is primarily used by the `gradio` CLI command for development workflows.
- **Default**: `""`
- **Example**:
```sh
export GRADIO_WATCH_DIRS="/path/to/src,/path/to/templates"
```
22. `GRADIO_VIBE_MODE`
- **Description**: Enables the Vibe editor mode, which provides an in-browser chat that can be used to write or edit your Gradio app using natural language. When enabled, anyone who can access the Gradio endpoint can modify files and run arbitrary code on the host machine. Use with extreme caution in production environments.
- **Default**: `""`
- **Options**: Any non-empty string enables the mode
- **Example**:
```sh
export GRADIO_VIBE_MODE="1"
```
23. `GRADIO_MCP_SERVER`
- **Description**: Enables the MCP (Model Context Protocol) server functionality in Gradio. When enabled, the Gradio app will be set up as an MCP server and documented functions will be added as MCP tools that can be used by LLMs. This allows LLMs to interact with your Gradio app's functionality through the MCP protocol.
- **Default**: `"False"`
- **Options**: `"True"`, `"False"`
- **Example**:
```sh
export GRADIO_MCP_SERVER="True"
```
| Key Environment Variables | https://gradio.app/guides/environment-variables | Additional Features - Environment Variables Guide |
*Options**: `"True"`, `"False"`
- **Example**:
```sh
export GRADIO_MCP_SERVER="True"
```
| Key Environment Variables | https://gradio.app/guides/environment-variables | Additional Features - Environment Variables Guide |
To set environment variables in your terminal, use the `export` command followed by the variable name and its value. For example:
```sh
export GRADIO_SERVER_PORT=8000
```
If you're using a `.env` file to manage your environment variables, you can add them like this:
```sh
GRADIO_SERVER_PORT=8000
GRADIO_SERVER_NAME="localhost"
```
Then, use a tool like `dotenv` to load these variables when running your application.
| How to Set Environment Variables | https://gradio.app/guides/environment-variables | Additional Features - Environment Variables Guide |
Client side functions are ideal for updating component properties (like visibility, placeholders, interactive state, or styling).
Here's a basic example:
```py
import gradio as gr
with gr.Blocks() as demo:
with gr.Row() as row:
btn = gr.Button("Hide this row")
This function runs in the browser without a server roundtrip
btn.click(
lambda: gr.Row(visible=False),
None,
row,
js=True
)
demo.launch()
```
| When to Use Client Side Functions | https://gradio.app/guides/client-side-functions | Additional Features - Client Side Functions Guide |
Client side functions have some important restrictions:
* They can only update component properties (not values)
* They cannot take any inputs
Here are some functions that will work with `js=True`:
```py
Simple property updates
lambda: gr.Textbox(lines=4)
Multiple component updates
lambda: [gr.Textbox(lines=4), gr.Button(interactive=False)]
Using gr.update() for property changes
lambda: gr.update(visible=True, interactive=False)
```
We are working to increase the space of functions that can be transpiled to JavaScript so that they can be run in the browser. [Follow the Groovy library for more info](https://github.com/abidlabs/groovy-transpiler).
| Limitations | https://gradio.app/guides/client-side-functions | Additional Features - Client Side Functions Guide |
Here's a more complete example showing how client side functions can improve the user experience:
$code_todo_list_js
| Complete Example | https://gradio.app/guides/client-side-functions | Additional Features - Client Side Functions Guide |
When you set `js=True`, Gradio:
1. Transpiles your Python function to JavaScript
2. Runs the function directly in the browser
3. Still sends the request to the server (for consistency and to handle any side effects)
This provides immediate visual feedback while ensuring your application state remains consistent.
| Behind the Scenes | https://gradio.app/guides/client-side-functions | Additional Features - Client Side Functions Guide |
Gradio demos can be easily shared publicly by setting `share=True` in the `launch()` method. Like this:
```python
import gradio as gr
def greet(name):
return "Hello " + name + "!"
demo = gr.Interface(fn=greet, inputs="textbox", outputs="textbox")
demo.launch(share=True) Share your demo with just 1 extra parameter π
```
This generates a public, shareable link that you can send to anybody! When you send this link, the user on the other side can try out the model in their browser. Because the processing happens on your device (as long as your device stays on), you don't have to worry about any packaging any dependencies.

A share link usually looks something like this: **https://07ff8706ab.gradio.live**. Although the link is served through the Gradio Share Servers, these servers are only a proxy for your local server, and do not store any data sent through your app. Share links expire after 1 week. (it is [also possible to set up your own Share Server](https://github.com/huggingface/frp/) on your own cloud server to overcome this restriction.)
Tip: Keep in mind that share links are publicly accessible, meaning that anyone can use your model for prediction! Therefore, make sure not to expose any sensitive information through the functions you write, or allow any critical changes to occur on your device. Or you can [add authentication to your Gradio app](authentication) as discussed below.
Note that by default, `share=False`, which means that your server is only running locally. (This is the default, except in Google Colab notebooks, where share links are automatically created). As an alternative to using share links, you can use use [SSH port-forwarding](https://www.ssh.com/ssh/tunneling/example) to share your local server with specific users.
| Sharing Demos | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
If you'd like to have a permanent link to your Gradio demo on the internet, use Hugging Face Spaces. [Hugging Face Spaces](http://huggingface.co/spaces/) provides the infrastructure to permanently host your machine learning model for free!
After you have [created a free Hugging Face account](https://huggingface.co/join), you have two methods to deploy your Gradio app to Hugging Face Spaces:
1. From terminal: run `gradio deploy` in your app directory. The CLI will gather some basic metadata, upload all the files in the current directory (respecting any `.gitignore` file that may be present in the root of the directory), and then launch your app on Spaces. To update your Space, you can re-run this command or enable the Github Actions option in the CLI to automatically update the Spaces on `git push`.
2. From your browser: Drag and drop a folder containing your Gradio model and all related files [here](https://huggingface.co/new-space). See [this guide how to host on Hugging Face Spaces](https://huggingface.co/blog/gradio-spaces) for more information, or watch the embedded video:
<video autoplay muted loop>
<source src="https://github.com/gradio-app/gradio/blob/main/guides/assets/hf_demo.mp4?raw=true" type="video/mp4" />
</video>
| Hosting on HF Spaces | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
You can add a button to your Gradio app that creates a unique URL you can use to share your app and all components **as they currently are** with others. This is useful for sharing unique and interesting generations from your application , or for saving a snapshot of your app at a particular point in time.
To add a deep link button to your app, place the `gr.DeepLinkButton` component anywhere in your app.
For the URL to be accessible to others, your app must be available at a public URL. So be sure to host your app like Hugging Face Spaces or use the `share=True` parameter when launching your app.
Let's see an example of how this works. Here's a simple Gradio chat ap that uses the `gr.DeepLinkButton` component. After a couple of messages, click the deep link button and paste it into a new browser tab to see the app as it is at that point in time.
$code_deep_link
$demo_deep_link
| Sharing Deep Links | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
Once you have hosted your app on Hugging Face Spaces (or on your own server), you may want to embed the demo on a different website, such as your blog or your portfolio. Embedding an interactive demo allows people to try out the machine learning model that you have built, without needing to download or install anything β right in their browser! The best part is that you can embed interactive demos even in static websites, such as GitHub pages.
There are two ways to embed your Gradio demos. You can find quick links to both options directly on the Hugging Face Space page, in the "Embed this Space" dropdown option:

Embedding with Web Components
Web components typically offer a better experience to users than IFrames. Web components load lazily, meaning that they won't slow down the loading time of your website, and they automatically adjust their height based on the size of the Gradio app.
To embed with Web Components:
1. Import the gradio JS library into into your site by adding the script below in your site (replace {GRADIO_VERSION} in the URL with the library version of Gradio you are using).
```html
<script
type="module"
src="https://gradio.s3-us-west-2.amazonaws.com/{GRADIO_VERSION}/gradio.js"
></script>
```
2. Add
```html
<gradio-app src="https://$your_space_host.hf.space"></gradio-app>
```
element where you want to place the app. Set the `src=` attribute to your Space's embed URL, which you can find in the "Embed this Space" button. For example:
```html
<gradio-app
src="https://abidlabs-pytorch-image-classifier.hf.space"
></gradio-app>
```
<script>
fetch("https://pypi.org/pypi/gradio/json"
).then(r => r.json()
).then(obj => {
let v = obj.info.version;
content = document.querySelector('.prose');
content.innerHTML = content.innerHTML.replaceAll("{GRADIO_VERSION}", v);
});
</script>
You can see examples of h | Embedding Hosted Spaces | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
=> {
let v = obj.info.version;
content = document.querySelector('.prose');
content.innerHTML = content.innerHTML.replaceAll("{GRADIO_VERSION}", v);
});
</script>
You can see examples of how web components look <a href="https://www.gradio.app">on the Gradio landing page</a>.
You can also customize the appearance and behavior of your web component with attributes that you pass into the `<gradio-app>` tag:
- `src`: as we've seen, the `src` attributes links to the URL of the hosted Gradio demo that you would like to embed
- `space`: an optional shorthand if your Gradio demo is hosted on Hugging Face Space. Accepts a `username/space_name` instead of a full URL. Example: `gradio/Echocardiogram-Segmentation`. If this attribute attribute is provided, then `src` does not need to be provided.
- `control_page_title`: a boolean designating whether the html title of the page should be set to the title of the Gradio app (by default `"false"`)
- `initial_height`: the initial height of the web component while it is loading the Gradio app, (by default `"300px"`). Note that the final height is set based on the size of the Gradio app.
- `container`: whether to show the border frame and information about where the Space is hosted (by default `"true"`)
- `info`: whether to show just the information about where the Space is hosted underneath the embedded app (by default `"true"`)
- `autoscroll`: whether to autoscroll to the output when prediction has finished (by default `"false"`)
- `eager`: whether to load the Gradio app as soon as the page loads (by default `"false"`)
- `theme_mode`: whether to use the `dark`, `light`, or default `system` theme mode (by default `"system"`)
- `render`: an event that is triggered once the embedded space has finished rendering.
Here's an example of how to use these attributes to create a Gradio app that does not lazy load and has an initial height of 0px.
```html
<gradio-app
space="gradio/Echocardiogram-Segmentation"
eager="true"
init | Embedding Hosted Spaces | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
ple of how to use these attributes to create a Gradio app that does not lazy load and has an initial height of 0px.
```html
<gradio-app
space="gradio/Echocardiogram-Segmentation"
eager="true"
initial_height="0px"
></gradio-app>
```
Here's another example of how to use the `render` event. An event listener is used to capture the `render` event and will call the `handleLoadComplete()` function once rendering is complete.
```html
<script>
function handleLoadComplete() {
console.log("Embedded space has finished rendering");
}
const gradioApp = document.querySelector("gradio-app");
gradioApp.addEventListener("render", handleLoadComplete);
</script>
```
_Note: While Gradio's CSS will never impact the embedding page, the embedding page can affect the style of the embedded Gradio app. Make sure that any CSS in the parent page isn't so general that it could also apply to the embedded Gradio app and cause the styling to break. Element selectors such as `header { ... }` and `footer { ... }` will be the most likely to cause issues._
Embedding with IFrames
To embed with IFrames instead (if you cannot add javascript to your website, for example), add this element:
```html
<iframe src="https://$your_space_host.hf.space"></iframe>
```
Again, you can find the `src=` attribute to your Space's embed URL, which you can find in the "Embed this Space" button.
Note: if you use IFrames, you'll probably want to add a fixed `height` attribute and set `style="border:0;"` to remove the border. In addition, if your app requires permissions such as access to the webcam or the microphone, you'll need to provide that as well using the `allow` attribute.
| Embedding Hosted Spaces | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
You can use almost any Gradio app as an API! In the footer of a Gradio app [like this one](https://huggingface.co/spaces/gradio/hello_world), you'll see a "Use via API" link.

This is a page that lists the endpoints that can be used to query the Gradio app, via our supported clients: either [the Python client](https://gradio.app/guides/getting-started-with-the-python-client/), or [the JavaScript client](https://gradio.app/guides/getting-started-with-the-js-client/). For each endpoint, Gradio automatically generates the parameters and their types, as well as example inputs, like this.

The endpoints are automatically created when you launch a Gradio application. If you are using Gradio `Blocks`, you can also name each event listener, such as
```python
btn.click(add, [num1, num2], output, api_name="addition")
```
This will add and document the endpoint `/addition/` to the automatically generated API page. Read more about the [API page here](./view-api-page).
| API Page | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
When a user makes a prediction to your app, you may need the underlying network request, in order to get the request headers (e.g. for advanced authentication), log the client's IP address, getting the query parameters, or for other reasons. Gradio supports this in a similar manner to FastAPI: simply add a function parameter whose type hint is `gr.Request` and Gradio will pass in the network request as that parameter. Here is an example:
```python
import gradio as gr
def echo(text, request: gr.Request):
if request:
print("Request headers dictionary:", request.headers)
print("IP address:", request.client.host)
print("Query parameters:", dict(request.query_params))
return text
io = gr.Interface(echo, "textbox", "textbox").launch()
```
Note: if your function is called directly instead of through the UI (this happens, for
example, when examples are cached, or when the Gradio app is called via API), then `request` will be `None`.
You should handle this case explicitly to ensure that your app does not throw any errors. That is why
we have the explicit check `if request`.
| Accessing the Network Request Directly | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
In some cases, you might have an existing FastAPI app, and you'd like to add a path for a Gradio demo.
You can easily do this with `gradio.mount_gradio_app()`.
Here's a complete example:
$code_custom_path
Note that this approach also allows you run your Gradio apps on custom paths (`http://localhost:8000/gradio` in the example above).
| Mounting Within Another FastAPI App | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
Password-protected app
You may wish to put an authentication page in front of your app to limit who can open your app. With the `auth=` keyword argument in the `launch()` method, you can provide a tuple with a username and password, or a list of acceptable username/password tuples; Here's an example that provides password-based authentication for a single user named "admin":
```python
demo.launch(auth=("admin", "pass1234"))
```
For more complex authentication handling, you can even pass a function that takes a username and password as arguments, and returns `True` to allow access, `False` otherwise.
Here's an example of a function that accepts any login where the username and password are the same:
```python
def same_auth(username, password):
return username == password
demo.launch(auth=same_auth)
```
If you have multiple users, you may wish to customize the content that is shown depending on the user that is logged in. You can retrieve the logged in user by [accessing the network request directly](accessing-the-network-request-directly) as discussed above, and then reading the `.username` attribute of the request. Here's an example:
```python
import gradio as gr
def update_message(request: gr.Request):
return f"Welcome, {request.username}"
with gr.Blocks() as demo:
m = gr.Markdown()
demo.load(update_message, None, m)
demo.launch(auth=[("Abubakar", "Abubakar"), ("Ali", "Ali")])
```
Note: For authentication to work properly, third party cookies must be enabled in your browser. This is not the case by default for Safari or for Chrome Incognito Mode.
If users visit the `/logout` page of your Gradio app, they will automatically be logged out and session cookies deleted. This allows you to add logout functionality to your Gradio app as well. Let's update the previous example to include a log out button:
```python
import gradio as gr
def update_message(request: gr.Request):
return f"Welcome, {request.username}"
with gr.Blocks() as | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
Let's update the previous example to include a log out button:
```python
import gradio as gr
def update_message(request: gr.Request):
return f"Welcome, {request.username}"
with gr.Blocks() as demo:
m = gr.Markdown()
logout_button = gr.Button("Logout", link="/logout")
demo.load(update_message, None, m)
demo.launch(auth=[("Pete", "Pete"), ("Dawood", "Dawood")])
```
By default, visiting `/logout` logs the user out from **all sessions** (e.g. if they are logged in from multiple browsers or devices, all will be signed out). If you want to log out only from the **current session**, add the query parameter `all_session=false` (i.e. `/logout?all_session=false`).
Note: Gradio's built-in authentication provides a straightforward and basic layer of access control but does not offer robust security features for applications that require stringent access controls (e.g. multi-factor authentication, rate limiting, or automatic lockout policies).
OAuth (Login via Hugging Face)
Gradio natively supports OAuth login via Hugging Face. In other words, you can easily add a _"Sign in with Hugging Face"_ button to your demo, which allows you to get a user's HF username as well as other information from their HF profile. Check out [this Space](https://huggingface.co/spaces/Wauplin/gradio-oauth-demo) for a live demo.
To enable OAuth, you must set `hf_oauth: true` as a Space metadata in your README.md file. This will register your Space
as an OAuth application on Hugging Face. Next, you can use `gr.LoginButton` to add a login button to
your Gradio app. Once a user is logged in with their HF account, you can retrieve their profile by adding a parameter of type
`gr.OAuthProfile` to any Gradio function. The user profile will be automatically injected as a parameter value. If you want
to perform actions on behalf of the user (e.g. list user's private repos, create repo, etc.), you can retrieve the user
token by adding a parameter of type `gr.OAuthToken`. You must def | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
e. If you want
to perform actions on behalf of the user (e.g. list user's private repos, create repo, etc.), you can retrieve the user
token by adding a parameter of type `gr.OAuthToken`. You must define which scopes you will use in your Space metadata
(see [documentation](https://huggingface.co/docs/hub/spaces-oauthscopes) for more details).
Here is a short example:
$code_login_with_huggingface
When the user clicks on the login button, they get redirected in a new page to authorize your Space.
<center>
<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/oauth_sign_in.png" style="width:300px; max-width:80%">
</center>
Users can revoke access to their profile at any time in their [settings](https://huggingface.co/settings/connected-applications).
As seen above, OAuth features are available only when your app runs in a Space. However, you often need to test your app
locally before deploying it. To test OAuth features locally, your machine must be logged in to Hugging Face. Please run `huggingface-cli login` or set `HF_TOKEN` as environment variable with one of your access token. You can generate a new token in your settings page (https://huggingface.co/settings/tokens). Then, clicking on the `gr.LoginButton` will log in to your local Hugging Face profile, allowing you to debug your app with your Hugging Face account before deploying it to a Space.
**Security Note**: It is important to note that adding a `gr.LoginButton` does not restrict users from using your app, in the same way that adding [username-password authentication](/guides/sharing-your-apppassword-protected-app) does. This means that users of your app who have not logged in with Hugging Face can still access and run events in your Gradio app -- the difference is that the `gr.OAuthProfile` or `gr.OAuthToken` will be `None` in the corresponding functions.
OAuth (with external providers)
It is also possible to authenticate with external OAuth pr | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
erence is that the `gr.OAuthProfile` or `gr.OAuthToken` will be `None` in the corresponding functions.
OAuth (with external providers)
It is also possible to authenticate with external OAuth providers (e.g. Google OAuth) in your Gradio apps. To do this, first mount your Gradio app within a FastAPI app ([as discussed above](mounting-within-another-fast-api-app)). Then, you must write an *authentication function*, which gets the user's username from the OAuth provider and returns it. This function should be passed to the `auth_dependency` parameter in `gr.mount_gradio_app`.
Similar to [FastAPI dependency functions](https://fastapi.tiangolo.com/tutorial/dependencies/), the function specified by `auth_dependency` will run before any Gradio-related route in your FastAPI app. The function should accept a single parameter: the FastAPI `Request` and return either a string (representing a user's username) or `None`. If a string is returned, the user will be able to access the Gradio-related routes in your FastAPI app.
First, let's show a simplistic example to illustrate the `auth_dependency` parameter:
```python
from fastapi import FastAPI, Request
import gradio as gr
app = FastAPI()
def get_user(request: Request):
return request.headers.get("user")
demo = gr.Interface(lambda s: f"Hello {s}!", "textbox", "textbox")
app = gr.mount_gradio_app(app, demo, path="/demo", auth_dependency=get_user)
if __name__ == '__main__':
uvicorn.run(app)
```
In this example, only requests that include a "user" header will be allowed to access the Gradio app. Of course, this does not add much security, since any user can add this header in their request.
Here's a more complete example showing how to add Google OAuth to a Gradio app (assuming you've already created OAuth Credentials on the [Google Developer Console](https://console.cloud.google.com/project)):
```python
import os
from authlib.integrations.starlette_client import OAuth, OAuthError
from fastapi import FastA | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
entials on the [Google Developer Console](https://console.cloud.google.com/project)):
```python
import os
from authlib.integrations.starlette_client import OAuth, OAuthError
from fastapi import FastAPI, Depends, Request
from starlette.config import Config
from starlette.responses import RedirectResponse
from starlette.middleware.sessions import SessionMiddleware
import uvicorn
import gradio as gr
app = FastAPI()
Replace these with your own OAuth settings
GOOGLE_CLIENT_ID = "..."
GOOGLE_CLIENT_SECRET = "..."
SECRET_KEY = "..."
config_data = {'GOOGLE_CLIENT_ID': GOOGLE_CLIENT_ID, 'GOOGLE_CLIENT_SECRET': GOOGLE_CLIENT_SECRET}
starlette_config = Config(environ=config_data)
oauth = OAuth(starlette_config)
oauth.register(
name='google',
server_metadata_url='https://accounts.google.com/.well-known/openid-configuration',
client_kwargs={'scope': 'openid email profile'},
)
SECRET_KEY = os.environ.get('SECRET_KEY') or "a_very_secret_key"
app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY)
Dependency to get the current user
def get_user(request: Request):
user = request.session.get('user')
if user:
return user['name']
return None
@app.get('/')
def public(user: dict = Depends(get_user)):
if user:
return RedirectResponse(url='/gradio')
else:
return RedirectResponse(url='/login-demo')
@app.route('/logout')
async def logout(request: Request):
request.session.pop('user', None)
return RedirectResponse(url='/')
@app.route('/login')
async def login(request: Request):
redirect_uri = request.url_for('auth')
If your app is running on https, you should ensure that the
`redirect_uri` is https, e.g. uncomment the following lines:
from urllib.parse import urlparse, urlunparse
redirect_uri = urlunparse(urlparse(str(redirect_uri))._replace(scheme='https'))
return await oauth.google.authorize_redirect(request, redirect_uri)
@app.route('/auth')
async def auth(request: Reque | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
direct_uri = urlunparse(urlparse(str(redirect_uri))._replace(scheme='https'))
return await oauth.google.authorize_redirect(request, redirect_uri)
@app.route('/auth')
async def auth(request: Request):
try:
access_token = await oauth.google.authorize_access_token(request)
except OAuthError:
return RedirectResponse(url='/')
request.session['user'] = dict(access_token)["userinfo"]
return RedirectResponse(url='/')
with gr.Blocks() as login_demo:
gr.Button("Login", link="/login")
app = gr.mount_gradio_app(app, login_demo, path="/login-demo")
def greet(request: gr.Request):
return f"Welcome to Gradio, {request.username}"
with gr.Blocks() as main_demo:
m = gr.Markdown("Welcome to Gradio!")
gr.Button("Logout", link="/logout")
main_demo.load(greet, None, m)
app = gr.mount_gradio_app(app, main_demo, path="/gradio", auth_dependency=get_user)
if __name__ == '__main__':
uvicorn.run(app)
```
There are actually two separate Gradio apps in this example! One that simply displays a log in button (this demo is accessible to any user), while the other main demo is only accessible to users that are logged in. You can try this example out on [this Space](https://huggingface.co/spaces/gradio/oauth-example).
| Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
Gradio apps can function as MCP (Model Context Protocol) servers, allowing LLMs to use your app's functions as tools. By simply setting `mcp_server=True` in the `.launch()` method, Gradio automatically converts your app's functions into MCP tools that can be called by MCP clients like Claude Desktop, Cursor, or Cline. The server exposes tools based on your function names, docstrings, and type hints, and can handle file uploads, authentication headers, and progress updates. You can also create MCP-only functions using `gr.api` and expose resources and prompts using decorators. For a comprehensive guide on building MCP servers with Gradio, see [Building an MCP Server with Gradio](https://www.gradio.app/guides/building-mcp-server-with-gradio).
| MCP Servers | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
When publishing your app publicly, and making it available via API or via MCP server, you might want to set rate limits to prevent users from abusing your app. You can identify users using their IP address (using the `gr.Request` object [as discussed above](accessing-the-network-request-directly)) or, if they are logged in via Hugging Face OAuth, using their username. To see a complete example of how to set rate limits, please see [this Gradio app](https://github.com/gradio-app/gradio/blob/main/demo/rate_limit/run.py).
| Rate Limits | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
By default, Gradio collects certain analytics to help us better understand the usage of the `gradio` library. This includes the following information:
* What environment the Gradio app is running on (e.g. Colab Notebook, Hugging Face Spaces)
* What input/output components are being used in the Gradio app
* Whether the Gradio app is utilizing certain advanced features, such as `auth` or `show_error`
* The IP address which is used solely to measure the number of unique developers using Gradio
* The version of Gradio that is running
No information is collected from _users_ of your Gradio app. If you'd like to disable analytics altogether, you can do so by setting the `analytics_enabled` parameter to `False` in `gr.Blocks`, `gr.Interface`, or `gr.ChatInterface`. Or, you can set the GRADIO_ANALYTICS_ENABLED environment variable to `"False"` to apply this to all Gradio apps created across your system.
*Note*: this reflects the analytics policy as of `gradio>=4.32.0`.
| Analytics | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
[Progressive Web Apps (PWAs)](https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps) are web applications that are regular web pages or websites, but can appear to the user like installable platform-specific applications.
Gradio apps can be easily served as PWAs by setting the `pwa=True` parameter in the `launch()` method. Here's an example:
```python
import gradio as gr
def greet(name):
return "Hello " + name + "!"
demo = gr.Interface(fn=greet, inputs="textbox", outputs="textbox")
demo.launch(pwa=True) Launch your app as a PWA
```
This will generate a PWA that can be installed on your device. Here's how it looks:

When you specify `favicon_path` in the `launch()` method, the icon will be used as the app's icon. Here's an example:
```python
demo.launch(pwa=True, favicon_path="./hf-logo.svg") Use a custom icon for your PWA
```

| Progressive Web App (PWA) | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
By default, each event listener has its own queue, which handles one request at a time. This can be configured via two arguments:
- `concurrency_limit`: This sets the maximum number of concurrent executions for an event listener. By default, the limit is 1 unless configured otherwise in `Blocks.queue()`. You can also set it to `None` for no limit (i.e., an unlimited number of concurrent executions). For example:
```python
import gradio as gr
with gr.Blocks() as demo:
prompt = gr.Textbox()
image = gr.Image()
generate_btn = gr.Button("Generate Image")
generate_btn.click(image_gen, prompt, image, concurrency_limit=5)
```
In the code above, up to 5 requests can be processed simultaneously for this event listener. Additional requests will be queued until a slot becomes available.
If you want to manage multiple event listeners using a shared queue, you can use the `concurrency_id` argument:
- `concurrency_id`: This allows event listeners to share a queue by assigning them the same ID. For example, if your setup has only 2 GPUs but multiple functions require GPU access, you can create a shared queue for all those functions. Here's how that might look:
```python
import gradio as gr
with gr.Blocks() as demo:
prompt = gr.Textbox()
image = gr.Image()
generate_btn_1 = gr.Button("Generate Image via model 1")
generate_btn_2 = gr.Button("Generate Image via model 2")
generate_btn_3 = gr.Button("Generate Image via model 3")
generate_btn_1.click(image_gen_1, prompt, image, concurrency_limit=2, concurrency_id="gpu_queue")
generate_btn_2.click(image_gen_2, prompt, image, concurrency_id="gpu_queue")
generate_btn_3.click(image_gen_3, prompt, image, concurrency_id="gpu_queue")
```
In this example, all three event listeners share a queue identified by `"gpu_queue"`. The queue can handle up to 2 concurrent requests at a time, as defined by the `concurrency_limit`.
Notes
- To ensure unlimited concurrency for an event listener, se | Configuring the Queue | https://gradio.app/guides/queuing | Additional Features - Queuing Guide |
identified by `"gpu_queue"`. The queue can handle up to 2 concurrent requests at a time, as defined by the `concurrency_limit`.
Notes
- To ensure unlimited concurrency for an event listener, set `concurrency_limit=None`. This is useful if your function is calling e.g. an external API which handles the rate limiting of requests itself.
- The default concurrency limit for all queues can be set globally using the `default_concurrency_limit` parameter in `Blocks.queue()`.
These configurations make it easy to manage the queuing behavior of your Gradio app.
| Configuring the Queue | https://gradio.app/guides/queuing | Additional Features - Queuing Guide |
- **1. Static files**. You can designate static files or directories using the `gr.set_static_paths` function. Static files are not be copied to the Gradio cache (see below) and will be served directly from your computer. This can help save disk space and reduce the time your app takes to launch but be mindful of possible security implications as any static files are accessible to all useres of your Gradio app.
- **2. Files in the `allowed_paths` parameter in `launch()`**. This parameter allows you to pass in a list of additional directories or exact filepaths you'd like to allow users to have access to. (By default, this parameter is an empty list).
- **3. Files in Gradio's cache**. After you launch your Gradio app, Gradio copies certain files into a temporary cache and makes these files accessible to users. Let's unpack this in more detail below.
| Files Gradio allows users to access | https://gradio.app/guides/file-access | Additional Features - File Access Guide |
First, it's important to understand why Gradio has a cache at all. Gradio copies files to a cache directory before returning them to the frontend. This prevents files from being overwritten by one user while they are still needed by another user of your application. For example, if your prediction function returns a video file, then Gradio will move that video to the cache after your prediction function runs and returns a URL the frontend can use to show the video. Any file in the cache is available via URL to all users of your running application.
Tip: You can customize the location of the cache by setting the `GRADIO_TEMP_DIR` environment variable to an absolute path, such as `/home/usr/scripts/project/temp/`.
Files Gradio moves to the cache
Gradio moves three kinds of files into the cache
1. Files specified by the developer before runtime, e.g. cached examples, default values of components, or files passed into parameters such as the `avatar_images` of `gr.Chatbot`
2. File paths returned by a prediction function in your Gradio application, if they ALSO meet one of the conditions below:
* It is in the `allowed_paths` parameter of the `Blocks.launch` method.
* It is in the current working directory of the python interpreter.
* It is in the temp directory obtained by `tempfile.gettempdir()`.
**Note:** files in the current working directory whose name starts with a period (`.`) will not be moved to the cache, even if they are returned from a prediction function, since they often contain sensitive information.
If none of these criteria are met, the prediction function that is returning that file will raise an exception instead of moving the file to cache. Gradio performs this check so that arbitrary files on your machine cannot be accessed.
3. Files uploaded by a user to your Gradio app (e.g. through the `File` or `Image` input components).
Tip: If at any time Gradio blocks a file that you would like it to process, add its path to the `allowed_paths` p | The Gradio cache | https://gradio.app/guides/file-access | Additional Features - File Access Guide |
d by a user to your Gradio app (e.g. through the `File` or `Image` input components).
Tip: If at any time Gradio blocks a file that you would like it to process, add its path to the `allowed_paths` parameter.
| The Gradio cache | https://gradio.app/guides/file-access | Additional Features - File Access Guide |
While running, Gradio apps will NOT ALLOW users to access:
- **Files that you explicitly block via the `blocked_paths` parameter in `launch()`**. You can pass in a list of additional directories or exact filepaths to the `blocked_paths` parameter in `launch()`. This parameter takes precedence over the files that Gradio exposes by default, or by the `allowed_paths` parameter or the `gr.set_static_paths` function.
- **Any other paths on the host machine**. Users should NOT be able to access other arbitrary paths on the host.
| The files Gradio will not allow others to access | https://gradio.app/guides/file-access | Additional Features - File Access Guide |
Sharing your Gradio application will also allow users to upload files to your computer or server. You can set a maximum file size for uploads to prevent abuse and to preserve disk space. You can do this with the `max_file_size` parameter of `.launch`. For example, the following two code snippets limit file uploads to 5 megabytes per file.
```python
import gradio as gr
demo = gr.Interface(lambda x: x, "image", "image")
demo.launch(max_file_size="5mb")
or
demo.launch(max_file_size=5 * gr.FileSize.MB)
```
| Uploading Files | https://gradio.app/guides/file-access | Additional Features - File Access Guide |
* Set a `max_file_size` for your application.
* Do not return arbitrary user input from a function that is connected to a file-based output component (`gr.Image`, `gr.File`, etc.). For example, the following interface would allow anyone to move an arbitrary file in your local directory to the cache: `gr.Interface(lambda s: s, "text", "file")`. This is because the user input is treated as an arbitrary file path.
* Make `allowed_paths` as small as possible. If a path in `allowed_paths` is a directory, any file within that directory can be accessed. Make sure the entires of `allowed_paths` only contains files related to your application.
* Run your gradio application from the same directory the application file is located in. This will narrow the scope of files Gradio will be allowed to move into the cache. For example, prefer `python app.py` to `python Users/sources/project/app.py`.
| Best Practices | https://gradio.app/guides/file-access | Additional Features - File Access Guide |
Both `gr.set_static_paths` and the `allowed_paths` parameter in launch expect absolute paths. Below is a minimal example to display a local `.png` image file in an HTML block.
```txt
βββ assets
β βββ logo.png
βββ app.py
```
For the example directory structure, `logo.png` and any other files in the `assets` folder can be accessed from your Gradio app in `app.py` as follows:
```python
from pathlib import Path
import gradio as gr
gr.set_static_paths(paths=[Path.cwd().absolute()/"assets"])
with gr.Blocks() as demo:
gr.HTML("<img src='/gradio_api/file=assets/logo.png'>")
demo.launch()
```
| Example: Accessing local files | https://gradio.app/guides/file-access | Additional Features - File Access Guide |
Make sure you have gradio 5.0 or higher installed as well as node 20+.
As of the time of publication, the latest release is 4.1.1.
Also, please read the [Five Minute Tour](./custom-components-in-five-minutes) of custom components and the [Key Concepts](./key-component-concepts) guide before starting.
| Step 0: Prerequisites | https://gradio.app/guides/pdf-component-example | Custom Components - Pdf Component Example Guide |
Navigate to a directory of your choosing and run the following command:
```bash
gradio cc create PDF
```
Tip: You should change the name of the component.
Some of the screenshots assume the component is called `PDF` but the concepts are the same!
This will create a subdirectory called `pdf` in your current working directory.
There are three main subdirectories in `pdf`: `frontend`, `backend`, and `demo`.
If you open `pdf` in your code editor, it will look like this:

Tip: For this demo we are not templating off a current gradio component. But you can see the list of available templates with `gradio cc show` and then pass the template name to the `--template` option, e.g. `gradio cc create <Name> --template <foo>`
| Step 1: Creating the custom component | https://gradio.app/guides/pdf-component-example | Custom Components - Pdf Component Example Guide |
We're going to use the [pdfjs](https://mozilla.github.io/pdf.js/) javascript library to display the pdfs in the frontend.
Let's start off by adding it to our frontend project's dependencies, as well as adding a couple of other projects we'll need.
From within the `frontend` directory, run `npm install @gradio/client @gradio/upload @gradio/icons @gradio/button` and `npm install --save-dev pdfjs-dist@3.11.174`.
Also, let's uninstall the `@zerodevx/svelte-json-view` dependency by running `npm uninstall @zerodevx/svelte-json-view`.
The complete `package.json` should look like this:
```json
{
"name": "gradio_pdf",
"version": "0.2.0",
"description": "Gradio component for displaying PDFs",
"type": "module",
"author": "",
"license": "ISC",
"private": false,
"main_changeset": true,
"exports": {
".": "./Index.svelte",
"./example": "./Example.svelte",
"./package.json": "./package.json"
},
"devDependencies": {
"pdfjs-dist": "3.11.174"
},
"dependencies": {
"@gradio/atoms": "0.2.0",
"@gradio/statustracker": "0.3.0",
"@gradio/utils": "0.2.0",
"@gradio/client": "0.7.1",
"@gradio/upload": "0.3.2",
"@gradio/icons": "0.2.0",
"@gradio/button": "0.2.3",
"pdfjs-dist": "3.11.174"
}
}
```
Tip: Running `npm install` will install the latest version of the package available. You can install a specific version with `npm install package@<version>`. You can find all of the gradio javascript package documentation [here](https://www.gradio.app/main/docs/js). It is recommended you use the same versions as me as the API can change.
Navigate to `Index.svelte` and delete mentions of `JSONView`
```ts
import { JsonView } from "@zerodevx/svelte-json-view";
```
```svelte
<JsonView json={value} />
```
| Step 2: Frontend - modify javascript dependencies | https://gradio.app/guides/pdf-component-example | Custom Components - Pdf Component Example Guide |
Run the `dev` command to launch the development server.
This will open the demo in `demo/app.py` in an environment where changes to the `frontend` and `backend` directories will reflect instantaneously in the launched app.
After launching the dev server, you should see a link printed to your console that says `Frontend Server (Go here): ... `.

You should see the following:

Its not impressive yet but we're ready to start coding!
| Step 3: Frontend - Launching the Dev Server | https://gradio.app/guides/pdf-component-example | Custom Components - Pdf Component Example Guide |
We're going to start off by first writing the skeleton of our frontend and then adding the pdf rendering logic.
Add the following imports and expose the following properties to the top of your file in the `<script>` tag.
You may get some warnings from your code editor that some props are not used.
That's ok.
```ts
import { tick } from "svelte";
import type { Gradio } from "@gradio/utils";
import { Block, BlockLabel } from "@gradio/atoms";
import { File } from "@gradio/icons";
import { StatusTracker } from "@gradio/statustracker";
import type { LoadingStatus } from "@gradio/statustracker";
import type { FileData } from "@gradio/client";
import { Upload, ModifyUpload } from "@gradio/upload";
export let elem_id = "";
export let elem_classes: string[] = [];
export let visible = true;
export let value: FileData | null = null;
export let container = true;
export let scale: number | null = null;
export let root: string;
export let height: number | null = 500;
export let label: string;
export let proxy_url: string;
export let min_width: number | undefined = undefined;
export let loading_status: LoadingStatus;
export let gradio: Gradio<{
change: never;
upload: never;
}>;
let _value = value;
let old_value = _value;
```
Tip: The `gradio`` object passed in here contains some metadata about the application as well as some utility methods. One of these utilities is a dispatch method. We want to dispatch change and upload events whenever our PDF is changed or updated. This line provides type hints that these are the only events we will be dispatching.
We want our frontend component to let users upload a PDF document if there isn't one already loaded.
If it is loaded, we want to display it underneath a "clear" button that lets our users upload a new document.
We're going to use the `Upload` and `ModifyUpload` components that come with the `@gradio/upload` package to do this.
Underneath the `</script>` tag, delete all | Step 4: Frontend - The basic skeleton | https://gradio.app/guides/pdf-component-example | Custom Components - Pdf Component Example Guide |
lets our users upload a new document.
We're going to use the `Upload` and `ModifyUpload` components that come with the `@gradio/upload` package to do this.
Underneath the `</script>` tag, delete all the current code and add the following:
```svelte
<Block {visible} {elem_id} {elem_classes} {container} {scale} {min_width}>
{if loading_status}
<StatusTracker
autoscroll={gradio.autoscroll}
i18n={gradio.i18n}
{...loading_status}
/>
{/if}
<BlockLabel
show_label={label !== null}
Icon={File}
float={value === null}
label={label || "File"}
/>
{if _value}
<ModifyUpload i18n={gradio.i18n} absolute />
{:else}
<Upload
filetype={"application/pdf"}
file_count="single"
{root}
>
Upload your PDF
</Upload>
{/if}
</Block>
```
You should see the following when you navigate to your app after saving your current changes:

| Step 4: Frontend - The basic skeleton | https://gradio.app/guides/pdf-component-example | Custom Components - Pdf Component Example Guide |
The `Upload your PDF` text looks a bit small and barebones.
Lets customize it!
Create a new file called `PdfUploadText.svelte` and copy the following code.
Its creating a new div to display our "upload text" with some custom styling.
Tip: Notice that we're leveraging Gradio core's existing css variables here: `var(--size-60)` and `var(--body-text-color-subdued)`. This allows our component to work nicely in light mode and dark mode, as well as with Gradio's built-in themes.
```svelte
<script lang="ts">
import { Upload as UploadIcon } from "@gradio/icons";
export let hovered = false;
</script>
<div class="wrap">
<span class="icon-wrap" class:hovered><UploadIcon /> </span>
Drop PDF
<span class="or">- or -</span>
Click to Upload
</div>
<style>
.wrap {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-height: var(--size-60);
color: var(--block-label-text-color);
line-height: var(--line-md);
height: 100%;
padding-top: var(--size-3);
}
.or {
color: var(--body-text-color-subdued);
display: flex;
}
.icon-wrap {
width: 30px;
margin-bottom: var(--spacing-lg);
}
@media (--screen-md) {
.wrap {
font-size: var(--text-lg);
}
}
.hovered {
color: var(--color-accent);
}
</style>
```
Now import `PdfUploadText.svelte` in your `<script>` and pass it to the `Upload` component!
```svelte
import PdfUploadText from "./PdfUploadText.svelte";
...
<Upload
filetype={"application/pdf"}
file_count="single"
{root}
>
<PdfUploadText />
</Upload>
```
After saving your code, the frontend should now look like this:

| Step 5: Frontend - Nicer Upload Text | https://gradio.app/guides/pdf-component-example | Custom Components - Pdf Component Example Guide |
This is the most advanced javascript part.
It took me a while to figure it out!
Do not worry if you have trouble, the important thing is to not be discouraged πͺ
Ask for help in the gradio [discord](https://discord.gg/hugging-face-879548962464493619) if you need and ask for help.
With that out of the way, let's start off by importing `pdfjs` and loading the code of the pdf worker from the mozilla cdn.
```ts
import pdfjsLib from "pdfjs-dist";
...
pdfjsLib.GlobalWorkerOptions.workerSrc = "https://cdn.bootcss.com/pdf.js/3.11.174/pdf.worker.js";
```
Also create the following variables:
```ts
let pdfDoc;
let numPages = 1;
let currentPage = 1;
let canvasRef;
```
Now, we will use `pdfjs` to render a given page of the PDF onto an `html` document.
Add the following code to `Index.svelte`:
```ts
async function get_doc(value: FileData) {
const loadingTask = pdfjsLib.getDocument(value.url);
pdfDoc = await loadingTask.promise;
numPages = pdfDoc.numPages;
render_page();
}
function render_page() {
// Render a specific page of the PDF onto the canvas
pdfDoc.getPage(currentPage).then(page => {
const ctx = canvasRef.getContext('2d')
ctx.clearRect(0, 0, canvasRef.width, canvasRef.height);
let viewport = page.getViewport({ scale: 1 });
let scale = height / viewport.height;
viewport = page.getViewport({ scale: scale });
const renderContext = {
canvasContext: ctx,
viewport,
};
canvasRef.width = viewport.width;
canvasRef.height = viewport.height;
page.render(renderContext);
});
}
// If the value changes, render the PDF of the currentPage
$: if(JSON.stringify(old_value) != JSON.stringify(_value)) {
if (_value){
get_doc(_value);
}
old_value = _value;
gradio.dispatch("change");
}
```
| Step 6: PDF Rendering logic | https://gradio.app/guides/pdf-component-example | Custom Components - Pdf Component Example Guide |
$: if(JSON.stringify(old_value) != JSON.stringify(_value)) {
if (_value){
get_doc(_value);
}
old_value = _value;
gradio.dispatch("change");
}
```
Tip: The `$:` syntax in svelte is how you declare statements to be reactive. Whenever any of the inputs of the statement change, svelte will automatically re-run that statement.
Now place the `canvas` underneath the `ModifyUpload` component:
```svelte
<div class="pdf-canvas" style="height: {height}px">
<canvas bind:this={canvasRef}></canvas>
</div>
```
And add the following styles to the `<style>` tag:
```svelte
<style>
.pdf-canvas {
display: flex;
justify-content: center;
align-items: center;
}
</style>
```
| Step 6: PDF Rendering logic | https://gradio.app/guides/pdf-component-example | Custom Components - Pdf Component Example Guide |
Now for the fun part - actually rendering the PDF when the file is uploaded!
Add the following functions to the `<script>` tag:
```ts
async function handle_clear() {
_value = null;
await tick();
gradio.dispatch("change");
}
async function handle_upload({detail}: CustomEvent<FileData>): Promise<void> {
value = detail;
await tick();
gradio.dispatch("change");
gradio.dispatch("upload");
}
```
Tip: The `gradio.dispatch` method is actually what is triggering the `change` or `upload` events in the backend. For every event defined in the component's backend, we will explain how to do this in Step 9, there must be at least one `gradio.dispatch("<event-name>")` call. These are called `gradio` events and they can be listended from the entire Gradio application. You can dispatch a built-in `svelte` event with the `dispatch` function. These events can only be listened to from the component's direct parent. Learn about svelte events from the [official documentation](https://learn.svelte.dev/tutorial/component-events).
Now we will run these functions whenever the `Upload` component uploads a file and whenever the `ModifyUpload` component clears the current file. The `<Upload>` component dispatches a `load` event with a payload of type `FileData` corresponding to the uploaded file. The `on:load` syntax tells `Svelte` to automatically run this function in response to the event.
```svelte
<ModifyUpload i18n={gradio.i18n} on:clear={handle_clear} absolute />
...
<Upload
on:load={handle_upload}
filetype={"application/pdf"}
file_count="single"
{root}
>
<PdfUploadText/>
</Upload>
```
Congratulations! You have a working pdf uploader!

| Step 7: Handling The File Upload And Clear | https://gradio.app/guides/pdf-component-example | Custom Components - Pdf Component Example Guide |
If a user uploads a PDF document with multiple pages, they will only be able to see the first one.
Let's add some buttons to help them navigate the page.
We will use the `BaseButton` from `@gradio/button` so that they look like regular Gradio buttons.
Import the `BaseButton` and add the following functions that will render the next and previous page of the PDF.
```ts
import { BaseButton } from "@gradio/button";
...
function next_page() {
if (currentPage >= numPages) {
return;
}
currentPage++;
render_page();
}
function prev_page() {
if (currentPage == 1) {
return;
}
currentPage--;
render_page();
}
```
Now we will add them underneath the canvas in a separate `<div>`
```svelte
...
<ModifyUpload i18n={gradio.i18n} on:clear={handle_clear} absolute />
<div class="pdf-canvas" style="height: {height}px">
<canvas bind:this={canvasRef}></canvas>
</div>
<div class="button-row">
<BaseButton on:click={prev_page}>
β¬
οΈ
</BaseButton>
<span class="page-count"> {currentPage} / {numPages} </span>
<BaseButton on:click={next_page}>
β‘οΈ
</BaseButton>
</div>
...
<style>
.button-row {
display: flex;
flex-direction: row;
width: 100%;
justify-content: center;
align-items: center;
}
.page-count {
margin: 0 10px;
font-family: var(--font-mono);
}
```
Congratulations! The frontend is almost complete π

| Step 8: Adding buttons to navigate pages | https://gradio.app/guides/pdf-component-example | Custom Components - Pdf Component Example Guide |
We're going to want users of our component to get a preview of the PDF if its used as an `example` in a `gr.Interface` or `gr.Examples`.
To do so, we're going to add some of the pdf rendering logic in `Index.svelte` to `Example.svelte`.
```svelte
<script lang="ts">
export let value: string;
export let type: "gallery" | "table";
export let selected = false;
import pdfjsLib from "pdfjs-dist";
pdfjsLib.GlobalWorkerOptions.workerSrc = "https://cdn.bootcss.com/pdf.js/3.11.174/pdf.worker.js";
let pdfDoc;
let canvasRef;
async function get_doc(url: string) {
const loadingTask = pdfjsLib.getDocument(url);
pdfDoc = await loadingTask.promise;
renderPage();
}
function renderPage() {
// Render a specific page of the PDF onto the canvas
pdfDoc.getPage(1).then(page => {
const ctx = canvasRef.getContext('2d')
ctx.clearRect(0, 0, canvasRef.width, canvasRef.height);
const viewport = page.getViewport({ scale: 0.2 });
const renderContext = {
canvasContext: ctx,
viewport
};
canvasRef.width = viewport.width;
canvasRef.height = viewport.height;
page.render(renderContext);
});
}
$: get_doc(value);
</script>
<div
class:table={type === "table"}
class:gallery={type === "gallery"}
class:selected
style="justify-content: center; align-items: center; display: flex; flex-direction: column;"
>
<canvas bind:this={canvasRef}></canvas>
</div>
<style>
.gallery {
padding: var(--size-1) var(--size-2);
}
</style>
```
Tip: Exercise for the reader - reduce the code duplication between `Index.svelte` and `Example.svelte` π
You will not be able to render examples until we make some changes to the backend code in the next step!
| Step 8.5: The Example view | https://gradio.app/guides/pdf-component-example | Custom Components - Pdf Component Example Guide |
The backend changes needed are smaller.
We're almost done!
What we're going to do is:
* Add `change` and `upload` events to our component.
* Add a `height` property to let users control the height of the PDF.
* Set the `data_model` of our component to be `FileData`. This is so that Gradio can automatically cache and safely serve any files that are processed by our component.
* Modify the `preprocess` method to return a string corresponding to the path of our uploaded PDF.
* Modify the `postprocess` to turn a path to a PDF created in an event handler to a `FileData`.
When all is said an done, your component's backend code should look like this:
```python
from __future__ import annotations
from typing import Any, Callable, TYPE_CHECKING
from gradio.components.base import Component
from gradio.data_classes import FileData
from gradio import processing_utils
if TYPE_CHECKING:
from gradio.components import Timer
class PDF(Component):
EVENTS = ["change", "upload"]
data_model = FileData
def __init__(self, value: Any = None, *,
height: int | None = None,
label: str | I18nData | None = None,
info: str | I18nData | None = None,
show_label: bool | None = None,
container: bool = True,
scale: int | None = None,
min_width: int | None = None,
interactive: bool | None = None,
visible: bool = True,
elem_id: str | None = None,
elem_classes: list[str] | str | None = None,
render: bool = True,
load_fn: Callable[..., Any] | None = None,
every: Timer | float | None = None):
super().__init__(value, label=label, info=info,
show_label=show_label, container=container,
scale=scale, min_width=min_width,
interactive=interactive, visible=visible,
| Step 9: The backend | https://gradio.app/guides/pdf-component-example | Custom Components - Pdf Component Example Guide |
show_label=show_label, container=container,
scale=scale, min_width=min_width,
interactive=interactive, visible=visible,
elem_id=elem_id, elem_classes=elem_classes,
render=render, load_fn=load_fn, every=every)
self.height = height
def preprocess(self, payload: FileData) -> str:
return payload.path
def postprocess(self, value: str | None) -> FileData:
if not value:
return None
return FileData(path=value)
def example_payload(self):
return "https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/fw9.pdf"
def example_value(self):
return "https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/fw9.pdf"
```
| Step 9: The backend | https://gradio.app/guides/pdf-component-example | Custom Components - Pdf Component Example Guide |
To test our backend code, let's add a more complex demo that performs Document Question and Answering with huggingface transformers.
In our `demo` directory, create a `requirements.txt` file with the following packages
```
torch
transformers
pdf2image
pytesseract
```
Tip: Remember to install these yourself and restart the dev server! You may need to install extra non-python dependencies for `pdf2image`. See [here](https://pypi.org/project/pdf2image/). Feel free to write your own demo if you have trouble.
```python
import gradio as gr
from gradio_pdf import PDF
from pdf2image import convert_from_path
from transformers import pipeline
from pathlib import Path
dir_ = Path(__file__).parent
p = pipeline(
"document-question-answering",
model="impira/layoutlm-document-qa",
)
def qa(question: str, doc: str) -> str:
img = convert_from_path(doc)[0]
output = p(img, question)
return sorted(output, key=lambda x: x["score"], reverse=True)[0]['answer']
demo = gr.Interface(
qa,
[gr.Textbox(label="Question"), PDF(label="Document")],
gr.Textbox(),
)
demo.launch()
```
See our demo in action below!
<video autoplay muted loop>
<source src="https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/PDFDemo.mov" type="video/mp4" />
</video>
Finally lets build our component with `gradio cc build` and publish it with the `gradio cc publish` command!
This will guide you through the process of uploading your component to [PyPi](https://pypi.org/) and [HuggingFace Spaces](https://huggingface.co/spaces).
Tip: You may need to add the following lines to the `Dockerfile` of your HuggingFace Space.
```Dockerfile
RUN mkdir -p /tmp/cache/
RUN chmod a+rwx -R /tmp/cache/
RUN apt-get update && apt-get install -y poppler-utils tesseract-ocr
ENV TRANSFORMERS_CACHE=/tmp/cache/
```
| Step 10: Add a demo and publish! | https://gradio.app/guides/pdf-component-example | Custom Components - Pdf Component Example Guide |
In order to use our new component in **any** gradio 4.0 app, simply install it with pip, e.g. `pip install gradio-pdf`. Then you can use it like the built-in `gr.File()` component (except that it will only accept and display PDF files).
Here is a simple demo with the Blocks api:
```python
import gradio as gr
from gradio_pdf import PDF
with gr.Blocks() as demo:
pdf = PDF(label="Upload a PDF", interactive=True)
name = gr.Textbox()
pdf.upload(lambda f: f, pdf, name)
demo.launch()
```
I hope you enjoyed this tutorial!
The complete source code for our component is [here](https://huggingface.co/spaces/freddyaboulton/gradio_pdf/tree/main/src).
Please don't hesitate to reach out to the gradio community on the [HuggingFace Discord](https://discord.gg/hugging-face-879548962464493619) if you get stuck.
| Conclusion | https://gradio.app/guides/pdf-component-example | Custom Components - Pdf Component Example Guide |
For this demo we will be tweaking the existing Gradio `Chatbot` component to display text and media files in the same message.
Let's create a new custom component directory by templating off of the `Chatbot` component source code.
```bash
gradio cc create MultimodalChatbot --template Chatbot
```
And we're ready to go!
Tip: Make sure to modify the `Author` key in the `pyproject.toml` file.
| Part 1 - Creating our project | https://gradio.app/guides/multimodal-chatbot-part1 | Custom Components - Multimodal Chatbot Part1 Guide |
Open up the `multimodalchatbot.py` file in your favorite code editor and let's get started modifying the backend of our component.
The first thing we will do is create the `data_model` of our component.
The `data_model` is the data format that your python component will receive and send to the javascript client running the UI.
You can read more about the `data_model` in the [backend guide](./backend).
For our component, each chatbot message will consist of two keys: a `text` key that displays the text message and an optional list of media files that can be displayed underneath the text.
Import the `FileData` and `GradioModel` classes from `gradio.data_classes` and modify the existing `ChatbotData` class to look like the following:
```python
class FileMessage(GradioModel):
file: FileData
alt_text: Optional[str] = None
class MultimodalMessage(GradioModel):
text: Optional[str] = None
files: Optional[List[FileMessage]] = None
class ChatbotData(GradioRootModel):
root: List[Tuple[Optional[MultimodalMessage], Optional[MultimodalMessage]]]
class MultimodalChatbot(Component):
...
data_model = ChatbotData
```
Tip: The `data_model`s are implemented using `Pydantic V2`. Read the documentation [here](https://docs.pydantic.dev/latest/).
We've done the hardest part already!
| Part 2a - The backend data_model | https://gradio.app/guides/multimodal-chatbot-part1 | Custom Components - Multimodal Chatbot Part1 Guide |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.