# API 엔드포인트로 사용하는 Spaces

Hugging Face의 모든 Gradio Space는 자동으로 API 엔드포인트로 제공됩니다. Python, JavaScript 또는 기타 HTTP 클라이언트에서 호출할 수 있습니다. 브라우저에서 Space를 사용할 수 있다면, API로 호출할 수 있습니다.

## 빠른 시작

Python 클라이언트를 설치하고 공개된 Space를 호출합니다:

```bash
pip install --upgrade gradio_client
```

```python
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 레코더

각 Space는 다음 위치에 OpenAPI 사양을 노출합니다:

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

예를 들어: `https://abidlabs-en2fr.hf.space/gradio_api/openapi.json`

전체 API 스키마를 이해하고 이를 자체 애플리케이션에 통합하는 데 유용합니다.

엔드포인트를 프로그래매틱으로 검사할 수도 있습니다:

```python
from gradio_client import Client

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

## Python 클라이언트

### 설치

```bash
pip install --upgrade gradio_client
```

Python 3.10 이상이 필요합니다.

### Space에 연결

```python
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](https://huggingface.co/settings/tokens)에서 발급받을 수 있습니다. 비공개 Spaces의 경우 **READ** 권한이 있는 토큰이 필요합니다.

### 예측 수행

**동기식(블로킹):**

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

**비동기(블로킹되지 않음):**

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

### 파일 처리

모든 파일 입력에는 `handle_file()`를 사용하세요:

```python
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")
```

### 작업 상태 모니터링

```python
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()
```

### 스트리밍/제너레이터 엔드포인트

여러 출력을 반환하는 엔드포인트의 경우:

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

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

## JavaScript 클라이언트

### 설치

```bash
npm i @gradio/client
```

또는 CDN을 통해 사용:

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

### 연결 및 예측

```javascript
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);
```

### 파일 처리

```javascript
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")
]);
```

### 결과 스트리밍

```javascript
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단계: 요청 제출**

```bash
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"]}'
```

응답:
```json
{"event_id": "abc123"}
```

**2단계: 결과 가져오기**

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

Response (서버 전송 이벤트):
```
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**의 요금으로 선불 크레딧을 사용하여 포함 일일 할당량을 초과하여 사용할 수 있습니다.

> [!TIP]
> 40분간의 일일 GPU 할당량, 더 높은 대기열 우선순위, 크레딧을 이용한 할당량 확장 기능을 위해 [PRO에 구독](https://huggingface.co/subscribe/pro)할 수 있습니다.

## 일반적인 패턴

### FastAPI 통합

```python
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}
```

### 재시도를 통한 오류 처리

```python
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를 호출할 때, 사용자의 인증을 전달하세요:

```python
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가 사용 가능한 상황에서, 특정 작업을 위한 Spaces를 찾고 싶을 때가 있습니다:

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

이것은 의미적 관련도 순으로 정렬된 Spaces를 Space ID, 좋아요 수, 짧은 설명을 포함한 메타데이터와 함께 반환합니다. API를 노출하는 Spaces로 필터링하려면 `sdk=gradio` 매개변수를 사용하세요.

## 자세히 알아보기

- [Gradio Python 클라이언트 가이드](https://www.gradio.app/guides/getting-started-with-the-python-client)
- [Gradio JavaScript 클라이언트 가이드](https://www.gradio.app/guides/getting-started-with-the-js-client)
- [curl로 Gradio 앱 쿼리하기](https://www.gradio.app/guides/querying-gradio-apps-with-curl)
- [Spaces ZeroGPU](./spaces-zerogpu)

