如何分享你的 Gradio 应用程序:
How to share your Gradio app:
通过在 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.
如果你想在互联网上拥有指向你的 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:
从终端:在你的应用程序目录中运行 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.
从你的浏览器:将包含你的 Gradio 模型和所有相关文件的文件夹拖放到此处。
From your browser: Drag and drop a folder containing your Gradio model and all related files here.
将 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:

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:
通过在你的站点中添加以下脚本,将 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'> <script type="module"
src="https://gradio.s3-us-west-2.amazonaws.com/{GRADIO_VERSION}/gradio.js">
</script>
</code></pre></div>
</code></pre></div>
添加
Add
`
<gradio-app src="https://$yourspacehost.hf.space"></gradio-app>
<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:
src :正如我们所见, src 属性链接到你想要嵌入的托管 Gradio 演示的 URL
src: as we've seen, the src attributes links to the URL of the hosted Gradio demo that you would like to embed
space :如果你的 Gradio 演示托管在 Hugging Face Space 上,则为可选的速记。 接受 username/space_name 而不是完整的 URL。 示例: gradio/Echocardiogram-Segmentation 。 如果提供了这个 attribute 属性,则不需要提供 src 。
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 :一个布尔值,指定页面的 html 标题是否应设置为 Gradio 应用程序的标题(默认为 "false" )
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 :加载 Gradio 应用程序时 Web 组件的初始高度(默认为 "300px" )。 请注意,最终高度是根据 Gradio 应用程序的大小设置的。
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 :是否显示边框和有关空间托管位置的信息(默认情况下为 "true" )
container: whether to show the border frame and information about where the Space is hosted (by default "true")
info :是否仅显示有关空间在嵌入式应用程序下托管位置的信息(默认情况下为 "true" )
info: whether to show just the information about where the Space is hosted underneath the embedded app (by default "true")
autoscroll :预测完成后是否自动滚动到输出(默认为 "false" )
autoscroll: whether to autoscroll to the output when prediction has finished (by default "false")
eager :是否在页面加载后立即加载 Gradio 应用程序(默认为 "false" )
eager: whether to load the Gradio app as soon as the page loads (by default "false")
theme_mode :是否使用 dark 、 light 或默认 system 主题模式(默认为 "system" )
theme_mode: whether to use the dark, light, or default system theme mode (by default "system")
下面是一个示例,说明如何使用这些属性创建一个不延迟加载且初始高度为 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(例如,如果你无法将 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 使用”链接。
If you click and open the space above, you'll see a "Use via API" link in the footer of the app.

这是记录用户可用于查询 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 应用程序,并且你想要为 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 脚本的路径是 /home/usr/scripts/project/app.py 并且你从 /home/usr/scripts/project/ 启动它,那么你共享的 Gradio 应用程序的用户将能够访问 /home/usr/scripts/project/ 中的任何文件。 这样做是为了让你可以轻松地在你的 Gradio 应用程序中引用这些文件(例如,你的应用程序的 examples )。
Files in the same directory (or a subdirectory) of where the Gradio script is launched from. For example, if the path to your gradio scripts is /home/usr/scripts/project/app.py and you launch it from /home/usr/scripts/project/, then users of your shared Gradio app will be able to access any files inside /home/usr/scripts/project/. This is done so that you can easily reference these files in your Gradio app (e.g. for your app's examples).
Gradio 创建的临时文件。 这些文件是由 Gradio 创建的,作为运行预测功能的一部分。 例如,如果你的预测函数返回一个视频文件,那么 Gradio 会将该视频保存到一个临时文件中,然后将临时文件的路径发送到前端。 你可以通过将环境变量 GRADIO_TEMP_DIR 设置为绝对路径来自定义 Gradio 创建的临时文件的位置,例如 /home/usr/scripts/project/temp/ 。
Temporary files created by Gradio. These are files that are created by Gradio as part of running your prediction function. For example, if your prediction function returns a video file, then Gradio will save that video to a temporary file and then send the path to the temporary file to the front end. You can customize the location of temporary files created by Gradio by setting the environment variable GRADIO_TEMP_DIR to an absolute path, such as /home/usr/scripts/project/temp/.
你通过 launch() 中的 allowed_paths 参数明确允许的文件。 此参数允许你传入你希望允许用户访问的附加目录或确切文件路径的列表。 (默认情况下,此参数为空列表)。
Files that you explicitly allow via 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).
Gradio 不允许访问:
Gradio DOES NOT ALLOW access to:
点文件(名称以 '.' 开头的任何文件)或名称以 '.'
Dotfiles (any files whose name begins with '.') or any files that are contained in any directory whose name begins with '.'
你通过 launch() 中的 blocked_paths 参数明确允许的文件。 你可以将附加目录列表或确切文件路径传递给 launch() 中的 blocked_paths 参数。 此参数优先于 Gradio 默认或通过 allowed_paths ths 公开的文件。
Files that you explicitly allow 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.
主机上的任何其他路径。 用户不应该能够访问主机上的其他任意路径。
Any other paths on the host machine. Users should NOT be able to access other arbitrary paths on the host.
请确保你正在运行最新版本的 gradio 以应用这些安全设置。
Please make sure you are running the latest version of gradio for these security settings to apply.