빠른 시작예제

캐릭터 일관성 유지

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장까지 보낼 수 있으며, 각 이미지는 가로와 세로 모두 4000px 미만이어야 합니다.

단계

참조 이미지별 미디어 ID 준비

contextImages에는 미디어 ID를 지정합니다. API로 생성한 이미지에는 작업의 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에 넣으면 한 캐릭터로 시리즈를 만들 수 있습니다. 캐릭터 시트를 한 번 생성하고 모든 장면에서 참조하세요.

전체 스크립트

캐릭터를 생성한 뒤, 그 캐릭터를 참조 이미지로 두 장면을 더 생성합니다. 먼저 환경 변수 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로 생성하면 구도는 비슷하게 유지되지만, 캐릭터의 세부까지 유지되지는 않습니다.
  • 인페인팅: 한 영역만 바꾸고 나머지는 그대로 둡니다. 인페인팅과 아웃페인팅을 참고하세요.

참고