API 엔드포인트로서의 Spaces
API 엔드포인트로서의 Spaces
허깅페이스의 모든 Gradio Space는 자동으로 API 엔드포인트로 사용할 수 있어요. Python, JavaScript, 또는 어떤 HTTP 클라이언트에서든 호출할 수 있죠. 브라우저에서 Space를 쓸 수 있다면 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" 링크가 있어요. 클릭하면 다음을 볼 수 있어요:
- 사용 가능한 모든 엔드포인트와 이름
- 파라미터 타입과 설명
- Python과 JavaScript용 자동 생성 코드 스니펫
- UI 상호작용에서 코드를 생성하는 API Recorder
또한 모든 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")
[!TIP] Hugging Face 토큰은 https://huggingface.co/settings/tokens에서 받아요. 프라이빗 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 상태 모니터링
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()
스트리밍/Generator 엔드포인트
여러 출력을 내는 엔드포인트의 경우:
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 (권장)
대부분의 Space는 두 단계 과정을 사용해요:
1단계: 요청 제출
curl -X POST "https://abidlabs-en2fr.hf.space/gradio_api/call/predict" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ***" \
-d '{"data": ["Hello, world"]}'
응답:
{"event_id": "abc123"}
2단계: 결과 가져오기
curl -N "https://abidlabs-en2fr.hf.space/gradio_api/call/predict/abc123" \
-H "Authorization: Bearer ***"
응답 (Server-Sent Events):
event: complete
data: ["Bonjour, le monde!"]
Authorization 헤더는 프라이빗 Spaces에 필요하며, 공개 Spaces에서는 더 나은 rate limit을 줘요.
ZeroGPU Spaces
ZeroGPU Spaces에는 계정 유형에 따른 사용량 할당량이 있어요:
| 계정 유형 | 포함된 일일 GPU 할당량 |
|---|---|
| 비인증 (Unauthenticated) | 2분 |
| 무료 계정 (Free account) | 5분 |
| PRO 계정 | 40분 |
토큰으로 인증하면 계정의 GPU 할당량이 소모돼요. 비인증 요청은 제한이 더 엄격한 공유 풀을 사용해요.
PRO, Team, Enterprise 사용자는 선불 크레딧으로 GPU 시간 10분당 $1 요율로 포함된 일일 할당량을 넘어설 수 있어요.
[!TIP] PRO 구독으로 일일 GPU 할당량 40분, 더 높은 큐 우선순위, 그리고 크레딧으로 할당량을 늘릴 수 있는 기능을 얻을 수 있어요.
일반적인 패턴
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가 있으니, 특정 작업에 맞는 것을 찾고 싶을 때가 있어요:
curl -s "https://huggingface.co/api/spaces/semantic-search?q=text+to+speech&sdk=gradio"
이것은 시맨틱 관련성으로 정렬된 Spaces를 반환하며, Space ID, 좋아요, 짧은 설명을 포함한 메타데이터를 담아요. sdk=gradio 파라미터를 사용해 API를 노출하는 Spaces만 필터링할 수 있어요.
더 알아보기 (Learn more)
- Gradio Python Client Guide
- Gradio JavaScript Client Guide
- Querying Gradio Apps with curl
- Spaces ZeroGPU
더 알아보기 (Learn more)
- 모든 Gradio Space는
gradio_client(Python) 또는@gradio/client(JS)로 API 호출할 수 있어요. - ZeroGPU Space는 계정 유형별로 일일 GPU 할당량이 달라요.