分享你的应用

如何分享你的 Gradio 应用程序:

How to share your Gradio app:

  1. 使用共享参数共享演示

    Sharing demos with the share parameter

  2. 在 HF Spaces 上托管

    Hosting on HF Spaces

  3. 嵌入托管空间

    Embedding hosted spaces

  4. 嵌入 Web 组件

    Embedding with web components

  5. 使用 API 页面

    Using the API page

  6. 在页面中添加身份验证

    Adding authentication to the page

  7. 访问网络请求

    Accessing Network Requests

  8. 在 FastAPI 中挂载

    Mounting within FastAPI

  9. 安全

    Security

分享演示

通过在 launch() 方法中设置 share=True 可以轻松公开共享 Gradio 演示。 像这样:

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

demo.launch(share=True)

这会生成一个公共的、可共享的链接,你可以将其发送给任何人! 当你发送此链接时,另一端的用户可以在他们的浏览器中试用该模型。 因为处理发生在你的设备上(只要你的设备保持开启状态!),你不必担心任何打包任何依赖项。 分享链接通常看起来像这样: XXXXX.gradio.app 。 虽然链接是通过 Gradio URL 提供的,但我们只是你本地服务器的代理,不会存储通过你的应用发送的任何数据。

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: XXXXX.gradio.app. Although the link is served through a Gradio URL, we are only a proxy for your local server, and do not store any data sent through your app.

但是请记住,这些链接是可公开访问的,这意味着任何人都可以使用你的模型进行预测! 因此,请确保不要通过你编写的函数暴露任何敏感信息,或让你的设备发生任何重大更改。 如果你设置 share=False (默认设置,colab notebooks 除外),则只会创建一个本地链接,该链接可以通过端口转发与特定用户共享。

Keep in mind, however, that these 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. If you set share=False (the default, except in colab notebooks), only a local link is created, which can be shared by port-forwarding with specific users.

共享链接在 72 小时后过期。

Share links expire after 72 hours.

在 HF Spaces 上托管

如果你想在互联网上拥有指向你的 Gradio 演示的永久链接,请使用 Hugging Face Spaces。 Hugging Face 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!

创建免费的 Hugging Face 帐户后,你可以通过三种方法将 Gradio 应用程序部署到 Hugging Face Spaces:

After you have created a free Hugging Face account, you have three methods to deploy your Gradio app to Hugging Face Spaces:

  1. 从终端:在你的应用程序目录中运行 gradio deploy 。 CLI 将收集一些基本元数据,然后启动你的应用程序。 要更新你的空间,你可以重新运行此命令或启用 Github 操作选项以自动更新 git push 上的空间。

    From terminal: run gradio deploy in your app directory. The CLI will gather some basic metadata and then launch your app. To update your space, you can re-run this command or enable the Github Actions option to automatically update the Spaces on git push.

  2. 从你的浏览器:将包含你的 Gradio 模型和所有相关文件的文件夹拖放到此处

    From your browser: Drag and drop a folder containing your Gradio model and all related files here.

  3. 将 Spaces 与你的 Git 存储库连接,Spaces 将从那里拉取 Gradio 应用程序。 有关详细信息,请参阅本指南如何在 Hugging Face Spaces 上主持

    Connect Spaces with your Git repository and Spaces will pull the Gradio app from there. See this guide how to host on Hugging Face Spaces for more information.

嵌入托管空间

在 Hugging Face Spaces(或你自己的服务器)上托管你的应用程序后,你可能希望将演示嵌入其他网站,例如你的博客或你的作品集。 嵌入交互式演示允许人们试用你构建的机器学习模型,而无需下载或安装任何东西——就在他们的浏览器中! 最好的部分是你甚至可以在 GitHub 页面等静态网站中嵌入交互式演示。

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.

有两种方法可以嵌入你的 Gradio 演示。 你可以直接在“拥抱面部空间”页面上的“嵌入此空间”下拉选项中找到这两个选项的快速链接:

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:

Embed this Space dropdown option

嵌入 Web 组件

Embedding with Web Components

Web 组件通常为用户提供比 IFrame 更好的体验。 Web 组件延迟加载,这意味着它们不会减慢你网站的加载时间,并且它们会根据 Gradio 应用程序的大小自动调整高度。

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.

嵌入 Web 组件:

To embed with Web Components:

  1. 通过在你的站点中添加以下脚本,将 gradio JS 库导入到你的站点中(将 URL 中的 {GRADIO_VERSION} 替换为你正在使用的 Gradio 库版本)。

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

    <div class='codeblock'><pre><code class='lang-html'> &lt;script type="module" src="https://gradio.s3-us-west-2.amazonaws.com/{GRADIO_VERSION}/gradio.js"> &lt;/script> </code></pre></div> </code></pre></div>

  2. 添加

    Add

    `

       <gradio-app src="https://$yourspacehost.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>
    
    

`

你可以查看 Web 组件外观的示例

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

你还可以使用传递给 <gradio-app> 标记的属性自定义 Web 组件的外观和行为:

You can also customize the appearance and behavior of your web component with attributes that you pass into the <gradio-app> tag:

下面是一个示例,说明如何使用这些属性创建一个不延迟加载且初始高度为 0px 的 Gradio 应用程序。

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>

_ 注意:虽然 Gradio 的 CSS 永远不会影响嵌入页面,但嵌入页面会影响嵌入的 Gradio 应用程序的样式。_ _ 确保父页面中的任何 CSS 都不会过于通用,以至于它也可以应用于嵌入式 Gradio 应用程序并导致样式中断。_ header { ... }footer { ... } 等元素选择器最有可能导致问题。

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.

嵌入 IFrame

Embedding with IFrames

要改为嵌入 IFrame(例如,如果你无法将 javascript 添加到你的网站),请添加此元素:

To embed with IFrames instead (if you cannot add javascript to your website, for example), add this element:

<iframe src="https://$your_space_host.hf.space"></iframe>

同样,你可以找到空间嵌入 URL 的 src= 属性,你可以在“嵌入此空间”按钮中找到它。

Again, you can find the src= attribute to your Space's embed URL, which you can find in the "Embed this Space" button.

注意:如果你使用 IFrame,你可能需要添加固定 height 属性并设置 style="border:0;" 去除钻孔器。 此外,如果你的应用需要访问网络摄像头或麦克风等权限,你还需要使用 allow 属性提供这些权限。

Note: if you use IFrames, you'll probably want to add a fixed height attribute and set style="border:0;" to remove the boreder. 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 页面

如果你单击并打开上面的空间,你将在应用程序的页脚中看到一个“通过 API 使用”链接。

If you click and open the space above, you'll see a "Use via API" link in the footer of the app.

Use via API

这是记录用户可用于查询 Interface 功能的 REST API 的页面。 Blocks 应用程序也可以生成一个 API 页面,尽管必须为每个事件侦听器显式命名 API,例如

This is a page that documents the REST API that users can use to query the Interface function. Blocks apps can also generate an API page, though the API has to be explicitly named for each event listener, such as

btn.click(add, [num1, num2], output, api_name="addition")

这会将端点 /api/addition/ 记录到自动生成的 API 页面。

This will document the endpoint /api/addition/ to the automatically generated API page.

注意:对于启用队列的Gradio 应用程序,如果用户向你的 API 端点发出 POST 请求,则可以绕过队列。 要禁用此行为,请在 queue() 方法中设置 api_open=False

Note: For Gradio apps in which queueing is enabled, users can bypass the queue if they make a POST request to your API endpoint. To disable this behavior, set api_open=False in the queue() method.

验证

你可能希望在你的应用程序前面放置一个身份验证页面,以限制谁可以打开你的应用程序。 使用 launch() 方法中的 auth= 关键字参数,你可以提供一个包含用户名和密码的元组,或可接受的用户名/密码元组列表; 下面是一个为名为“admin”的单个用户提供基于密码的身份验证的示例:

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":

demo.launch(auth=("admin", "pass1234"))

对于更复杂的身份验证处理,你甚至可以传递一个函数,该函数将用户名和密码作为参数,并返回 True 以允许身份验证,否则返回 False。 这可用于向 3rd 方身份验证服务发出请求等。

For more complex authentication handling, you can even pass a function that takes a username and password as arguments, and returns True to allow authentication, False otherwise. This can be used for, among other things, making requests to 3rd-party authentication services.

下面是一个函数示例,它接受用户名和密码相同的任何登录:

Here's an example of a function that accepts any login where the username and password are the same:

def same_auth(username, password):
    return username == password
demo.launch(auth=same_auth)

为使身份验证正常工作,必须在你的浏览器中启用第三方 cookie。 默认情况下,Safari、Chrome 隐身模式不是这种情况。

For authentication to work properly, third party cookies must be enabled in your browser. This is not the case by default for Safari, Chrome Incognito Mode.

直接访问网络请求

当用户对你的应用做出预测时,你可能需要底层网络请求,以便获取请求标头(例如用于高级身份验证)、记录客户端的 IP 地址或其他原因。 Gradio 以类似于 FastAPI 的方式支持这一点:只需添加一个类型提示为 gr.Request 函数参数,Gradio 就会将网络请求作为该参数传入。 这是一个例子:

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, 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(name, request: gr.Request):
    if request:
        print("Request headers dictionary:", request.headers)
        print("IP address:", request.client.host)
    return name

io = gr.Interface(echo, "textbox", "textbox").launch()

注意:如果你的函数是直接调用的,而不是通过 UI 调用的(例如,当示例被缓存时会发生这种情况),则 request 将为 None 。 你应该明确处理这种情况,以确保你的应用不会抛出任何错误。 这就是为什么我们有明确的检查 if request

Note: if your function is called directly instead of through the UI (this happens, for example, when examples are cached), 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.

在另一个 FastAPI 应用程序中安装

在某些情况下,你可能有一个现有的 FastAPI 应用程序,并且你想要为 Gradio 演示添加一个路径。 你可以使用 gradio.mount_gradio_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:

from fastapi import FastAPI
import gradio as gr

CUSTOM_PATH = "/gradio"

app = FastAPI()


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


io = gr.Interface(lambda x: "Hello, " + x + "!", "textbox", "textbox")
app = gr.mount_gradio_app(app, io, path=CUSTOM_PATH)


# Run this from the terminal as you would normally start a FastAPI app: `uvicorn run:app`
# and navigate to http://localhost:8000/gradio in your browser.

请注意,此方法还允许你在自定义路径(上例中的 http://localhost:8000/gradio )上运行 Gradio 应用程序。

Note that this approach also allows you run your Gradio apps on custom paths (http://localhost:8000/gradio in the example above).

安全和文件访问

与他人共享你的 Gradio 应用程序(通过将其托管在 Spaces、你自己的服务器上或通过临时共享链接)会将主机上的某些文件公开给你的 Gradio 应用程序的用户。

Sharing your Gradio app with others (by hosting it on Spaces, on your own server, or through temporary share links) exposes certain files on the host machine to users of your Gradio app.

特别是,Gradio 应用程序允许用户访问三种文件:

In particular, Gradio apps ALLOW users to access to three kinds of files:

Gradio 不允许访问:

Gradio DOES NOT ALLOW access to:

请确保你正在运行最新版本的 gradio 以应用这些安全设置。

Please make sure you are running the latest version of gradio for these security settings to apply.