Hub 文件
Spaces 作為 API 端點
並獲得增強的文件體驗
開始使用
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 的頁尾都有一個「Use via API」(透過 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 parametersPython 客戶端
安裝
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 權杖(Token)。對於私人 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"]}'Response
{"event_id": "abc123"}步驟 2:獲取結果
curl -N "https://abidlabs-en2fr.hf.space/gradio_api/call/predict/abc123" \
-H "Authorization: Bearer $HF_TOKEN"回應(Server-Sent Events)
event: complete
data: ["Bonjour, le monde!"]私有 Spaces 需要 Authorization 標頭,且該標頭可為公開 Spaces 提供更好的速率限制。
ZeroGPU Spaces
ZeroGPU Spaces 根據您的帳戶類型設有使用配額
| 帳戶類型 | 包含的每日 GPU 配額 |
|---|---|
| 未經身份驗證 | 2 分鐘 |
| 免費帳戶 | 5 分鐘 |
| PRO 帳戶 | 40 分鐘 |
當您使用權杖進行身份驗證時,將會消耗您帳戶的 GPU 配額。未經身份驗證的請求會使用共用資源池,且限制更嚴格。
PRO、Team 和 Enterprise 使用者可以使用預付點數,以每 10 分鐘 GPU 時間 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 呼叫 Space
當從您自己的 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 可用,您有時需要找到針對特定任務的 Space。
curl -s "https://huggingface.co/api/spaces/semantic-search?q=text+to+speech&sdk=gradio"這會回傳按語意關聯性排序的 Spaces,其中包含包含 Space ID、按讚數和簡短說明的元資料。使用 sdk=gradio 參數來篩選出公開 API 的 Spaces。