Hub documentation

Spaces 作为 API 端点

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Spaces 作为 API 端点

Hugging Face 上的每个 Gradio Space 都自动作为 API 端点可用。您可以从 Python、JavaScript 或任何 HTTP 客户端调用它。如果您能在浏览器中使用某个 Space,就可以将其作为 API 调用。

快速入门

安装 Python 客户端并调用任意公共 Space:

pip install --upgrade gradio_client
from gradio_client import Client

client = Client("abidlabs/en2fr", token="hf_...")
result = client.predict("Hello, world!", api_name="/predict")
print(result)  # "Bonjour, le monde!"

查看可用的 API 端点

每个 Gradio Space 的页脚中都有一个“通过 API 使用”链接。点击它即可查看:

  • 所有可用端点及其名称
  • 参数类型和描述
  • Python 和 JavaScript 的自动生成代码片段
  • 一个可从您的 UI 交互生成代码的 API 记录器

每个 Space 还会在以下位置公开一个 OpenAPI 规范:

https://<space-subdomain>.hf.space/gradio_api/openapi.json

例如:https://abidlabs-en2fr.hf.space/gradio_api/openapi.json

这有助于理解完整的 API 架构,并将其集成到您自己的应用程序中。

您也可以通过编程方式检查端点:

from gradio_client import Client

client = Client("abidlabs/whisper", token="hf_...")
client.view_api()  # Prints all endpoints with parameters

Python 客户端

安装

pip install --upgrade gradio_client

需要 Python 3.10+。

连接到 Space

from gradio_client import Client

# Public Space
client = Client("username/space-name")

# Private Space (requires token)
client = Client("username/private-space", token="hf_xxxxx")

在 https://huggingface.co/settings/tokens 获取您的 Hugging Face 令牌。对于私有 Spaces,您需要一个具有 READ 权限的令牌。

进行预测

同步(阻塞):

result = client.predict("Hello", api_name="/predict")

异步(非阻塞):

job = client.submit("Hello", api_name="/predict")
# Do other work...
result = job.result()  # Get result when ready

处理文件

对于任何文件输入,请使用 handle_file():

from gradio_client import Client, handle_file

client = Client("abidlabs/whisper", token="hf_...")

# From local file
result = client.predict(audio=handle_file("audio.wav"), api_name="/predict")

# From URL
result = client.predict(audio=handle_file("https://example.com/audio.wav"), api_name="/predict")

监控任务状态

job = client.submit("Hello", api_name="/predict")

# Check status
status = job.status()
print(f"Queue position: {status.rank}, ETA: {status.eta}")

# Check if complete
if job.done():
    result = job.result()

# Cancel a pending job
job.cancel()

流式/生成器端点

对于返回多个输出的端点:

job = client.submit(prompt="Write a story", api_name="/generate")

# Iterate over streaming outputs
for output in job:
    print(output)

JavaScript 客户端

安装

npm i @gradio/client

或通过 CDN 使用:

<script type="module">
  import { Client } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js";
</script>

连接与预测

import { Client } from "@gradio/client";

const app = await Client.connect("abidlabs/en2fr", { token: "hf_..." });
const result = await app.predict("/predict", ["Hello"]);
console.log(result.data);

处理文件

import { Client, handle_file } from "@gradio/client";

const app = await Client.connect("abidlabs/whisper", { token: "hf_..." });
const result = await app.predict("/predict", [
  handle_file("https://example.com/audio.wav")
]);

流式结果

const job = app.submit("/predict", ["Hello"]);

for await (const message of job) {
  if (message.type === "data") {
    console.log("Result:", message.data);
  }
  if (message.type === "status") {
    console.log("Queue position:", message.position);
  }
}

REST API(curl)

您也可以在不使用任何客户端库的情况下,直接通过 HTTP 调用 Gradio Spaces。

基于队列的 API(推荐)

大多数 Spaces 使用两步流程:

第 1 步:提交您的请求

curl -X POST "https://abidlabs-en2fr.hf.space/gradio_api/call/predict" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $HF_TOKEN" \
  -d '{"data": ["Hello, world"]}'

响应:

{"event_id": "abc123"}

步骤 2:获取结果

curl -N "https://abidlabs-en2fr.hf.space/gradio_api/call/predict/abc123" \
  -H "Authorization: Bearer $HF_TOKEN"

响应(服务器发送事件):

event: complete
data: ["Bonjour, le monde!"]

Authorization 请求头对于私有 Spaces 是必需的,并且可以为公共 Spaces 提供更好的速率限制。

ZeroGPU Spaces

ZeroGPU Spaces 的使用配额基于您的账户类型:

账户类型每日 GPU 配额
未认证2 分钟
免费账户5 分钟
PRO 账户40 分钟

使用令牌进行身份验证时,将消耗您账户的 GPU 配额。未验证的请求则使用限制更严格的共享资源池。

PRO、Team 和 Enterprise 用户可以通过预付费额度超出其每日包含的配额,GPU 时间的费率为每 10 分钟 1 美元。

您可以订阅 PRO,以获取每天 40 分钟的 GPU 配额、更高的队列优先级,以及使用积分扩展配额的功能。

常见模式

FastAPI 集成

from fastapi import FastAPI
from gradio_client import Client, handle_file

app = FastAPI()
client = Client("abidlabs/whisper", token="hf_...")

@app.post("/transcribe/")
async def transcribe(file_url: str):
    result = client.predict(audio=handle_file(file_url), api_name="/predict")
    return {"transcription": result}

使用重试进行错误处理

import time
from gradio_client import Client

def predict_with_retry(client, *args, max_retries=3, **kwargs):
    for attempt in range(max_retries):
        try:
            return client.predict(*args, **kwargs)
        except Exception as e:
            if attempt < max_retries - 1:
                time.sleep(2 ** attempt)  # Exponential backoff
            else:
                raise

client = Client("username/space", token="hf_...")
result = predict_with_retry(client, "input", api_name="/predict")

从另一个 Space 调用 Spaces

从您自己的 Gradio 应用调用 ZeroGPU Space 时,请转发用户的身份验证信息:

import gradio as gr
from gradio_client import Client

def process(prompt, request: gr.Request):
    x_ip_token = request.headers.get('x-ip-token', '')
    client = Client("owner/zerogpu-space", headers={"x-ip-token": x_ip_token})
    return client.predict(prompt, api_name="/predict")

demo = gr.Interface(fn=process, inputs="text", outputs="text")
demo.launch()

通过语义搜索查找 Spaces

拥有数千个 Gradio Spaces,有时您希望找到适用于特定任务的一个:

curl -s "https://huggingface.co/api/spaces/semantic-search?q=text+to+speech&sdk=gradio"

这将返回按语义相关性排序的 Spaces,元数据包括 Space ID、点赞数和简短描述。使用 sdk=gradio 参数可筛选出提供 API 的 Spaces。

了解更多

Update on GitHub