# SpacesをAPIエンドポイントとして

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は2段階のプロセスを使用します:

**ステップ 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には、アカウントタイプに基づいた使用量クォータが設定されています：

| アカウントタイプ | 含まれる1日あたりのGPUクォータ |
|-------------|--------------------------|
| 認証なし | 2分 |
| 無料アカウント | 5分 |
| PROアカウント | 40分 |

トークンで認証を行うと、アカウントのGPUクォータが消費されます。認証なしのリクエストは、より厳しい制限が設けられた共有プールを使用します。

PRO、Team、Enterprise のユーザーは、GPU 時間の **10 分あたり $1** のレートで、事前購入クレジットを使用して、含まれる 1 日あたりのクォータを超えて利用できます。

> [!TIP]
> 1日あたり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")
```

### 別のスペースからスペースを呼び出す

独自の 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が利用可能であるため、特定のタスクに合ったものを探したい場合があります：

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

