跳到主要内容

Gradio Spaces

Gradio 提供了一个简单直观的界面,可以从一组输入中运行模型,并以图像、音频、3D 对象等多种格式展示输出。Gradio 现在甚至还提供了用于数据可视化的 Plot 输出组件,支持 Matplotlib、Bokeh 和 Plotly!更多内容可以查看 Gradio 团队的 Getting started 指南。

创建新 Space 时选择 Gradio 作为 SDK,会在 README.md 的 YAML 区块中将 sdk 属性设置为 gradio,从而自动使用最新版本的 Gradio 初始化 Space。如果你想使用特定的 Gradio 版本,可以编辑 sdk_version 属性。

你可以访问 Gradio 文档 了解其完整功能,并查看 Gradio Guides 中的教程,快速上手!

你的第一个 Gradio Space: Hot Dog Classifier

在下面的章节中,你将学习创建 Space、配置 Space 以及部署代码的基础流程。我们将使用 Gradio 创建一个 Hot Dog Classifier Space,用来演示 julien-c/hotdog-not-hotdog 模型,该模型可以检测给定图片中是否包含热狗 🌭

你可以在这里查看完成版示例:NimaBoscarino/hotdog-gradio

Create a new Gradio Space

我们先创建一个全新的 Space,并选择 Gradio 作为 SDK。Hugging Face Spaces 本质上是 Git 仓库,这意味着你可以通过推送 commit 以增量方式(并与他人协作)开发你的 Space。开始前可以先阅读 Getting Started with Repositories 指南,了解如何创建和编辑文件。

Add the dependencies

Hot Dog Classifier 中,我们将通过 🤗 Transformers pipeline 来使用模型,因此需要先安装一些依赖。这可以通过在仓库中创建 requirements.txt 文件并添加以下依赖来完成:

transformers
torch

Spaces 运行时会自动安装这些依赖。

Create the Gradio interface

要创建 Gradio 应用,在仓库中新建一个名为 app.py 的文件,并写入以下代码:

import gradio as gr
from transformers import pipeline

pipeline = pipeline(task="image-classification", model="julien-c/hotdog-not-hotdog")

def predict(input_img):
predictions = pipeline(input_img)
return input_img, {p["label"]: p["score"] for p in predictions}

gradio_app = gr.Interface(
predict,
inputs=gr.Image(label="Select hot dog candidate", sources=['upload', 'webcam'], type="pil"),
outputs=[gr.Image(label="Processed Image"), gr.Label(label="Result", num_top_classes=2)],
title="Hot Dog? Or Not?",
)

if __name__ == "__main__":
gradio_app.launch()

这个 Python 脚本使用 🤗 Transformers pipeline 加载 julien-c/hotdog-not-hotdog 模型,并通过 Gradio 接口对外提供服务。该 Gradio 应用会让你上传一张图片,然后将其分类为 hot dognot hot dog。将代码保存到 app.py 后,打开 Space 的 App 标签页,就可以看到你的应用在运行了!

Hot Dog ClassifierHot Dog Classifier

将 Gradio Space 嵌入到其他网页

你可以通过 Web Components 或 HTML <iframe> 标签,将 Gradio Space 嵌入到其他网页中。更多细节可以参考本仓库文档Gradio 文档