プログラム画像生成:スケールするバッチパイプラインの構築方法

本番対応のプログラムによる画像生成パイプラインを構築。大規模プロンプトエンジニアリング、バッチ処理、リトライロジック、非同期生成、S3/CMS統合、コスト分析を網羅。完全なPythonサンプル付き。

by AnyCap

Generation、Orchestration、Integrationの各レイヤーが光るデータフローラインで接続されたプログラムによる画像生成パイプライン

ほとんどの画像生成チュートリアルは1枚の画像で終わります。curlコマンドと綺麗な出力を見せて「完了」です。「猫の画像を生成して」くらいなら十分でしょう。しかし実際のプロジェクトで500枚の画像が必要な時には全く役に立ちません。

プログラムによる画像生成 — 人間の介入なしにコードから大規模に画像を生成すること — は別のスキルです。このガイドではパイプライン全体をカバーします:大規模プロンプトエンジニアリング、バッチ処理、エラーハンドリング、非同期処理、出力管理、そして本番システムへの統合まで。


本番画像パイプラインの3つのレイヤー

すべての本番画像パイプラインには3つのレイヤーがあります:

レイヤー 役割 ツール
Generation プロンプトを画像に変換 AnyCap CLI、REST API
Orchestration バッチ、リトライ、並行性の管理 Pythonスクリプト、キューシステム
Integration アプリ、CMS、ストレージへの接続 Webhook、S3、CMS API

ほとんどの開発者はレイヤー1しか考えません。しかしレイヤー2と3がパイプラインの成否を分けます。


レイヤー1:大規模プロンプトエンジニアリング

1枚の画像を生成する時は、完璧なプロンプトを丹念に作り込めます。500枚生成する時は、プロンプトシステムが必要です。

テンプレートアプローチ

# prompts.py — 一元化されたプロンプトテンプレート
from dataclasses import dataclass
from typing import Optional

@dataclass
class ImageJob:
    template: str
    params: dict
    output_path: str
    model: str = "nano-banana-2"
    
PROMPT_TEMPLATES = {
    "product_hero": "Eコマース商品写真: {product_name}, {color}, スタジオライティング、白背景、1024x1024、商業写真",
    "blog_hero": "ブログヘッダーイラスト: {topic}, {style}スタイル, {mood}な雰囲気, 1200x630, エディトリアル",
    "social_post": "ソーシャルメディアビジュアル: {subject}, {platform}フォーマット, {vibe}なテイスト, {dimensions}",
}

def build_prompt(template_key: str, **params) -> str:
    return PROMPT_TEMPLATES[template_key].format(**params)

スケールアップパターン

# CSVから100枚の商品写真を生成
import csv, subprocess, json
from concurrent.futures import ThreadPoolExecutor, as_completed

def generate_single(job: ImageJob) -> dict:
    prompt = build_prompt(job.template, **job.params)
    
    result = subprocess.run([
        "anycap", "image", "generate",
        "--prompt", prompt,
        "--model", job.model,
        "--output-format", "json",
        "-o", job.output_path
    ], capture_output=True, text=True)
    
    return {
        "output_path": job.output_path,
        "success": result.returncode == 0,
        "data": json.loads(result.stdout) if result.returncode == 0 else None,
        "error": result.stderr if result.returncode != 0 else None
    }

# データからジョブリストを構築
jobs = []
with open("products.csv") as f:
    for row in csv.DictReader(f):
        jobs.append(ImageJob(
            template="product_hero",
            params={"product_name": row["name"], "color": row["color"]},
            output_path=f"output/{row['sku']}.png"
        ))

# 並行性制御付きで実行
with ThreadPoolExecutor(max_workers=4) as executor:
    futures = {executor.submit(generate_single, job): job for job in jobs}
    for future in as_completed(futures):
        result = future.result()
        status = "✅" if result["success"] else "❌"
        print(f"{status} {result['output_path']}")

レイヤー2:オーケストレーション — 誰もが忘れる部分

生成は簡単です。大規模で信頼性を確保するのが本当のエンジニアリングです。

パターン1:非同期バッチ処理

大規模バッチ(100枚以上)では、ブロッキングを避けるために非同期モードを使用します:

# バッチジョブを送信
anycap image generate \
  --prompt "$(python build-prompts.py --csv products.csv)" \
  --model nano-banana-2 \
  --async \
  --batch-size 20 \
  --webhook "https://your-app.com/webhooks/images" \
  -o output/products/

Webhookが完了次第結果を受信します。ポーリング不要。タイムアウト問題もなし。

パターン2:指数バックオフによるリトライ

import time, random

def generate_with_retry(job: ImageJob, max_retries: int = 3) -> dict:
    for attempt in range(max_retries):
        result = generate_single(job)
        if result["success"]:
            return result
        
        if attempt < max_retries - 1:
            wait = (2 ** attempt) + random.uniform(0, 1)
            print(f"リトライ {attempt + 1}/{max_retries} ({job.output_path}) {wait:.1f}秒後")
            time.sleep(wait)
    
    return result  # 最後の失敗を返す

パターン3:キュー基盤アーキテクチャ

本番システムでは、適切なキューを使用します:

# Redisベースのシンプルなジョブキュー
import redis, json

r = redis.Redis()

def enqueue_job(job: ImageJob):
    r.lpush("image_jobs", json.dumps({
        "template": job.template,
        "params": job.params,
        "output_path": job.output_path,
        "model": job.model,
    }))

def worker_loop():
    while True:
        _, job_data = r.brpop("image_jobs")
        job = json.loads(job_data)
        result = generate_single(ImageJob(**job))
        
        if result["success"]:
            r.lpush("image_results", json.dumps(result))
        else:
            r.lpush("image_failures", json.dumps(result))

レイヤー3:統合 — 画像を必要な場所へ届ける

S3へのアップロード

import boto3

s3 = boto3.client("s3")

def upload_to_s3(local_path: str, bucket: str, key: str) -> str:
    s3.upload_file(local_path, bucket, key, ExtraArgs={
        "ContentType": "image/png",
        "CacheControl": "public, max-age=31536000",
    })
    return f"https://{bucket}.s3.amazonaws.com/{key}"

CMSへの投稿

import requests

def update_cms_product_image(sku: str, image_url: str):
    requests.patch(
        f"https://cms.example.com/api/products/{sku}",
        headers={"Authorization": "Bearer $CMS_TOKEN"},
        json={"image_url": image_url}
    )

チームへの通知

def notify_slack(message: str):
    requests.post(
        "https://hooks.slack.com/services/YOUR/WEBHOOK/URL",
        json={"text": message}
    )

完全なパイプラインスクリプト

#!/usr/bin/env python3
"""production-pipeline.py — 完全な画像生成パイプライン"""

import csv, subprocess, json, time, random, sys
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
import boto3, requests

# --- 設定 ---
S3_BUCKET = "my-assets"
SLACK_WEBHOOK = "https://hooks.slack.com/services/YOUR/WEBHOOK"
MAX_WORKERS = 4
MAX_RETRIES = 3

PROMPTS = {
    "product": "Eコマース写真: {name}, {color}, スタジオ、白背景、1024x1024",
    "lifestyle": "ライフスタイル写真: {name}, {color}, {scene}, 自然光、1024x1024",
}

@dataclass
class Job:
    template: str
    params: dict
    output: str
    model: str = "nano-banana-2"

def generate(job: Job) -> dict:
    prompt = PROMPTS[job.template].format(**job.params)
    for attempt in range(MAX_RETRIES):
        result = subprocess.run([
            "anycap", "image", "generate",
            "--prompt", prompt, "--model", job.model,
            "--output-format", "json", "-o", job.output
        ], capture_output=True, text=True)
        if result.returncode == 0:
            data = json.loads(result.stdout)
            return {"path": job.output, "url": data.get("image_url"), "success": True}
        if attempt < MAX_RETRIES - 1:
            time.sleep((2 ** attempt) + random.uniform(0, 1))
    return {"path": job.output, "success": False, "error": result.stderr}

def upload(path: str) -> str:
    key = path.replace("output/", "")
    s3 = boto3.client("s3")
    s3.upload_file(path, S3_BUCKET, key, ExtraArgs={"ContentType": "image/png"})
    return f"https://{S3_BUCKET}.s3.amazonaws.com/{key}"

def notify(text: str):
    requests.post(SLACK_WEBHOOK, json={"text": text})

def run_pipeline(csv_path: str):
    jobs = []
    with open(csv_path) as f:
        for row in csv.DictReader(f):
            jobs.append(Job("product", {"name": row["name"], "color": row["color"]}, f"output/{row['sku']}.png"))
    
    notify(f"🚀 パイプライン開始: {len(jobs)}枚の画像")
    
    results = []
    with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
        futures = {executor.submit(generate, job): job for job in jobs}
        for future in as_completed(futures):
            result = future.result()
            if result["success"]:
                result["s3_url"] = upload(result["path"])
                results.append(result)
    
    success = len(results)
    failed = len(jobs) - success
    notify(f"{'✅' if failed == 0 else '⚠️'} パイプライン完了: {success}/{len(jobs)}枚成功。{failed}枚失敗。")
    return results

if __name__ == "__main__":
    run_pipeline(sys.argv[1])

パイプラインに適したモデルの選択

パイプラインタイプ モデル 理由
ヒーロー画像、最終出力 Seedream 5 最高のファーストパス品質
大量生成、バリエーション Nano Banana 2 最速・最安
修正、リファインメント Nano Banana Pro 最高のimage-to-image編集
プロトタイピング、反復 Nano Banana 2 初期段階では速度 > 完成度

スケール時のコスト

ボリューム Nano Banana 2 Seedream 5 手動デザイン
100枚 ~$0.50 ~$1.50 $500-1,000
1,000枚 ~$5 ~$15 $5,000-10,000
10,000枚 ~$50 ~$150 $50,000+
100,000枚 ~$500 ~$1,500 現実的でない

最終更新: 2026年5月