opensi·si

In this Guide, we dive more deeply into the various aspects of sharing a Gradio app with others. We will cover:

Sharing Your App

In this Guide, we dive more deeply into the various aspects of sharing a Gradio app with others. We will cover:

  1. Sharing demos with the share parameter
  2. Hosting on HF Spaces
  3. Sharing Deep Links
  4. Embedding hosted spaces
  5. Using the API page
  6. Accessing network requests
  7. Mounting within FastAPI
  8. Authentication
  9. MCP Servers
  10. Rate Limits
  11. Analytics
  12. Progressive Web Apps (PWAs)

Sharing Demos

Gradio demos can be easily shared publicly by setting share=True in the launch() method. Like this:

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: ** 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 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 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 to share your local server with specific users.

Hosting on HF Spaces

If you'd like to have a permanent link to your Gradio demo on the internet, use Hugging Face Spaces. Hugging Face Spaces provides the infrastructure to permanently host your machine learning model for free!

After you have created a free Hugging Face account, 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. See this guide how to host on Hugging Face Spaces for more information, or watch the embedded video:

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.

import gradio as gr
import random

def random_response(message, history):
    return random.choice(["Hi!", "Hello!", "Greetings!"])

with gr.Blocks() as demo:
    gr.ChatInterface(
        random_response,
        title="Greeting Bot",
        description="Ask anything and receive a nice greeting!",
        api_name="chat",
    )
    gr.DeepLinkButton()

if __name__ == "__main__":
    demo.launch(share=True)

Embedding Hosted Spaces

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).
  1. Add
<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:

<gradio-app
	src="https://abidlabs-pytorch-image-classifier.hf.space"
></gradio-app>

You can see examples of how web components look on the Gradio landing page.

You can also customize the appearance and behavior of your web component with attributes that you pass into the `` 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.

<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.

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:

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.

API Page

You can use almost any Gradio app as an API! In the footer of a Gradio app like this one, 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, or the JavaScript 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

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.

Accessing the Network Request Directly

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:

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.

Mounting Within Another FastAPI App

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:

コード(54 行)
"""
Test script for https://github.com/gradio-app/gradio/issues/11848
Gradio does not show media when FastAPI is behind a reverse proxy (root_path).

Simulates a reverse proxy by wrapping the FastAPI app in an outer
Starlette app mounted at /myapp. Gradio is mounted at /gradio inside.

Open http://localhost:8000/myapp/gradio/ to test.
"""

import os
from contextlib import asynccontextmanager

from fastapi import FastAPI
from starlette.applications import Starlette
from starlette.routing import Mount
import gradio as gr

CUSTOM_PATH = "/gradio"
PROXY_PREFIX = "/myapp"

app = FastAPI()

@app.get("/")
def read_main():
    return {"message": "This is your main app"}

def identity(image):
    return image

demo = gr.Interface(
    fn=identity,
    inputs=gr.Image(type="filepath"),
    outputs=gr.Image(label="Output Image"),
)

app = gr.mount_gradio_app(app, demo, path=CUSTOM_PATH, root_path=f"{PROXY_PREFIX}{CUSTOM_PATH}")

@asynccontextmanager
async def lifespan(outer_app):
    async with app.router.lifespan_context(app):
        yield

outer_app = Starlette(
    routes=[Mount(PROXY_PREFIX, app=app)],
    lifespan=lifespan,
)

if __name__ == "__main__":
    import uvicorn

    port = int(os.environ.get("GRADIO_SERVER_PORT", 8000))
    print(f"\nOpen http://localhost:{port}{PROXY_PREFIX}{CUSTOM_PATH}/\n")
    uvicorn.run(outer_app, host="0.0.0.0", port=port)

Note that this approach also allows you run your Gradio apps on custom paths (`` in the example above).