Happy Pony API Get an API key →

Character swap

Pricing: Character swap

Replace one to three people in a video with the characters in reference pictures. The source performance (pose, gaze, expression, movement), the scene and the source audio are kept; the chosen people change. One picture per person swapped in. One mp4 comes back.

There are three jobs. Leave mode out and the renderer picks the right whole-frame job for your request:

The whole-frame jobs redraw the scene too, close to the source but not pixel for pixel, so anything that must not change (another person, an object, subtitles) belongs in the description. Send your own description, or leave it out and say who to replace in plain words (prompt, for example "the woman on the right"): a vision model then watches the clip and writes the description while the job waits in the queue. If it cannot, the job runs as masked with the defaults instead of failing.

Known whole-frame defects: a short shot of someone else can take the next shot's framing, an object named in the description can appear before the source shows it, and burned-in text or subtitles are redrawn unless keep names them (or paste_back covers them). A precise description fixes most of them.

POST https://api.happypony.io/api/v1/jobs/character-swap
GET  https://api.happypony.io/api/v1/jobs/:requestId/status
GET  https://api.happypony.io/api/v1/jobs/:requestId
PUT  https://api.happypony.io/api/v1/jobs/:requestId/cancel

1) Create a request

POST https://api.happypony.io/api/v1/jobs/character-swap with Content-Type: application/json. The clip and the pictures are fetched and stored when the request is created, so a URL that cannot be fetched is a 400 invalid_media and nothing is charged. A local file can be uploaded first.

Field Type Required Default Description
video_url string yes http(s) URL of the source clip (mp4, mov, webm or mkv, up to 200 MB).
pictures string[] yes 1 to 3 http(s) URLs of pictures (jpg, png or webp), one per person swapped in. picture_url (one URL string) is accepted instead for a single person. A clear, front-facing full or half-body shot works best.
mode string no chosen by the renderer Leave it out unless you need one job by name. bfs: the whole frame, one picture only (two or more is a 400). regen (alias nomask): the whole frame on the general swap model, one pass for every picture; naming it switches bfs off. masked (alias sequential): one masked pass per person. Left out, a request with mask, dry_run: true or one prompt per picture is masked; anything else is bfs with one picture and regen with several.
description object no written by a vision model from the clip and prompt bfs and regen: the clip in English, shot by shot. See The description. With it, prompts, window_prompts, mask, dry_run and mode masked are a 400.
prompt string no the most prominent person per picture Who to swap and whether the outfit stays, in plain words: "the person on the right", "the woman in the red dress gets Picture 1, the man gets Picture 2". A hint for the vision model that writes the description (or, on masked, picks the targets); never sent to the renderer. Up to 2000 characters.
keep_outfit boolean no false A hint for the vision model that writes the description: true keeps the clothes of the clip, only face, hair and identity come from the pictures. With your own description, set characters[].keep_outfit instead.
duration_seconds integer no 10 1 to 20. Only the first duration_seconds of the clip are processed; a shorter clip renders its whole length. A bfs job renders at most 16 s: a longer request is cut to 16 s, and that is what is billed. At resolution 768 the limit is 15.
start_seconds number no 0 0 to 3600. Where in the clip the processed span starts; duration_seconds counts from there, so the 20 s cap is 20 s of rendered clip wherever it starts. A start past the end of the clip fails the job. The clip's audio is cut the same way. Times in description, mask, paste_back and window_prompts are relative to the start of the processed span, not of the source.
seed integer no random The same inputs and seed give the same result.
swap_strength number no 1.0 on bfs and regen, 1.6 on masked 0 (the swap LoRA off: the plain model swaps from the words alone) or 0.5 to 2.0. How strongly the new look overrides the source person. Leave it out on bfs.
window integer no 226 on regen, 124 on masked Frames per render window: 226 (about 9.4 s) or 124 (about 5.2 s). 768 renders 124 only; 226 with it is a 400. A bfs job is always one window: leave it out.
reference_background string no grey on bfs and regen, keep on masked grey: each person is cut out of their picture onto grey first, so the picture's own scene, caption or watermark cannot reach the video. keep: the pictures as they are.
targets array no chosen by the vision model Always an array (a bare string is a 400), one per picture, in order: "leftmost", "rightmost", "largest" (one picture only) or an integer position (0 = leftmost, -1 = rightmost). On masked it skips the vision model's choice of who to replace; on regen it is a hint for the description.
prompts string[] no written from the vision model's plan masked: your own English worker prompts, skipping the plan: one per picture (or one for all). Refer to the pictures as <Picture 1> … and to the clip as <Video 1>.
sam_text string no person masked: what region of each target is replaced, in a few English words: person (the whole person, the default), head (only the head, when the new character keeps the source outfit and build). Up to 200 characters.
resolution string no follows the clip on bfs, else 480 480, 600, 704 or 768: the size of the render (a pixel budget; the clip keeps its aspect ratio). Left out, a bfs job follows the source up to 704 (a 720p or 1080p clip renders at 704, a 540p clip at 480); regen and masked render at 480. Higher sizes are sharper and slower; 600 and 704 help small faces and reflections. 768 takes about three times the render time, at most 15 s (duration_seconds ≤ 15).
targets: "all" masked, one picture only: swap every instance the mask finds (a person and their reflection in a mirror), not one person.
mask object no masked only. Tunes the swap mask: see Mask levers.
window_prompts object no {"<window>": "prompt"}: a prompt for one render window (0-based, window frames each), for a change of action or expression mid-clip. Windows not listed use the main prompt. One-pass jobs without a description only: one picture on masked, or regen with prompts. Values up to 4000 characters.
lipsync string no auto auto (pin the mouth to the source audio when the clip has some), on or off.
paste_back object[] no Up to 8 { "rect": [x, y, w, h], "frames"?: [start_s, end_s] }, rect in 0–1 fractions of the frame: source pixels copied back over the render inside each rectangle, for subtitles, logos or text inside the mask band.
dry_run boolean no false masked only. true: no render, only the mask preview and per-frame stats, in seconds.
People 5 s 10 s 15 s 20 s
1 1 2 3 4
2 2 4 6 8
3 3 6 9 12

The pictures and the clip go through the content check, so a request can answer 422 content_rejected (Errors). Adult clips render with the same recipe and every lever, on an adult-capable model swapped in for the default one.

The description (description)

What the whole-frame renderer is told about the clip. It never sees the clip the way a viewer does: it writes its prompt from this, so a shot left out or a person not mentioned comes out wrong. Every string is English, at most 500 characters. Describe only what the clip shows: no dialogue, story, praise words or instructions to the model. Unknown keys are a 400.

Key Type Description
scene string One sentence: the place, the light and the camera; the style when it is not live action. Best under 25 words.
characters object[] Exactly one per picture, in the order of pictures.
characters[].look string What the character in that picture looks like, as a list of attributes: gender, age, build, skin, eyes, hair, facial hair, accessories, clothes (leave the clothes out with keep_outfit). Best under 45 words.
characters[].replaces string A complete noun phrase that starts with "the" and names the person replaced in the clip by hair and clothes, with LEFT, RIGHT or MIDDLE when other people stay in the frame. Best under 20 words.
characters[].changes string, optional One or two sentences on what must visibly differ from the replaced person: a hat that goes, hair that now shows, the new clothes that stay on through the action. Best under 35 words.
characters[].keep_outfit boolean, optional true: the output keeps the clothes of the clip; only face, hair and identity come from the picture.
shots object[], 1–24 Every shot of the rendered clip in order, without gaps: the first starts at 0, the last ends at the rendered length, a new one at each hard cut. Each start is at least the previous end (0.05 s slack) and 0 ≤ start < end.
shots[].start, shots[].end number Seconds from the start of the processed span.
shots[].present boolean, optional false when no replaced person is visible in the shot (a back, hands or legs count as visible). Default true. List these shots too: one left out takes the next shot's framing and people. At least one shot is true.
shots[].action string The framing first, then where the replaced person is, how they move and what happens to them, never their own hair or clothes. "He" / "She" is the replaced person, anyone else by their look. A present: false shot says who is there and ends with "She is not in this shot." (or "He"). Name an object only in the shots where it is visible. Best under 55 words for a one-shot clip, 30 per shot otherwise.
keep string[], up to 12, optional One to four short phrases for what must survive: every other person with their position, an object that is handed over, burned-in text or subtitles. No scenery.

The whole description becomes one prompt of at most 6000 characters; a description that would make a longer one is a 400. Example, one picture over 5.2 s:

{
  "video_url": "https://assets.example.com/meadow.mp4",
  "pictures": ["https://assets.example.com/new-look.png"],
  "duration_seconds": 6,
  "description": {
    "scene": "Golden-hour meadow of dry grass with autumn trees behind, soft backlight, handheld camera that follows the two men in a medium shot throughout.",
    "characters": [
      {
        "look": "Male, mid twenties, slim build, light-brown skin, dark-brown eyes, black voluminous curly hair of medium length, clean-shaved, thin round gold-rimmed glasses, light-blue denim trucker jacket, white t-shirt, khaki chino trousers, tan suede boots",
        "replaces": "the man on the RIGHT, wearing a dark-grey cowboy hat and a tan-brown fringed suede shirt",
        "changes": "He wears no cowboy hat: his black curls and round gold glasses are visible, and the light-blue denim jacket, white t-shirt and khaki trousers stay on him through the lunge, the lift and the final embrace."
      }
    ],
    "shots": [
      { "start": 0, "end": 5.2, "present": true, "action": "Medium two-shot, the two men stand side by side with arms around each other, laughing. He lunges at the other man and is lifted off the ground in a spinning bear hug, then set down, both laughing, still embracing." }
    ],
    "keep": ["the man on the LEFT in the black cowboy hat, cream fringed shirt, blue jeans and brown belt"]
  }
}

A description written in Simplified Chinese for the earlier contract is still accepted.

Mask levers (mask)

masked only. The mask is what the swap may repaint: each target person as found by SAM, grown by a band. A wrong mask is the usual cause of a bad swap (the wrong person, a flickering edge, a cup or a microphone swapped too), so check a mask preview before a long or tricky render. The levers apply in this order: largest, expand, temporal, frames, subtract, boxes.

Key Type Default Description
expand integer 0–96 64 Band (px) the mask is grown by. 32 suits close-ups and medium shots; wider covers loose hair and clothes but repaints more of the background.
temporal integer 0–8 0 Joins each frame's mask with its ±N neighbours (fills flicker and dropped frames).
largest boolean false Keep only the largest blob per frame (drops stray detections).
cuts boolean false For a clip with several shots: the tracker starts again at every hard cut, so a shot without the person is left alone. Pair it with a sam_text that names the person ("woman").
shots up to 32 { "time": s, "targets": [...] } Who is replaced in each shot (implies cuts): time is a second inside the shot, targets one per picture as in targets, or "none" to leave the shot alone for that picture. Shots not listed use targets.
detect_time number (s) 0 The frame where the target is detected; pick one where the person is clearly visible. Inside the processed clip and inside frames when both are set.
frames [start_s, end_s] whole clip Mask (and so swap) only inside this time range.
subtract up to 4 { "text": string ≤ 200, "expand"?: 0–64 (default 18) } Occluders cut out of the mask, named in English ("the coffee cup", "microphone").
boxes up to 8 { "rect": [x, y, w, h], "set": 0 or 1, "frames"?: [start_s, end_s] } Rectangles (0–1 fractions of the frame) forced into (set: 1) or out of (set: 0) the mask, optionally only for a time range.

Numbers must be numbers and flags booleans (no numeric strings); an unknown key, a value out of range or a time range that starts past the processed clip (duration_seconds, or 20 s, 15 s at 768) is a 400 before anything is charged, as are mask or dry_run on bfs or regen and window_prompts with two or more pictures on masked.

Request body:

{
  "video_url": "https://assets.example.com/duo.mp4",
  "pictures": ["https://assets.example.com/new-woman.png", "https://assets.example.com/new-man.png"],
  "prompt": "the woman becomes Picture 1, the man becomes Picture 2",
  "duration_seconds": 10
}
curl -X POST https://api.happypony.io/api/v1/jobs/character-swap \
  -H "Authorization: Bearer $HP_KEY" -H "Content-Type: application/json" \
  -d '{"video_url": "https://assets.example.com/solo.mp4", "picture_url": "https://assets.example.com/new-look.png", "duration_seconds": 5}'

Response 202 (fields: Create response):

{
  "request_id": "48520",
  "type": "character-swap",
  "status": "IN_QUEUE",
  "credits": 4,
  "status_url": "https://api.happypony.io/api/v1/jobs/48520/status",
  "response_url": "https://api.happypony.io/api/v1/jobs/48520",
  "cancel_url": "https://api.happypony.io/api/v1/jobs/48520/cancel"
}

2) Poll for status

Poll the status_url until status is COMPLETED, FAILED or CANCELLED (fields: Status response). Once it leaves the queue, one person over 5 s takes about a minute and a half at 480p and longer at higher sizes (a 15 s clip at 704p takes several minutes); on regen one pass covers every picture, so two people take about as long as one; on masked two people over 10 s take about six minutes. Without your own description, writing one adds a little before the render starts. A queued job can be cancelled with PUT on the cancel_url (Cancel a request).

curl https://api.happypony.io/api/v1/jobs/48520/status -H "Authorization: Bearer $HP_KEY"
{
  "request_id": "48520",
  "type": "character-swap",
  "status": "IN_PROGRESS",
  "created_at": "2026-11-04T10:00:00.000Z",
  "completed_at": null,
  "credits": 4,
  "status_url": "…", "response_url": "…", "cancel_url": "…"
}

3) Fetch the result

When status is COMPLETED, fetch the response_url (common fields: Result response). The video is under videos, not images:

curl https://api.happypony.io/api/v1/jobs/48520 -H "Authorization: Bearer $HP_KEY"
{
  "request_id": "48520",
  "type": "character-swap",
  "status": "COMPLETED",
  "created_at": "2026-11-04T10:00:00.000Z",
  "completed_at": "2026-11-04T10:06:10.000Z",
  "credits": 4,
  "videos": [{ "url": "https://…signed…", "format": "mp4" }],
  "expires_in": 259200,
  "parameters": { "prompt": "the woman becomes Picture 1, the man becomes Picture 2",
                  "pictures": 2, "duration_seconds": 10, "mode": null, "seed": null, "swap_strength": null },
  "status_url": "…", "response_url": "…", "cancel_url": "…"
}
Field Type Description
videos object[] One mp4 with the source audio; empty until COMPLETED, and always empty for a dry_run.
files object[] When the renderer sends them: every output as { name, url, content_type, format }. Beside the mp4 that is compare.png (source and result frames side by side), so you can check a render without watching it, and on masked mask_preview.png (the mask drawn over source frames). Absent when there are none.
parameters object prompt, pictures (how many), duration_seconds, mode, seed and swap_strength (null where the default was used), and any of resolution, targets, description, keep_outfit, mask, window_prompts, window, reference_background, lipsync, paste_back and dry_run that were sent. A description the vision model wrote is not echoed.

Mask preview (dry run)

A dry_run: true job renders nothing. It finds the mask on every frame and returns a picture of it and its statistics, in seconds:

{
  "request_id": "48533",
  "type": "character-swap",
  "status": "COMPLETED",
  "credits": 1,
  "dry_run": true,
  "videos": [],
  "mask_preview": { "url": "https://…signed…", "content_type": "image/png" },
  "mask_stats": { "url": "https://…signed…", "content_type": "application/json",
                  "data": { "fps": 24, "passes": [{ "pass": 0, "render_would_fail": false, "mask": { "coverage_min": 0.08, "coverage_mean": 0.11, "coverage_max": 0.14 } }] } },
  "files": [{ "name": "mask_preview.png", "url": "…", "content_type": "image/png", "format": "png" },
            { "name": "mask_stats.json", "url": "…", "content_type": "application/json", "format": "json" }],
  "expires_in": 259200,
  "parameters": { "duration_seconds": 10, "mask": { "expand": 32 }, "dry_run": true, "resolution": null, "…": "…" }
}

parameters is abridged: it echoes every lever you sent (sam_text, targets, …) plus resolution. mask_preview shows the mask in green over frames across the clip: it should cover the person to swap, and only them, on every frame. mask_stats.data (inlined when small; otherwise fetch mask_stats.url) has per-pass and per-frame coverage: a frame with no mask, or render_would_fail: true, means a real render with the same settings would fail, so fix the mask first (detect_time, temporal, boxes). A sudden jump in coverage usually means the mask jumped to another person or object. A dry run is masked only (regen builds no mask). Send the same request without dry_run to render.

Full example

Create, poll until done, download:

curl (bash)

# Needs curl and jq. Usage: HP_KEY=hp_… ./charswap.sh
JOB=$(curl -s -X POST https://api.happypony.io/api/v1/jobs/character-swap \
  -H "Authorization: Bearer $HP_KEY" -H "Content-Type: application/json" \
  -d '{"video_url": "https://assets.example.com/duo.mp4",
       "pictures": ["https://assets.example.com/new-woman.png", "https://assets.example.com/new-man.png"],
       "prompt": "the woman becomes Picture 1, the man becomes Picture 2",
       "duration_seconds": 10}')
echo "$JOB" | jq .
STATUS_URL=$(echo "$JOB" | jq -r .status_url)
RESPONSE_URL=$(echo "$JOB" | jq -r .response_url)

while :; do
  STATUS=$(curl -s "$STATUS_URL" -H "Authorization: Bearer $HP_KEY" | jq -r .status)
  [ "$STATUS" = IN_QUEUE ] || [ "$STATUS" = IN_PROGRESS ] || break
  sleep 15
done
echo "$STATUS"
curl -s -o swap.mp4 "$(curl -s "$RESPONSE_URL" -H "Authorization: Bearer $HP_KEY" | jq -r '.videos[0].url')"

Python

# pip install requests   |   HP_KEY=hp_… python charswap.py
import os, time, requests

BASE = "https://api.happypony.io/api/v1/jobs"
H = {"Authorization": f"Bearer {os.environ['HP_KEY']}"}

# A local clip instead of a public URL: upload it first.
# clip = requests.post(f"{BASE}/uploads", headers=H, files={"file": open("duo.mp4", "rb")}).json()["url"]
job = requests.post(f"{BASE}/character-swap", headers=H, json={
    "video_url": "https://assets.example.com/duo.mp4",
    "pictures": ["https://assets.example.com/new-woman.png", "https://assets.example.com/new-man.png"],
    "prompt": "the woman becomes Picture 1, the man becomes Picture 2",
    "duration_seconds": 10,
})
job.raise_for_status()
job = job.json()
print("job", job["request_id"], "costs", job["credits"], "credits")

while (s := requests.get(job["status_url"], headers=H).json())["status"] in ("IN_QUEUE", "IN_PROGRESS"):
    time.sleep(15)
result = requests.get(job["response_url"], headers=H).json()
if result["status"] != "COMPLETED":
    raise SystemExit(f"{result['status']}: {result.get('error', '')}")
with open(f"swap-{job['request_id']}.mp4", "wb") as f:
    f.write(requests.get(result["videos"][0]["url"]).content)

Node.js

// Node 18+ (built-in fetch). Save as charswap.mjs: HP_KEY=hp_… node charswap.mjs
import { writeFileSync } from "node:fs";

const BASE = "https://api.happypony.io/api/v1/jobs";
const AUTH = { Authorization: `Bearer ${process.env.HP_KEY}` };

async function call(url, init = {}) {
  const res = await fetch(url, { ...init, headers: { ...AUTH, ...init.headers } });
  if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
  return res.json();
}

const job = await call(`${BASE}/character-swap`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    video_url: "https://assets.example.com/duo.mp4",
    pictures: ["https://assets.example.com/new-woman.png", "https://assets.example.com/new-man.png"],
    prompt: "the woman becomes Picture 1, the man becomes Picture 2",
    duration_seconds: 10,
  }),
});
console.log("job", job.request_id, "costs", job.credits, "credits");

let status;
while (true) {
  ({ status } = await call(job.status_url));
  if (!["IN_QUEUE", "IN_PROGRESS"].includes(status)) break;
  await new Promise((r) => setTimeout(r, 15_000));
}
const result = await call(job.response_url);
if (status !== "COMPLETED") throw new Error(`${status}: ${result.error ?? ""}`);
const res = await fetch(result.videos[0].url); // presigned: no auth header
writeFileSync(`swap-${job.request_id}.mp4`, Buffer.from(await res.arrayBuffer()));

角色替换

价格:角色替换

用参考图片中的角色替换视频里的一到三个人。保留原视频的表演(姿势、视线、表情、动作)、场景和原声,替换选中的人物。每张图片对应一个要换入的人。返回一个 mp4。

有三种任务。不传 mode 时,渲染器会为请求选择合适的整帧任务:

整帧任务也会重绘场景,接近原视频但不是逐像素一致,所以不能变的东西(其他人、物体、字幕)要写进描述。可以自己发送 description,也可以不发,用自然语言说明替换谁(prompt,例如"右边的女人"):任务排队期间,视觉模型会观看视频并写出描述。如果写不出来,任务会以默认设置按 masked 运行,而不是失败。

整帧任务已知的问题:别人的短镜头可能沿用下一个镜头的构图;描述中提到的物体可能比原视频更早出现;画面内嵌的文字或字幕会被重绘,除非在 keep 中写明(或用 paste_back 覆盖)。准确的描述可以解决其中大部分问题。

POST https://api.happypony.io/api/v1/jobs/character-swap
GET  https://api.happypony.io/api/v1/jobs/:requestId/status
GET  https://api.happypony.io/api/v1/jobs/:requestId
PUT  https://api.happypony.io/api/v1/jobs/:requestId/cancel

1) 创建请求

POST https://api.happypony.io/api/v1/jobs/character-swap,Content-Type: application/json。创建请求时会下载并保存视频和图片,因此无法下载的 URL 会返回 400 invalid_media,不扣积分。本地文件可以先上传。

字段 类型 必填 默认值 说明
video_url string 是 源视频的 http(s) URL(mp4、mov、webm 或 mkv,最大 200 MB)。
pictures string[] 是 1 到 3 个图片 http(s) URL(jpg、png 或 webp),每张对应一个要换入的人。只替换一个人时也可以改用 picture_url(一个 URL 字符串)。清晰的正面全身或半身照效果最好。
mode string 否 由渲染器选择 除非需要指定某个任务,否则不要传。bfs:整帧,仅限一张图片(两张及以上返回 400)。regen(别名 nomask):使用通用替换模型的整帧任务,一遍处理所有图片;指定它会关闭 bfs。masked(别名 sequential):每个人一遍遮罩处理。不提供时,带有 mask、dry_run: true 或每张图片一个提示词的请求为 masked;其余情况一张图片为 bfs,多张为 regen。
description object 否 由视觉模型根据视频和 prompt 写出 bfs 和 regen:用英文逐镜头描述视频,见视频描述。提供它时,prompts、window_prompts、mask、dry_run 和 mode masked 都会返回 400。
prompt string 否 每张图片对应画面中最显眼的人 用自然语言说明替换谁、是否保留服装:"右边的人"、"穿红裙子的女人换成图片 1,男人换成图片 2"。这是给撰写描述的视觉模型(masked 时为选择替换对象)的提示,不会发送给渲染器。最多 2000 个字符。
keep_outfit boolean 否 false 给撰写描述的视觉模型的提示:true 保留视频中的服装,只从图片中取脸、发型和身份。自己提供 description 时,请改用 characters[].keep_outfit。
duration_seconds integer 否 10 1 到 20。只处理视频的前 duration_seconds 秒;更短的视频按其完整长度渲染。bfs 任务最多渲染 16 秒:更长的请求会被截到 16 秒,并按 16 秒计费。resolution 为 768 时上限是 15。
start_seconds number 否 0 0 到 3600。处理区间在视频中的起点;duration_seconds 从这里开始计,所以 20 秒上限指的是渲染出的 20 秒,无论从哪里开始。起点超出视频末尾时任务失败。视频音频同样按此截取。description、mask、paste_back 和 window_prompts 中的时间都相对于处理区间的起点,而不是原视频。
seed integer 否 随机 相同的输入和 seed 得到相同的结果。
swap_strength number 否 bfs 和 regen 为 1.0,masked 为 1.6 0(关闭换脸 LoRA:基础模型只按文字替换)或 0.5 到 2.0。新形象覆盖原人物的强度。bfs 任务不要传。
window integer 否 regen 为 226,masked 为 124 每个渲染窗口的帧数:226(约 9.4 秒)或 124(约 5.2 秒)。768 只能用 124,同时设置 226 返回 400。bfs 任务始终只有一个窗口:不要传。
reference_background string 否 bfs 和 regen 为 grey,masked 为 keep grey:先把每个人从图片中抠到灰色背景上,图片自身的场景、文字或水印不会进入视频。keep:按原样使用图片。
targets array 否 由视觉模型选择 必须是数组(裸字符串返回 400),每张图片一个,按顺序:"leftmost"、"rightmost"、"largest"(仅限一张图片)或整数位置(0 = 最左,-1 = 最右)。masked 时跳过视觉模型对替换对象的选择;regen 时作为撰写描述的提示。
prompts string[] 否 根据视觉模型的规划生成 masked:自己写的英文 worker 提示词,跳过规划:每张图片一个(或一个通用)。用 <Picture 1> … 指代图片,用 <Video 1> 指代视频。
sam_text string 否 person masked:每个替换对象中被替换的区域,用几个英文单词描述:person(整个人,默认)、head(只换头部,适合新角色保留原服装且体型相同的情况)。最多 200 个字符。
resolution string 否 bfs 跟随原视频,其余为 480 480、600、704 或 768:渲染尺寸(像素预算,保持原视频的宽高比)。不提供时,bfs 任务跟随原视频,最高 704(720p 或 1080p 的视频以 704 渲染,540p 的以 480 渲染);regen 和 masked 以 480 渲染。尺寸越大越清晰,也越慢;600 和 704 有助于小脸和倒影。768 的渲染时间约为三倍,最长 15 秒(duration_seconds ≤ 15)。
targets: "all" masked,仅限一张图片:替换遮罩找到的所有实例(例如一个人和镜子里的倒影),而不是一个人。
mask object 否 仅 masked。调整替换遮罩,见遮罩参数。
window_prompts object 否 {"<窗口>": "提示词"}:为某个渲染窗口(从 0 开始,每个 window 帧)单独指定提示词,用于视频中途动作或表情的变化。未列出的窗口使用主提示词。仅限没有 description 的单遍任务:masked 下一张图片,或带 prompts 的 regen。每个值最多 4000 个字符。
lipsync string 否 auto auto(视频有声音时让口型对齐原声)、on 或 off。
paste_back object[] 否 最多 8 个 { "rect": [x, y, w, h], "frames"?: [start_s, end_s] },rect 为画面的 0–1 比例:在每个矩形内把原视频像素贴回渲染结果上,用于遮罩边带内的字幕、标志或文字。
dry_run boolean 否 false 仅 masked。true:不渲染,只返回遮罩预览和逐帧统计,几秒完成。
人数 5 秒 10 秒 15 秒 20 秒
1 1 2 3 4
2 2 4 6 8
3 3 6 9 12

图片和视频会经过内容审核,因此请求可能返回 422 content_rejected(错误)。成人内容的视频使用同样的流程和全部参数,只是换用一个能处理成人内容的模型替代默认模型。

视频描述(description)

整帧重绘渲染器得到的视频信息。它不像观众那样看到视频:它根据描述写提示词,所以漏掉的镜头或没提到的人都会出错。所有字符串都用英文,最多 500 个字符。只描述视频里看得到的内容:不要写台词、剧情、赞美的词或给模型的指令。未知的键返回 400。

键 类型 说明
scene string 一句话:地点、光线和镜头;不是实拍时写明风格。最好不超过 25 个单词。
characters object[] 每张图片恰好一个,顺序与 pictures 相同。
characters[].look string 这张图片中角色的样子,按属性列出:性别、年龄、体型、肤色、眼睛、头发、胡须、配饰、服装(设置 keep_outfit 时不写服装)。最好不超过 45 个单词。
characters[].replaces string 一个以 "the" 开头的完整名词短语,用发型和服装指出视频中被替换的人;画面中还有其他人时加上 LEFT、RIGHT 或 MIDDLE。最好不超过 20 个单词。
characters[].changes string,可选 一两句话,说明与被替换的人相比必须看得出的变化:去掉的帽子、露出来的头发、在整个动作中一直穿着的新服装。最好不超过 35 个单词。
characters[].keep_outfit boolean,可选 true:输出保留视频中的服装,只从图片中取脸、发型和身份。
shots object[],1–24 渲染片段中的每个镜头,按顺序、无间隙:第一个从 0 开始,最后一个在渲染长度处结束,每个硬切换开始一个新镜头。每个 start 不早于上一个 end(允许 0.05 秒误差),且 0 ≤ start < end。
shots[].start、shots[].end number 秒,从处理区间的起点算起。
shots[].present boolean,可选 镜头中看不到被替换的人时为 false(背影、手或腿也算看得到)。默认 true。这些镜头也要列出:漏掉的镜头会沿用下一个镜头的构图和人物。至少一个镜头为 true。
shots[].action string 先写景别,再写被替换的人在哪里、怎么动、发生了什么,不要写其本人的头发或服装。"He" / "She" 指被替换的人,其他人用外貌指代。present: false 的镜头写明画面里有谁,并以 "She is not in this shot."(或 "He")结尾。物体只写在它出现的镜头里。单镜头视频最好不超过 55 个单词,多镜头每个不超过 30 个。
keep string[],最多 12 个,可选 一到四个短语,写必须保留的东西:其他每个人(带位置)、被递交的物体、画面内嵌的文字或字幕。不要写场景。

整个描述会合成一个最多 6000 个字符的提示词;会超出的描述返回 400。示例,一张图片、5.2 秒:

{
  "video_url": "https://assets.example.com/meadow.mp4",
  "pictures": ["https://assets.example.com/new-look.png"],
  "duration_seconds": 6,
  "description": {
    "scene": "Golden-hour meadow of dry grass with autumn trees behind, soft backlight, handheld camera that follows the two men in a medium shot throughout.",
    "characters": [
      {
        "look": "Male, mid twenties, slim build, light-brown skin, dark-brown eyes, black voluminous curly hair of medium length, clean-shaved, thin round gold-rimmed glasses, light-blue denim trucker jacket, white t-shirt, khaki chino trousers, tan suede boots",
        "replaces": "the man on the RIGHT, wearing a dark-grey cowboy hat and a tan-brown fringed suede shirt",
        "changes": "He wears no cowboy hat: his black curls and round gold glasses are visible, and the light-blue denim jacket, white t-shirt and khaki trousers stay on him through the lunge, the lift and the final embrace."
      }
    ],
    "shots": [
      { "start": 0, "end": 5.2, "present": true, "action": "Medium two-shot, the two men stand side by side with arms around each other, laughing. He lunges at the other man and is lifted off the ground in a spinning bear hug, then set down, both laughing, still embracing." }
    ],
    "keep": ["the man on the LEFT in the black cowboy hat, cream fringed shirt, blue jeans and brown belt"]
  }
}

按早期约定用简体中文写的描述仍然可以使用。

遮罩参数(mask)

仅 masked。遮罩决定替换可以重绘的区域:SAM 找到的每个替换对象,再向外扩展一圈边带。遮罩出错是替换效果差的常见原因(换错了人、边缘闪烁、杯子或麦克风也被替换),所以在较长或较难的渲染之前,先看一次遮罩预览。各参数按以下顺序生效:largest、expand、temporal、frames、subtract、boxes。

键 类型 默认值 说明
expand 整数 0–96 64 遮罩向外扩展的边带(像素)。特写和中景用 32 合适;更宽能覆盖飘动的头发和衣物,但会重绘更多背景。
temporal 整数 0–8 0 把每帧的遮罩与前后 N 帧合并(填补闪烁和丢帧)。
largest boolean false 每帧只保留最大的一块(去掉零散的误检)。
cuts boolean false 用于有多个镜头的视频:跟踪器在每个硬切换处重新开始,没有这个人的镜头不会被改动。配合一个指明这个人的 sam_text("woman")。
shots 最多 32 个 { "time": 秒, "targets": [...] } 每个镜头替换谁(隐含 cuts):time 是镜头内的某一秒,targets 每张图片一个,取值同 targets,或用 "none" 让该图片不改动这个镜头。未列出的镜头使用 targets。
detect_time 数字(秒) 0 检测替换对象所用的帧;选人物清晰可见的一帧。必须在处理范围内,同时设置 frames 时也必须在其中。
frames [start_s, end_s] 整段视频 只在这个时间范围内生成遮罩(也就是只在其中替换)。
subtract 最多 4 个 { "text": 字符串 ≤ 200, "expand"?: 0–64(默认 18) } 从遮罩中挖掉的遮挡物,用英文命名("the coffee cup"、"microphone")。
boxes 最多 8 个 { "rect": [x, y, w, h], "set": 0 或 1, "frames"?: [start_s, end_s] } 强制加入(set: 1)或排除(set: 0)遮罩的矩形(画面的 0–1 比例),可只作用于某个时间范围。

数字必须是数字,开关必须是布尔值(不接受数字字符串);未知的键、超出范围的值,或起点超出处理范围(duration_seconds,未提供时为 20 秒,768 时为 15 秒)的时间范围,都会在扣费前返回 400;bfs 或 regen 下的 mask 或 dry_run,以及 masked 下两张及以上图片时的 window_prompts 也一样。

请求体:

{
  "video_url": "https://assets.example.com/duo.mp4",
  "pictures": ["https://assets.example.com/new-woman.png", "https://assets.example.com/new-man.png"],
  "prompt": "穿红裙子的女人换成图片 1,男人换成图片 2",
  "duration_seconds": 10
}
curl -X POST https://api.happypony.io/api/v1/jobs/character-swap \
  -H "Authorization: Bearer $HP_KEY" -H "Content-Type: application/json" \
  -d '{"video_url": "https://assets.example.com/solo.mp4", "picture_url": "https://assets.example.com/new-look.png", "duration_seconds": 5}'

响应 202(字段见创建响应):

{
  "request_id": "48520",
  "type": "character-swap",
  "status": "IN_QUEUE",
  "credits": 4,
  "status_url": "https://api.happypony.io/api/v1/jobs/48520/status",
  "response_url": "https://api.happypony.io/api/v1/jobs/48520",
  "cancel_url": "https://api.happypony.io/api/v1/jobs/48520/cancel"
}

2) 轮询状态

轮询 status_url,直到 status 为 COMPLETED、FAILED 或 CANCELLED(字段见状态响应)。离开队列后,480p 下一个人 5 秒约需一分半钟,尺寸越大越久(704p 的 15 秒视频需要几分钟);regen 一遍处理所有图片,所以两个人与一个人用时相近;masked 下两个人 10 秒约需六分钟。不自己提供 description 时,撰写描述会让渲染稍晚开始。排队中的任务可以对 cancel_url 发送 PUT 取消(取消请求)。

curl https://api.happypony.io/api/v1/jobs/48520/status -H "Authorization: Bearer $HP_KEY"
{
  "request_id": "48520",
  "type": "character-swap",
  "status": "IN_PROGRESS",
  "created_at": "2026-11-04T10:00:00.000Z",
  "completed_at": null,
  "credits": 4,
  "status_url": "…", "response_url": "…", "cancel_url": "…"
}

3) 获取结果

status 为 COMPLETED 后,请求 response_url(通用字段见结果响应)。视频位于 videos 下,而不是 images:

curl https://api.happypony.io/api/v1/jobs/48520 -H "Authorization: Bearer $HP_KEY"
{
  "request_id": "48520",
  "type": "character-swap",
  "status": "COMPLETED",
  "created_at": "2026-11-04T10:00:00.000Z",
  "completed_at": "2026-11-04T10:06:10.000Z",
  "credits": 4,
  "videos": [{ "url": "https://…signed…", "format": "mp4" }],
  "expires_in": 259200,
  "parameters": { "prompt": "the woman becomes Picture 1, the man becomes Picture 2",
                  "pictures": 2, "duration_seconds": 10, "mode": null, "seed": null, "swap_strength": null },
  "status_url": "…", "response_url": "…", "cancel_url": "…"
}
字段 类型 说明
videos object[] 一个保留原声的 mp4;COMPLETED 之前为空,dry_run 时始终为空。
files object[] 渲染器提供时:每个输出为 { name, url, content_type, format }。除 mp4 外还有 compare.png(原视频帧与结果帧并排),不看视频也能检查渲染效果;masked 时还有 mask_preview.png(画在原视频帧上的遮罩)。没有时不出现。
parameters object prompt、pictures(图片数量)、duration_seconds、mode、seed 和 swap_strength(使用默认值时为 null),以及请求中提供的 resolution、targets、description、keep_outfit、mask、window_prompts、window、reference_background、lipsync、paste_back 和 dry_run。视觉模型写的描述不会回显。

遮罩预览(试运行)

dry_run: true 的任务不渲染。它在每一帧上找出遮罩,返回遮罩图片和统计数据,几秒完成:

{
  "request_id": "48533",
  "type": "character-swap",
  "status": "COMPLETED",
  "credits": 1,
  "dry_run": true,
  "videos": [],
  "mask_preview": { "url": "https://…signed…", "content_type": "image/png" },
  "mask_stats": { "url": "https://…signed…", "content_type": "application/json",
                  "data": { "fps": 24, "passes": [{ "pass": 0, "render_would_fail": false, "mask": { "coverage_min": 0.08, "coverage_mean": 0.11, "coverage_max": 0.14 } }] } },
  "files": [{ "name": "mask_preview.png", "url": "…", "content_type": "image/png", "format": "png" },
            { "name": "mask_stats.json", "url": "…", "content_type": "application/json", "format": "json" }],
  "expires_in": 259200,
  "parameters": { "duration_seconds": 10, "mask": { "expand": 32 }, "dry_run": true, "resolution": null, "…": "…" }
}

parameters 有删节:它会回显你发送的每个参数(sam_text、targets……)以及 resolution。mask_preview 用绿色把遮罩画在整段视频的若干帧上:每一帧都应覆盖要替换的人,且只覆盖这个人。mask_stats.data(较小时直接内联,否则请求 mask_stats.url)包含每遍和每帧的覆盖率:某帧没有遮罩,或 render_would_fail: true,表示用同样设置的真实渲染会失败,请先修正遮罩(detect_time、temporal、boxes)。覆盖率突然跳变通常说明遮罩跳到了另一个人或物体上。试运行仅限 masked(regen 不生成遮罩)。去掉 dry_run 发送同样的请求即可渲染。

完整示例

创建、轮询直到完成、下载:

curl (bash)

# Needs curl and jq. Usage: HP_KEY=hp_… ./charswap.sh
JOB=$(curl -s -X POST https://api.happypony.io/api/v1/jobs/character-swap \
  -H "Authorization: Bearer $HP_KEY" -H "Content-Type: application/json" \
  -d '{"video_url": "https://assets.example.com/duo.mp4",
       "pictures": ["https://assets.example.com/new-woman.png", "https://assets.example.com/new-man.png"],
       "prompt": "the woman becomes Picture 1, the man becomes Picture 2",
       "duration_seconds": 10}')
echo "$JOB" | jq .
STATUS_URL=$(echo "$JOB" | jq -r .status_url)
RESPONSE_URL=$(echo "$JOB" | jq -r .response_url)

while :; do
  STATUS=$(curl -s "$STATUS_URL" -H "Authorization: Bearer $HP_KEY" | jq -r .status)
  [ "$STATUS" = IN_QUEUE ] || [ "$STATUS" = IN_PROGRESS ] || break
  sleep 15
done
echo "$STATUS"
curl -s -o swap.mp4 "$(curl -s "$RESPONSE_URL" -H "Authorization: Bearer $HP_KEY" | jq -r '.videos[0].url')"

Python

# pip install requests   |   HP_KEY=hp_… python charswap.py
import os, time, requests

BASE = "https://api.happypony.io/api/v1/jobs"
H = {"Authorization": f"Bearer {os.environ['HP_KEY']}"}

# A local clip instead of a public URL: upload it first.
# clip = requests.post(f"{BASE}/uploads", headers=H, files={"file": open("duo.mp4", "rb")}).json()["url"]
job = requests.post(f"{BASE}/character-swap", headers=H, json={
    "video_url": "https://assets.example.com/duo.mp4",
    "pictures": ["https://assets.example.com/new-woman.png", "https://assets.example.com/new-man.png"],
    "prompt": "the woman becomes Picture 1, the man becomes Picture 2",
    "duration_seconds": 10,
})
job.raise_for_status()
job = job.json()
print("job", job["request_id"], "costs", job["credits"], "credits")

while (s := requests.get(job["status_url"], headers=H).json())["status"] in ("IN_QUEUE", "IN_PROGRESS"):
    time.sleep(15)
result = requests.get(job["response_url"], headers=H).json()
if result["status"] != "COMPLETED":
    raise SystemExit(f"{result['status']}: {result.get('error', '')}")
with open(f"swap-{job['request_id']}.mp4", "wb") as f:
    f.write(requests.get(result["videos"][0]["url"]).content)

Node.js

// Node 18+ (built-in fetch). Save as charswap.mjs: HP_KEY=hp_… node charswap.mjs
import { writeFileSync } from "node:fs";

const BASE = "https://api.happypony.io/api/v1/jobs";
const AUTH = { Authorization: `Bearer ${process.env.HP_KEY}` };

async function call(url, init = {}) {
  const res = await fetch(url, { ...init, headers: { ...AUTH, ...init.headers } });
  if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
  return res.json();
}

const job = await call(`${BASE}/character-swap`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    video_url: "https://assets.example.com/duo.mp4",
    pictures: ["https://assets.example.com/new-woman.png", "https://assets.example.com/new-man.png"],
    prompt: "the woman becomes Picture 1, the man becomes Picture 2",
    duration_seconds: 10,
  }),
});
console.log("job", job.request_id, "costs", job.credits, "credits");

let status;
while (true) {
  ({ status } = await call(job.status_url));
  if (!["IN_QUEUE", "IN_PROGRESS"].includes(status)) break;
  await new Promise((r) => setTimeout(r, 15_000));
}
const result = await call(job.response_url);
if (status !== "COMPLETED") throw new Error(`${status}: ${result.error ?? ""}`);
const res = await fetch(result.videos[0].url); // presigned: no auth header
writeFileSync(`swap-${job.request_id}.mp4`, Buffer.from(await res.arrayBuffer()));