Skip to content

Turn one topic into a finished Vox-style paper-collage explainer/ad video — automated end to end on Atlas Cloud + ffmpeg. An agent skill.

aroll: talking-head → collage mode + ASR bridge, aspect routing, newsprint preset (#3)

kiana-liang0f66dc444fc1
diff --git a/README.md b/README.md
index f500bd0..fe92e97 100644
--- a/README.md
+++ b/README.md
@@ -111,7 +111,7 @@ SKILL.md the skill (English) — the workflow the agent follows
SKILL.zh.md the same skill in Chinese
AGENTS.md entry point for non-Claude agents (Codex, …)
references/ the creative engine
- prompt-guide.md the LOOK layer — prompt structures, vocab & 8 theme presets
+ prompt-guide.md the LOOK layer — prompt structures, vocab & 9 theme presets
beat-layer.md 14 narrative arcs + hook/pacing + shot patterns
voices.md xai/tts voice roster — pick a voice_id per language/tone
models-and-gotchas.md every API / ffmpeg gotcha, already solved
diff --git a/README.zh.md b/README.zh.md
index ce29533..5e19e14 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -111,7 +111,7 @@ SKILL.md 技能本体(英文)——agent 遵循的工作流
SKILL.zh.md 同一技能的中文版
AGENTS.md 非 Claude agent(Codex 等)的入口
references/ 创意引擎
- prompt-guide.md 画面/LOOK 层:提示词结构 + 词库 + 8 套主题预设
+ prompt-guide.md 画面/LOOK 层:提示词结构 + 词库 + 9 套主题预设
beat-layer.md 14 种叙事弧线 + 钩子/节奏 + 镜头模式
voices.md xai/tts 音色表 —— 按语种/调性挑 voice_id
models-and-gotchas.md 每一个 API / ffmpeg 坑,都已填平
diff --git a/SKILL.md b/SKILL.md
index 13730d3..e4e7c29 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -58,13 +58,15 @@ This is the default, most-automated path. Every stage is one script, all driven
count per duration (30s→6–8, 60s→10–12); split each beat into **2 shots** (wide+detail) with
**per-shot `camera_move` VARIED across adjacent beats** (never repeat; `static` on the payoff)
and **rich `element_motion`** (see step 4). Each beat: `narration`, `title_cn`/`title_en`,
- `scene`, `bg`, `feel`, `hook`. This draft is the **one mandatory approval gate** — show the
- user the beat map before generating. Examples in `examples/`.
+ `scene`, `bg`, `feel`, `hook`. This draft is the **first mandatory approval gate** — show the
+ user the beat map before generating (the aspect-routing approximation in step 4 is the other
+ one). Examples in `examples/`.
2. **Pick the visual style (hybrid — do this BEFORE keyframes).** Do not reuse one house style
for every topic. Read `references/prompt-guide.md` (§5 theme presets); pick 3–4 **theme presets**
(`styles.THEME_PRESETS`: `american-retro`, `swiss-modern`, `punk-zine`,
- `soviet-constructivist`, `wpa-propaganda`, `70s-groovy`, `chinese-ink`, `atomic-age`) that fit
+ `soviet-constructivist`, `wpa-propaganda`, `70s-groovy`, `chinese-ink`, `atomic-age`,
+ `newsprint-editorial`) that fit
the topic's era/culture/tone — **or compose a custom theme** by mixing the prompt-guide dimensions
(medium/era/palette/type/finish) when none fit. Match the topic, **not** the language (an
English film on Chinese history should look Chinese). A theme bundles the whole LOOK layer
@@ -96,6 +98,13 @@ This is the default, most-automated path. Every stage is one script, all driven
text is hard-protected only on shots that have a title** (detail shots without a headline are
free to go wild). For **real people / brand logos**, Omni & Seedance refuse — set
`"video_model": "kwaivgi/kling-video-o3-pro/image-to-video"`.
+ **Aspect routing** (`styles.resolve_video_aspect`, second approval gate): `clips.py` resolves
+ `doc["aspect"]` against the chosen `video_model`'s own supported ratios — exact match wins;
+ Omni is 16:9/9:16 only, Kling reference-to-video adds 1:1, Kling image-to-video/video-edit and
+ Seedance just follow the input/ratio param. When there's no exact match it picks the nearest
+ ratio but **stops and asks you to confirm** (set `"aspect_approx_confirmed": true` once you
+ have) rather than silently reframing the film — every clip in one run shares the same resolved
+ aspect so the finished film is never mixed.
5. **Voice + music.** `python3 scripts/audio.py out/<project>`
One consistent narrator via **xai/tts-v1** + instrumental BGM via **minimax/music-2.6**.
@@ -129,6 +138,41 @@ A common mistake is one long shot per beat. On a 9:16 / social piece especially,
Add a `shots` array to each beat (see schema). Give each shot its own short `scene` and
`motion`; set `"title": true` only on the wide shot so the headline shows once per beat.
+## A-roll mode (talking-head → collage)
+
+The standard workflow above is **B-roll**: a topic becomes AI-generated collage posters
+that get animated. **A-roll is the reverse case** — the user already has a real recorded
+talking-head video (a presenter speaking to camera) and wants it *itself* turned into the
+collage look, keeping their actual performance (face, lip movement, gestures) intact. There
+is no poster to generate; the "keyframe" is the presenter's own footage. Use A-roll when the
+user gives you a video file of themselves/a presenter talking, not a topic to write from
+scratch.
+
+1. **Transcribe + auto-segment.** `python3 scripts/asr_beats.py <project_dir> <source.mp4>`
+ Runs xai/stt-v1 on the source's own audio and cuts it into beats at sentence-ending
+ punctuation or natural pause gaps (never exceeding ~9.5s, under Omni/Kling video-edit's
+ 10s per-call cap). Writes `beats.json` with each beat's `start`/`end`/`text` — **this is
+ the same mandatory approval gate as the B-roll beat map**: review it, set `"theme"` (run
+ `style_bakeoff.py` the same way — the presenter's segment works fine as the bake-off
+ source), and optionally fill in a `content_beats` string per beat (a sticker/stamp idea
+ to layer in) before generating anything.
+
+2. **Generate.** `python3 scripts/aroll_clips.py <project_dir> [only_ids]`
+ Cuts each beat's time range out of the source, uploads it, and re-styles it with a
+ **photographic paper-cutout sticker** treatment on the presenter — her real likeness,
+ lip movement, eye-line and gestures follow the source frame-for-frame; only the
+ silhouette edge and the world around her are paper-collage. Default model is
+ `google/gemini-omni-flash/video-edit`; any beat it rejects automatically retries on
+ `bytedance/seedance-2.0/reference-to-video` (set via `video_model`/`video_model_fallback`
+ in beats.json). **Never ask the model to redraw or halftone-texture the face itself** —
+ that gets rejected regardless of how the prompt is worded (tried both a strong and a
+ softened phrasing; both failed). Uses the same aspect-routing confirm gate as `clips.py`.
+
+3. **Assemble.** `python3 scripts/aroll_assemble.py <project_dir>`
+ Muxes each generated clip with the *original* beat segment's own audio (never whatever
+ audio the video model produced) so lip-sync is guaranteed regardless of which model
+ handled that beat, normalizes every beat to one canvas, and concats into `final.mp4`.
+
## beats.json schema
```json
diff --git a/SKILL.zh.md b/SKILL.zh.md
index 310271e..c8eff00 100644
--- a/SKILL.zh.md
+++ b/SKILL.zh.md
@@ -46,11 +46,12 @@ Vox 拼贴的**样子**和**动效**是两件事、两步:
`out/<project>/beats.json`:**第1段标题必须是 ≤3 秒的钩子**;beat 数量按时长(30s→6–8,60s→10–12);
每段拆 **2 镜**(广角+特写),**每镜 `camera_move` 相邻段要不同**(不重复;`static` 留给点题段),
**`element_motion` 写丰富**(见第4步)。每段:`narration`、`title_cn`/`title_en`、`scene`、`bg`、
- `feel`、`hook`。这份草稿是**唯一强制确认关口**——生成前先给用户过。示例见 `examples/`。
+ `feel`、`hook`。这份草稿是**第一个强制确认关口**——生成前先给用户过(第4步的画幅近似值是第二个)。示例见 `examples/`。
2. **选视觉风格(混合式——在生关键帧前做)。** 别所有主题都用一个风格。读 `references/prompt-guide.md`(§5 主题预置);
从 **主题预置**(`styles.THEME_PRESETS`:`american-retro`、`swiss-modern`、`punk-zine`、
- `soviet-constructivist`、`wpa-propaganda`、`70s-groovy`、`chinese-ink`、`atomic-age`)里挑 3–4 个
+ `soviet-constructivist`、`wpa-propaganda`、`70s-groovy`、`chinese-ink`、`atomic-age`、
+ `newsprint-editorial`)里挑 3–4 个
贴主题(年代/文化/调性)的,**库里没有就现调一个**(混 prompt-guide 的 媒介/年代/配色/字体/质感)。
**匹配主题、不匹配语言**(英文讲中国史照样该中式)。一个主题打包整个"看的层"
(idiom+配色+字体+质感+情绪+运动)。跑 bake-off 让用户看图 pick——AI 出主意、库保底、人拍板。
@@ -75,6 +76,11 @@ Vox 拼贴的**样子**和**动效**是两件事、两步:
护栏——平面2D/单向/不 morph,适合重文字讲解片)或 `loose`(放开让模型探索 3D/大胆运镜,抽卡重滚)。
**只有带标题的镜头才硬锁文字**(无标题的特写镜随便浪)。**真人 / 品牌 logo**:Omni 和 Seedance 会拒——设
`"video_model": "kwaivgi/kling-video-o3-pro/image-to-video"`。
+ **画幅路由**(`styles.resolve_video_aspect`,第二个确认关口):`clips.py` 会把 `doc["aspect"]` 拿去跟选定
+ `video_model` 自己支持的比例做匹配——能精确匹配就直接用;Omni 只有 16:9/9:16,Kling reference-to-video
+ 多一个 1:1,Kling image-to-video/video-edit 和 Seedance 则跟随输入/ratio 参数走。**匹配不上时会选最近似的
+ 比例,但会停下来要求你确认**(确认后设 `"aspect_approx_confirmed": true`),不会默默改画幅——同一次运行里
+ 所有镜头都用同一个已解析比例,成片不会混画幅。
5. **旁白 + 配乐。** `python3 scripts/audio.py out/<project>`
用 **xai/tts-v1** 出单一音色旁白 + **minimax/music-2.6** 出器乐 BGM。**按主题+语种挑 `voice_id`**(别只用默认)—— 见 `references/voices.md`(5 个多语种 + ~66 个各语种母语音色,标了性别);默认 `leo`(男、纪录片感)。
@@ -97,6 +103,32 @@ Vox 拼贴的**样子**和**动效**是两件事、两步:
- 广角当 shot `a` 复用;特写 shot `b` 另写更紧的场景。`keyframes.py` 会**跳过已有 `keyframe_url` 的镜**,
所以加 `b` 镜重跑只生成新的。
+## A-roll 模式(数字人口播 → 拼贴)
+
+上面的标准流程是 **B-roll**:一个主题被写成 AI 生成的拼贴海报再动起来。**A-roll 是反过来的场景**
+——用户已经有一段真实录制的数字人口播视频(真人对镜头说话),想把这段视频**本身**变成拼贴风格,
+同时保留她的真实表演(脸、口型、手势)。这里没有海报要生成;"关键帧"就是主播本人的真实素材。
+当用户给的是一段真人/主播说话的视频文件,而不是要从零写的主题时,走这条路。
+
+1. **转录 + 自动切分。** `python3 scripts/asr_beats.py <project_dir> <source.mp4>`
+ 对源视频自带的音轨跑 xai/stt-v1,按句尾标点或自然停顿把它切成多段(不超过 ~9.5s,压在
+ Omni/Kling video-edit 单次调用 10s 上限内)。写出 `beats.json`,每段带 `start`/`end`/`text`
+ ——**这是跟 B-roll 分镜表一样的强制确认关口**:先过一遍,设好 `"theme"`(照样跑
+ `style_bakeoff.py`,直接用主播这段素材当 bake-off 源即可),想加就给某段填一句
+ `content_beats`(贴纸/印章创意),再进入生成。
+
+2. **生成。** `python3 scripts/aroll_clips.py <project_dir> [only_ids]`
+ 从源视频切出每段的时间范围、上传,再套上**摄影质感的纸片贴纸**处理——主播的真实长相、
+ 口型、眼神、手势逐帧跟随源视频,只有轮廓边缘和周围世界是拼贴风格。默认模型是
+ `google/gemini-omni-flash/video-edit`;任何一段被它拒绝都会自动重试
+ `bytedance/seedance-2.0/reference-to-video`(可在 beats.json 里用 `video_model`/
+ `video_model_fallback` 改)。**千万别要求模型把脸本身重绘/半调网点化**——不管措辞多软化
+ 都会被拒(强硬版、软化版都试过,都失败)。画幅路由确认关卡跟 `clips.py` 共用同一套。
+
+3. **合成。** `python3 scripts/aroll_assemble.py <project_dir>`
+ 把每段生成的画面跟**原始**那段音频(而不是视频模型自己出的音频)对上,保证不管哪个模型
+ 处理了这段,口型都对得上;再把每段统一到同一画幅,拼接成 `final.mp4`。
+
## beats.json schema
```json
diff --git a/references/prompt-guide.md b/references/prompt-guide.md
index 1e5633e..045227d 100644
--- a/references/prompt-guide.md
+++ b/references/prompt-guide.md
@@ -229,6 +229,7 @@ hand-writing each prompt. The library (`styles.THEME_PRESETS`):
| `70s-groovy` | 1970s | mustard/rust/avocado | bulbous display serif | riso grain | punchy | culture, food, nostalgia |
| `chinese-ink` | Chinese woodblock/ink | ink + vermilion | Chinese brush + red seal | rice-paper, seal | calm/punchy | Chinese history/culture |
| `atomic-age` | 1950s futurism | teal/orange/cream | atomic script | halftone | punchy | science, space, future |
+| `newsprint-editorial` | mid-century front-page news feature | cream/deep red/mustard/charcoal | bold condensed newsprint headline | aged paper, heavy halftone | punchy | news, AI/tech explainers, editorial features |
**How to use:** the agent reads the topic → suggests 3–4 fitting presets (or composes a new one
by mixing the banks in §1–§2) → `style_bakeoff.py` renders one beat in each → the user picks. The
diff --git a/scripts/aroll_assemble.py b/scripts/aroll_assemble.py
new file mode 100644
index 0000000..f612c89
--- /dev/null
+++ b/scripts/aroll_assemble.py
@@ -0,0 +1,85 @@
+#!/usr/bin/env python3
+"""
+A-roll assembly: mux each beat's generated visual clip with the ORIGINAL beat
+segment's own audio -- never whatever audio the video model itself produced or
+kept -- then concat all beats into one final.mp4.
+
+Why remux instead of trusting the model: Omni video-edit's schema has no audio-
+passthrough control at all, and the fallback models (Kling, Seedance) handle it
+inconsistently. Pulling the audio straight from the untouched source segment is
+the only way to guarantee the presenter's real voice stays in perfect lip-sync
+regardless of which model generated that beat.
+
+Usage: python3 aroll_assemble.py <project_dir>
+"""
+import json
+import os
+import subprocess
+import sys
+
+RES = {"16:9": (1920, 1080), "9:16": (1080, 1920), "1:1": (1080, 1080),
+ "4:3": (1440, 1080), "3:4": (1080, 1440)}
+
+
+def ff(args):
+ subprocess.run(["ffmpeg", "-y", "-loglevel", "error", *args], check=True)
+
+
+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 run(project_dir):
+ bpath = os.path.join(project_dir, "beats.json")
+ with open(bpath) as f:
+ doc = json.load(f)
+ src = doc["source_video"]
+ W, H = RES.get(doc.get("aspect", "9:16"), (1080, 1920))
+ tmp = os.path.join(project_dir, "_seg")
+ os.makedirs(tmp, exist_ok=True)
+
+ muxed = []
+ for beat in doc["beats"]:
+ clip = beat.get("clip_path")
+ if not clip or not os.path.exists(clip):
+ print(f"[{beat['id']}] no generated clip -- skipped (missing from final)")
+ continue
+ audio_path = os.path.join(tmp, f"audio_{beat['id']}.aac")
+ ff(["-ss", f"{beat['start']:.2f}", "-i", src, "-t", f"{beat['dur']:.2f}",
+ "-vn", "-c:a", "aac", audio_path])
+ vd, ad = probe_dur(clip), probe_dur(audio_path)
+ d = min(vd, ad) if vd and ad else (vd or ad)
+ if not d:
+ print(f"[{beat['id']}] couldn't probe a duration -- skipped")
+ continue
+ # normalize every beat to the same canvas (models may return different
+ # native sizes even at the same aspect) so the final concat is safe
+ out = os.path.join(tmp, f"muxed_{beat['id']}.mp4")
+ fc = (f"[0:v]scale={W}:{H}:force_original_aspect_ratio=increase,"
+ f"crop={W}:{H},setsar=1,fps=24[v]")
+ ff(["-i", clip, "-i", audio_path, "-filter_complex", fc, "-map", "[v]", "-map", "1:a:0",
+ "-t", f"{d:.2f}", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", out])
+ muxed.append(out)
+ print(f"[{beat['id']}] muxed ({d:.2f}s)")
+
+ if not muxed:
+ raise SystemExit("no beats had a generated clip -- run aroll_clips.py first")
+
+ listf = os.path.join(tmp, "concat_list.txt")
+ with open(listf, "w") as f:
+ for m in muxed:
+ f.write(f"file '{os.path.abspath(m)}'\n")
+ final = os.path.join(project_dir, "final.mp4")
+ ff(["-f", "concat", "-safe", "0", "-i", listf, "-c", "copy", final])
+ print("FINAL:", final, f"({len(muxed)}/{len(doc['beats'])} beats)")
+
+
+if __name__ == "__main__":
+ proj = sys.argv[1] if len(sys.argv) > 1 else os.path.join(
+ os.path.dirname(__file__), "..", "out", "aroll-demo")
+ run(os.path.abspath(proj))
diff --git a/scripts/aroll_clips.py b/scripts/aroll_clips.py
new file mode 100644
index 0000000..5f4c381
--- /dev/null
+++ b/scripts/aroll_clips.py
@@ -0,0 +1,183 @@
+#!/usr/bin/env python3
+"""
+A-roll clip stage: cut each ASR beat's time range out of the source recording
+(see asr_beats.py) and re-style it as a mixed-media collage clip, keeping the
+presenter's own performance -- lip movement, eye-line, gestures -- frame-for-
+frame. Unlike B-roll there is no synthesized poster to animate: the "keyframe"
+IS the presenter's real footage, so this talks to video-edit / reference-to-
+video models instead of image-to-video.
+
+Model routing (validated 2026-07-16 against a real production clip):
+ 1. google/gemini-omni-flash/video-edit (default). Accepts real people and a
+ PHOTOGRAPHIC paper-cutout sticker treatment on the presenter (proven).
+ Rejects (1010002) a prompt that asks it to redraw/halftone-texture the
+ face itself -- tried both a strong and a softened phrasing, both
+ rejected, so build_prompt() below never asks for that.
+ 2. bytedance/seedance-2.0/reference-to-video (fallback) for any beat Omni
+ rejects.
+Kling O3 pro's video-edit/reference-to-video were also validated as a further
+fallback (they don't policy-block this content) but default to a flat vector-
+illustration look rather than photographic, so they're not the auto-fallback
+here -- wire them in via video_model_fallback if you've confirmed the look.
+
+Usage: python3 aroll_clips.py <project_dir>
+"""
+import json
+import os
+import subprocess
+import sys
+
+from provider import get_provider, run_jobs
+from styles import resolve_theme, resolve_video_aspect
+
+PRIMARY_MODEL = "google/gemini-omni-flash/video-edit"
+FALLBACK_MODEL = "bytedance/seedance-2.0/reference-to-video"
+
+
+def cut_segment(src, start, end, dest, pad=0.15):
+ """Cut this beat's [start,end] (+ a small pad) out of the source, re-encoded
+ so it's a clean, independently seekable upload for the video-edit call."""
+ dur = max(end - start, 0.1) + pad
+ ss = max(start - pad / 2, 0)
+ subprocess.run(["ffmpeg", "-y", "-v", "error", "-ss", f"{ss:.2f}", "-i", src,
+ "-t", f"{dur:.2f}", "-c:v", "libx264", "-c:a", "aac",
+ "-pix_fmt", "yuv420p", dest], check=True)
+
+
+def build_prompt(theme, content_beats=""):
+ """Presenter-lock + theme block. Only the B1 pattern Omni actually accepts:
+ a PHOTOGRAPHIC paper-cutout sticker (silhouette/edge re-styled), never a
+ redrawn or halftone-textured face -- that's the one thing that got this
+ content rejected, in both a strong and a softened phrasing."""
+ tp = theme or {}
+ idiom = tp.get("idiom", "american-retro")
+ palette = tp.get("palette", "bold retro primaries")
+ type_style = tp.get("type_style", "bold condensed headlines")
+ finish = tp.get("finish", "aged paper, high contrast")
+ beats_line = f"\n\nCONTENT BEATS: {content_beats}" if content_beats else ""
+ return (
+ "Transform my raw talking-head video into a mixed-media collage motion graphic.\n\n"
+ "TALKING-HEAD LOCK (most important):\n"
+ "The presenter is a PHOTOGRAPHIC paper cut-out sticker with a bold black printed "
+ "outline and a torn-paper silhouette edge -- her actual photographic likeness, "
+ "facial performance, LIP MOVEMENTS, eye-line and hand gestures follow the source "
+ "video frame-for-frame, unmodified. Do NOT re-texture, redraw, or halftone-print the "
+ "face or skin itself -- only the silhouette edge and the world around her are paper-"
+ "collage. Keep ALL motion, timing and framing from the source. Keep the presenter "
+ "centered, matching the source video's own orientation.\n\n"
+ f"STYLE (background & props): {idiom}. Palette: {palette}. Typography: {type_style}. "
+ f"Finish: {finish}. Clearly layered hand-cut paper cut-outs with visible torn and "
+ "scissor-cut edges, tape corners and soft real paper drop shadows, on a bold flat "
+ "paper background. Halftone print dots, newspaper-clipping scraps, paper-stencil "
+ "shapes, aged paper texture. PRINTED / illustrated cut-outs for the background and "
+ f"props, NOT CGI, NOT 3D.{beats_line}\n\n"
+ "CONSTRAINTS: background elements and stamps never cover her face or hands; "
+ "everything except the presenter's face/skin reads as printed paper."
+ )
+
+
+def video_params(model, video_url, aspect, dur):
+ """Per-model request body. Audio is intentionally NOT requested/trusted from
+ any of these models -- aroll_assemble.py always remuxes the original beat
+ segment's own audio afterward, so lip-sync never depends on a model's
+ audio-passthrough behavior (Omni's video-edit schema doesn't even expose
+ one)."""
+ if "seedance" in model:
+ return dict(reference_videos=[video_url], duration=max(4, min(15, round(dur))),
+ ratio=aspect, resolution="1080p", generate_audio=False)
+ if "kling-video-o3-pro/reference-to-video" in model:
+ return dict(video=video_url, aspect_ratio=aspect, duration=max(3, min(15, round(dur))),
+ keep_original_sound=False, sound=False)
+ if "kling" in model: # video-edit: follows input, no aspect param
+ return dict(video=video_url, keep_original_sound=False)
+ return dict(video=video_url) # gemini-omni-flash/video-edit
+
+
+def run(project_dir, only=None):
+ bpath = os.path.join(project_dir, "beats.json")
+ with open(bpath) as f:
+ doc = json.load(f)
+ if doc.get("mode") != "aroll":
+ raise SystemExit("beats.json has no \"mode\": \"aroll\" -- run asr_beats.py first, "
+ "or use clips.py for a B-roll project.")
+ src = doc["source_video"]
+ aspect = doc.get("aspect", "9:16")
+ theme = resolve_theme(doc.get("theme")) or {}
+ primary = doc.get("video_model", PRIMARY_MODEL)
+ fallback = doc.get("video_model_fallback", FALLBACK_MODEL)
+ seg_dir = os.path.join(project_dir, "segments")
+ clip_dir = os.path.join(project_dir, "clips")
+ os.makedirs(seg_dir, exist_ok=True)
+ os.makedirs(clip_dir, exist_ok=True)
+
+ prov = get_provider(doc.get("provider"))
+
+ def gate_aspect(model):
+ resolved, exact = resolve_video_aspect(aspect, model)
+ if not exact and not doc.get("aspect_approx_confirmed"):
+ print(f"ASPECT MISMATCH on {model}: project aspect \"{aspect}\" has no exact "
+ f"match; nearest supported is \"{resolved}\". Confirm with the user, then "
+ f"set \"aspect_approx_confirmed\": true in beats.json to proceed.")
+ return None
+ return resolved or aspect
+
+ a_primary = gate_aspect(primary)
+ if a_primary is None:
+ return
+
+ # ---- cut + upload each beat's segment, queue the primary-model submission ----
+ specs, meta = {}, {}
+ for beat in doc["beats"]:
+ key = str(beat["id"])
+ if only and key not in only:
+ continue
+ seg_path = os.path.join(seg_dir, f"seg_{key}.mp4")
+ cut_segment(src, beat["start"], beat["end"], seg_path)
+ url = prov.upload(seg_path)
+ prompt = build_prompt(theme, beat.get("content_beats", ""))
+ params = video_params(primary, url, a_primary, beat["dur"])
+ specs[key] = (lambda m=primary, p=prompt, pr=params: prov.submit_video(m, p, **pr))
+ meta[key] = {"beat": beat, "seg_path": seg_path, "url": url}
+ print(f"[{key}] queued on {primary.split('/')[-2]} ({beat['dur']}s)")
+
+ done = run_jobs(prov, specs, poll_s=8, stall_s=240, max_retries=1, deadline_s=900)
+
+ # ---- fallback pass: only the beats the primary model rejected/failed ----
+ retry_keys = [k for k, u in done.items() if not u]
+ if retry_keys:
+ a_fallback = gate_aspect(fallback)
+ if a_fallback is None:
+ print(f"skipping fallback for beats {retry_keys}: aspect gate blocked above")
+ else:
+ print(f"[{fallback.split('/')[-2]}] retrying beats {retry_keys}")
+ fb_specs = {}
+ for key in retry_keys:
+ m = meta[key]
+ prompt = build_prompt(theme, m["beat"].get("content_beats", ""))
+ params = video_params(fallback, m["url"], a_fallback, m["beat"]["dur"])
+ fb_specs[key] = (lambda mo=fallback, p=prompt, pr=params:
+ prov.submit_video(mo, p, **pr))
+ fb_done = run_jobs(prov, fb_specs, poll_s=8, stall_s=240, max_retries=1, deadline_s=900)
+ done.update({k: v for k, v in fb_done.items() if v})
+
+ for key, url in done.items():
+ beat = meta[key]["beat"]
+ if not url:
+ print(f"[{key}] FAILED on both primary and fallback -- beat will be missing "
+ f"from the assembled film")
+ continue
+ dest = os.path.join(clip_dir, f"clip_{key}.mp4")
+ prov.download(url, dest)
+ beat["clip_path"] = dest
+ print(f"[{key}] saved {dest}")
+
+ with open(bpath, "w") as f:
+ json.dump(doc, f, ensure_ascii=False, indent=2)
+ print("updated", bpath)
+
+
+if __name__ == "__main__":
+ proj = sys.argv[1] if len(sys.argv) > 1 else os.path.join(
+ os.path.dirname(__file__), "..", "out", "aroll-demo")
+ only = set(sys.argv[2].split(",")) if len(sys.argv) > 2 else None
+ run(os.path.abspath(proj), only=only)
diff --git a/scripts/asr_beats.py b/scripts/asr_beats.py
new file mode 100644
index 0000000..074c5d0
--- /dev/null
+++ b/scripts/asr_beats.py
@@ -0,0 +1,166 @@
+#!/usr/bin/env python3
+"""
+ASR bridge (A-roll only): turn a raw talking-head recording's own baked-in audio
+into a beats.json skeleton, so A-roll mode can cut and re-style it beat-by-beat
+without anyone hand-timing the source video.
+
+Unlike B-roll (Claude authors `narration` text up front, audio.py then synthesizes
+it), A-roll starts from audio that already exists: the presenter already spoke it
+on camera. So the direction is reversed -- transcribe first, segment the
+transcript into natural beats by sentence-ending punctuation and pause gaps, and
+write out beat time ranges + text. This draft is still the same "first mandatory
+approval gate" as the B-roll beat map (see SKILL.md step 1): review/edit it
+(theme, content_beats, video_model) before running aroll_clips.py.
+
+Usage:
+ python3 asr_beats.py <project_dir> <source_video_or_audio> [--language en]
+ [--keyterm name1,name2] [--max-beat-dur 9.5]
+"""
+import argparse
+import json
+import os
+import subprocess
+import sys
+
+import atlas_cloud
+from provider import get_provider
+
+# Both Omni video-edit and Kling video-edit cap a single call at 10s; leave headroom
+# so a beat that lands right on the limit doesn't get rejected for being 10.0s exactly.
+MAX_BEAT_DUR = 9.5
+MIN_BEAT_DUR = 2.0
+PAUSE_GAP_S = 0.35 # a gap this long between words reads as a natural pause
+SENTENCE_END = (".", "!", "?")
+
+
+def probe_dims(path):
+ out = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0",
+ "-show_entries", "stream=width,height", "-of", "csv=p=0", path],
+ capture_output=True, text=True).stdout.strip()
+ if not out:
+ return None
+ w, h = (int(x) for x in out.split(",")[:2])
+ return w, h
+
+
+def nearest_named_aspect(w, h):
+ """Snap a raw pixel size to the nearest of the common named ratios, purely so
+ beats.json carries a human-readable target -- the real routing/approximation
+ decision still happens in styles.resolve_video_aspect at generation time."""
+ named = {"16:9": 16 / 9, "9:16": 9 / 16, "1:1": 1.0, "4:3": 4 / 3, "3:4": 3 / 4}
+ ratio = w / h
+ return min(named, key=lambda k: abs(named[k] - ratio))
+
+
+def extract_audio(src, dest):
+ subprocess.run(["ffmpeg", "-y", "-v", "error", "-i", src, "-vn",
+ "-acodec", "libmp3lame", "-q:a", "2", dest], check=True)
+
+
+def segment_words(words, max_dur=MAX_BEAT_DUR, min_dur=MIN_BEAT_DUR, pause_gap=PAUSE_GAP_S):
+ """Group word-level ASR timestamps into beats. A beat ends at a sentence-ending
+ word once it's at least min_dur long, or at a pause gap, or is force-cut before
+ max_dur so no single call ever exceeds a video model's per-call duration cap.
+ Trailing fragments shorter than min_dur are merged into the previous beat."""
+ beats, cur = [], []
+
+ def flush():
+ if not cur:
+ return
+ beats.append({
+ "start": round(cur[0]["start"], 2),
+ "end": round(cur[-1]["end"], 2),
+ "text": " ".join(w["text"] for w in cur),
+ })
+ cur.clear()
+
+ for i, w in enumerate(words):
+ cur.append(w)
+ dur = w["end"] - cur[0]["start"]
+ is_last = i == len(words) - 1
+ gap_next = (words[i + 1]["start"] - w["end"]) if not is_last else None
+ sentence_end = w["text"].rstrip().endswith(SENTENCE_END)
+ if is_last:
+ flush()
+ elif dur >= max_dur: # force cut -- never exceed the model cap
+ flush()
+ elif dur >= min_dur and (sentence_end or (gap_next is not None and gap_next >= pause_gap)):
+ flush()
+
+ # merge any too-short trailing beat into its predecessor rather than emitting a
+ # sub-min_dur clip that's awkward to generate/cut on its own
+ merged = []
+ for b in beats:
+ if merged and (b["end"] - b["start"]) < min_dur:
+ merged[-1]["end"] = b["end"]
+ merged[-1]["text"] += " " + b["text"]
+ else:
+ merged.append(b)
+ return merged
+
+
+def run(project_dir, source, language=None, keyterm=None, max_beat_dur=MAX_BEAT_DUR,
+ provider_name=None):
+ os.makedirs(project_dir, exist_ok=True)
+ bpath = os.path.join(project_dir, "beats.json")
+
+ dims = probe_dims(source)
+ aspect = nearest_named_aspect(*dims) if dims else "9:16"
+
+ audio_path = source
+ if not source.lower().endswith((".mp3", ".wav", ".m4a", ".flac", ".ogg")):
+ audio_path = os.path.join(project_dir, "asr_audio.mp3")
+ print(f"extracting audio -> {audio_path}")
+ extract_audio(source, audio_path)
+
+ prov = get_provider(provider_name)
+ print("uploading audio for ASR...")
+ audio_url = prov.upload(audio_path)
+ print("transcribing (xai/stt-v1)...")
+ result = atlas_cloud.transcribe(audio_url, language=language,
+ keyterm=keyterm.split(",") if keyterm else None)
+ words = result.get("words", [])
+ if not words:
+ raise SystemExit("ASR returned no word timestamps -- check the source audio")
+
+ segments = segment_words(words, max_dur=max_beat_dur)
+ beats = [{
+ "id": i + 1,
+ "start": s["start"],
+ "end": s["end"],
+ "dur": round(s["end"] - s["start"], 2),
+ "text": s["text"],
+ "content_beats": "", # optional: fill in per-beat sticker/stamp/overlay ideas
+ } for i, s in enumerate(segments)]
+
+ doc = {
+ "project": os.path.basename(project_dir.rstrip("/")),
+ "mode": "aroll",
+ "source_video": os.path.abspath(source),
+ "language": result.get("language") or language or "en",
+ "aspect": aspect,
+ "style": "collage",
+ "theme": None, # fill in after a style bake-off
+ "video_model": "google/gemini-omni-flash/video-edit",
+ "video_model_fallback": "bytedance/seedance-2.0/reference-to-video",
+ "transcript": result.get("text", ""),
+ "beats": beats,
+ }
+ with open(bpath, "w") as f:
+ json.dump(doc, f, ensure_ascii=False, indent=2)
+ print(f"wrote {len(beats)} beats -> {bpath}")
+ print("review/edit theme + content_beats, then run aroll_clips.py "
+ "(this draft is the approval gate -- don't generate off it unreviewed).")
+
+
+if __name__ == "__main__":
+ ap = argparse.ArgumentParser()
+ ap.add_argument("project_dir")
+ ap.add_argument("source", help="raw talking-head video or audio file")
+ ap.add_argument("--language", default=None)
+ ap.add_argument("--keyterm", default=None, help="comma-separated names/terms to bias ASR toward")
+ ap.add_argument("--max-beat-dur", type=float, default=MAX_BEAT_DUR)
+ ap.add_argument("--provider", default=None)
+ a = ap.parse_args()
+ run(os.path.abspath(a.project_dir), a.source, language=a.language, keyterm=a.keyterm,
+ max_beat_dur=a.max_beat_dur, provider_name=a.provider)
diff --git a/scripts/atlas_cloud.py b/scripts/atlas_cloud.py
index 64a2baf..ee256b9 100644
--- a/scripts/atlas_cloud.py
+++ b/scripts/atlas_cloud.py
@@ -63,6 +63,19 @@ def _get(path: str, base: str = MEDIA_BASE, timeout: int = 60, retries: int = 3)
req = urllib.request.Request(base + path, headers=_headers(json_body=False))
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.load(r)
+ except urllib.error.HTTPError as e:
+ # A prediction that failed upstream (e.g. a content-policy rejection) can
+ # come back wrapped in a non-2xx status, but the body is still the normal
+ # JSON envelope with the real status/error_code -- `except URLError` below
+ # would catch this too (HTTPError subclasses it) but collapses it to a bare
+ # "HTTP Error 400: Bad Request" and throws the diagnosis away. Parse it and
+ # hand it back like any other response so callers see the real status.
+ body = e.read().decode(errors="replace")
+ try:
+ return json.loads(body)
+ except ValueError:
+ last = AtlasCloudError(f"GET {path} -> {e.code}: {body[:400]}")
+ break
except (urllib.error.URLError, TimeoutError) as e: # transient
last = e
time.sleep(2 ** i)
@@ -94,6 +107,33 @@ def submit_media(model: str, **params) -> str:
return _post("/model/generateVideo", body)["data"]["id"]
+def transcribe(audio_url: str, interval: int = 3, timeout_s: int = 300, **params) -> dict:
+ """Blocking ASR via xai/stt-v1. Returns the full stt_result: {"text", "language",
+ "duration", "words": [{"text","start","end"}, ...]} (word-level timestamps).
+
+ Submits to /model/generateAudio (the model's real endpoint per its schema),
+ NOT /model/generateVideo like submit_media -- and polls for the raw stt_result
+ dict directly rather than going through poll()/get_status(), because those only
+ surface outputs[0] (the plain transcript string) and would silently drop the
+ word timestamps this exists to fetch.
+ """
+ body = {"model": "xai/stt-v1", "audio": audio_url, **params}
+ pid = _post("/model/generateAudio", body)["data"]["id"]
+ deadline = time.time() + timeout_s
+ while time.time() < deadline:
+ time.sleep(interval)
+ d = _get(f"/model/prediction/{pid}").get("data", {})
+ status = d.get("status", "?")
+ if status in ("completed", "succeeded"):
+ result = d.get("stt_result")
+ if not result:
+ raise AtlasCloudError(f"{pid}: completed but no stt_result")
+ return result
+ if status == "failed":
+ raise AtlasCloudError(f"{pid} failed: {json.dumps(d)[:300]}")
+ raise AtlasCloudError(f"{pid} timed out after {timeout_s}s")
+
+
def poll(prediction_id: str, interval: int = 3, timeout_s: int = 900) -> str:
"""Poll a prediction until done; return the first output URL."""
deadline = time.time() + timeout_s
diff --git a/scripts/clips.py b/scripts/clips.py
index b53d5b5..8042f36 100644
--- a/scripts/clips.py
+++ b/scripts/clips.py
@@ -12,7 +12,7 @@ import os
import sys
from provider import get_provider, run_jobs
-from styles import resolve_theme
+from styles import resolve_theme, resolve_video_aspect
VIDEO_MODEL = "google/gemini-omni-flash/image-to-video"
@@ -108,6 +108,23 @@ def run(project_dir, only=None):
clip_dir = os.path.join(project_dir, "clips")
os.makedirs(clip_dir, exist_ok=True)
+ # Aspect routing: prefer the project's own target aspect; only fall back to an
+ # approximation when this model has no matching enum value, and never apply that
+ # approximation without a human confirming it first (see styles.resolve_video_aspect).
+ resolved_aspect, aspect_exact = resolve_video_aspect(aspect, model)
+ if not aspect_exact:
+ if not doc.get("aspect_approx_confirmed"):
+ print(f"ASPECT MISMATCH: project aspect \"{aspect}\" has no exact match on "
+ f"{model}; nearest supported is \"{resolved_aspect}\". This changes the "
+ f"output framing — confirm with the user before generating, then set "
+ f"\"aspect_approx_confirmed\": true in beats.json to proceed (or pick a "
+ f"different video_model / aspect).")
+ return
+ print(f"[aspect] using confirmed approximation \"{resolved_aspect}\" for project "
+ f"aspect \"{aspect}\" on {model}")
+ if resolved_aspect:
+ aspect = resolved_aspect # every shot below shares this one resolved aspect
+
prov = get_provider(doc.get("provider"))
specs, by_key = {}, {}
for beat in doc["beats"]:
@@ -136,7 +153,9 @@ def run(project_dir, only=None):
if "seedance" in model: # ratio (not aspect_ratio); real-person OK
params = dict(image=url, duration=dur, ratio=aspect,
resolution=vid_res, generate_audio=False)
- elif "kling" in model: # no aspect param (follows input); allows real people
+ elif "kling-video-o3-pro/reference-to-video" in model: # has an aspect_ratio enum
+ params = dict(image=url, duration=dur, aspect_ratio=aspect, sound=False)
+ elif "kling" in model: # image-to-video / video-edit: follows input; allows real people
params = dict(image=url, duration=dur, sound=False)
else: # gemini omni flash
params = dict(image=url, duration=dur, aspect_ratio=aspect, resolution="720p")
diff --git a/scripts/styles.py b/scripts/styles.py
index 4fa68d0..ebbd7ed 100644
--- a/scripts/styles.py
+++ b/scripts/styles.py
@@ -95,6 +95,13 @@ STYLE_LIBRARY = {
"Mixed-media collage of Chinese woodblock-print and ink-mural cut-out figures, aged "
"rice-paper and Chinese newspaper clippings, vermilion seal stamps. Oriental, historical."
),
+ "newsprint-editorial": (
+ "Vintage newsprint editorial collage in the style of a mid-century front-page news "
+ "feature: bold cut-out photographs and illustrations laid over a broadsheet newspaper "
+ "page, heavy halftone print dots, aged newsprint texture with slight ink "
+ "misregistration, tactile cinematic editorial energy — reads like a newspaper feature "
+ "spread brought to life, not an ad."
+ ),
}
DEFAULT_STYLE = "american-retro"
@@ -126,6 +133,9 @@ THEME_PRESETS = {
"atomic-age": {"idiom": "1950s atomic-age retro-futurism", "palette": "teal, orange, cream",
"type_style": "atomic script + geometric caps", "finish": "halftone, starbursts",
"mood": "optimistic, bright", "motion_style": "punchy"},
+ "newsprint-editorial": {"idiom": "newsprint-editorial", "palette": "cream white, deep red, mustard yellow, charcoal black",
+ "type_style": "bold condensed newsprint headlines, all-caps", "finish": "aged paper, heavy halftone dots, high contrast, slight print misregistration",
+ "mood": "energetic, tactile, cinematic editorial", "motion_style": "punchy"},
}
@@ -154,6 +164,53 @@ def image_params(model, aspect="16:9", resolution="1k"):
return {"aspect_ratio": aspect, "resolution": resolution}
+# ---- Video-model aspect routing -------------------------------------------------
+# Each video model natively accepts a fixed enum of aspect ratios, or none at all
+# (it just follows whatever the input image/video already is). None = "follows input".
+VIDEO_ASPECT_SUPPORT = {
+ "gemini-omni-flash/image-to-video": ["16:9", "9:16"],
+ "gemini-omni-flash/video-edit": None,
+ "seedance-2.0/reference-to-video": ["16:9", "9:16", "1:1", "4:3", "3:4", "21:9", "9:21", "adaptive"],
+ "kling-video-o3-pro/reference-to-video": ["16:9", "9:16", "1:1"],
+ "kling-video-o3-pro/image-to-video": None,
+ "kling-video-o3-pro/video-edit": None,
+}
+
+
+def _aspect_value(aspect):
+ w, h = aspect.split(":")
+ return float(w) / float(h)
+
+
+def resolve_video_aspect(project_aspect, model):
+ """Route the project's target aspect (`doc["aspect"]`) to what `model` actually
+ accepts. Rule (Kiana, 2026-07-16): prefer the exact same ratio as the project's
+ target; if the model has no matching enum value, fall back to the nearest one —
+ but that fallback is an approximation and the caller MUST surface it for human
+ confirmation before generating (see clips.py), never apply it silently. Every
+ shot in one project run resolves through this same function with the same
+ project_aspect, so a finished film never mixes aspect ratios across clips.
+
+ Returns (resolved_aspect_or_None, exact). resolved_aspect is None when the model
+ has no enum at all (it just follows the input, nothing to pass/confirm).
+ """
+ support = None
+ for key, enum in VIDEO_ASPECT_SUPPORT.items():
+ if key in model:
+ support = enum
+ break
+ if support is None: # unknown model, or a "follows input" model
+ return None, True
+ if project_aspect in support:
+ return project_aspect, True
+ if project_aspect == "adaptive":
+ return ("adaptive" if "adaptive" in support else support[0]), True
+ target = _aspect_value(project_aspect)
+ nearest = min((a for a in support if a != "adaptive"),
+ key=lambda a: abs(_aspect_value(a) - target))
+ return nearest, False
+
+
def _headline(title_cn, title_en, style, type_style=None):
if title_cn: # bilingual (CJK styles)
return (" " + TITLE_TREATMENT.format(title_cn=title_cn, title_en=title_en))