Gradio 月活跃用户突破 100 万!

阅读更多
Gradio logo
  1. 其他教程
  2. 使用 Nginx 在您的 Web 服务器上运行 Gradio

使用 Nginx 在您的 Web 服务器上运行 Gradio 应用

简介

Gradio 是一个 Python 库,可让您为机器学习模型和数据处理管道快速创建可自定义的 Web 应用程序。Gradio 应用可以免费部署在 Hugging Face Spaces 上。

但在某些情况下,您可能希望在自己的 Web 服务器上部署 Gradio 应用。您可能已在使用高性能 Web 服务器 Nginx 来为您的网站(例如 https://www.example.com)提供服务,并且您希望将 Gradio 附加到您网站上的特定子路径(例如 https://www.example.com/gradio-demo)。

在本指南中,我们将指导您完成在您自己的 Web 服务器上的 Nginx 后面运行 Gradio 应用以实现此目的的过程。

先决条件

  1. 安装了 NginxGradio 的 Linux Web 服务器
  2. 保存在您的 Web 服务器上的 Python 文件中的工作 Gradio 应用

编辑您的 Nginx 配置文件

  1. 首先,编辑您的 Web 服务器上的 Nginx 配置文件。默认情况下,它位于:/etc/nginx/nginx.conf

http 块中,添加以下行以从单独的文件中包含服务器块配置

include /etc/nginx/sites-enabled/*;
  1. /etc/nginx/sites-available 目录中创建一个新文件(如果该目录尚不存在,请创建该目录),使用代表您的应用的文件名,例如:sudo nano /etc/nginx/sites-available/my_gradio_app

  2. 将以下内容粘贴到您的文件编辑器中

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-HostX-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;

在您的 Web 服务器上运行您的 Gradio 应用

  1. 在启动 Gradio 应用之前,您需要将 root_path 设置为与您在 Nginx 配置中指定的子路径相同。这对于 Gradio 在根域以外的任何子路径上运行是必要的。

    注意: 除了子路径之外,您还可以为 root_path 提供完整的 URL(以 httphttps 开头),在这种情况下,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")
  1. 通过键入 tmux 并按 Enter 键启动 tmux 会话(可选)

建议您在 tmux 会话中运行 Gradio 应用,以便您可以轻松地使其在后台运行

  1. 然后,启动您的 Gradio 应用。只需键入 python,后跟您的 Gradio Python 文件的名称。默认情况下,您的应用将在 localhost:7860 上运行,但如果它在不同的端口上启动,您将需要更新上面的 Nginx 配置文件。

重启 Nginx

  1. 如果您在 tmux 会话中,请键入 CTRL+B(或 CMD+B),然后按“D”键退出。

  2. 最后,通过运行 sudo systemctl restart nginx 重启 nginx。

就是这样!如果您在浏览器中访问 https://example.com/gradio-demo,您应该会在那里看到您的 Gradio 应用正在运行