例: 画像から動画生成

Atlas Cloud API を使用した画像からの動画生成の完全な例

概要

このチュートリアルでは、画像から動画への完全なワークフロー(ソース画像のアップロード、動画の生成、結果の取得)を説明します。

前提条件

  • API キー付きの Atlas Cloud アカウント
  • ソース画像ファイル(JPEG、PNG、または WebP)
  • Python 3.7+ と requests ライブラリ

Python の完全な例

import requests
import time
import os

API_KEY = os.environ.get("ATLASCLOUD_API_KEY", "your-api-key")
BASE_URL = "https://api.atlascloud.ai/api/v1"

def upload_image(file_path):
    """ローカル画像をアップロードして一時 URL を取得する。"""
    with open(file_path, "rb") as f:
        response = requests.post(
            f"{BASE_URL}/model/uploadMedia",
            headers={"Authorization": f"Bearer {API_KEY}"},
            files={"file": f}
        )
    response.raise_for_status()
    url = response.json().get("url")
    print(f"Uploaded: {url}")
    return url

def generate_video(image_url, prompt, model="kling-v2.0"):
    """画像から動画生成タスクを送信する。"""
    response = requests.post(
        f"{BASE_URL}/model/generateVideo",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        },
        json={
            "model": model,
            "prompt": prompt,
            "image_url": image_url
        }
    )
    response.raise_for_status()
    return response.json()["data"]["id"]

def wait_for_result(prediction_id, interval=5, timeout=300):
    """タイムアウト付きで生成結果をポーリングする。"""
    elapsed = 0
    while elapsed < timeout:
        response = requests.get(
            f"{BASE_URL}/model/prediction/{prediction_id}",
            headers={"Authorization": f"Bearer {API_KEY}"}
        )
        result = response.json()
        status = result["data"]["status"]

        if status == "completed":
            return result["data"]["outputs"][0]
        elif status == "failed":
            raise Exception(f"Failed: {result['data'].get('error')}")

        print(f"  Status: {status} ({elapsed}s)")
        time.sleep(interval)
        elapsed += interval

    raise TimeoutError("Generation timed out")

# ステップ 1: ソース画像をアップロード
print("Step 1: Uploading image...")
image_url = upload_image("my_photo.jpg")

# ステップ 2: 動画を生成
prompt = "The person slowly turns their head and smiles, camera zooms in slightly"
print(f"Step 2: Generating video with prompt: {prompt}")
prediction_id = generate_video(image_url, prompt)
print(f"Task submitted: {prediction_id}")

# ステップ 3: 結果を待つ
print("Step 3: Waiting for video...")
video_url = wait_for_result(prediction_id)
print(f"Video ready: {video_url}")

Node.js の完全な例

import fs from "fs";

const API_KEY = process.env.ATLASCLOUD_API_KEY || "your-api-key";
const BASE_URL = "https://api.atlascloud.ai/api/v1";

async function uploadImage(filePath) {
  const formData = new FormData();
  formData.append("file", new Blob([fs.readFileSync(filePath)]));

  const response = await fetch(`${BASE_URL}/model/uploadMedia`, {
    method: "POST",
    headers: { Authorization: `Bearer ${API_KEY}` },
    body: formData,
  });

  if (!response.ok) throw new Error(`Upload failed: ${response.status}`);
  const { url } = await response.json();
  console.log(`Uploaded: ${url}`);
  return url;
}

async function generateVideo(imageUrl, prompt, model = "kling-v2.0") {
  const response = await fetch(`${BASE_URL}/model/generateVideo`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ model, prompt, image_url: imageUrl }),
  });

  if (!response.ok) throw new Error(`Generate failed: ${response.status}`);
  return (await response.json()).data.id;
}

async function waitForResult(predictionId, interval = 5000, timeout = 300000) {
  const start = Date.now();
  while (Date.now() - start < timeout) {
    const response = await fetch(
      `${BASE_URL}/model/prediction/${predictionId}`,
      { headers: { Authorization: `Bearer ${API_KEY}` } }
    );
    const result = await response.json();

    if (result.data.status === "completed") return result.data.outputs[0];
    if (result.data.status === "failed") throw new Error(result.data.error);

    console.log(`  Status: ${result.data.status}`);
    await new Promise((r) => setTimeout(r, interval));
  }
  throw new Error("Timeout");
}

// ワークフローを実行
console.log("Step 1: Uploading image...");
const imageUrl = await uploadImage("my_photo.jpg");

console.log("Step 2: Generating video...");
const predictionId = await generateVideo(
  imageUrl,
  "The person slowly turns and smiles, gentle camera movement"
);

console.log("Step 3: Waiting for result...");
const videoUrl = await waitForResult(predictionId);
console.log(`Video ready: ${videoUrl}`);

ヒント

  • 動画モデル: モデルによって強みが異なる — 品質なら Kling、モーションなら Seedance、シネマティックスタイルなら Vidu
  • モーションのプロンプト: 希望する動き、カメラモーション、シーンの変化を記述
  • 画像品質: 高品質なソース画像の方が一般的により良い動画結果を生成
  • 生成時間: 動画生成はモデルとパラメータに応じて通常30秒から3分
  • ポーリング間隔: 不要な API コールを減らすため、動画には5秒間隔を使用(画像の2秒に対して)

次のステップ