PopNowAPI 文件
指南
主要內容

配方

可直接複製執行的 Python 和 Node.js 配方,適用於 PopNow AI 圖片、影片和文字轉語音 API:從 CSV 批次生成圖片、照片轉影片、逐行配音,以及影片完成時傳送 Slack 通知。

四個小腳本,覆蓋人們最先想到要自動化的幾類任務。每個都是完整的:安裝 requests(或使用 Node 18+),設定 POPNOW_API_KEY,然後執行即可。它們共用同樣的三個輔助函式(呼叫、等待、儲存),所以看懂其中一個之後,其他的只需要幾行改動。popnow.ai 上的配方頁面會為你選擇的任意模型生成同樣的腳本。

配方模型每項費用
從 CSV 批次生成圖片alibaba/z-image-turbo/text-to-image每張圖 $0.01
照片轉影片minimax/h3/image-to-video768p 5 秒 $0.185
逐行配音google/gemini-3.8-flash-tts/text-to-speech約每 20 秒語音 $0.007
影片完成時傳送 Slack 通知minimax/h3/image-to-video768p 5 秒 $0.185

可以在模型頁中把模型換成任何其他模型;input 欄位只保留該模型 schema 中列出的那些。

輔助函式

每個 Python 配方都以下面這些內容結尾。create 傳送帶冪等鍵的任務,wait 以退避方式輪詢直到任務進入終止狀態且檔案已複製完成,save 下載第一個檔案。

helpers.py
import os, time
import requests

BASE = "https://api.popnow.ai/api/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['POPNOW_API_KEY']}"}


def call(method, path, **kwargs):
    headers = {**HEADERS, **kwargs.pop("headers", {})}
    body = requests.request(method, BASE + path, headers=headers, timeout=60, **kwargs).json()
    if body["code"] != 200:
        raise RuntimeError(f'{body["code"]} {body["msg"]}')
    return body["data"]


def create(payload, key):
    return call("POST", "/jobs/createTask", json=payload, headers={"Idempotency-Key": key})["taskId"]


def wait(task_id):
    delay = 2.0
    while True:
        time.sleep(delay)
        task = call("GET", "/jobs/recordInfo", params={"taskId": task_id})
        assets = (task.get("output") or {}).get("assets") or []
        copying = any(a.get("pending") and not a.get("unavailable") for a in assets)
        if task["state"] in ("succeeded", "failed", "canceled", "expired") and not copying:
            return task
        delay = min(delay * 1.5, 15.0)


def save(task, path):
    if task["state"] != "succeeded":
        raise RuntimeError(f'{task["state"]}: {task.get("errorMessage", "no detail")}')
    url = task["output"]["assets"][0]["url"]
    with open(path, "wb") as f:
        f.write(requests.get(url, timeout=300).content)

從 CSV 批次生成圖片

prompts.csv 有一個 prompt 欄位;每一列生成一張圖,儲存在 out/ 中。所有任務先統一提交,之後再統一收取結果,因此它們是並行生成的。冪等鍵由列內容推導而來,所以腳本崩潰後重新執行,已經成功受理的列不會被重複收費。

batch_images.py
import csv, hashlib, pathlib
from helpers import create, wait, save

MODEL = "alibaba/z-image-turbo/text-to-image"

out = pathlib.Path("out")
out.mkdir(exist_ok=True)
with open("prompts.csv", newline="", encoding="utf-8") as f:
    rows = [r["prompt"] for r in csv.DictReader(f) if r.get("prompt")]

tasks = []
for i, prompt in enumerate(rows, start=1):
    key = "batch-" + hashlib.sha256(f"{i}:{prompt}".encode()).hexdigest()[:32]
    tasks.append((i, create({"model": MODEL, "input": {"prompt": prompt, "aspect_ratio": "1:1"}}, key)))

for i, task_id in tasks:
    save(wait(task_id), out / f"{i:03d}.png")
    print("saved", i)

同樣的功能,用 Node.js 18+ 實現,不需要安裝任何套件:

batch_images.mjs
import { createHash } from 'node:crypto';
import { readFile, writeFile, mkdir } from 'node:fs/promises';

const API = 'https://api.popnow.ai/api/v1';
const auth = { Authorization: `Bearer ${process.env.POPNOW_API_KEY}` };
const call = async (path, init = {}) => {
  const body = await fetch(API + path, { ...init, headers: { ...auth, ...init.headers } }).then((r) => r.json());
  if (body.code !== 200) throw new Error(`${body.code} ${body.msg}`);
  return body.data;
};

const prompts = (await readFile('prompts.txt', 'utf8')).split('\n').map((l) => l.trim()).filter(Boolean);
await mkdir('out', { recursive: true });

const ids = await Promise.all(prompts.map((prompt, i) => call('/jobs/createTask', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', 'Idempotency-Key': 'batch-' + createHash('sha256').update(`${i}:${prompt}`).digest('hex').slice(0, 32) },
  body: JSON.stringify({ model: 'alibaba/z-image-turbo/text-to-image', input: { prompt, aspect_ratio: '1:1' } }),
}).then((d) => d.taskId)));

for (const [i, id] of ids.entries()) {
  let task;
  do {
    await new Promise((r) => setTimeout(r, 3000));
    task = await call(`/jobs/recordInfo?taskId=${id}`);
  } while (task.state === 'queued' || task.state === 'running');
  if (task.state !== 'succeeded') { console.error(i, task.state, task.errorMessage); continue; }
  const file = await fetch(task.output.assets[0].url).then((r) => r.arrayBuffer());
  await writeFile(`out/${String(i + 1).padStart(3, '0')}.png`, Buffer.from(file));
}

照片轉影片

先上傳一張本機照片,再請圖片生成影片的模型讓它動起來。執行方式為 python photo_to_video.py photo.jpg。

photo_to_video.py
import mimetypes, sys, uuid
import requests
from helpers import call, create, wait, save

MODEL = "minimax/h3/image-to-video"


def upload(path):
    """Local file -> popnow:// reference you can put in any image, video or audio field."""
    data = open(path, "rb").read()
    kind = mimetypes.guess_type(path)[0] or "image/jpeg"
    ticket = call("POST", "/common/upload-url", json={"contentType": kind, "bytes": len(data)})
    requests.put(ticket["uploadUrl"], data=data, headers=ticket.get("headers", {}), timeout=120).raise_for_status()
    return call("POST", f'/files/{ticket["fileId"]}/commit')["uri"]


ref = upload(sys.argv[1])
task_input = {"image_url": ref, "prompt": "Gentle camera push-in, hair moving in the wind", "duration_seconds": 5, "resolution": "768p"}
task_id = create({"model": MODEL, "input": task_input}, str(uuid.uuid4()))
save(wait(task_id), "clip.mp4")
print("saved clip.mp4")

在寫程式碼之前,先用下面的命令測試請求:

curl -X POST "https://api.popnow.ai/api/v1/jobs/createTask" \
  -H "Authorization: Bearer $POPNOW_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{"model": "minimax/h3/image-to-video", "input": {"image_url": "https://media.popnow.ai/movie/lighthouse.webp", "prompt": "The waves roll in slowly", "duration_seconds": 5}}'

逐行配音

lines.txt 每行放一句臺詞;每句生成一個獨立的音訊檔案,儲存在 voice/ 中,全部使用同一個聲音。voice_id 可選的值包括 Kore、Puck、Charon 和 Aoede;該模型的頁面列出了所有選項,以及 style 和 accent。

voiceover.py
import hashlib, pathlib
from helpers import create, wait, save

MODEL = "google/gemini-3.8-flash-tts/text-to-speech"

out = pathlib.Path("voice")
out.mkdir(exist_ok=True)
lines = [l.strip() for l in open("lines.txt", encoding="utf-8") if l.strip()]

tasks = []
for i, line in enumerate(lines, start=1):
    key = "voice-" + hashlib.sha256(f"{i}:{line}".encode()).hexdigest()[:32]
    tasks.append((i, create({"model": MODEL, "input": {"text": line, "voice_id": "Kore", "style": "empathetic"}}, key)))

for i, task_id in tasks:
    task = wait(task_id)
    mime = ((task.get("output") or {}).get("assets") or [{}])[0].get("mime", "")
    ext = {"audio/mpeg": ".mp3", "audio/wav": ".wav", "audio/ogg": ".ogg"}.get(mime, ".audio")
    save(task, out / f"{i:03d}{ext}")
    print("saved", i)

影片完成時傳送 Slack 通知

不輪詢,而是在建立任務時傳入 callBackUrl。一個小型 Express 伺服器會驗證原始請求內容的簽名,然後把結果傳送到 Slack 的傳入 Webhook。請設定 POPNOW_WEBHOOK_SECRET(從 API 控制台取得)和 SLACK_WEBHOOK_URL。

notify.mjs (npm install express)
import { createHash, createHmac, randomUUID, timingSafeEqual } from 'node:crypto';
import express from 'express';

const BASE = 'https://api.popnow.ai/api/v1';

// 1. Create the task with a callBackUrl that points at this server.
export async function createVideo() {
  const res = await fetch(BASE + '/jobs/createTask', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.POPNOW_API_KEY}`,
      'Content-Type': 'application/json',
      'Idempotency-Key': randomUUID(),
    },
    body: JSON.stringify({
      model: 'minimax/h3/image-to-video',
      input: { image_url: 'https://media.popnow.ai/movie/lighthouse.webp', prompt: 'The waves roll in slowly', duration_seconds: 5 },
      callBackUrl: 'https://your-server.example.com/hooks/popnow',
    }),
  });
  return (await res.json()).data.taskId;
}

// 2. Receive the finished task, check the signature on the raw body, then post to Slack.
const app = express();
app.post('/hooks/popnow', express.raw({ type: 'application/json' }), async (req, res) => {
  const timestamp = req.header('X-Webhook-Timestamp');
  const signature = req.header('X-Webhook-Signature') ?? '';
  const event = JSON.parse(req.body.toString('utf8'));
  const task = event.data;
  const digest = createHash('sha256').update(req.body).digest('hex');
  const expected = createHmac('sha256', process.env.POPNOW_WEBHOOK_SECRET)
    .update(`${task.taskId}.${timestamp}.${digest}`)
    .digest('base64');
  const ok = expected.length === signature.length && timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
  if (!ok || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return res.status(401).end();
  res.status(200).end(); // answer first; deliveries are retried until you return 2xx

  const text = task.state === 'succeeded'
    ? `Video ready: ${task.output.assets[0].url}`
    : `Task ${task.taskId} ${task.state}: ${task.errorMessage ?? 'no detail'}`;
  await fetch(process.env.SLACK_WEBHOOK_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text }) });
});
app.listen(3000);

Slack 訊息中的連結是簽名連結,約 20 分鐘內有效;如果別人可能稍後再開啟,請同時傳送 taskId。Webhook頁說明了重試和重複送達的處理。

價格與限制

每個配方都從獨立的 API 美元餘額按模型正常單價結算,沒有額外費用;查詢任務和上傳檔案免費。失敗項目不收費,每個項目都有自己的冪等鍵,因此重新執行指令碼只會建立先前未成功送出的項目。大量執行前,先用 jobs/quote替一個項目報價,並為金鑰設定每日上限(驗證)。只要遵守速率限制,同時送出幾百個任務沒有問題。

常見錯誤

錯誤原因解決方法
KeyError: 'POPNOW_API_KEY'目前 shell 中沒有設定該變數export POPNOW_API_KEY="sk-popnow-..."
RuntimeError: 400 …,並指出某個欄位該模型不接受這個欄位或值檢視該模型的頁面;每個模型的欄位各不相同
RuntimeError: 40201 …API 美元餘額不足以支付下一個任務在 API 帳單儲值;已受理的任務會繼續執行
RuntimeError: 429 …同時發出的請求過多分小批次提交,並遵守 Retry-After
RuntimeError: failed: …某一項失敗或被拒絕該項沒有收費;修正那一列後重新執行
commit 時回傳 RuntimeError: 40003 …上傳的位元組與上傳憑證不匹配申請新的憑證並重新上傳
Webhook 回傳 401簽名是基於解析後的 JSON 計算的,而不是原始位元組;或者金鑰錯誤使用 express.raw,並使用 API 控制台中的金鑰

有官方的 Python 或 Node SDK 嗎?

有,兩者都是開源的,並以 popnow 的名義發布在 PyPI 和 npm 上:pip install popnow 和 npm install popnow。SDK、命令列工具與開源工具頁有詳細資訊。這些配方只使用 requests 和內建的 fetch,因此無需安裝任何額外的東西即可執行。

一個批次任務可以同時執行多少個?

很多:一次全部提交,然後統一收取。請遵守「速率限制」頁上的限制,並為用於批次任務的金鑰設定每日消費上限。

如果腳本在批次任務中途崩潰怎麼辦?

重新執行即可。每一列都使用與之前相同的冪等鍵,因此已經受理的列會回傳原來的任務,而不會被重複收費。

本頁內容