Gradio 是一个 Python 库,可让您快速为机器学习模型和数据处理管道创建可定制的 Web 应用程序。Gradio 应用程序可以免费部署在 Hugging Face Spaces 上。
但在某些情况下,您可能希望将 Gradio 应用程序部署到自己的 Web 服务器上。您可能已经在使用 Nginx(一个高性能 Web 服务器)来为您的网站(例如 https://www.example.com)提供服务,并且您希望将 Gradio 附加到您网站上的特定子路径(例如 https://www.example.com/gradio-demo)。
在本指南中,我们将指导您完成在自己的 Web 服务器上在 Nginx 后面运行 Gradio 应用程序以实现此目的的过程。
先决条件
/etc/nginx/nginx.conf在 http 块中,添加以下行以包含来自单独文件的服务器块配置
include /etc/nginx/sites-enabled/*;在 /etc/nginx/sites-available 目录中创建新文件(如果目录不存在,则创建它),使用代表您的应用程序的文件名,例如:sudo nano /etc/nginx/sites-available/my_gradio_app
将以下内容粘贴到您的文件编辑器中
server {
listen 80;
server_name example.com www.example.com; # Change this to your domain name
location /gradio-demo/ { # Change this if you'd like to server your Gradio app on a different path
proxy_pass http://127.0.0.1:7860/; # Change this if your Gradio app will be running on a different port
proxy_buffering off;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
}
}设置 X-Forwarded-Host 和 X-Forwarded-Proto 标头非常重要,因为 Gradio 会使用这些标头以及下面讨论的 root_path 参数来构建您的应用程序正在服务的公共 URL。Gradio 使用公共 URL 来获取各种静态资源。如果未设置这些标头,您的 Gradio 应用程序可能会以损坏状态加载。
注意: $host 变量不包括主机端口。如果您正在为 Gradio 应用程序提供原始 IP 地址和端口,则应改为在这些行中使用 $http_host 变量
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;在启动 Gradio 应用程序之前,您需要将 root_path 设置为与 Nginx 配置中指定的子路径相同。这对于 Gradio 在域的根目录之外的任何子路径上运行是必需的。
注意:您可以提供一个完整的 URL 作为 root_path(以 http 或 https 开头),而不是子路径,在这种情况下,root_path 将被视为绝对 URL 而不是 URL 后缀(但在这种情况下,如果域发生更改,您需要更新 root_path)。
这是一个 Gradio 应用程序的简单示例,其自定义 root_path 对应于上面的 Nginx 配置。
import gradio as gr
import time
def test(x):
time.sleep(4)
return x
gr.Interface(test, "textbox", "textbox").queue().launch(root_path="/gradio-demo")tmux 并按 Enter 键启动 tmux 会话(可选)建议您在 tmux 会话中运行 Gradio 应用程序,以便您可以轻松地使其在后台运行
python,后跟 Gradio python 文件的名称。默认情况下,您的应用程序将在 localhost:7860 上运行,但如果它在不同的端口上启动,您需要更新上面的 nginx 配置文件。如果您在 tmux 会话中,请按 CTRL+B(或 CMD+B),然后按“D”键退出。
最后,通过运行 sudo systemctl restart nginx 重新启动 nginx。
就是这样!如果您在浏览器上访问 https://example.com/gradio-demo,您应该会看到您的 Gradio 应用程序在那里运行