Gradio 代理与 MCP 黑客马拉松
获奖者Gradio 代理与 MCP 黑客马拉松
获奖者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
变量不包含主机端口。如果您通过原始 IP 地址和端口来服务您的 Gradio 应用,您应该在这些行中使用 $http_host
变量代替。
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;
在启动 Gradio 应用之前,您需要将 root_path
设置为与您在 Nginx 配置中指定的子路径相同。这对于 Gradio 在域名根路径以外的任何子路径上运行都是必需的。
注意:除了子路径,您还可以为 root_path
提供一个完整的 URL(以 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
并按回车键来启动一个 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 应用在那里运行了。