Reverse-engineer any video, shot by shot: filmed, AI-generated or coded, and how to remake it. Breakdowns in the open VIDEO.md format. 逆向一切视频,逐个镜头看是拍的、AI 生成的还是代码做的,再告诉你怎么复刻;拆解结果按 VIDEO.md 格式输出。
Python agent-skillsai-videoaigc-detectionclaude-codecodexffmpegprompt-engineeringremotionreverse-engineeringshort-videoshot-detectionsubtitlesvideo-analysisvideo-breakdownvideo-editingvideo-generationvideomdvlm
"""VIDEO.md: a video breakdown laid out for models. Read the card, then the map, then open only the file you need.
The output directory is the package. Levels, each cheaper than the next:
L0 VIDEO.md front matter the card: what the video is, how it was made, how sure ~150 tokens
L1 VIDEO.md body overview, open questions and the map of every file below ~1k tokens
L2 video/<topic>.md one topic per file; video/timeline.md is the spine: one line per shot
L3 video/shots/07.md everything about one shot: what is visible, what is inferred and why, remake prompts
L4 breakdown.json, shots/, stems/, sfx/, packaging/ raw data and media
Every file opens with front matter saying what it covers and roughly how many tokens it holds, so a reader can decide
before opening it. Paths are relative to the package root. In timeline lines a key ending in `~` is the tools'
inference; keys without it are what is visible on screen or measured directly. The spec is https://github.com/videomd/videomd; reading and checking use the `videomd` package.
"""
from __future__ import annotations
import html
import re
import shutil
from pathlib import Path
import yaml
from .readings import shot_description
from . import entities, narrative, performance
from .classify import LABEL_ZH
from .i18n import T, join
FORMAT = "videomd"
VERSION = 1
ENTRY = "VIDEO.md"
DIR = "video"
BLOCK = "videomd-timeline"
MAP_BLOCK = "videomd-map"
# producer-side values -> the neutral ids in the spec
DECIDED_BY = {"deterministic": "tools", "fused": "model", "fused_agent": "agent", "user": "human"}
OVERLAY_ID = {"huazi": "styled_text"}
# shot-boundary kinds from the cut detector -> transition ids in the spec (`x-` = not in the taxonomy); plain cuts are not written
TRANSITION_ID = {"jump": "jump_cut", "fade": "fade_through", "dissolve": "dissolve", "wipe": "wipe", "flash": "flash",
"slide": "slide", "whip": "whip", "zoom": "zoom", "spin": "spin", "blur": "x-blur", "glitch": "glitch",
"shake": "x-shake", "effect": "x-effect", "mg_transition": "x-mg_transition",
"morph": "x-morph", "match": "x-match"}
# timeline keys, in line order; `~` = inferred by the tools
KEYS = ("story", "seen", "act", "layers", "camera", "transition", "overlay", "made~", "material~", "remake", "flag")
# ------------------------------------------------------------------ helpers ---------------------------------------
def tokens(text: str) -> int:
"""Rough token count: ~4 ASCII characters per token, ~1.5 tokens per 2 CJK characters."""
ascii_n = sum(c.isascii() for c in text)
return int(ascii_n / 4 + (len(text) - ascii_n) * 0.75) + 1
def _one_line(s, limit: int | None = None) -> str:
s = re.sub(r"\s+", " ", str(s or "")).replace(" | ", " / ").replace("|", "/").strip()
return s[:limit] + "…" if limit and len(s) > limit else s
def _front(meta: dict, body: str) -> str:
fm = yaml.safe_dump(meta, allow_unicode=True, sort_keys=False, width=1000).strip()
return f"---\n{fm}\n---\n\n{body.strip()}\n"
def _sized(meta: dict, body: str) -> str:
"""Front matter + body, with the body's size in the front matter."""
return _front({**meta, "tokens": tokens(body)}, body)
_RE_DETAILS = re.compile(r'^<details(?: class="ref")?><summary>(.*)</summary>$')
_RE_INLINE_IMG = re.compile(r"!\[[^\]]*\]\(([^)\s]+)\)")
def _plain(lines: list[str]) -> str:
"""A report section without the HTML folds: a model reads the whole file it opened."""
out = []
for ln in lines:
s = ln.strip()
m = _RE_DETAILS.match(s)
if m:
out.append(f"**{html.unescape(m.group(1))}**")
elif s != "</details>" and not ln.startswith("![") and not (s.startswith("<!--") and s.endswith("-->")):
out.append(_RE_INLINE_IMG.sub(r"`\1`", ln))
return re.sub(r"\n{3,}", "\n\n", "\n".join(out)).strip()
def _shot_name(i: int) -> str:
return f"{i:02d}"
# ------------------------------------------------------------------ timeline (the spine) --------------------------
_TRANSITION_WORDS = {"jump_cut": ("跳切", "jump cut"), "fade_through": ("黑场/白场过渡", "fade through"), "dissolve": ("叠化", "dissolve"),
"wipe": ("划像", "wipe"), "flash": ("闪白", "flash"), "slide": ("推移", "slide"), "whip": ("甩镜", "whip pan"),
"zoom": ("缩放转场", "zoom"), "spin": ("旋转转场", "spin"), "x-blur": ("模糊转场", "blur"), "glitch": ("故障转场", "glitch"),
"x-shake": ("抖动转场", "shake"), "x-effect": ("转场特效", "transition effect"),
"x-mg_transition": ("版式切换", "layout change"), "x-morph": ("形变转场", "morph"),
"x-match": ("匹配剪辑", "match cut")}
def _transition_in(r: dict) -> dict:
"""The spec's transition_in for a shot record: type, and time / direction when measured; {} for a plain cut."""
tid = TRANSITION_ID.get(r.get("transition_in") or "cut")
if not tid:
return {}
tr = r.get("transition") or {}
# the spec's time spans the start of the shot
span = ({"time": [round(min(tr["start"], r["start"]), 3), round(max(tr["end"], r["start"]), 3)]}
if tr.get("start") is not None and tr.get("end") is not None and "start" in r else {})
return {"type": tid, **span, **{k: tr[k] for k in ("direction", "via", "mode") if tr.get(k)}}
def timeline_line(r: dict, roles: dict, units: dict) -> str:
from .report import CAMERA_ZH, _layers, _origin, _route
base = r["base"]
f = {}
n = roles.get(r["index"]) or {}
if n.get("role_zh") or n.get("point"):
f["story"] = _one_line(join(x for x in (n.get("role_zh"), n.get("point")) if x), 48)
desc = shot_description(r)
if desc:
f["seen"] = _one_line(desc, 60)
act = performance.of(r)
if act:
f["act"] = _one_line(performance.summary(act), 40)
f["camera"] = CAMERA_ZH.get((r.get("features") or {}).get("camera", "unknown"), "—")
trans = TRANSITION_ID.get(r.get("transition_in") or "cut")
if trans:
dur = (r.get("transition") or {}).get("duration")
f["transition"] = T(*_TRANSITION_WORDS[trans]) + (f" {dur:.1f}s" if dur and dur >= 0.1 else "")
if _layers(r) != "—":
f["overlay"] = _layers(r)
made = f"{base['label_zh']} {base['confidence']:.0%}"
alt = next(((k, v) for k, v in sorted(base["probs"].items(), key=lambda kv: -kv[1]) if k != base["label"] and v >= 0.01), None)
if alt and base["decided_by"] != "user":
made += T(" · 次选 {l} {p:.0%}", " · runner-up {l} {p:.0%}", l=LABEL_ZH[alt[0]], p=alt[1])
f["made~"] = made
f["material~"] = _one_line(_origin(r), 40)
f["remake"] = _one_line(_route(r, units), 30)
flags = []
if base["decided_by"] == "user":
flags.append(T("用户纠正", "user correction"))
elif base["confidence"] < 0.6:
flags.append(T("低置信", "low confidence"))
if base.get("uncertain"):
flags.append(T("待确认", "to confirm"))
if base.get("disputed"):
flags.append(T("有分歧", "disputed"))
if flags:
f["flag"] = ",".join(flags)
head = f"#{_shot_name(r['index'])} {r['start']:.1f}-{r['end']:.1f}"
return " | ".join([head] + [f"{k} {f[k]}" for k in KEYS if f.get(k)])
def _legend() -> list[str]:
return [T("每行一个镜头:`#编号 起-止(秒) | 键 值 | …`。键后带 `~` 的是工具推断,不带的是画面里看得到或直接测得的。",
"One shot per line: `#<n> start-end (s) | key value | …`. A key ending in `~` is the tools' inference; keys without it are visible on screen or measured directly."),
T("`story` 在叙事里的作用和讲的点 · `seen` 画面里看到的 · `act` 表演(情绪、强度、表情)· `camera` 运镜 · `overlay` 叠加层 · `made~` 制作方式(推断)· "
"`material~` 素材来源(推断)· `remake` 复刻路线 · `flag` 需要复核",
"`story` job in the story and the point · `seen` what is on screen · `act` acting (emotion, strength, face) · `camera` camera move · `overlay` overlays · `made~` how it was made (inferred) · "
"`material~` where the material came from (inferred) · `remake` remake route · `flag` needs a second look"),
T("某一镜的全部细节在 `{d}/shots/编号.md`(如 `{d}/shots/07.md`)。", "Full detail for a shot is in `{d}/shots/<n>.md` (e.g. `{d}/shots/07.md`).", d=DIR)]
# ------------------------------------------------------------------ per-shot files ---------------------------------
def _beats(r: dict) -> list[dict]:
"""The shot's key frames as the spec's `beats`: moments worth finding without splitting a long shot."""
out = []
for k in r.get("keyframes") or []:
t = k.get("t")
role = k.get("role", "")
if t is None or role in ("first", "last") or not r["start"] <= t <= r["end"]:
continue
out.append({"time": [round(t, 3), round(t, 3)], "what": T(*KEY_ROLE_WORDS.get(role, (role or "画面变化", role or "change")))})
return out
def _pip_layers(r: dict, stickers: list[dict]) -> list[dict]:
"""A composite picture, when a picture-in-picture window covers at least half of the shot."""
span = max(1e-3, r["end"] - r["start"])
pips = [s for s in stickers if s.get("kind") == "pip" and s.get("confidence") != "low" and s.get("bbox")
and not s.get("in_picture") and (min(s["t1"], r["end"]) - max(s["t0"], r["start"])) / span >= 0.5]
if not pips:
return []
layers = [{"id": "main", "role": "base", "region": [0, 0, 1, 1]}]
for n, s in enumerate(pips, 1):
x, y, w, h = (max(0.0, min(1.0, float(v))) for v in s["bbox"])
layers.append({"id": f"pip{n}", "role": "pip", "region": [x, y, min(w, round(1 - x, 4)), min(h, round(1 - y, 4))],
**({"seen": _one_line(s["what"], 60)} if s.get("what") else {})})
return layers
def _shot_file(r: dict, *, scene: int | None = None, stickers: list[dict] | None = None) -> str:
from .report import _shot_detail_md
base = r["base"]
probs = sorted(base["probs"].items(), key=lambda kv: -kv[1])
assets = r.get("assets") or {}
beats = _beats(r)
layers = _pip_layers(r, stickers or [])
meta = {
FORMAT: VERSION, "part": "shot", "shot": r["index"], "time": [round(r["start"], 3), round(r["end"], 3)],
"camera": (r.get("features") or {}).get("camera", "unknown"),
"overlays": sorted({OVERLAY_ID.get(l["kind"], l["kind"]) for l in r.get("layers", [])}),
"inferred": {"made": base["label"], "p": base["confidence"],
"alternatives": dict([(k, v) for k, v in probs if k != base["label"] and v > 0][:2]),
"decided_by": DECIDED_BY.get(base["decided_by"], base["decided_by"]), "real_material": bool((r.get("material") or {}).get("has_real_material"))},
"flags": [k for k in ("uncertain", "disputed") if base.get(k)] + (["low_confidence"] if base["confidence"] < 0.6 and base["decided_by"] != "user" else []),
**({"scene": scene} if scene else {}),
**({"beats": beats} if beats else {}),
**({"layers": layers} if layers else {}),
**({"transition_in": _transition_in(r)} if _transition_in(r) else {}),
**({"keyframes": [[k["t"], k.get("role", "")] for k in r["keyframes"]]} if r.get("keyframes") else {}),
"frames": {k: v for k, v in (("sheet", assets.get("sheet")), ("first", assets.get("first_frame")), ("last", assets.get("last_frame"))) if v},
}
title = T("# 镜头 {i} · {a}–{z}s · {v}", "# Shot {i} · {a}–{z}s · {v}", i=r["index"], a=f"{r['start']:.1f}", z=f"{r['end']:.1f}", v=r.get("verdict", ""))
return _sized(meta, title + "\n\n" + _plain(_shot_detail_md(r)))
# ------------------------------------------------------------------ topic files ------------------------------------
def _topics(b: dict) -> list[tuple[str, str, str, list[str]]]:
"""(file stem, title, when to read it, report section lines)."""
from .moments import videomd as moments_md
from .report import _audio_md, _cast_md, _content_md, _expand_md_marks, _remake_md, _visual_md, packaging_md
return [
("moments", T("特殊时刻", "Special moments"), T("魔术揭秘、反转、高潮、穿帮:时间、关键帧、片段", "reveals, twists, climaxes, goofs: times, key frames, clips"), moments_md(b)),
("content", T("内容与结构", "Content and structure"), T("要讲什么、叙事线、结构时间轴、台词", "what it says, the narrative line, structure, the script"), _content_md(b)),
("cast", T("角色、场景与道具", "Cast, scenes and props"), T("做角色参考图、写首帧提示词", "reference images for characters, first-frame prompts"), _cast_md(b)),
("sound", T("声音", "Sound"), T("人声、BGM、音效、节拍和来源", "voice, music, sound effects, beats and sources"), _expand_md_marks(_audio_md(b), b)),
("rhythm", T("节奏与关键帧", "Rhythm and key frames"), T("切点和转场的时间、镜头长度、画面变化曲线、每镜关键帧", "when cuts and transitions happen, shot lengths, the change curve, key frames of each shot"), rhythm_md(b)),
("look", T("拍法、打光与剪辑", "Camera, lighting and editing"), T("有实拍镜头时:景别、机位、布光、器材", "for filmed shots: framing, camera, lighting, kit"), _visual_md(b)),
("packaging", T("剪辑包装", "Packaging"), T("字幕、花字、贴纸、画中画的时间和样式", "subtitles, styled text, stickers, picture-in-picture: timing and style"), packaging_md(b)),
("remake", T("复刻方案", "Remake plan"), T("生成单元、拍摄场次、代码合成、要准备的真实素材、表演与情绪", "generation units, shoots, code builds, real material to collect, acting and emotion"), _remake_md(b)),
]
KEY_ROLE_WORDS = {"first": ("首帧", "first"), "last": ("尾帧", "last"), "move_start": ("动作开始", "move starts"),
"move_end": ("动作到位", "move ends"), "extreme": ("转折 / 极值", "turn / extreme"), "enter": ("元素出现", "element in"),
"exit": ("元素离开", "element out"), "framing": ("构图变化", "framing change"), "expression": ("表情峰值", "expression peak"),
"transition_mid": ("转场中段", "mid-transition"), "light": ("颜色光线突变", "colour / light change"),
"beat": ("卡点", "on the beat"), "missed": ("补的关键帧", "added key frame"), "change": ("画面变化", "change")}
def _curve(vals: list[float], every: float, per: float = 0.5) -> str:
"""The change curve as one digit (0-9) per `per` seconds: the rhythm at a glance, a few tokens per second."""
k = max(1, int(round(per / every)))
return "".join(str(min(9, int(max(vals[i:i + k]) * 10))) for i in range(0, len(vals), k))
def rhythm_md(b: dict) -> list[str]:
"""Cuts, transitions, shot lengths, the change curve and every shot's key frames, with times."""
rh, sv = b.get("rhythm") or {}, b.get("survey") or {}
if not rh and not any(r.get("keyframes") for r in b.get("shots", [])):
return []
out = [T("# 节奏与关键帧", "# Rhythm and key frames"), ""]
fps = float((b.get("source") or {}).get("fps") or 0)
if fps:
out += [T("帧率 {f:g}fps。时间后面的 @数字 是原片帧号(从 0 起):复刻时按帧号对齐切点和关键帧,秒数四舍五入会差一帧。",
"{f:g} fps. The @number after a time is the original's frame number (from 0): line cuts and key frames up by "
"frame number, rounded seconds can be a frame off.", f=fps), ""]
def at(t: float, frame=None) -> str:
f = frame if frame is not None else (int(round(t * fps)) if fps else None)
return f"{t:.3f}s" + (f" @{f}" if f is not None else "")
if rh:
out += [T("每分钟 {n} 刀,平均镜头 {m}s;镜头长度:{l}", "{n} cuts a minute, mean shot {m}s; shot lengths: {l}",
n=rh.get("cuts_per_min"), m=rh.get("mean_shot_s"), l=" ".join(f"{x:.1f}" for x in rh.get("shot_lengths", []))), ""]
if rh.get("change"):
out += [T("画面变化曲线(每 0.5 秒一位,0 静止 – 9 全变):", "Change curve (one digit per 0.5 s, 0 still – 9 all new):"),
"", f"`{_curve(rh['change'], float(rh.get('change_step_s') or 0.25))}`", ""]
if sv.get("cuts"):
out += [T("## 切点和转场", "## Cuts and transitions"), ""]
names = sv.get("scenes") or [] # what each stretch shows, as the closer looks named it
last = [""]
def named(t0: float, t1: float) -> str:
got = [n["name"] for n in names if t0 - 0.05 <= n["t"] < t1 - 0.05 and n["name"] != last[0]]
if not got:
return ""
last[0] = got[-1]
return f" → {got[-1]}"
ends = [c["t"] for c in sv["cuts"]] + [1e9]
if (first := named(0.0, ends[0])):
out.append(f"- {at(0.0, 0)}{first}")
for k, c in enumerate(sv["cuts"]):
span = c.get("span") or [c["t"], c["t"]]
dur = f" {span[1] - span[0]:.2f}s" if span[1] > span[0] and c.get("kind", "cut") not in ("cut", "jump") else ""
dur = f" {span[1] - span[0]:.2f}s ({at(span[0])} – {at(span[1])})" if dur else ""
out.append(f"- {at(c['t'], c.get('frame'))} {c.get('kind', 'cut')}{dur}" + (T("(待确认)", " (to confirm)") if c.get("unsure") else "")
+ named(span[0], ends[k + 1]))
out.append("")
rows = [(r["index"], r["keyframes"]) for r in b.get("shots", []) if r.get("keyframes")]
if rows:
out += [T("## 每镜关键帧", "## Key frames per shot"), ""]
for i, kf in rows:
out.append(f"- #{i}: " + ", ".join(f"{at(k['t'], k.get('frame'))} {T(*KEY_ROLE_WORDS.get(k.get('role', ''), (k.get('role', ''), k.get('role', ''))))}" for k in kf))
return out
def _has_body(text: str) -> bool:
return sum(1 for ln in text.splitlines() if ln.strip() and not ln.startswith("#")) >= 1
# ------------------------------------------------------------------ entry (L0 + L1) -----------------------------------
def _card(b: dict, *, scenes: int = 0, transcript: str | None = None) -> dict:
s, src = b["summary"], b["source"]
from . import __version__
readers = ["tools"] + (["model"] if b["analysis"]["vlm"].get("used") else []) + (["agent"] if (b["analysis"].get("review") or {}).get("shots") else [])
if any(r["base"]["decided_by"] == "user" for r in b["shots"]):
readers.append("human")
source = {"file": src["filename"]}
digest = _sha256(src.get("path"))
if digest:
source["sha256"] = digest
source.update({"duration": src["duration"], "size": f"{src['width']}x{src['height']}", "fps": src["fps"], "aspect": src["aspect_ratio"]})
return {
FORMAT: VERSION, "name": slug(Path(src["filename"]).stem), "description": _description(b),
"source": source, "shots": len(b["shots"]), **({"scenes": scenes} if scenes else {}),
**({"tracks": {"transcript": transcript}} if transcript else {}), "lang": b.get("lang", "zh"),
"made_mix": {m["label"]: m["ratio"] for m in s["production_mix"]}, "confidence": s["confidence"],
"readers": readers, "open_questions": len(entities.open_questions(b)),
"generator": {"name": "rea-video", "version": __version__},
}
def slug(stem: str) -> str:
"""A card name: lowercase letters, digits and single hyphens, at most 64 characters."""
s = re.sub(r"[^a-z0-9]+", "-", stem.lower()).strip("-")[:64].strip("-")
return s or "video"
def _description(b: dict) -> str:
"""What the video is about first, then how it was made: an agent picks a package by this line."""
about = _about(b)
made = join(f"{m['label_zh']} {m['ratio']:.0%}" for m in b["summary"]["production_mix"])
made = T("制作方式(推断):{m}", "Made with (inferred): {m}", m=made)
return _one_line(f"{about} {made}" if about else made, 1000)
def _about(b: dict) -> str:
"""What the video shows or says, from the best source this run has: the whole-video read, the story beats, what
the shots show, the opening lines, the file's title. Empty only when none of them says anything."""
whole = _one_line((b.get("review_story") or {}).get("summary") or (b.get("whole_video_vlm") or {}).get("summary"), 600)
if whole:
return whole
points = list(dict.fromkeys(p for st in narrative.beats(b) for p in st.get("points") or [] if p))[:3]
if points:
return _one_line(T(";", "; ").join(points), 600)
seen = [d for d in (shot_description(r) for r in b.get("shots", [])) if d][:2]
if seen:
return _one_line(T(";", "; ").join(seen), 400)
said = [str(ln.get("text") or "").strip() for ln in ((b.get("speech") or {}).get("lines") or [])[:3]]
said = [x for x in said if x]
if said:
return T("开场台词:「{x}」。", "Opens with: “{x}”.", x=_one_line(" ".join(said), 160))
title = re.sub(r"[_\-\s]*\d{6,}[_\-\s\d]*", " ", Path(str((b.get("source") or {}).get("filename") or "")).stem).strip(" _-")
return T("《{t}》。", "“{t}”.", t=_one_line(title, 80)) if re.search(r"[^\W\d_]", title) else ""
LONG_VIDEO_S = 120.0 # past this, a reader wants the parts of the video before its timeline
def _scenes(b: dict) -> list[dict]:
"""The story beats as the spec's scenes, for a long video. Nothing unless they cover every shot once, in order."""
shots = b.get("shots") or []
if float((b.get("source") or {}).get("duration") or 0) < LONG_VIDEO_S or len(shots) < 2:
return []
steps = narrative.beats(b)
if len(steps) < 2 or [i for st in steps for i in st["shots"]] != [r["index"] for r in shots]:
return []
by = {r["index"]: r for r in shots}
return [{"n": n, "first": st["shots"][0], "last": st["shots"][-1], "shots": st["shots"],
"start": by[st["shots"][0]]["start"], "end": by[st["shots"][-1]]["end"],
"story": _one_line(join(x for x in (st.get("role_zh"), (st.get("points") or [""])[0]) if x), 60)}
for n, st in enumerate(steps, 1)]
def _scenes_md(scenes: list[dict]) -> str:
lines = [f"#S{s['n']:02d} {s['start']:.3f}-{s['end']:.3f} | shots {s['first']}-{s['last']}" + (f" | story {s['story']}" if s["story"] else "")
for s in scenes]
body = "\n".join([T("# 场景", "# Scenes"), "", T("长视频先读这里,再打开对应镜头。", "For a long video, read this first, then open the shots you need."),
"", "```videomd-scenes", *lines, "```"])
return _sized({FORMAT: VERSION, "part": "scenes", "scenes": len(scenes)}, body)
def _vtt_time(t: float) -> str:
ms = int(round(max(0.0, float(t)) * 1000))
h, ms = divmod(ms, 3_600_000)
m, ms = divmod(ms, 60_000)
s, ms = divmod(ms, 1000)
return f"{h:02d}:{m:02d}:{s:02d}.{ms:03d}"
def _transcript(b: dict) -> str:
"""Who says what, when, as WebVTT. Empty when no speech was recognised."""
out = ["WEBVTT", ""]
for ln in (b.get("speech") or {}).get("lines") or []:
text = html.escape(_one_line(ln.get("text"), 500), quote=False) if isinstance(ln, dict) else ""
if not text or ln.get("start") is None or ln.get("end") is None or float(ln["end"]) <= float(ln["start"]):
continue
who = re.sub(r"[<>&\n]", "", str(ln.get("speaker") or "")).strip()
out += [f"{_vtt_time(ln['start'])} --> {_vtt_time(ln['end'])}", f"<v {who}>{text}" if who else text, ""]
return "\n".join(out) if len(out) > 2 else ""
def _sha256(path) -> str | None:
"""sha256 of the whole source file, when it is still where the breakdown found it."""
import hashlib
if not path or not Path(path).is_file():
return None
h = hashlib.sha256()
with open(path, "rb") as fh:
for chunk in iter(lambda: fh.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def _next_steps(b: dict) -> list[str]:
"""The commands to run next for this video, so a reader of this page alone takes the right route."""
labels = {sh["base"]["label"] for sh in b["shots"]}
L = []
if not (b.get("analysis") or {}).get("review") and not ((b.get("analysis") or {}).get("vlm") or {}).get("used"):
L.append(T("没开 VLM:能看图就先复核,`rea-video review <本目录>` → 填 `review_answers.json` → `rea-video apply-review <本目录>`",
"No VLM ran: if you can see images, review first: `rea-video review <this dir>` → fill `review_answers.json` → `rea-video apply-review <this dir>`"))
L.append(T("复刻:生成、拼接和验收由 Capsule Cinema 负责。`rea-video remake <本目录>` 会交给它,能自动做的先做掉,其余原片占位;`remake/status.md` 逐镜写了还要做什么。拿到新镜头写进 `remake/mine.json` 再跑一次",
"Remake: Capsule Cinema does the generation, assembly and checks. `rea-video remake <this dir>` hands over to it, does what can be done automatically and keeps the original elsewhere; `remake/status.md` "
"says per shot what is left. Add incoming clips to `remake/mine.json` and run it again"))
if "code_render" in labels:
L.append(T("代码渲染镜头建议让编程能力强的模型(如 Claude Opus 5.5 及以上、Gemini 4 系列)按 `video/rhythm.md` 的节奏和关键帧写代码重做,可以参考 HyperFrames、Remotion;"
"`rea-video code-remake <本目录>` 只出粒子 / 数据可视化这类画面的快速草稿",
"Code-rendered shots are best rebuilt in code by a strong coding model (such as Claude Opus 5.5 or later, or the Gemini 4 series), optionally on HyperFrames or Remotion, from the rhythm and key frames in "
"`video/rhythm.md`; `rea-video code-remake <this dir>` only makes a quick draft for particles / data-visualisation pictures"))
mo = b.get("moments") or {}
if mo.get("status") == "pending" and mo.get("genre") in ("magic", "drama"): # other videos: only when the user asks
L.append(T("特殊时刻(魔术揭秘、反转、高潮、穿帮)还没找:`rea-video moments <本目录>`,按输出看图作答" +
(";这是魔术视频,建议做" if mo.get("genre") == "magic" else ""),
"Special moments (reveals, twists, climaxes, goofs) not looked for yet: `rea-video moments <this dir>`, answer from the images" +
("; a magic video: worth doing" if mo.get("genre") == "magic" else "")))
if (b.get("production_plan") or {}).get("drive"):
L.append(T("舞蹈 / 动作镜头不走首尾帧生成:`rea-video drive <本目录>` 出去掉字幕、按停顿切好的驱动视频,生成好的段用 `--join` 拼回;路线和提示词在 `video/remake.md` 的「动作驱动」",
"Dance / action shots are not generated from first / last frames: `rea-video drive <this dir>` writes caption-free drive clips cut at calm moments, "
"and `--join` puts the generated segments back; routes and prompts under “Motion drive” in `video/remake.md`"))
if labels & {"ai_video", "cg_3d", "anim_2d", "stop_motion", "avatar"}:
L.append(T("AI 类镜头:提示词在 `video/remake.md` 的「生成单元」;要自动生成用 Capsule Cinema:`scripts/remake_reference.py prepare <本目录>`,再 `run <jobs.json> --dry-run`,会计费,先问用户",
"AI shots: prompts are in the generation units of `video/remake.md`; for automatic generation use Capsule Cinema: `scripts/remake_reference.py prepare <this dir>`, then `run <jobs.json> --dry-run` (paid: ask the user first)"))
return L
def _overview(b: dict, files: list[tuple[str, str, str, int]]) -> str:
s = b["summary"]
w = b.get("whole_video_vlm") or {}
story_sum = (b.get("review_story") or {}).get("summary") or w.get("summary")
L = [f"# {b['source']['filename']}", "", T("**结论**(推断):{v}", "**Verdict** (inferred): {v}", v=s["verdict"])]
if story_sum:
L.append(T("**讲什么**:{s}", "**What it says**: {s}", s=_one_line(story_sum, 200)))
steps = narrative.beats(b)
if steps:
L.append(T("**叙事线**:", "**Narrative**: ") + " → ".join(
f"#{st['shots'][0]:02d}" + (f"-{st['shots'][-1]:02d}" if len(st["shots"]) > 1 else "") + f" {st['role_zh'] or _one_line((st['points'] or ['?'])[0], 16)}"
for st in steps))
L.append(T("**制作方式**(推断,按时长):", "**Made with** (inferred, by duration): ") + join(f"{m['label_zh']} {m['ratio']:.0%}" for m in s["production_mix"]))
if s.get("production"):
L.append(T("**复刻**:{p}", "**Remake**: {p}", p=s["production"]))
rm = s.get("real_material") or {}
if rm.get("shots"):
L.append(T("**要拿到的真实素材**:{n} 个镜头({r:.0%} 时长),清单见 `{d}/remake.md`", "**Real material to collect**: {n} shots ({r:.0%} of the duration), list in `{d}/remake.md`", d=DIR,
n=len(rm["shots"]), r=rm["ratio"]))
L += ["", T("## 下一步", "## Next steps"), ""] + [f"- {x}" for x in _next_steps(b)]
qs = entities.open_questions(b)
L += ["", T("## 不确定点", "## Open questions"), ""] + ([f"- {_one_line(q, 160)}" for q in qs[:8]] or [T("- 没有", "- None")])
if len(qs) > 8:
L.append(T("- 另有 {n} 处,见 `{d}/timeline.md` 里带 `flag` 的行", "- {n} more, see the `flag` lines in `{d}/timeline.md`", d=DIR, n=len(qs) - 8))
L += ["", T("## 地图", "## Map"), "",
T("先读本页;要细节时只打开需要的文件。每行是 `路径 | 约 token | 里面有什么 · 什么时候读`,路径相对本目录。",
"Read this page first; for detail, open only the file you need. Each line is `path | ~tokens | what is in it · when to read it`; paths are relative to this directory."), "",
f"```{MAP_BLOCK}"]
L += [f"{p} | {n if n else '-'} | {_one_line(title)} · {_one_line(when)}" for p, title, when, n in files] + ["```"]
L += ["", T("## 读法", "## How to read"), ""] + [f"- {x}" for x in _legend()] + [
T("- 「看到的」可以对着截图核实;「推断」是工具和看图模型的判断,依据写在每镜文件的「判断依据」里,两者对不上时以截图为准。",
"- What is “seen” can be checked against the frames; what is “inferred” is the tools' and image readers' judgement, with the basis in each shot file. When they disagree, trust the frames.")]
return "\n".join(L)
# ------------------------------------------------------------------ write -------------------------------------------
def write(b: dict, out: Path) -> Path:
"""Write the package into `out` (the breakdown's output directory). Returns the entry file."""
from .report import _unit_of
d = out / DIR
if d.is_dir():
shutil.rmtree(d, ignore_errors=True) # generated: a re-run with a different shot count must not leave stale shot files
for old in list(d.rglob("*")) if d.is_dir() else []:
if old.is_file():
old.unlink(missing_ok=True)
(d / "shots").mkdir(parents=True, exist_ok=True)
files: list[tuple[str, str, str, int]] = []
def put(rel: str, text: str, title: str, when: str) -> None:
(out / rel).write_text(text, encoding="utf-8")
files.append((rel, title, when, tokens(text)))
roles, units = narrative.shot_roles(b), _unit_of(b)
lines = [timeline_line(r, roles, units) for r in b["shots"]]
body = "\n".join([T("# 时间线", "# Timeline"), ""] + _legend() + ["", f"```{BLOCK}"] + lines + ["```"])
put(f"{DIR}/timeline.md", _sized({FORMAT: VERSION, "part": "timeline", "shots": len(lines)}, body),
T("时间线:一行一个镜头", "Timeline: one line per shot"), T("想知道某段讲什么、哪镜要复核、某镜怎么做", "what a stretch says, which shots need review, how a shot was made"))
scenes = _scenes(b)
if scenes:
put(f"{DIR}/scenes.md", _scenes_md(scenes), T("场景:长视频的分段", "Scenes: the parts of a long video"),
T("长视频先读这里,再打开对应镜头", "read first for a long video, then open the shots you need"))
for stem, title, when, section in _topics(b):
text = _plain(section)
if _has_body(text):
put(f"{DIR}/{stem}.md", _sized({FORMAT: VERSION, "part": stem}, text), title, when)
transcript_rel = None
transcript = _transcript(b)
if transcript:
transcript_rel = f"{DIR}/transcript.vtt"
put(transcript_rel, transcript, T("台词轨:谁在什么时候说了什么", "Transcript: who says what, when"),
T("引用台词、做字幕和配音", "quoting speech, subtitles and voice-over"))
scene_of = {i: s["n"] for s in scenes for i in s["shots"]}
stickers = (b.get("packaging") or {}).get("stickers") or []
shot_tokens = 0
for r in b["shots"]:
text = _shot_file(r, scene=scene_of.get(r["index"]), stickers=stickers)
(d / "shots" / f"{_shot_name(r['index'])}.md").write_text(text, encoding="utf-8")
shot_tokens += tokens(text)
files.append((f"{DIR}/shots/*.md", T("逐镜细节,token 是每个文件的平均值", "Per-shot detail, tokens per file on average"),
T("核实某一镜:看得到的、推断和依据、提示词、帧图", "checking one shot: what is seen, the inference and its basis, prompts, frames"),
shot_tokens // max(1, len(b["shots"]))))
if (out / "breakdown.json").is_file():
files.append(("breakdown.json", T("完整原始数据", "Full raw data"), T("程序读取;模型一般不用打开", "for programs; a model rarely needs it"),
tokens((out / "breakdown.json").read_text(encoding="utf-8"))))
for rel, what, when in (
("shots/", T("每镜的联系表和首尾帧", "contact sheet, first and last frame of each shot"), T("看图核实", "checking by eye")),
("storyboard.jpg", T("全片故事板", "storyboard of the whole video"), T("一眼看全片", "the whole video at a glance")),
("stems/", T("人声、配乐、音效分轨", "voice, music and effects stems"), T("听声音、复刻配音配乐", "listening, remaking the sound")),
("sfx/", T("每处音效的试听片段", "a clip of each sound effect"), T("找同款音效", "finding matching effects")),
("packaging/", T("字幕文件、包装时间轴、贴纸截图", "subtitle files, packaging timeline, sticker frames"), T("复刻字幕和包装", "remaking subtitles and packaging")),
("moments/", T("特殊时刻的关键帧、揭秘图和慢放短片", "key frames, step diagrams and slow-motion clips of special moments"), T("看魔术揭秘和关键瞬间", "checking reveals and key moments")),
("frames/", T("画面场景:每场景原尺寸帧、画上去那一层的抠图和采样点、测量值", "picture scenes: full-size frames, the drawn layer cut out and sampled, measurements"),
T("复刻代码渲染画面", "remaking rendered pictures")),
("audio.png", T("声音波形和节拍图", "waveform and beat chart"), T("看节奏", "seeing the rhythm"))):
if rel == "packaging/" and not any(f[0] == f"{DIR}/packaging.md" for f in files):
continue
if (out / rel.rstrip("/")).exists():
files.append((rel, what, when, 0))
entry = out / ENTRY
card = _card(b, scenes=len(scenes), transcript=transcript_rel)
entry.write_text(_front(card, _overview(b, files)), encoding="utf-8")
import subprocess
import sys
if sys.platform == "darwin" and shutil.which("dot_clean"):
subprocess.run(["dot_clean", "-m", str(d), str(out)], capture_output=True, check=False)
return entry
# ------------------------------------------------------------------ read and check: the videomd reference library --
def read(root: Path) -> dict:
"""The package as data: {"card", "map", "timeline": [shot dicts], "shots": {n: front matter}}."""
import videomd
return videomd.read(root)
def check(root: Path) -> list[str]:
"""Problems that make `root` a non-conforming package (empty list = conforms), per the VIDEO.md spec."""
import videomd
return videomd.check(root)