NLP Course documentation

與 Hugging Face Hub 整合

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

與 Hugging Face Hub 整合

Open In Colab Open In Studio Lab

為了讓你的生活更輕鬆, Gradio 直接與 Hugging Face Hub 和 Hugging Face Spaces 集成。你可以僅使用 一行代碼 從中心和空間加載演示。

從 Hugging Face Hub 加載模型

首先, 從 Hugging Face 通過 Hub 提供的數千個模型中選擇一個, 如 第四章 中所述。

使用特殊的 Interface.load() 方法, 你可以傳遞 "model/" (或者, 等效的, "huggingface/") 後面是模型名稱。例如, 這裡是為大型語言模型 GPT-J構建演示的代碼, 添加幾個示例輸入:

import gradio as gr

title = "GPT-J-6B"
description = "Gradio Demo for GPT-J 6B, a transformer model trained using Ben Wang's Mesh Transformer JAX. 'GPT-J' refers to the class of model, while '6B' represents the number of trainable parameters. To use it, simply add your text, or click one of the examples to load them. Read more at the links below."
article = "<p style='text-align: center'><a href='https://github.com/kingoflolz/mesh-transformer-jax' target='_blank'>GPT-J-6B: A 6 Billion Parameter Autoregressive Language Model</a></p>"
examples = [
    ["The tower is 324 metres (1,063 ft) tall,"],
    ["The Moon's orbit around Earth has"],
    ["The smooth Borealis basin in the Northern Hemisphere covers 40%"],
]
gr.Interface.load(
    "huggingface/EleutherAI/gpt-j-6B",
    inputs=gr.Textbox(lines=5, label="Input Text"),
    title=title,
    description=description,
    article=article,
    examples=examples,
    enable_queue=True,
).launch()

上述代碼將生成以下界面:

以這種方式加載模型使用 Hugging Face 的 Inference API,而不是將模型加載到內存中。這對於像 GPT-J 或 T0pp這樣需要大量 RAM 的大型模型是理想的。

從 Hugging Face Spaces 空間加載

要從hugs Face Hub加載任何空間並在本地重新創建它, 你可以將 spaces/ 傳遞給 Interface, 再加上空間的名稱。

還記得第 1 節中刪除圖像背景的演示嗎? 讓我們從 Hugging Face Spaces 加載它:

gr.Interface.load("spaces/abidlabs/remove-bg").launch()

從Hub或Spaces加載演示的一個很酷的地方是, 你可以通過覆蓋任何參數來自定義它們。在這裡, 我們添加一個標題並讓它與網絡攝像頭一起使用:

gr.Interface.load(
    "spaces/abidlabs/remove-bg", inputs="webcam", title="Remove your webcam background!"
).launch()

現在我們已經探索了幾種將Gradio與hugs Face Hub集成的方法, 讓我們來看看 Interface 類的一些高級功能。這就是下一節的主題!