クイックスタート使用例

キャラクターの一貫性

PixAI API で、アニメキャラクターを複数の画像で同じ見た目に保ちます。Tsubaki.3 に最大 3 枚の参照画像を渡し、各画像から何を取り入れるかをプロンプトで指定します。

POST /v2/image/create の contextImages に参照画像を指定すると、Tsubaki.3 はそれを元に画像を描きます。同じキャラクターを新しいシーンに描く、ある画像のキャラクターを別の画像のポーズで描く、気に入った画像の一部だけを少し変える、といったことができます。

ベースURL: https://api.pixai.art/v2。すべてのリクエストに Authorization: Bearer YOUR_API_KEY を付けてください。API キーの取得方法はPixAI APIを使用するには?をご参照ください。

参照画像は Tsubaki.3(modelVersionId 2024383379556065549)でのみ使えます。最大 3 枚まで指定でき、各画像は縦横とも 4000 px 未満である必要があります。

手順

参照画像ごとにメディア ID を用意する

contextImages にはメディア ID を指定します。生成した画像には、タスクの outputs.mediaIds にすでにメディア ID があります。キャラクターを一度生成し、以降のすべての画像でその ID を再利用してください。

手元のファイルを使う場合はアップロードします。アップロード URL を取得し、バイト列を PUT してから登録します。登録したときの id がメディア ID です。

curl -X POST https://api.pixai.art/v2/media/image/upload-url \
  -H "Authorization: Bearer $PIXAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{}'
# → {"uploadUrl": "...", "externalId": "..."}

curl -X PUT "UPLOAD_URL" -H "Content-Type: image/png" --data-binary @character.png

curl -X POST https://api.pixai.art/v2/media/image/register \
  -H "Authorization: Bearer $PIXAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"externalId": "EXTERNAL_ID"}'
# → {"id": "MEDIA_ID", "type": "IMAGE", ...}

プロンプトを書く

参照画像は contextImages の順に image1、image2、image3 と呼びます。指示は英語の文章で書いてください。何を作るか、そして各画像から何を残すかを記述します。

目的プロンプトの例
同じキャラクターを新しいシーンにDraw the girl from image1 sitting in a café by the window on a rainy day. Keep her face, hair and outfit exactly as in image1.
キャラクターを別のポーズにRedraw the character in image1 in the pose shown in image2. Keep her outfit, hair color and face exactly as in image1.
一部だけを変更Change the girl's navy coat to a bright red coat. Keep everything else in image1 as it is: her face, hair, pose and the background.

一部を変更する場合は、変えずに残すものを明記してください。プロンプトで触れていない部分は変わる可能性があります。

画像を生成する

curl -X POST https://api.pixai.art/v2/image/create \
  -H "Authorization: Bearer $PIXAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "modelVersionId": "2024383379556065549",
    "contextImages": ["CHARACTER_MEDIA_ID", "POSE_MEDIA_ID"],
    "prompt": "Redraw the character in image1 in the pose shown in image2. Keep her outfit, hair color and face exactly as in image1. Anime illustration, soft cel shading.",
    "aspectRatio": "2:3"
  }'

その後、最初のAPIリクエストと同じように、status が completed になるまで GET /v2/task/{id} をポーリングし、outputs.mediaUrls をダウンロードします。

存在しないメディア ID を指定すると 404 FILE_NOT_FOUND が返ります。

アスペクト比は参照画像と同じにしてください。縦長の参照画像で "aspectRatio": "3:2" を指定したテストでは、縦長の絵の左右に空白の帯が付き、帯が幅の半分以上を占めました。

結果をつなげて使う

完了した画像にはそれぞれメディア ID があります。その ID を再び contextImages に渡すと、1 人のキャラクターでシリーズを作れます。キャラクターの設定画を一度生成し、すべてのシーンでそれを使ってください。

まとめて実行するスクリプト

キャラクターを生成し、そのキャラクターを参照画像にしてさらに 2 つのシーンを生成します。事前に環境変数 PIXAI_API_KEY を設定してください。

requests をインストールしてください。

import os
import time

import requests

API = "https://api.pixai.art/v2"
HEADERS = {"Authorization": f"Bearer {os.environ['PIXAI_API_KEY']}"}
TSUBAKI_3 = "2024383379556065549"


def generate(prompt, context_images=(), aspect_ratio="2:3"):
    """画像を生成し、完了を待ってタスクを返す。"""
    body = {"modelVersionId": TSUBAKI_3, "prompt": prompt, "aspectRatio": aspect_ratio}
    if context_images:
        body["contextImages"] = list(context_images)
    resp = requests.post(f"{API}/image/create", headers=HEADERS, json=body)
    resp.raise_for_status()
    task = resp.json()
    while task["status"] in ("waiting", "running"):
        time.sleep(2)
        resp = requests.get(f"{API}/task/{task['id']}", headers=HEADERS)
        if resp.status_code == 404:  # 作成直後のタスクは一時的に 404 を返すことがあります。ポーリングを続けます。
            continue
        resp.raise_for_status()
        task = resp.json()
    if task["status"] != "completed":
        raise SystemExit(f"Task ended as {task['status']}: {task.get('taskStatusMsgI18n')}")
    return task


def save(task, name):
    url = task["outputs"]["mediaUrls"][0]
    with open(name, "wb") as f:
        f.write(requests.get(url).content)


character = generate(
    "A full-body anime illustration of a girl with short silver hair and blue eyes, "
    "wearing a navy coat and a red scarf, standing on a plain white background."
)
save(character, "character.webp")
ref = character["outputs"]["mediaIds"][0]

scenes = {
    "cafe.webp": "Draw the girl from image1 reading a book in a café by the window on a rainy day. "
    "Keep her face, hair and outfit exactly as in image1.",
    "beach.webp": "Draw the girl from image1 walking along a beach at sunset, carrying her coat. "
    "Keep her face, hair and scarf exactly as in image1.",
}
for name, prompt in scenes.items():
    save(generate(prompt, context_images=[ref], aspect_ratio="2:3"), name)

Node.js 20 以降で、characters.mjs として保存します。

import { writeFile } from 'node:fs/promises';

const API = 'https://api.pixai.art/v2';
const HEADERS = {
  Authorization: `Bearer ${process.env.PIXAI_API_KEY}`,
  'Content-Type': 'application/json',
};
const TSUBAKI_3 = '2024383379556065549';

async function call(path, init = {}) {
  const res = await fetch(`${API}${path}`, { headers: HEADERS, ...init });
  if (!res.ok) throw new Error(`${path}: ${res.status} ${await res.text()}`);
  return res.json();
}

// 作成直後のタスクは一時的に 404 を返すことがあるため、ポーリングを続けます。
async function poll(taskId) {
  const res = await fetch(`${API}/task/${taskId}`, { headers: HEADERS });
  if (res.status === 404) return null;
  if (!res.ok) throw new Error(`/task/${taskId}: ${res.status} ${await res.text()}`);
  return res.json();
}

async function generate(prompt, contextImages = [], aspectRatio = '2:3') {
  const body = { modelVersionId: TSUBAKI_3, prompt, aspectRatio };
  if (contextImages.length) body.contextImages = contextImages;
  let task = await call('/image/create', { method: 'POST', body: JSON.stringify(body) });
  while (task.status === 'waiting' || task.status === 'running') {
    await new Promise((resolve) => setTimeout(resolve, 2000));
    task = (await poll(task.id)) ?? task;
  }
  if (task.status !== 'completed') {
    throw new Error(`Task ended as ${task.status}: ${JSON.stringify(task.taskStatusMsgI18n)}`);
  }
  return task;
}

async function save(task, name) {
  const res = await fetch(task.outputs.mediaUrls[0]);
  await writeFile(name, Buffer.from(await res.arrayBuffer()));
}

const character = await generate(
  'A full-body anime illustration of a girl with short silver hair and blue eyes, ' +
    'wearing a navy coat and a red scarf, standing on a plain white background.',
);
await save(character, 'character.webp');
const ref = character.outputs.mediaIds[0];

const scenes = {
  'cafe.webp':
    'Draw the girl from image1 reading a book in a café by the window on a rainy day. ' +
    'Keep her face, hair and outfit exactly as in image1.',
  'beach.webp':
    'Draw the girl from image1 walking along a beach at sunset, carrying her coat. ' +
    'Keep her face, hair and scarf exactly as in image1.',
};
for (const [name, prompt] of Object.entries(scenes)) {
  await save(await generate(prompt, [ref], '2:3'), name);
}

キャラクターの一貫性を保つほかの方法

  • LoRA: そのキャラクターで学習した LoRA を loras で適用します。モデルと LoRA を探して使うをご参照ください。
  • 同じ seed: プロンプトを少しだけ変えて同じ seed を使います。構図は近くなりますが、キャラクターの細部までは保たれません。
  • インペイント: 一部の領域だけを変更し、残りはそのまま保ちます。インペイントとアウトペイントをご参照ください。

リファレンス