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,因此无需安装任何额外的东西即可运行。

一个批量任务可以同时运行多少个?

很多:一次全部提交,然后统一收取。请遵守速率限制页上的限制,并为用于批量任务的密钥设置每日消费上限。

如果脚本在批量任务中途崩溃怎么办?

重新运行即可。每一行都使用与之前相同的幂等键,因此已经受理的行会返回原来的任务,而不会被重复收费。

本页内容