範例:圖片轉影片生成

使用 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")

# 第一步:上傳來源圖片
print("Step 1: Uploading image...")
image_url = upload_image("my_photo.jpg")

# 第二步:生成影片
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}")

# 第三步:等待結果
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 分鐘,取決於模型和參數
  • 輪詢間隔:影片使用 5 秒間隔(圖片使用 2 秒),以減少不必要的 API 呼叫

後續步驟