Turn one topic into a finished Vox-style paper-collage explainer/ad video — automated end to end on Atlas Cloud + ffmpeg. An agent skill.
Python aiai-videoclaude-codeclaude-skillcollage-videodsh-pluginexplainer-videoffmpeggenerative-aillmmotion-graphicspythontext-to-videottsvideovideo-generationvox
feat: host mode — a digital presenter speaks on camera (#15)
Alisa6a85a7c34161
diff --git a/README.md b/README.mdindex 2f4b5c2..88e78f5 100644--- a/README.md+++ b/README.md@@ -55,10 +55,11 @@ topic└─ final.mp4```-That flow is **B-roll** — a topic in, everything generated. Two more input modalities reuse the same engine:+That flow is **B-roll** — a topic in, everything generated. Two more input modalities, plus a presenter mode, reuse the same engine:- **A-roll — you already have a talking-head video.** It is ASR-segmented into beats and re-styled into the collage look, keeping the real face, lip-sync and gestures frame-for-frame (`gemini-omni-flash/video-edit`, auto-retrying on `seedance-2.0/reference-to-video`).- **C-roll — you have one still photo** (a selfie, a product shot). The subject is cut out as a photographic sticker — never redrawn — and each beat's poster is generated around it (`nano-banana-2/edit`). The narration can be cloned into the subject's own voice.+- **Host — one image of a presenter.** Selected beats cut to a digital presenter who speaks the narration, lip-synced, inside the collage world (16:9 and 9:16; position and size adjustable). The presenter and the world are generated as two plates and keyed together (`seedance-2.0/reference-to-video` + `gemini-omni-flash/image-to-video`).Two ideas make or break the result, and the skill is built around both:@@ -76,6 +77,7 @@ Two human decision gates keep you in control (approve the beat map; pick the sty| Animate (**real people / brands**) | `kwaivgi/kling-video-o3-pro/image-to-video` || Re-style a talking-head (A-roll) | `google/gemini-omni-flash/video-edit` || Anchor a photo in the collage (C-roll) | `google/nano-banana-2/edit` |+| Presenter on camera (Host) | `bytedance/seedance-2.0/reference-to-video` + `google/gemini-omni-flash/image-to-video` || Narration | `xai/tts-v1` || Narration in a real person's voice | `bytedance/seed-audio-1.0` (voice cloning) || Music | `minimax/music-2.6` |diff --git a/README.zh.md b/README.zh.mdindex b674a1a..51ae23a 100644--- a/README.zh.md+++ b/README.zh.md@@ -55,10 +55,11 @@ https://github.com/user-attachments/assets/ed08d230-7bcb-4b48-a17d-23c079208f9f└─ final.mp4```-上面这条是 **B-roll**——一个选题进去,画面全靠生成。另外两种输入形态复用同一套引擎:+上面这条是 **B-roll**——一个选题进去,画面全靠生成。另外两种输入形态和一个主持人模式复用同一套引擎:- **A-roll——你已经有一段口播视频。** 它会被 ASR 自动切成段,再整段套上拼贴风格,真人的脸、口型、手势逐帧保留(`gemini-omni-flash/video-edit`,失败自动重试 `seedance-2.0/reference-to-video`)。- **C-roll——你只有一张静态照片**(自拍、产品图)。主体被抠成摄影质感的贴纸——绝不重绘——每一段的海报围着它生成(`nano-banana-2/edit`)。旁白还能克隆成主体本人的声音。+- **Host——一张主持人形象图。** 指定的 beat 会切到数字人,对口型念旁白,站在拼贴世界里(支持 16:9 和 9:16,位置和大小可调)。人物和世界分两块板生成再抠绿合成(`seedance-2.0/reference-to-video` + `gemini-omni-flash/image-to-video`)。两个关键理念决定成败,技能就是围绕它们搭的:@@ -76,6 +77,7 @@ https://github.com/user-attachments/assets/ed08d230-7bcb-4b48-a17d-23c079208f9f| 动效(**真人 / 品牌**) | `kwaivgi/kling-video-o3-pro/image-to-video` || 口播视频转拼贴(A-roll) | `google/gemini-omni-flash/video-edit` || 照片锚进拼贴(C-roll) | `google/nano-banana-2/edit` |+| 数字人出镜(Host) | `bytedance/seedance-2.0/reference-to-video` + `google/gemini-omni-flash/image-to-video` || 旁白 | `xai/tts-v1` || 用真人本人的声音念旁白 | `bytedance/seed-audio-1.0`(声音克隆) || 配乐 | `minimax/music-2.6` |diff --git a/SKILL.md b/SKILL.mdindex 4d03db1..0abac47 100644--- a/SKILL.md+++ b/SKILL.md@@ -213,6 +213,27 @@ or a collage ad built around a real product shot (validated on both, 2026-07-17)above); derive stamp/snap-zoom timing from the narration's ASR word timestamps(`asr_beats.py` works on any audio, not just A-roll footage).+## Host mode (a presenter speaks on camera)++Use when the user wants a **digital presenter on screen** speaking some of the narration,+from ONE still image of that presenter (not a recorded video: that is A-roll). Mark those+beats with a shot `"kind": "host"`; every other beat stays normal B-roll. Full recipe,+rules and limits: `references/host-mode.md` (read it before using this mode).++1. Add `host.avatar` (a finished character design, never redrawn) and, per host beat, one+ shot with `kind: "host"`, a world-only `scene` and an `element_motion` that names each+ element and pins its shape. The beat's narration must be at most 9.5 s.+2. `audio.py` first, then `python3 scripts/host_plates.py out/<project>`: **look at both+ plates** (flat green, face intact, empty region clear) before spending on video.+3. `python3 scripts/host_clips.py out/<project>` prints a cost estimate and stops; show it to+ the user, then re-run with `--yes`. It generates the presenter (Seedance) and the world+ (Omni) separately, adopts the presenter clip's own audio, and keys them together.+4. `clips.py` and `keyframes.py` skip host shots; `assemble.py` never stretches them.++The user can place and size the presenter with `host.position` and `host.size`. 16:9 and+9:16 are supported. A host clip costs about twice a B-roll clip per second. Known issue:+the world video can drift (see the reference); re-roll it if it does.+## beats.json schema```json@@ -237,6 +258,7 @@ or a collage ad built around a real product shot (validated on both, 2026-07-17)"caption_style": "white", // white (default: clean white subtitle) | paper (cream cut-out collage look)"captions": true, // false = no burned-in captions (deliver clean, subtitle in post)"watermark": "Made with Atlas Cloud",+ "host": {"avatar": "path/to/presenter.jpg", "position": "left", "size": 0.25}, // host mode only (references/host-mode.md)"mode": "croll", // C-roll only — plus the four fields below"anchor_photo": "path/to/photo.png", // C-roll: the still to anchor (person or product)"croll_subject": "portrait", // C-roll: portrait | productdiff --git a/SKILL.zh.md b/SKILL.zh.mdindex 3914f1b..05b5734 100644--- a/SKILL.zh.md+++ b/SKILL.zh.md@@ -158,6 +158,23 @@ Vox 拼贴的**样子**和**动效**是两件事、两步:的旁白 + 配乐);印章/急推的时间点从旁白的 ASR 词级时间戳推(`asr_beats.py` 对任意音频都能用,不限 A-roll 素材)。+## Host 模式(数字人在镜头里口播)++用户想让**一个数字人出镜**念其中几段旁白、素材只有这个人的**一张静图**时使用(不是录好的视频,+那是 A-roll)。把这些 beat 里的镜头标成 `"kind": "host"`,其余 beat 仍是普通 B-roll。完整配方、+规则和限制见 `references/host-mode.md`(用这个模式前先读)。++1. 配 `host.avatar`(一张定稿的角色形象,绝不重绘),每个 host beat 放一个 `kind: "host"` 的镜头:+ `scene` 只写世界板(不含人),`element_motion` 点名每个元素并钉死形状。该 beat 旁白不超过 9.5 秒。+2. 先跑 `audio.py`,再跑 `python3 scripts/host_plates.py out/<project>`:**花视频钱之前先看两张板**+ (绿幕平整、脸没被重绘、留空区域是干净的)。+3. `python3 scripts/host_clips.py out/<project>` 先打印费用估算然后停下,给用户看过再加 `--yes`。它分别+ 生成人物(Seedance)和世界(Omni),采用人物视频自带的音轨,再抠绿合成。+4. `clips.py`、`keyframes.py` 会跳过 host 镜头;`assemble.py` 不会拉伸它们。++用户可以用 `host.position`、`host.size` 调人物位置和大小。支持 16:9 和 9:16。host 镜头每秒成本约为+B-roll 的两倍。已知问题:世界视频可能漂移(见 reference),漂了就重抽。+## beats.json schema```json@@ -182,6 +199,7 @@ Vox 拼贴的**样子**和**动效**是两件事、两步:"caption_style": "white", // white(默认:干净白字幕)| paper(奶油剪纸拼贴风)"captions": true, // false = 不烧字幕(交干净成片,字幕留到后期上)"watermark": "Made with Atlas Cloud",+ "host": {"avatar": "path/to/presenter.jpg", "position": "left", "size": 0.25}, // 仅 host 模式(references/host-mode.md)"mode": "croll", // 仅 C-roll —— 外加下面四个字段"anchor_photo": "path/to/photo.png", // C-roll:要锚定的静态图(人物或产品)"croll_subject": "portrait", // C-roll:portrait | productdiff --git a/references/host-mode.md b/references/host-mode.mdnew file mode 100644index 0000000..2ccfc01--- /dev/null+++ b/references/host-mode.md@@ -0,0 +1,120 @@+# Host mode — a presenter speaks on camera++A **host shot** (`"kind": "host"`) cuts to a presenter who speaks the beat's narration,+lip-synced, standing inside the paper-collage world. The input is ONE still image of the+presenter (a finished character design). It is not A-roll (that needs a real recorded+video) and not C-roll (a silent photo sticker).++Validated on the 60s "A Brief History of Silicon Valley" film (two host beats) and re-tested+on 16:9 and 9:16 when this mode was added.++## Why two plates++No single model gives lip-sync + a stable face + a moving background. Seedance lip-syncs+and holds the likeness but re-invents the background; Omni moves flat paper best but takes+no audio. So each host shot is two plates, generated separately and keyed together:++| Plate | Still | Video |+|---|---|---|+| **Person** | presenter on flat chroma green `#00B140` (`nano-banana-2/edit`) | `seedance-2.0/reference-to-video`, driven by the beat's narration |+| **World** | the collage with the presenter's area left empty, no people (`nano-banana-2/text-to-image`, same theme as the film) | `gemini-omni-flash/image-to-video`, camera locked |++Then `colorkey` + `despill` and `overlay=0:0`. Both plates share one framing, so no+repositioning is needed.++## Workflow++```+beats.json -> audio.py -> keyframes.py (skips host) -> host_plates.py -> LOOK at the plates+ -> host_clips.py (prints a cost estimate; re-run with --yes) -> clips.py (skips host) -> assemble.py+```++- `audio.py` must run first: the beat's narration is the reference audio.+- `host_plates.py <project> [ids] [--redo]` — two stills per shot (~$0.24). **Check them+ before paying for video**: flat even green, the face is the presenter's and not a redraw,+ nothing in the world plate's empty region, the presenter where you want them.+- `host_clips.py <project> [ids] [--yes] [--redo]` — spends money. Without `--yes` it only+ prints the plan and an estimate; show that to the user first. Clips already on disk are+ reused. To regenerate only one plate's video, delete its `person_clip_path` or+ `world_clip_path` from beats.json.+- `lipsync_score.py <audio> <video> [--mouth x,y,w,h]` — optional QA (needs numpy).++## beats.json++```jsonc+"host": {+ "avatar": "path/to/presenter.jpg", // a FINISHED character design, never redrawn (str or list)+ "subject": "woman", // optional noun for prompts, default "presenter"+ "outfit": "a cream ivory zip-up hoodie", // optional, locks clothing so the body does not drift+ "position": "left", // where they stand; see Layouts+ "size": 0.25, // head height / frame height, 0.08-0.6+ "person_video_model": "bytedance/seedance-2.0/reference-to-video", // optional+ "world_video_model": "google/gemini-omni-flash/image-to-video" // optional+},+"beats": [{+ "id": 1, "narration": "...", "feel": "bright, curious",+ "shots": [{+ "id": "a", "kind": "host", "title": false,+ "scene": "WORLD plate only: low torn-paper hills, a big sun disc, ... (no people)",+ "element_motion": "WORLD motion: name EVERY element and pin its shape"+ }]+}]+```++A host beat has exactly ONE shot (the presenter speaks the whole beat) and its narration+must be **at most 9.5 s** (the clip is `ceil(narration + 0.5)` seconds and Omni is verified+up to 10 s). Split longer lines into two beats. `scene` and `element_motion` describe the+world only; do not mention the presenter's area in `scene`, the script adds it.++## Layouts and adjusting the presenter++The frame spec lives in one table, `HOST_LAYOUTS` in `scripts/host.py`:++| Aspect | `position` choices | Default | Notes |+|---|---|---|---|+| 16:9 | `left`, `center`, `right` | `left`, head 0.25 | validated |+| 9:16 | `lower` | `lower`, head ~1/7 | validated once (6 s) |++`size` is a hint, not a measurement: asked for 1/7 on 9:16 the model drew about 1/5. Check+the person plate and adjust. Custom `position`/`size` means the default mouth box of+`lipsync_score.py` no longer applies; pass `--mouth`. Other aspect ratios are rejected with+a pointer to the table. To add one: a new entry (regions, placement and world-clear+templates, mouth box) plus one validation run. Omni image-to-video only accepts 16:9 and+9:16, so 1:1 and 4:3 need a different world-video model or a crop.++## Rules (each earned by a failed run)++1. **The audio fed to Seedance must equal the requested video length exactly.** The script+ pads with silence. Shorter audio makes the mouth drift across the whole clip.+2. **The beat's audio becomes the model's OWN output track**, extracted and normalised to+ -18 LUFS. Seedance re-times the reference audio (best lag +0.08 s against its own track,+ -0.44 s against the original narration), and the error is not a constant shift. The+ original is kept as `narration_audio_reference`.+3. **One reference image only.** Two images (green plate + studio portrait) scored 0.033+ against 0.095 for one.+4. **Lock the camera on both plates.** If one moves, the composite slides apart.+5. **Pin each world element's shape** in `element_motion` ("the plane stays the same+ propeller plane"). "Add nothing new" alone does not stop Omni morphing things.+6. **Host shots are never time-stretched.** Their audio is their clip; `assemble.py` skips+ the `narration + 0.5 s` extension and the slow-down for `kind: "host"`.++## Known limits++- **World-video drift.** Even with shapes pinned, Omni sometimes re-renders the world: in+ both 2026-10 tests the paper trees turned photographic, colours shifted, clouds appeared+ and one frame grew a stray face at the top edge. The sun and plane held shape in one run+ and not in the other. A shorter clip did not fix it. Re-roll (delete `world_clip_path`),+ simplify the world plate, or try another `world_video_model`.+- Validated only with a semi-real illustrated digital-human design. A raw real-person selfie+ is untested and may be refused.+- The host beat speaks the model's rendition of the narration while neighbouring beats speak+ the TTS voice; the timbre match across that cut is not measured.+- Seedance has the lowest phoneme fidelity of the models tried (correlation 0.246 vs+ InfiniteTalk 0.503, Kling 0.460, OmniHuman 0.422, on one plate). It was kept for+ expression and likeness. A best-lag near 0 with low correlation means model limit; a+ non-zero lag means a timing bug you can fix.+- A host clip is ~$0.36 per second (Seedance 720p ~$0.194, Omni $0.13, two stills $0.24 per+ shot) against ~$0.16 for B-roll; with `seedance-2.0-fast` the person part is roughly a+ third. Prices are from 2026-07-30 official pages: verify before relying on them.+- The mixed loudness of a -18 LUFS host track plus `assemble.py`'s final gain can clip;+ lower `mix.voice` / `mix.music` in beats.json if the master peaks above 0 dB.diff --git a/references/models-and-gotchas.md b/references/models-and-gotchas.mdindex 926b018..7c44062 100644--- a/references/models-and-gotchas.md+++ b/references/models-and-gotchas.md@@ -75,6 +75,16 @@ The local ffmpeg is minimal: **no libass, no drawtext** (no libfreetype). So:- **Verify by extracting frames** — you can't read an mp4's content. `mjpeg` refusesfull-range YUV, so add `format=yuvj420p` when grabbing jpgs.+## Host mode (Seedance reference-to-video + Omni, keyed)++- Seedance takes `reference_images` / `reference_audios` (not `images`), `ratio` (not+ `aspect_ratio`), and a reference audio of 2-15 s. Omni takes `image` + `aspect_ratio` and is+ only verified to 10 s.+- Pricing units differ and the catalog `base_price` is NOT a per-second price: Seedance is+ billed per token (720p about $0.194/s after promo, list $0.2429), Omni $0.13/s with a 3 s+ minimum, nano-banana by resolution (1k $0.08, 2k $0.12). Read the model page, not the field.+- Full recipe and rules: `references/host-mode.md`.+## CostA ~30s standard film ≈ **$0.8–1.0** (6 keyframes + 6 clips + VO + music). The element-leveldiff --git a/scripts/assemble.py b/scripts/assemble.pyindex 3d2e0c7..d32dde7 100644--- a/scripts/assemble.py+++ b/scripts/assemble.py@@ -65,10 +65,12 @@ def run(project_dir):# ensure the beat covers its narration (extend last shot if needed)durs = [float(s.get("dur", 10)) for s in shot_list]need = float(beat.get("narration_dur", sum(durs))) + TAIL- if sum(durs) < need:+ # a host shot's audio IS its clip, so it is never extended or slowed (sync would break)+ if sum(durs) < need and shot_list[-1].get("kind") != "host":durs[-1] += need - sum(durs)for s, d in zip(shot_list, durs):- segs.append({"clip": s["clip_path"], "dur": round(d, 2)})+ segs.append({"clip": s["clip_path"], "dur": round(d, 2),+ "host": s.get("kind") == "host"})t += dbeat_spans.append({"start": beat_start, "dur": round(t - beat_start, 2), "beat": beat})total = round(t, 2)@@ -81,7 +83,7 @@ def run(project_dir):# clip), slow it to fill instead of freezing the last frame.cd = probe_dur(s["clip"])factor = s["dur"] / cd if cd > 0 else 1.0- pre = f"setpts={factor:.4f}*PTS," if factor > 1.02 else ""+ pre = f"setpts={factor:.4f}*PTS," if factor > 1.02 and not s["host"] else ""# blurred-fill background so off-aspect clips (e.g. 3:4 card in 9:16) get a# nice bg instead of black bars; for matching-aspect clips the fg fills fully.fc = (f"[0:v]{pre}split[s0][s1];"diff --git a/scripts/atlas_cloud.py b/scripts/atlas_cloud.pyindex ee256b9..6fae8bf 100644--- a/scripts/atlas_cloud.py+++ b/scripts/atlas_cloud.py@@ -93,8 +93,9 @@ def submit_image(model: str, prompt: str, **params) -> str:def submit_video(model: str, prompt: str, **params) -> str:"""Submit a video generation task; return prediction id.- For image-to-video pass image="<url>"; for reference-to-video pass- images=["<url>", ...] (1-5 refs).+ For image-to-video pass image="<url>"; for reference-to-video pass the model's own+ keys: Kling takes images=["<url>", ...] (1-5 refs); Seedance 2.0 takes+ reference_images=[...] and reference_audios=[...] (see references/host-mode.md)."""body = {"model": model, "prompt": prompt, **params}return _post("/model/generateVideo", body)["data"]["id"]diff --git a/scripts/clips.py b/scripts/clips.pyindex 9395e99..37f6745 100644--- a/scripts/clips.py+++ b/scripts/clips.py@@ -136,6 +136,8 @@ def run(project_dir, only=None):for shot, key in shots_of(beat):if only and key not in only:continue+ if shot.get("kind") == "host": # presenter shots use host_clips.py+ continueurl = shot.get("keyframe_url")if not url and shot.get("keyframe_path") and os.path.exists(shot["keyframe_path"]):# user-provided keyframe (e.g. hand-made collage card) -> upload itdiff --git a/scripts/host.py b/scripts/host.pynew file mode 100644index 0000000..a70f812--- /dev/null+++ b/scripts/host.py@@ -0,0 +1,301 @@+#!/usr/bin/env python3+"""+Host mode shared module: layout table, prompt templates, validation, cost estimate.++A host shot (`"kind": "host"`) is a presenter speaking the beat's narration on camera,+lip-synced, standing inside the collage world. It is built from TWO plates generated+separately and keyed together (see references/host-mode.md):++ person plate green-screen still of the presenter -> Seedance 2.0 reference-to-video+ world plate the collage with that area left empty -> Gemini Omni image-to-video++host_plates.py makes the stills, host_clips.py animates + composites them. Everything that+depends on the frame spec lives in HOST_LAYOUTS below, so a new aspect ratio is one new+entry here (plus a validation run) rather than an edit to the pipeline.+"""+import math+import os+import re+import subprocess++# ---- models -----------------------------------------------------------------------------+PERSON_PLATE_MODEL = "google/nano-banana-2/edit"+WORLD_PLATE_MODEL = "google/nano-banana-2/text-to-image"+PERSON_VIDEO_MODEL = "bytedance/seedance-2.0/reference-to-video" # default; host.person_video_model overrides+WORLD_VIDEO_MODEL = "google/gemini-omni-flash/image-to-video" # default; host.world_video_model overrides++CHROMA = "0x00B140" # key colour as ffmpeg wants it+CHROMA_HEX = "#00B140" # the same colour as the prompt says it+TAIL = 0.5 # assemble.py's breathing room after the narration+MIN_VIDEO_S = 4 # shortest Seedance clip we request+MAX_VIDEO_S = 10 # Omni image-to-video is verified up to 10s (Seedance allows 15)++# ---- layout registry: ONE entry per supported aspect ratio ------------------------------+# regions position name -> (region phrase, REGION shouted in the plate prompt)+# default_position / default_head the validated defaults (head = fraction of frame height)+# placement template for the person-plate prompt+# world_clear what the world plate must keep empty so the presenter fits there+# mouth_box (x, y, w, h) fractions of the frame for lipsync_score.py. Valid ONLY for the+# default position + size; with a custom one pass --mouth to lipsync_score.py+# Users adjust the presenter with host.position and host.size in beats.json (resolve_layout).+HOST_LAYOUTS = {+ "16:9": {+ "regions": {"left": ("left third", "LEFT THIRD"),+ "center": ("middle third", "MIDDLE THIRD"),+ "right": ("right third", "RIGHT THIRD")},+ "default_position": "left",+ "default_head": 0.25,+ "placement": ("They are shown from the waist up, standing and facing the camera like a "+ "documentary host, positioned in the {REGION} of the frame with their head "+ "about {head} of the frame height — never a big head-and-shoulders crop."),+ "world_clear": ("Leave the {region} of the composition clearly empty — no element, scrap "+ "or text intrudes there."),+ "mouth_box": (0.215, 0.408, 0.07, 0.065),+ },+ "9:16": {+ "regions": {"lower": ("lower half", "LOWER HALF")},+ "default_position": "lower",+ "default_head": 1 / 7,+ "placement": ("They are shown from the waist up, standing and facing the camera like a "+ "documentary host, centred horizontally in the {REGION} of the frame with "+ "the body running off the bottom edge and their head about {head} of the "+ "frame height, the top of the head near the middle of the frame — never a "+ "big head-and-shoulders crop."),+ "world_clear": ("Leave the {region} of the composition clearly empty — no element, scrap "+ "or text intrudes there."),+ "mouth_box": (0.45, 0.437, 0.12, 0.035), # measured on the 9:16 test plate (2026-10-06)+ },+}+_HEAD_WORDS = {0.25: "one quarter", 0.2: "one fifth", 1 / 7: "one seventh", 1 / 6: "one sixth",+ 0.5: "one half", 1 / 3: "one third"}+++def head_phrase(h):+ for k, w in _HEAD_WORDS.items():+ if abs(h - k) < 1e-6:+ return w+ return f"{round(h * 100)} percent"+++# ---- prompts (validated wording from the Silicon Valley film; pronouns made neutral) -----+PERSON_PLATE_PROMPT = (+ "The attached reference image(s) are the finished character design of the host — the FIRST "+ "image is authoritative. The {subject} is already exactly right: DO NOT redesign, restyle, "+ "repaint or re-illustrate them. Carry them over verbatim — the same face, the same features "+ "and proportions, the same skin rendering, the same hair, the same soft neutral "+ "expression{outfit_lock}. They are a GLOSSY FULL-COLOUR PRINT of that image, scissor-cut "+ "around their silhouette with a thin torn WHITE paper border. {placement} THE ENTIRE REST OF "+ "THE FRAME IS ONE COMPLETELY FLAT, EVEN, PURE CHROMA-KEY GREEN ({chroma}) — a solid unbroken "+ "green field with no gradient, no texture, no shading, no paper, no scenery, no scraps, no "+ "shadow and no text of any kind. Nothing at all except their cut-out print on flat green. "+ "Aspect ratio {aspect}."+)++WORLD_PLATE_SUFFIX = (+ " No people and no figures anywhere in the image. {world_clear} Newspaper scraps carry "+ "completely UNREADABLE blurred micro-text."+)++# One reference image, bound explicitly with @image1. A second image made the model reconcile+# two different pictures instead of animating the plate (correlation 0.033 vs 0.095).+PERSON_VIDEO_PROMPT = (+ "The {subject} in @image1 speaks to camera as a documentary host, their lips synced "+ "precisely to audio 1. Their face, features, face shape, skin and hair stay exactly as in "+ "@image1 — do not restyle, age, slim or beautify them. Keep the mouth movement SMALL and "+ "natural: gentle close-lipped articulation with only slight jaw movement, never a wide open "+ "mouth, never bared teeth or a gaping shape. They have a warm, lively facial expression — "+ "small friendly head movements, natural blinks, eyebrows and eyes alive as they talk — and "+ "gesture easily with one hand. They keep their exact position and scale in the {region} "+ "of the frame{outfit_clause}, still a scissor-cut print with its torn white paper border. "+ "THE GREEN BACKGROUND MUST STAY A COMPLETELY FLAT, EVEN, UNIFORM PURE GREEN for the whole "+ "shot — no gradient, no shading, no shadows cast onto it, no texture, no objects, nothing "+ "else appears on it. The camera is locked off: no push-in, no pan, no zoom, no reframing. "+ "{feel}"+)++# The camera must be locked on BOTH plates: if one moved, the composite would slide apart.+WORLD_VIDEO_PROMPT = (+ "Animate this still into a living paper-collage motion graphic, flat 2D printed cut-outs, "+ "not photoreal. The camera is completely locked off — no push-in, no pan, no zoom, no "+ "reframing whatsoever.\n"+ "ELEMENT MOTION (this is the whole point — the world is alive the entire time): every "+ "element already in the still moves, but each one KEEPS ITS OWN EXACT SHAPE while it does. "+ "{element_motion}\n"+ "Keep the {region} of the frame clear and calm — nothing drifts into it.\n"+ "AESTHETIC: preserve the printed, halftone, torn paper and tape textures of the still "+ "exactly, and keep the flat background colour.\n"+ "CONSTRAINTS: rigid flat paper layers only — no 3D rotation, no perspective change, no "+ "morphing or melting. Nothing new enters the frame, no element is added or removed, and "+ "every element is still present at the end. Animate the motion only; do not re-render or "+ "redraw the picture. {feel}"+)++# Used when a shot has no element_motion. Safe, but the recipe works best when the author names+# each element and pins its shape (Omni turned a propeller plane into a paper dart, and gave a+# flat sun rays, whenever the prompt only said "add nothing new").+DEFAULT_WORLD_MOTION = (+ "The torn-paper layers drift slowly at slightly different depths in continuous gentle "+ "parallax. Any figure, vehicle or object stays exactly the same cut-out it is in the still "+ "and only drifts, bobs or sways in place — it never changes into another shape. The "+ "geometric paper scraps bob and rotate only a few degrees. The tape corners and torn paper "+ "edges flutter. Motion amplitude is subtle and restrained throughout."+)++# ---- cost (2026-07-30 official pages — verify before relying on it) ----------------------+PRICE_IMAGE_2K = 0.12 # per still (nano-banana-2, 2k)+PRICE_PERSON_PER_S = 0.194 # Seedance 2.0 720p, after the -20% promo (list 0.2429)+PRICE_PERSON_FAST_PER_S = 0.058 # Seedance 2.0 Fast: ESTIMATE = standard x 0.3 (the catalog ratio)+PRICE_WORLD_PER_S = 0.13 # Omni, billed from 3s+++def article_free(phrase):+ """'a cream hoodie' -> 'cream hoodie' (prompts supply their own article)."""+ return re.sub(r"^(a|an|the)\s+", "", (phrase or "").strip(), flags=re.I)+++def person_model(doc):+ """The person-video model: host.person_video_model, else the Seedance 2.0 default."""+ return (doc.get("host") or {}).get("person_video_model") or PERSON_VIDEO_MODEL+++def world_model(doc):+ return (doc.get("host") or {}).get("world_video_model") or WORLD_VIDEO_MODEL+++def person_price(model):+ return PRICE_PERSON_FAST_PER_S if "fast" in model else PRICE_PERSON_PER_S+++def host_cfg(doc):+ """The project-level `host` block with prompt-ready fields filled in."""+ h = dict(doc.get("host") or {})+ avatar = h.get("avatar")+ h["avatars"] = [avatar] if isinstance(avatar, str) else list(avatar or [])+ h["subject"] = h.get("subject") or "presenter"+ outfit = article_free(h.get("outfit"))+ h["outfit_lock"] = f", and the same {outfit}" if outfit else ""+ h["outfit_clause"] = f" and their {outfit} is unchanged" if outfit else ""+ return h+++def layout_for(aspect):+ if aspect not in HOST_LAYOUTS:+ raise SystemExit(f"host mode has no layout for aspect \"{aspect}\" (supported: "+ f"{', '.join(HOST_LAYOUTS)}). Add an entry to HOST_LAYOUTS in "+ f"scripts/host.py and validate it before using another ratio.")+ return HOST_LAYOUTS[aspect]+++def resolve_layout(doc):+ """The layout for this project: the aspect's defaults, adjusted by the user's+ host.position (a region name from the layout) and host.size (head height as a fraction of+ the frame height, 0.08-0.6). The model treats size as a hint, not a measurement, so check+ the person plate before paying for video. Returns region/placement/world_clear and+ mouth_box (None when position or size is customised)."""+ base = layout_for(doc.get("aspect", "16:9"))+ h = doc.get("host") or {}+ pos = h.get("position") or base["default_position"]+ if pos not in base["regions"]:+ raise SystemExit(f"host.position \"{pos}\" is not available for {doc.get('aspect', '16:9')} "+ f"(choose one of: {', '.join(base['regions'])})")+ try:+ head = float(h.get("size") or base["default_head"])+ except (TypeError, ValueError):+ raise SystemExit("host.size must be a number: head height as a fraction of frame height")+ if not 0.08 <= head <= 0.6:+ raise SystemExit(f"host.size {head} is outside 0.08-0.6 (head height / frame height)")+ region, shout = base["regions"][pos]+ custom = pos != base["default_position"] or abs(head - base["default_head"]) > 1e-9+ return {"region": region,+ "placement": base["placement"].format(REGION=shout, head=head_phrase(head)),+ "world_clear": base["world_clear"].format(region=region),+ "mouth_box": None if custom else base["mouth_box"]}+++def probe_dur(path):+ out = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration",+ "-of", "csv=p=0", path], capture_output=True, text=True).stdout+ try:+ return float(out.strip())+ except ValueError:+ return 0.0+++def host_shots(doc):+ """Yield (beat, shot, key) for every shot with kind == 'host'."""+ for beat in doc["beats"]:+ for shot in beat.get("shots") or []:+ if shot.get("kind") == "host":+ yield beat, shot, f"{beat['id']}{shot.get('id', '')}"+++def reference_audio(beat):+ """The beat's ORIGINAL narration, not the model-sung track host_clips swaps in.++ host_clips.py replaces `narration_audio` with the presenter clip's own audio and keeps the+ original as `narration_audio_reference`. If audio.py has since regenerated the narration,+ `narration_audio` no longer equals the adopted track and is itself the new original.+ """+ cur = beat.get("narration_audio")+ if beat.get("host_own_audio") and cur == beat["host_own_audio"]:+ return beat.get("narration_audio_reference") or cur+ return cur+++def video_seconds(narration_s):+ """Clip length: cover the narration plus assemble's tail so the beat is never stretched."""+ return min(MAX_VIDEO_S, max(MIN_VIDEO_S, math.ceil(narration_s + TAIL)))+++def validate(doc, need_audio=False):+ """Check host-mode preconditions and return [(beat, shot, key)]. Exits with ALL problems."""+ shots = list(host_shots(doc))+ if not shots:+ raise SystemExit("no shot has \"kind\": \"host\" — nothing to do")+ problems = []+ resolve_layout(doc)+ cfg = host_cfg(doc)+ if not cfg["avatars"]:+ problems.append("beats.json needs host.avatar (a path/URL to the presenter image)")+ for a in cfg["avatars"]:+ if not a.startswith("http") and not os.path.exists(os.path.expanduser(a)):+ problems.append(f"host.avatar not found: {a}")+ for beat in doc["beats"]:+ hs = [s for s in (beat.get("shots") or []) if s.get("kind") == "host"]+ if hs and len(beat["shots"]) != 1:+ problems.append(f"beat {beat['id']}: a host beat must have exactly ONE shot (the "+ f"presenter speaks the whole beat)")+ for beat, shot, key in shots:+ if not shot.get("scene"):+ problems.append(f"[{key}] needs a \"scene\" (the WORLD plate, no people)")+ if need_audio:+ ref = reference_audio(beat)+ if not ref or not os.path.exists(ref):+ problems.append(f"[{key}] no narration audio — run audio.py first")+ continue+ dur = probe_dur(ref)+ if dur + TAIL > MAX_VIDEO_S:+ problems.append(f"[{key}] narration is {dur:.1f}s; a host beat must be "+ f"<= {MAX_VIDEO_S - TAIL:.1f}s (Omni's verified clip cap is "+ f"{MAX_VIDEO_S}s) — split the line into two beats")+ elif dur < 3:+ print(f"[{key}] warning: narration is only {dur:.1f}s; the clip is "+ f"{MIN_VIDEO_S}s minimum, so the presenter will stand silent for the rest")+ if problems:+ raise SystemExit("host mode:\n - " + "\n - ".join(problems))+ return shots+++def estimate(person_s, world_s, person_per_s=PRICE_PERSON_PER_S):+ """Rough cost lines + total for the videos still to generate.++ person_s / world_s: shot key -> seconds to generate (absent = already exists, free).+ """+ lines, total = [], 0.0+ for key in sorted(set(person_s) | set(world_s)):+ p = person_s.get(key, 0) * person_per_s+ w = world_s.get(key, 0) * PRICE_WORLD_PER_S+ lines.append(f" [{key}] person {person_s.get(key, 0)}s ${p:.2f} + "+ f"world {world_s.get(key, 0)}s ${w:.2f}")+ total += p + w+ return lines, totaldiff --git a/scripts/host_clips.py b/scripts/host_clips.pynew file mode 100644index 0000000..f32e3a6--- /dev/null+++ b/scripts/host_clips.py@@ -0,0 +1,190 @@+#!/usr/bin/env python3+"""+Host stage 2: animate both plates, adopt the presenter's own audio, key and stack.++ person plate -> Seedance 2.0 reference-to-video, driven by the beat's narration+ world plate -> Gemini Omni image-to-video (flat paper-collage motion, camera locked)+ composite -> chroma-key the green out of the person clip, overlay on the world clip++Three rules in here each came from a failed run (details: references/host-mode.md):+ 1. The audio handed to Seedance is padded to EXACTLY the video length.+ 2. The beat's audio then becomes Seedance's OWN output track, not the original narration —+ Seedance re-times the reference audio, so laying the original back over the video builds+ in a ~0.4s error that no constant shift can remove.+ 3. The finished shot is never time-stretched (assemble.py honours kind == "host").++This spends money. Without --yes it only prints the plan and an estimate; show that to the+user, and re-run with --yes once they agree.++Usage: python3 host_clips.py <project_dir> [only_ids] [--yes] [--redo]+ --redo regenerates the videos even if clips already exist (re-composite is always free)+"""+import json+import os+import subprocess+import sys++from host import (CHROMA, DEFAULT_WORLD_MOTION, PERSON_VIDEO_PROMPT, WORLD_VIDEO_PROMPT,+ estimate, host_cfg, person_model, person_price, probe_dur,+ reference_audio, resolve_layout, validate, video_seconds, world_model)+from provider import get_provider, run_jobs++FPS = 24+RES = {"16:9": (1920, 1080), "9:16": (1080, 1920)}+++def sh(args):+ subprocess.run(args, check=True)+++def pad_audio(src, dest, seconds):+ """Pad with trailing silence to EXACTLY `seconds`.++ Seedance spreads the lip motion over the whole requested video length instead of stopping+ when the audio does: 7.04s of speech in an 8s clip came back ~14% slow, the mouth stayed+ open after the speech ended, and the sync drifted the longer the shot ran.+ """+ sh(["ffmpeg", "-y", "-loglevel", "error", "-i", src, "-af", "apad", "-t", f"{seconds}",+ "-c:a", "libmp3lame", "-q:a", "2", dest])+ return dest+++def adopt_model_audio(plate, dest, level_db=-18.0):+ """Extract the presenter clip's own audio and level-match it (content is verbatim)."""+ sh(["ffmpeg", "-y", "-loglevel", "error", "-i", plate, "-vn",+ "-af", f"loudnorm=I={level_db}:TP=-2:LRA=9", "-ac", "1", "-ar", "44100",+ "-c:a", "libmp3lame", "-q:a", "2", dest])+ return dest+++def composite(person, world, dest, size, similarity=0.20, blend=0.06):+ """Key the flat green out of the person clip and lay it over the world clip.++ Both plates share one framing, so the overlay is at 0:0 with no repositioning. No time+ shift is applied: with the model's own audio adopted, the measured offset is ~0 and any+ shift would only break it.+ """+ w, h = size+ fc = (f"[0:v]scale={w}:{h},fps={FPS},setsar=1[bg];"+ f"[1:v]scale={w}:{h},fps={FPS},setsar=1,"+ f"colorkey={CHROMA}:{similarity}:{blend},despill=type=green:mix=0.5[fg];"+ f"[bg][fg]overlay=0:0:format=auto,format=yuv420p[v]")+ sh(["ffmpeg", "-y", "-loglevel", "error", "-i", world, "-i", person, "-filter_complex", fc,+ "-map", "[v]", "-an", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", dest])+++def run(project_dir, only=None, confirmed=False, redo=False):+ bpath = os.path.join(project_dir, "beats.json")+ with open(bpath) as f:+ doc = json.load(f)+ shots = [t for t in validate(doc, need_audio=True) if not only or t[2] in only]+ aspect = doc.get("aspect", "16:9")+ layout = resolve_layout(doc)+ size = RES[aspect]+ cfg = host_cfg(doc)+ pmodel, wmodel = person_model(doc), world_model(doc)+ plates_dir = os.path.join(project_dir, "clips", "plates")+ audio_dir = os.path.join(project_dir, "audio", "host")+ for d in (plates_dir, audio_dir):+ os.makedirs(d, exist_ok=True)++ missing = [k for _, s, k in shots if not (s.get("person_plate_url") and s.get("world_plate_url"))]+ if missing:+ sys.exit(f"no plates for {', '.join(missing)} — run host_plates.py first")++ # ---- plan + cost gate ----+ seconds = {k: video_seconds(probe_dur(reference_audio(b))) for b, _, k in shots}++ def need(shot, field):+ """Generate this clip unless it is already on disk (--redo forces)."""+ return redo or not os.path.exists(shot.get(f"{field}_path") or "")++ person_s = {k: seconds[k] for _, s, k in shots if need(s, "person_clip")}+ world_s = {k: seconds[k] for _, s, k in shots if need(s, "world_clip")}+ print("host clips plan:")+ for _, _, k in shots:+ what = [n for n, d in (("person", person_s), ("world", world_s)) if k in d]+ print(f" [{k}] {seconds[k]}s clip: " + (f"generate {' + '.join(what)}" if what+ else "reuse existing clips (re-composite only)"))+ if person_s or world_s:+ lines, total = estimate(person_s, world_s, person_price(pmodel))+ print(f"person model: {pmodel}\nworld model: {wmodel}\nestimate (prices from 2026-07-30 official pages — verify):")+ print("\n".join(lines))+ print(f" TOTAL ~ ${total:.2f}")+ if not confirmed:+ print("\nNothing submitted. Show this estimate to the user; re-run with --yes to go.")+ return++ prov = get_provider(doc.get("provider"))+ specs, meta = {}, {}+ for beat, shot, key in shots:+ vdur = seconds[key]+ shot["plate_dur"] = vdur+ feel = f"Tone: {beat.get('feel', 'warm and clear')}."+ if key in person_s:+ padded = pad_audio(reference_audio(beat), os.path.join(audio_dir, f"ref_{key}.mp3"),+ vdur)+ audio_url = prov.upload(padded)+ prompt = PERSON_VIDEO_PROMPT.format(+ subject=cfg["subject"], region=layout["region"], outfit_clause=cfg["outfit_clause"],+ feel=feel)+ shot["person_video_prompt"] = prompt+ specs[f"{key}-person"] = (lambda p=shot["person_plate_url"], a=audio_url, v=vdur,+ t=prompt: prov.submit_video(+ pmodel, t, reference_images=[p], reference_audios=[a], duration=v,+ ratio=aspect, resolution="720p", generate_audio=True, watermark=False,+ bitrate_mode="standard"))+ meta[f"{key}-person"] = (shot, "person_clip")+ if key in world_s:+ prompt = WORLD_VIDEO_PROMPT.format(+ element_motion=shot.get("element_motion") or DEFAULT_WORLD_MOTION,+ region=layout["region"], feel=feel)+ shot["world_video_prompt"] = prompt+ specs[f"{key}-world"] = (lambda p=shot["world_plate_url"], v=vdur,+ t=prompt: prov.submit_video(+ wmodel, t, image=p, duration=v, aspect_ratio=aspect,+ resolution="720p"))+ meta[f"{key}-world"] = (shot, "world_clip")++ done = run_jobs(prov, specs, poll_s=5, stall_s=300, max_retries=2, deadline_s=1500)+ for k, url in done.items():+ if not url:+ print(f"[{k}] FAILED")+ continue+ shot, field = meta[k]+ dest = os.path.join(plates_dir, f"{k}.mp4")+ prov.download(url, dest)+ shot[f"{field}_url"], shot[f"{field}_path"] = url, dest+ print(f"[{k}] saved {dest} ({probe_dur(dest):.2f}s)")++ # ---- adopt the presenter's own audio, then key + stack ----+ for beat, shot, key in shots:+ pc, wc = shot.get("person_clip_path"), shot.get("world_clip_path")+ if not (pc and wc and os.path.exists(pc) and os.path.exists(wc)):+ print(f"[{key}] missing a clip — skipping composite")+ continue+ own = os.path.join(audio_dir, f"own_{key}.mp3")+ adopt_model_audio(pc, own)+ original = reference_audio(beat)+ beat["narration_audio_reference"] = original+ beat["narration_audio"] = beat["host_own_audio"] = own+ beat["narration_dur"] = round(probe_dur(own), 3)+ beat.pop("narration_audio_url", None)+ dest = os.path.join(project_dir, "clips", f"clip_{key}.mp4")+ composite(pc, wc, dest, size)+ shot["clip_path"] = dest+ shot["dur"] = round(probe_dur(dest), 3) # assemble keeps host shots at this length+ shot.pop("clip_url", None)+ print(f"[{key}] composited -> {dest} ({shot['dur']}s, audio {beat['narration_dur']}s)")++ with open(bpath, "w") as f:+ json.dump(doc, f, ensure_ascii=False, indent=2)+ print("updated", bpath)+++if __name__ == "__main__":+ args = [a for a in sys.argv[1:] if not a.startswith("--")]+ if not args:+ sys.exit("usage: python3 host_clips.py <project_dir> [only_ids] [--yes] [--redo]")+ only = set(args[1].split(",")) if len(args) > 1 else None+ run(os.path.abspath(args[0]), only, confirmed="--yes" in sys.argv, redo="--redo" in sys.argv)diff --git a/scripts/host_plates.py b/scripts/host_plates.pynew file mode 100644index 0000000..8092ac8--- /dev/null+++ b/scripts/host_plates.py@@ -0,0 +1,106 @@+#!/usr/bin/env python3+"""+Host stage 1: the two STILLS for every host shot.++ person plate the presenter image carried over verbatim as a cut-out print on flat chroma+ green (nano-banana-2/edit)+ world plate the collage world with the presenter's area left empty and no people in it+ (nano-banana-2/text-to-image, same theme as the rest of the film)++Look at both before running host_clips.py — the plates are the cheap checkpoint (~$0.24 per+shot). Check that the green is flat and even, the face is the presenter's and not a redraw,+and the world has nothing in the empty region.++Usage: python3 host_plates.py <project_dir> [only_ids] [--redo]+ only_ids is a comma list of shot keys, e.g. 1a,7a+"""+import json+import os+import sys++from host import (CHROMA_HEX, PERSON_PLATE_MODEL, PERSON_PLATE_PROMPT, WORLD_PLATE_MODEL,+ WORLD_PLATE_SUFFIX, host_cfg, resolve_layout, validate)+from provider import get_provider, run_jobs+from styles import compose_collage_prompt, image_params, resolve_theme+++def run(project_dir, only=None, redo=False):+ bpath = os.path.join(project_dir, "beats.json")+ with open(bpath) as f:+ doc = json.load(f)+ shots = validate(doc)+ aspect = doc.get("aspect", "16:9")+ layout = resolve_layout(doc)+ cfg = host_cfg(doc)+ img_res = doc.get("image_resolution", "2k")+ theme = resolve_theme(doc.get("theme")) or {}+ collage_style = theme.get("idiom") or doc.get("collage_style", "american-retro")+ kf_dir = os.path.join(project_dir, "keyframes")+ os.makedirs(kf_dir, exist_ok=True)++ prov = get_provider(doc.get("provider"))+ if cfg.get("_avatar_src") == cfg["avatars"] and cfg.get("_avatar_urls"):+ avatar_urls = cfg["_avatar_urls"] # cached upload, same source images+ else:+ avatar_urls = [a if a.startswith("http") else prov.upload(os.path.expanduser(a))+ for a in cfg["avatars"]]+ doc["host"]["_avatar_src"], doc["host"]["_avatar_urls"] = cfg["avatars"], avatar_urls++ person_prompt = PERSON_PLATE_PROMPT.format(+ subject=cfg["subject"], outfit_lock=cfg["outfit_lock"], placement=layout["placement"],+ chroma=CHROMA_HEX, aspect=aspect)++ specs, meta = {}, {}+ for beat, shot, key in shots:+ if only and key not in only:+ continue+ if redo or not shot.get("person_plate_url"):+ specs[f"{key}-person"] = (lambda: prov.submit_image(+ PERSON_PLATE_MODEL, person_prompt, images=avatar_urls,+ **image_params(PERSON_PLATE_MODEL, aspect, img_res)))+ meta[f"{key}-person"] = (shot, "person_plate", person_prompt)+ if redo or not shot.get("world_plate_url"):+ world_prompt = compose_collage_prompt(+ shot["scene"], "", "", beat.get("bg", "flat cream paper"), aspect,+ with_title=False, style=collage_style,+ palette=theme.get("palette") or doc.get("palette"),+ type_style=theme.get("type_style") or doc.get("type_style"),+ finish=theme.get("finish") or doc.get("finish"),+ ) + WORLD_PLATE_SUFFIX.format(world_clear=layout["world_clear"])+ specs[f"{key}-world"] = (lambda p=world_prompt: prov.submit_image(+ WORLD_PLATE_MODEL, p, **image_params(WORLD_PLATE_MODEL, aspect, img_res)))+ meta[f"{key}-world"] = (shot, "world_plate", world_prompt)++ if not specs:+ print("all plates already exist (use --redo to regenerate)")+ done = run_jobs(prov, specs, poll_s=3, stall_s=90, max_retries=2, deadline_s=420)++ for k, url in done.items():+ if not url:+ print(f"[{k}] FAILED")+ continue+ shot, field, prompt = meta[k]+ key = k.rsplit("-", 1)[0]+ dest = os.path.join(kf_dir, f"{field}_{key}.jpg")+ prov.download(url, dest)+ shot[f"{field}_url"] = url+ shot[f"{field}_path"] = dest+ shot[f"{field}_prompt"] = prompt+ # a new plate makes its video (and the composite) stale+ side = field.split("_")[0] # person | world+ for stale in (f"{side}_clip_path", f"{side}_clip_url", "clip_path", "clip_url"):+ shot.pop(stale, None)+ print(f"[{k}] saved {dest}")++ with open(bpath, "w") as f:+ json.dump(doc, f, ensure_ascii=False, indent=2)+ print("updated", bpath)+ print("NEXT: open the plates in keyframes/ and check them before host_clips.py")+++if __name__ == "__main__":+ args = [a for a in sys.argv[1:] if not a.startswith("--")]+ if not args:+ sys.exit("usage: python3 host_plates.py <project_dir> [only_ids] [--redo]")+ only = set(args[1].split(",")) if len(args) > 1 else None+ run(os.path.abspath(args[0]), only, redo="--redo" in sys.argv)diff --git a/scripts/keyframes.py b/scripts/keyframes.pyindex 6c42e4d..e2a6160 100644--- a/scripts/keyframes.py+++ b/scripts/keyframes.py@@ -50,6 +50,8 @@ def run(project_dir):specs, by_key = {}, {}for beat in doc["beats"]:for shot, key in shots_of(beat):+ if shot.get("kind") == "host": # presenter shots use host_plates.py+ continueif shot.get("keyframe_url"): # already generated (e.g. reused wide) -> skipcontinuescene = shot["scene"]diff --git a/scripts/lipsync_score.py b/scripts/lipsync_score.pynew file mode 100644index 0000000..23fa1dc--- /dev/null+++ b/scripts/lipsync_score.py@@ -0,0 +1,111 @@+#!/usr/bin/env python3+"""+Score lip-sync objectively (optional QA for host mode; needs numpy + Pillow).++Correlates mouth-region frame-difference energy against the audio envelope at 25 fps and+reports two numbers per video:++ best lag the timing check. A non-zero lag means a constant offset: a TIMING bug you can+ fix (wrong audio, padding, a stray time shift).+ corr@0 the fidelity check. Low correlation at zero lag means the mouth moves at the right+ times but its shape does not follow the phonemes: a MODEL limit that prompts+ cannot fix; only a different model can.++Same metric, same plate, same audio for every video, so the numbers are comparable across+models. Measured on one green plate (2026-07-30): InfiniteTalk 0.503, Kling 0.460, OmniHuman+0.422, Seedance 0.246, all at ~0 lag once the audio was handled correctly.++The mouth box is a fraction of the frame, (x, y, w, h). The default is calibrated to the+standard host layout; if the presenter's size or position differs, find the mouth on a frame+and pass --mouth.++Usage: python3 lipsync_score.py <audio.mp3> <video.mp4> [more.mp4 ...] [--mouth x,y,w,h]+"""+import glob+import os+import shutil+import subprocess+import sys+import tempfile++FPS = 25+++def _np():+ try:+ import numpy as np+ from PIL import Image+ except ImportError:+ sys.exit("lipsync_score.py needs numpy and Pillow: pip install numpy pillow")+ return np, Image+++def envelope(audio, n, np):+ out = subprocess.run(["ffmpeg", "-v", "error", "-i", audio, "-ac", "1", "-ar", "16000",+ "-f", "s16le", "-"], capture_output=True).stdout+ x = np.frombuffer(out, dtype=np.int16).astype(float)+ hop = 16000 // FPS+ return np.array([np.sqrt((x[i * hop:(i + 1) * hop] ** 2).mean() + 1e-9)+ for i in range(min(n, len(x) // hop))])+++def mouth_motion(video, box, np, Image):+ x, y, w, h = box+ crop = f"crop=iw*{w}:ih*{h}:iw*{x}:ih*{y}"+ tmp = tempfile.mkdtemp(prefix="lipsync_")+ try:+ subprocess.run(["ffmpeg", "-y", "-v", "error", "-i", video, "-vf",+ f"{crop},scale=112:-1,fps={FPS},format=gray",+ os.path.join(tmp, "f_%04d.png")], check=True)+ frames = [np.asarray(Image.open(p), dtype=float)+ for p in sorted(glob.glob(os.path.join(tmp, "f_*.png")))]+ finally:+ shutil.rmtree(tmp, ignore_errors=True)+ return np.array([0.0] + [np.abs(frames[i] - frames[i - 1]).mean()+ for i in range(1, len(frames))])+++def _z(a, np):+ a = a - a.mean()+ s = a.std()+ return a / s if s > 1e-9 else a+++def score(video, audio, box):+ np, Image = _np()+ m = mouth_motion(video, box, np, Image)+ e = envelope(audio, len(m), np)+ n = min(len(m), len(e))+ o, ee = _z(m[:n], np), _z(e[:n], np)+ best = (0, -9.0)+ for lag in range(-25, 26):+ if lag < 0:+ a, b = o[-lag:], ee[:len(ee) + lag]+ elif lag == 0:+ a, b = o, ee+ else:+ a, b = o[:len(o) - lag], ee[lag:]+ k = min(len(a), len(b))+ c = float((a[:k] * b[:k]).mean())+ if c > best[1]:+ best = (lag, c)+ return best[0] / FPS, best[1], float((o * ee).mean()), len(m) / FPS+++if __name__ == "__main__":+ argv = sys.argv[1:]+ box = None+ if "--mouth" in argv:+ i = argv.index("--mouth")+ box = tuple(float(v) for v in argv[i + 1].split(","))+ del argv[i:i + 2]+ if len(argv) < 2:+ sys.exit(__doc__)+ if box is None:+ from host import HOST_LAYOUTS+ box = HOST_LAYOUTS["16:9"]["mouth_box"]+ audio = argv[0]+ print(f"{'video':18} {'dur':>6} {'corr@0':>8} {'best lag':>9} {'best corr':>10}")+ for v in argv[1:]:+ lag, bc, c0, dur = score(v, audio, box)+ print(f"{os.path.basename(v)[:-4][:18]:18} {dur:6.2f} {c0:+8.3f} {lag:+9.3f}s {bc:+10.3f}")diff --git a/vox-director.skill b/vox-director.skillindex 15fa7af..53306fd 100644Binary files a/vox-director.skill and b/vox-director.skill differ