> This is a page from the ElevenLabs documentation. For a complete page index, fetch https://elevenlabs.io/docs/llms.txt. For the full documentation in a single file, fetch https://elevenlabs.io/docs/llms-full.txt.

# テンプレートクイックスタート

このチュートリアルでは、PythonまたはTypeScriptスクリプトから公開テンプレートを実行します。このテンプレートは、服をスマートフォンで気軽に撮影した写真を、きれいな商品写真に変換し、スクリプトがその隣に結果を保存します。所要時間は約5分で、実行自体は1分未満です。

![スマートフォンで撮影した写真と商品写真](/docs/_fern-img/6afed41d4d791df68c87f183bd8db1d4aca8b4be3e946cc518534bda902f9528.webp)

**テンプレート**は、公開された[ElevenCreative Flow](/docs/ja/eleven-creative/products/flows)です。固定の**入力**セットを受け取り、固定の**出力**セットを生成するモデルの連鎖です。ここで実行する[Phone Photo to Packshot](https://elevenlabs.io/app/templates/Yz4DETxRv4uXyIo5PnEy)は、画像を1枚受け取り、画像を1枚返します。モデルとプロンプトは作成者がすでに選んでいるため、コードでは写真を渡すだけです。

> **Warning**
>
> テンプレートの実行には、プロ以上のプランが必要です。

## セットアップ

#### APIキーを作成

[ダッシュボードでAPIキーを作成](https://elevenlabs.io/app/settings/api-keys)し、安全に[APIへアクセス](/docs/ja/api-reference/authentication)するために使用します。

キーは管理されたシークレットとして保存し、好みに応じて`.env`ファイルによる環境変数として、またはアプリの設定で直接SDKに渡してください。

**`.env`**

```js title=".env"
ELEVENLABS_API_KEY=<your_api_key_here>
```

キーに**画像＆ビデオ**権限を付与します。

#### SDKをインストール

#### SDK

`dotenv`ライブラリも使用して、環境変数からAPIキーを読み込みます。

```python
pip install elevenlabs
pip install python-dotenv
```

```typescript
npm install @elevenlabs/elevenlabs-js
npm install dotenv
```

#### CLI

ElevenLabs CLIをインストールします。Homebrew（macOS）とScoop（Windows）を推奨します。

**`Homebrew (macOS)`**

```bash title="Homebrew (macOS)"
brew install elevenlabs/tap/elevenlabs
```

**`Scoop (Windows)`**

```powershell title="Scoop (Windows)"
scoop bucket add elevenlabs https://github.com/elevenlabs/scoop-bucket
scoop install elevenlabs
```

**`npm`**

```bash title="npm"
npm install -g @elevenlabs/cli
```

**`curl`**

```bash title="curl"
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/elevenlabs/cli/releases/latest/download/elevenlabs-cli-installer.sh | sh
```

> **Tip**
>
> AIコーディングアシスタントを使っていますか？プロジェクトで`elevenlabs generate-skills`を実行すると、各コマンドグループ用の
> `SKILL.md`が`skills/`に作成されます。これにより、ドキュメントを貼り付けなくても、アシスタントがCLIのすべての機能を把握できます。
> 別の場所に配置するには`--output-dir`を使ってください。CLIに組み込まれたAPI定義を読み取るため、APIキーは不要で、オフラインでも動作します。また、
> インストールしているCLIのバージョンに常に対応します。

次に認証します。ブラウザが開き、CLIを承認できます。

```bash
elevenlabs auth login
```

#### 写真を取得

サンプル写真を、スクリプトを作成するフォルダにダウンロードします。

```bash
curl -o garment.jpg https://storage.googleapis.com/eleven-public-cdn/documentation_assets/templates/garment.jpg
```

## テンプレートのコードを確認

ElevenLabsアプリで[Phone Photo to Packshot](https://elevenlabs.io/app/templates/Yz4DETxRv4uXyIo5PnEy)を開き、**API**タブを選択します。すべてのテンプレートにこのタブがあり、cURL、Python、TypeScriptで実行するコードが表示されます。

![テンプレートのAPIタブ](/docs/_fern-img/801c9d2e2736964b35f5bad954092c973b21eedc03801128f1ed8bf31ea095b1.webp)

このタブでは、APIキーの取得、結果の取得方法の選択、テンプレートの実行という3つの手順を説明します。**結果の取得方法を選択**では、デフォルトで**結果を待機**が選択されています。3番目の手順ではcURLのコードが開きます。**Python**または**TypeScript**を選択すると、手順が**実行して結果を待機**に変わります。このスニペットは実行を開始し、完了を待ってから各出力を表示します。テンプレートの入力ごとに、入力IDをキーとして`inputs`の下に1つの値を渡し、出力IDで`outputs`から各結果を読み取ります。このテンプレートには、`garment_photo`という入力が1つ、`packshot`という出力が1つあります。コードで必要な名前は、この2つのIDだけです。

## テンプレートを実行

`packshot.py`または`packshot.mts`を作成します。APIタブのスニペットに、次の変更を加えたものです。

* APIキーを`.env`ファイルから読み込みます。
* ElevenLabsにすでにアップロードされているファイルのIDである`YOUR_ASSET_ID`の代わりに、写真をbase64で渡します。
* スクリプトは実行中に1行表示し、URLを表示する代わりに商品写真を`packshot.jpg`として保存します。

**`packshot.py`**

```python title="packshot.py" maxLines=0
import base64
import os
import urllib.request

from dotenv import load_dotenv
from elevenlabs import ElevenLabs, TemplateInputReference_InlineBase64

load_dotenv()

client = ElevenLabs(api_key=os.environ["ELEVENLABS_API_KEY"])

with open("garment.jpg", "rb") as f:
    photo = base64.b64encode(f.read()).decode()

print("Running the template, this takes up to a minute...")

# Starts a run and waits for it to finish, checking back as often as the API
# asks. In production, receive the result by webhook instead.
run = client.flows.templates.runs.create_and_wait(
    template_id="Yz4DETxRv4uXyIo5PnEy",
    # Pins the version this tutorial was written against.
    version_id="Kqs4nRrpndEjQ54BhbwE",
    inputs={
        "garment_photo": TemplateInputReference_InlineBase64(
            content_base_64=photo,
            mime_type="image/jpeg",
        ),
    },
)

packshot = run.outputs["packshot"]
# Checking `type` tells your editor this output is an image, which has a content_url.
if packshot.type == "image" and packshot.status == "completed" and packshot.content_url:
    urllib.request.urlretrieve(packshot.content_url, "packshot.jpg")
    print("Saved packshot.jpg")
else:
    print("The run failed:", packshot.failure_reason)

```

**`packshot.mts`**

```typescript title="packshot.mts" maxLines=0
import { ElevenLabsClient } from "@elevenlabs/elevenlabs-js";
import "dotenv/config";
import { readFile, writeFile } from "fs/promises";

const client = new ElevenLabsClient({
  apiKey: process.env.ELEVENLABS_API_KEY,
});

const photo = await readFile("garment.jpg");

console.log("Running the template, this takes up to a minute...");

// Starts a run and waits for it to finish, checking back as often as the API
// asks. In production, receive the result by webhook instead.
const run = await client.flows.templates.runs.createAndWait("Yz4DETxRv4uXyIo5PnEy", {
  // Pins the version this tutorial was written against.
  versionId: "Kqs4nRrpndEjQ54BhbwE",
  inputs: {
    garment_photo: {
      type: "inline_base64",
      contentBase64: photo.toString("base64"),
      mimeType: "image/jpeg",
    },
  },
});

const packshot = run.outputs["packshot"];
// Checking `type` tells TypeScript this output is an image, which has a contentUrl.
if (packshot.type === "image" && packshot.status === "completed" && packshot.contentUrl) {
  const response = await fetch(packshot.contentUrl);
  await writeFile("packshot.jpg", Buffer.from(await response.arrayBuffer()));
  console.log("Saved packshot.jpg");
} else {
  console.error("The run failed:", packshot.failureReason);
}

```

`create_and_wait`（TypeScriptでは`createAndWait`）は実行を開始した後、すべての出力が完了するまでAPIが推奨する間隔で状態を確認します。失敗した実行は例外として送出されずに返されるため、スクリプトでは読み取る前に出力の`status`を確認します。`version_id`は、このチュートリアルで使用したテンプレートのバージョンを固定します。そのため、後でテンプレートが編集されてもスクリプトは壊れません。

スクリプトを実行します。このテンプレートの実行には約1,020クレジットかかり、アプリで実行する場合と同じです。

```python
python packshot.py
```

```typescript
npx tsx packshot.mts
```

30秒から1分後、スクリプトに次のように表示されます。

```text
Running the template, this takes up to a minute...
Saved packshot.jpg
```

`packshot.jpg`を開きます。写真の服が、無地のスタジオ背景にあるマネキンに着せられ、ベッドや照明は取り除かれています。

> **Note**
>
> `create_and_wait`はスクリプトやテンプレートの試用向けです。本番環境では、実行中に
> アプリケーションがリクエストを開いたままにしないよう、代わりに[webhook](/docs/ja/eleven-api/guides/how-to/image-and-video/webhooks)で
> 完了した実行を受け取ります。[チームのテンプレートを実行](/docs/ja/eleven-api/guides/how-to/templates/run-a-template)で方法を確認できます。

## 自分の写真で実行

スマートフォンで好きな服を撮影します。良い写真である必要はありません。ベッドの上のTシャツや、椅子に掛けたジャケットでも使えます。`garment.jpg`としてJPEG形式で保存し、もう一度スクリプトを実行します。

すべてのテンプレート実行で同じモデルと設定を使用するため、同じスタジオ風の服の商品写真が得られます。ただし、同じ写真でも実行ごとに細部は異なる場合があります。

## 学んだこと

* テンプレートは名前付きの**入力**を受け取り、名前付きの**出力**を生成します。その**API**タブには実行コードが表示されます。
* `flows.templates.runs.create_and_wait`は、入力IDごとに1つの値を指定して**実行**を開始し、完了時に戻ります。各出力はIDで読み取り、`status`を確認します。
* 本番環境では、**webhook**が完了した各実行を配信するため、待機は発生しません。

## 次のステップ

#### [チームのテンプレートを実行](/docs/ja/eleven-api/guides/how-to/templates/run-a-template)

テンプレートのAPIタブからコードをコピーし、各入力タイプを指定して、webhookで結果を受け取り、バージョンを固定します。

#### [Webhook](/docs/ja/eleven-api/guides/how-to/image-and-video/webhooks)

本番用webhookを設定し、署名を手動で検証して、再試行と重複イベントを処理します。

#### [テンプレートを作成](/docs/ja/eleven-creative/products/flows#creating-a-template)

チームがFlowをテンプレートに変換する方法：入力と出力の選択、および共有。

#### [APIリファレンス](/docs/ja/api-reference/flows/templates/runs/create)

テンプレート実行のすべてのパラメータ。