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
report: 按人读顺序重排,角色 / 场景 / 脚本 / 声音各成一张卡,细节折叠
junea4323e62b6d6
diff --git a/docs/decompose.md b/docs/decompose.mdindex 7071a9e..baf50e0 100644--- a/docs/decompose.md+++ b/docs/decompose.md@@ -78,7 +78,9 @@```out/<name>/breakdown.json Video IR(rea_video.breakdown.v1):每镜特征、证据、概率、叠加层、复刻计划- report.html/md 人读报告+ report.html/md 人读报告(同一份内容,HTML 由 Markdown 渲染):结论 → 内容与结构(概括、钩子、结构时间轴、脚本)→ 角色、场景与道具 →+ 声音(人声 / 背景音乐 / 音效 / 环境声各一张卡)→ 拍法、打光与剪辑 → 剪辑包装层 → 复刻方案(含真实素材和参考素材清单)→+ 分镜表 → 不确定点 → 附录(逐镜取证折叠、元数据)。角色、场景、道具和脚本来自 VLM 整片分析或 agent 看图(review_answers.json 顶层 cast)storyboard.jpg 分镜总览(按制作方式着色)shots/ 每镜联系表、首帧、尾帧(首尾帧也是复刻输入)clips/, vlm_cache/ VLM 输入片段和缓存(仅 --vlm)diff --git a/rea_video/aspects/__init__.py b/rea_video/aspects/__init__.pyindex da7f670..8a0beb8 100644--- a/rea_video/aspects/__init__.py+++ b/rea_video/aspects/__init__.py@@ -152,13 +152,14 @@ def shot_text(r: dict) -> str:# ---------------------------------------------------------------- report -----------------------------------------def _src(row: dict) -> str:+ """Who said what. A source that agrees with the verdict is named only; one that differs shows its own value."""+ final = str(row.get("final", "")).strip()bits = []- if row.get("measured") not in (None, ""):- bits.append(T("测量:{v}", "measured: {v}", v=row["measured"]))- if row.get("vlm"):- bits.append(T("VLM:{v}", "VLM: {v}", v=row["vlm"]))- if row.get("agent"):- bits.append(T("看图:{v}", "agent review: {v}", v=row["agent"]))+ for key, name in (("measured", T("测量", "measured")), ("vlm", "VLM"), ("agent", T("看图", "agent review"))):+ v = row.get(key)+ if v in (None, ""):+ continue+ bits.append(name if str(v).strip() == final else f"{name}{T(':', ': ')}{v}")return semi().join(bits)@@ -178,9 +179,11 @@ def report_md(b: dict) -> list[str]:L += [T("- 注意:{n}", "- Note: {n}", n=n) for n in li["setup"]["notes"]]rows = [(a, r) for a in REGISTRY for r in (A.get(a.key) or {}).get("fields", [])]if rows:- L += ["", T("| 维度 | 项目 | 结论 | 来源 |", "| Aspect | Item | Verdict | Sources |"), "|---|---|---|---|"]+ L += ["", f"<details><summary>{html.escape(T('逐项测量与看图结果({n} 项)', 'Per-item measurements and image readings ({n})', n=len(rows)))}</summary>", "",+ T("| 维度 | 项目 | 结论 | 来源 |", "| Aspect | Item | Verdict | Sources |"), "|---|---|---|---|"]for a, r in rows:L.append(f"| {a.title} | {r['zh']} | {str(r['final']).replace('|', '/')} | {_src(r).replace('|', '/')} |")+ L += ["", "</details>"]L += ["", T("- 说明:光比、软硬、色温、景别由主体像素测得(有人脸用人脸,没有用画面清晰区域,后者是估算);平台转码会压暗部,软硬和补光偏保守;""机位角度、光源种类、眼神光、轮廓光以看图结果为准。测量和看图不一致时两者都列出。","- Note: lighting ratio, soft / hard, colour temperature and shot size are measured on the subject's pixels (the face when there is one, "diff --git a/rea_video/audio.py b/rea_video/audio.pyindex f2a2c58..c63f34d 100644--- a/rea_video/audio.py+++ b/rea_video/audio.py@@ -441,8 +441,8 @@ def merge_audio_with_vlm(audio: dict, whole: dict | None) -> dict:plan.append({"track": "voice", "rule": "A01-narration" if n.get("type") != "human" else "A01-narration","what": (T("TTS 旁白", "TTS voice-over") if n.get('type') == 'tts' else (T("真人口播/对白", "human talking head / dialogue") if n.get('type') == 'human' else T("人声", "voice"))+ f"{T(',', ', ')}{n.get('voice') or voice.get('gender_hint') or ''}{T(',', ', ')}{n.get('style') or ''}").strip(T(",", ", ")),- "how": T("capsule-cinema DoubaoTTSTool / UniversalTTSTool(或 MiniMax 克隆音色);需要卡原时间窗时用时长可控 TTS(A02)",- "capsule-cinema DoubaoTTSTool / UniversalTTSTool (or a MiniMax cloned voice); use duration-controlled TTS (A02) when it must fit the original time window"),+ "how": T("capsule-cinema DoubaoTTSTool / UniversalTTSTool(或 MiniMax 克隆音色);需要卡原时间窗时用时长可控 TTS",+ "capsule-cinema DoubaoTTSTool / UniversalTTSTool (or a MiniMax cloned voice); use duration-controlled TTS when it must fit the original time window"),"segments": voice.get("segments", [])[:40], "lines": n.get("lines", [])[:60],"real_material": n.get("type") == "human"})if music.get("present") or m.get("present"):diff --git a/rea_video/cli.py b/rea_video/cli.pyindex d7e7cf0..12cfff1 100644--- a/rea_video/cli.py+++ b/rea_video/cli.py@@ -266,6 +266,15 @@ def cmd_summary(args) -> int:+ (f" | {shot_text(r)}" if r["base"]["label"] in ("live_action", "avatar") and shot_text(r) else ""))if s.get("aspects"):lines += [""] + s["aspects"]+ from .entities import cast++ c = cast(b)+ if c["characters"] or c["scenes"]:+ lines.append("")+ for ch in c["characters"]:+ lines.append(f"{T('角色', 'Character')} {ch['id']} {ch['name']} | {ch['look']} | {T('镜头', 'shots')} {','.join(str(i) for i in ch['shots']) or '-'}")+ for sc in c["scenes"]:+ lines.append(f"{T('场景', 'Scene')} {sc['id']} {sc['where']} {sc['when']} | {sc['look']} | {T('镜头', 'shots')} {','.join(str(i) for i in sc['shots']) or '-'}")a = b.get("audio", {})if a.get("has_audio"):mu = a.get("music", {})diff --git a/rea_video/entities.py b/rea_video/entities.pynew file mode 100644index 0000000..b73ddfb--- /dev/null+++ b/rea_video/entities.py@@ -0,0 +1,144 @@+"""Cross-shot entities for the human report: who is in the video (characters), where it happens (scenes),+what appears in it (props), the script (who says what, when) and the open questions the reader should check.++The VLM whole-video pass and the agent review both answer the same `cast` shape; the review wins when present.+Everything here is tolerant of missing data: with no VLM and no review the report still gets a props list from+the per-shot references and a "no cast available" note instead of an empty section.+"""+from __future__ import annotations++from .i18n import LangDict, T, join, semi++KIND_ZH = LangDict({"person": "真人", "animal": "动物", "cartoon": "卡通形象", "avatar": "数字人", "product": "商品", "other": "其他"},+ en={"person": "person", "animal": "animal", "cartoon": "cartoon character", "avatar": "digital avatar", "product": "product", "other": "other"})+_KINDS = tuple(KIND_ZH)+_MAX = 12+++def _shots(v) -> list[int]:+ out: list[int] = []+ for x in v if isinstance(v, list) else []:+ try:+ i = int(x)+ except (TypeError, ValueError):+ continue+ if i > 0 and i not in out:+ out.append(i)+ return out+++def _s(d: dict, k: str, n: int = 200) -> str:+ v = d.get(k)+ return str(v).strip()[:n] if isinstance(v, (str, int, float)) and str(v).strip() else ""+++def clean_cast(raw) -> dict:+ """Validate a `cast` answer (VLM or agent). Returns {} when nothing usable is in it."""+ if not isinstance(raw, dict):+ return {}+ chars, scenes, props = [], [], []+ for i, c in enumerate(raw.get("characters") or []):+ if not isinstance(c, dict) or not (_s(c, "name") or _s(c, "look")):+ continue+ kind = c.get("kind") if c.get("kind") in _KINDS else "other"+ chars.append({"id": _s(c, "id", 8) or chr(ord("A") + len(chars)), "name": _s(c, "name", 40), "kind": kind,+ "look": _s(c, "look", 300), "role": _s(c, "role", 80), "voice": _s(c, "voice", 80), "shots": _shots(c.get("shots"))})+ for sc in raw.get("scenes") or []:+ if not isinstance(sc, dict) or not (_s(sc, "where") or _s(sc, "look")):+ continue+ scenes.append({"id": _s(sc, "id", 8) or f"S{len(scenes) + 1}", "where": _s(sc, "where", 80), "when": _s(sc, "when", 40),+ "look": _s(sc, "look", 200), "shots": _shots(sc.get("shots"))})+ for p in raw.get("props") or []:+ if not isinstance(p, dict) or not _s(p, "name"):+ continue+ props.append({"name": _s(p, "name", 60), "note": _s(p, "note", 160), "shots": _shots(p.get("shots"))})+ out = {"characters": chars[:_MAX], "scenes": scenes[:_MAX], "props": props[:_MAX * 2], "style": _s(raw, "style", 200)}+ return out if (chars or scenes or props or out["style"]) else {}+++def _props_from_shots(b: dict) -> list[dict]:+ """Fallback props: the per-shot `material.references` (things seen in AI / 3D shots that the remake needs as reference)."""+ seen: dict[str, dict] = {}+ for r in b.get("shots", []):+ for a in (r.get("material") or {}).get("references", []):+ key = (a.get("kind_zh") or a.get("kind") or "") + "|" + (a.get("description") or "")[:40]+ p = seen.setdefault(key, {"name": a.get("kind_zh") or a.get("kind") or "", "note": a.get("description") or "", "shots": []})+ if r["index"] not in p["shots"]:+ p["shots"].append(r["index"])+ return list(seen.values())+++def cast(b: dict) -> dict:+ """Merged cast for the report: review > VLM whole-video answer; props fall back to per-shot references.+ Adds `source` ("review" | "vlm" | None) and `face_shots` (shots where a face detector saw people)."""+ rv = b.get("review_cast") or {}+ vl = clean_cast(b.get("whole_video_vlm") or {})+ out = {"characters": rv.get("characters") or vl.get("characters") or [],+ "scenes": rv.get("scenes") or vl.get("scenes") or [],+ "props": rv.get("props") or vl.get("props") or [],+ "style": rv.get("style") or vl.get("style") or "",+ "source": "review" if rv else ("vlm" if vl else None)}+ if not out["props"]:+ out["props"] = _props_from_shots(b)+ if not out["style"]:+ styles = []+ for r in b.get("shots", []):+ st = ((r.get("vlm") or {}).get("style") or "").strip()+ if st and st not in styles:+ styles.append(st)+ out["style"] = semi().join(styles[:2])+ out["face_shots"] = [r["index"] for r in b.get("shots", []) if isinstance(r.get("faces"), (int, float)) and r["faces"] >= 0.3]+ return out+++def script(b: dict) -> list[dict]:+ """Lines of dialogue / narration with time and speaker, from the whole-video VLM; falls back to segment copy."""+ w = b.get("whole_video_vlm") or {}+ rows = []+ for ln in ((w.get("narration") or {}).get("lines") or []):+ if isinstance(ln, dict) and _s(ln, "text"):+ rows.append({"start": ln.get("start"), "end": ln.get("end"), "speaker": _s(ln, "speaker", 20), "text": _s(ln, "text", 200)})+ if rows:+ return rows+ for seg in w.get("segments") or []:+ if isinstance(seg, dict) and _s(seg, "copy"):+ rows.append({"start": seg.get("start"), "end": seg.get("end"), "speaker": "", "text": _s(seg, "copy", 200)})+ return rows+++def open_questions(b: dict) -> list[str]:+ """What a reader should verify by eye / ear, collected from every part of the breakdown. Ordered: picture, material, audio, packaging."""+ q: list[str] = []+ s = b.get("summary") or {}+ if s.get("vlm") and any(k in str(s["vlm"]) for k in ("失败", "未配置", "未开", "failed", "not configured", "off")):+ q.append(T("VLM 没有生效({v}):实拍 / AI / 3D 的区分只靠信号取证,建议配置多模态模型后加 --vlm 重跑,或由 agent 看图复核",+ "The VLM did not run ({v}): live action / AI / 3D is decided by signal forensics alone; configure a multimodal model and rerun with --vlm, or have an agent review the frames", v=s["vlm"]))+ for r in b.get("shots", []):+ base = r.get("base") or {}+ tag = T("镜头 #{i}({a:.1f}–{z:.1f}s)", "Shot #{i} ({a:.1f}–{z:.1f}s)", i=r["index"], a=r["start"], z=r["end"])+ if base.get("disputed"):+ q.append(f"{tag}{T(':', ': ')}{base['disputed']}")+ elif base.get("uncertain"):+ q.append(f"{tag}{T(':', ': ')}{base['uncertain']}")+ elif base.get("confidence", 1) < 0.6:+ alt = sorted((base.get("probs") or {}).items(), key=lambda kv: -kv[1])[:2]+ q.append(tag + T(":{l} 只有 {c:.0%} 置信", ": {l} at only {c:.0%} confidence", l=base.get("label_zh", ""), c=base["confidence"])+ + (T(",次选 {a}", ", runner-up {a}", a=alt[1][0]) if len(alt) > 1 else ""))+ unsure = sorted({it.get("kind_zh", "") for it in (r.get("material") or {}).get("items", []) if it.get("real_material") is None})+ if unsure:+ q.append(tag + T(":{k} 是真实素材还是生成的,待确认", ": {k}: real material or generated, to confirm", k=join(unsure)))+ src = b.get("sound_sources") or {}+ for k, name in (("music", T("背景音乐", "music")), ("voice", T("人声", "voice"))):+ v = src.get(k) or {}+ top = max((v.get("probs") or {"x": 1.0}).values())+ if v and (v.get("source") == "unknown" or top < 0.6):+ q.append(T("{n}来源待确认:倾向{s}({p:.0%})", "{n} source to confirm: leaning {s} ({p:.0%})", n=name, s=v.get("source_zh", ""), p=top)+ + (T("。{h}", ". {h}", h=v["how_to_confirm"][0]) if v.get("how_to_confirm") else ""))+ pack = b.get("packaging") or {}+ low = [st for st in pack.get("stickers", []) if not st.get("in_picture") and st.get("confidence") in ("low", "vlm")]+ if low:+ q.append(T("贴纸 / 动图 {n} 处需要看图确认是不是后期贴的(截图在 packaging/):{ids}",+ "{n} stickers / GIFs need a look to confirm they were added in post (crops under packaging/): {ids}",+ n=len(low), ids=join(f"{st['id']} {st['t0']:.1f}s" for st in low[:6])))+ seen: set[str] = set()+ return [x for x in q if not (x in seen or seen.add(x))]diff --git a/rea_video/production.py b/rea_video/production.pyindex c59e9f1..8ccce01 100644--- a/rea_video/production.py+++ b/rea_video/production.py@@ -195,7 +195,7 @@ def _unit(seg: list[dict], k: int, lim: dict, model: dict | None, style: str, ca": reference for action, camera movement and cutting rhythm (reference only, do not copy the picture)"), "user": False})cont = Noneif prev_unit and same_scene_prev and seg[0].get("transition_in") == "cut" and abs(prev_unit["ranges"][-1][1] - t0) < 1e-3:- cont = T("首帧用 {p} 的尾帧,接上动作(S05)", "first frame = last frame of {p}, continue the action (S05)", p=prev_unit["id"])+ cont = T("首帧用 {p} 的尾帧,接上动作", "first frame = last frame of {p}, continue the action", p=prev_unit["id"])elif lim["first_frame"]:cont = T("首帧:参照原片第 {i} 镜首帧({f})的构图出图", "first frame: generate an image matching the composition of source shot {i}'s first frame ({f})",i=seg[0]["index"], f=seg[0]["assets"]["first_frame"]) + (T(",产品换成 @图片1", ", with the product replaced by @图片1") if product else "")@@ -254,10 +254,10 @@ def _unit(seg: list[dict], k: int, lim: dict, model: dict | None, style: str, ca"lip sync and motion must be frame-accurate (R19)")if label == "cg_3d" or "cg_3d" in votes:unit["alt"] = T("另一条路:3D 工程。让 LLM 写 Blender 脚本或 Three.js 场景,角色/道具建模一次、按镜头设机位渲染,"- "多角度和角色一致性最好,改文案和镜头也只是改代码(R08)",+ "多角度和角色一致性最好,改文案和镜头也只是改代码","Alternative: a 3D project. Have an LLM write a Blender script or a Three.js scene; model the characters / props once and ""render each shot from its own camera. Best for multiple angles and character consistency, and changing copy or shots is "- "just a code change (R08)")+ "just a code change")return unit@@ -418,9 +418,9 @@ def report_md(plan: dict) -> list[str]:L += [f"- {plan['engine_note']}"]if plan["units"]:lim = plan["model_limits"]- L += [T("- 分组规则:同场景、硬切相连的 AI 镜头合并为一次生成(S01);单次 ≤{mx:.0f}s;单元内连续硬切尽量 ≤{p}s、最多 {m}s(S06);在叠化/淡入淡出和换场景处切开(S03)",- "- Grouping: AI shots in the same scene joined by hard cuts are generated in one call (S01); ≤{mx:.0f}s per call; "- "consecutive hard cuts inside a unit preferably ≤{p}s, at most {m}s (S06); split at dissolves / fades and scene changes (S03)",+ L += [T("- 分组规则:同场景、硬切相连的 AI 镜头合并为一次生成;单次 ≤{mx:.0f}s;单元内连续硬切尽量 ≤{p}s、最多 {m}s;在叠化/淡入淡出和换场景处切开",+ "- Grouping: AI shots in the same scene joined by hard cuts are generated in one call; ≤{mx:.0f}s per call; "+ "consecutive hard cuts inside a unit preferably ≤{p}s, at most {m}s; split at dissolves / fades and scene changes",mx=lim["max"], p=plan["rules"]["hardcut_s"]["prefer"], m=plan["rules"]["hardcut_s"]["max"])]if plan.get("audio_note"):L.append(T("- 声音:{a}", "- Audio: {a}", a=plan["audio_note"]))diff --git a/rea_video/report.py b/rea_video/report.pyindex 2ec61e6..b6b6358 100644--- a/rea_video/report.py+++ b/rea_video/report.py@@ -1,15 +1,22 @@-"""Human-readable reports (Markdown + standalone HTML) from a breakdown. Language: see i18n (breakdown["lang"])."""+"""Human-readable reports from a breakdown: report.md, and report.html rendered from the same Markdown.++Reading order is short-first, long-last: verdict and numbers → what the video says (structure, script) → who / where+(cast) → sound → look and camera → packaging → how to remake it → shot list → open questions → appendix (per-shot+forensics, metadata). Machine-oriented detail (per-shot evidence, measurement tables, 100-row text timelines) is folded+into <details> so it is there when needed and out of the way otherwise. Language: see i18n (breakdown["lang"]).+"""from __future__ import annotationsimport html+import refrom pathlib import Path-from . import aspects+from . import aspects, entitiesfrom .classify import LABEL_ZHfrom .i18n import LangDict, T, join, lang, semi+from .production import report_md as production_mdfrom .util import fmt_timefrom .visual import LABEL_COLOR-from .production import report_md as production_mdfrom .vlm import vlm_noteKIND_ZH = LangDict({"subtitle": "字幕", "title": "标题", "label": "文字", "static_graphic": "图形贴片", "layout_template": "版式模板",@@ -27,6 +34,47 @@ ANIM_ZH = LangDict({"cut": "直接出现", "pop": "弹出", "fade": "淡入", "sGENDER_ZH = LangDict({"male": "偏男声", "female": "偏女声"}, en={"male": "male-leaning", "female": "female-leaning"})CONF_ZH = LangDict({"medium": "中", "low": "低", "vlm": "VLM 看到"}, en={"medium": "medium", "low": "low", "vlm": "seen by VLM"})MODE_ZH = LangDict({"music": "背景音乐", "voice": "人声", "sfx": "音效"}, en={"music": "Music", "voice": "Voice", "sfx": "Sound effects"})+# how a shot gets remade, in words (the rule ids stay in breakdown.json for agents)+ROUTE_ZH = LangDict({"ai_video": "AI 生成(首尾帧)", "live_action": "实拍", "avatar": "TTS + 数字人", "cg_3d": "AI 生成 / 3D 渲染",+ "code_render": "代码渲染", "screen_capture": "录屏重建", "still_motion": "本地 ffmpeg 推拉", "static_hold": "静帧",+ "anim_2d": "AI 生成(2D 动画)", "stop_motion": "实拍定格"},+ en={"ai_video": "AI generation (first / last frame)", "live_action": "reshoot", "avatar": "TTS + avatar", "cg_3d": "AI generation / 3D render",+ "code_render": "code render", "screen_capture": "screen recording", "still_motion": "local ffmpeg move", "static_hold": "static frame",+ "anim_2d": "AI generation (2D animation)", "stop_motion": "stop motion shoot"})+SFX_SRC_ZH = LangDict({"vlm": "听到", "deterministic": "信号候选(低置信)", "review": "看图复核", "merged": "听到 + 信号"},+ en={"vlm": "heard", "deterministic": "signal candidate (low confidence)", "review": "agent review", "merged": "heard + signal"})+ENDING_ZH = LangDict({"natural_end": "自然结束", "fade_out": "淡出", "hard_cut": "硬切断"}, en={"natural_end": "ends naturally", "fade_out": "fades out", "hard_cut": "cut off hard"})+NARR_ZH = LangDict({"tts": "TTS 合成", "human": "真人", "none": "无", "mixed": "真人 + TTS"}, en={"tts": "TTS", "human": "human", "none": "none", "mixed": "human + TTS"})++_MIX_MARK = "<!--mix-->"+_STEMS_MARK = "<!--stems-->"+_FOLD_ROWS = 12 # tables longer than this are folded into <details>+++def _colon() -> str:+ return T(":", ": ")+++def _cell(x) -> str:+ return str(x if x not in (None, "") else "—").replace("|", "/").replace("\n", " ")+++def _row(*cells) -> str:+ return "| " + " | ".join(_cell(c) for c in cells) + " |"+++def _table(header: list[str], rows: list[list], fold_title: str | None = None) -> list[str]:+ """A Markdown table; long ones are folded behind a <details> with `fold_title`."""+ if not rows:+ return []+ L = [_row(*header), "|" + "---|" * len(header)] + [_row(*r) for r in rows]+ if fold_title and len(rows) > _FOLD_ROWS:+ return ["", f"<details><summary>{html.escape(fold_title)}</summary>", ""] + L + ["", "</details>"]+ return [""] + L+++def _shots_str(ids) -> str:+ return join(f"#{i}" for i in ids) if ids else "—"def _layers(rec: dict) -> str:@@ -48,8 +96,7 @@ def _origin(rec: dict) -> str:kinds.append(it["kind_zh"])unsure = sorted({it["kind_zh"] for it in m.get("items", []) if it.get("real_material") is None})refs = list(dict.fromkeys(x["kind_zh"] for x in m.get("references", [])))- colon = T(":", ": ")- return (m.get("origin_zh", "—") + (f"{colon}{join(kinds)}" if kinds else "")+ return (m.get("origin_zh", "—") + (f"{_colon()}{join(kinds)}" if kinds else "")+ (semi() + T("待确认是否真实:", "real or not, to confirm: ") + join(unsure) if unsure else "")+ (semi() + T("复刻参考:", "references for the remake: ") + join(refs) if refs else ""))@@ -62,185 +109,260 @@ def _decided_by(b: dict) -> str:return T("仅确定性取证", "deterministic forensics only")-def markdown(b: dict) -> str:- s = b["summary"]- src = b["source"]+def _unit_of(b: dict) -> dict[int, str]:+ """shot index -> generation unit / shooting scene / code project id from the production plan."""+ plan = b.get("production_plan") or {}+ out: dict[int, str] = {}+ for u in plan.get("units", []):+ for i in u["shots"]:+ out[i] = u["id"]+ for s in plan.get("shoot", []):+ for i in s["shots"]:+ out[i] = s["id"]+ for c in plan.get("code", []):+ for i in c["shots"]:+ out[i] = c["id"]+ return out+++def _route(r: dict, units: dict[int, str]) -> str:+ base = ROUTE_ZH.get(r["base"]["label"], r["replication"].get("executor", ""))+ u = units.get(r["index"])+ return f"{base} · {u}" if u else base+++def _t(x) -> str:+ try:+ return f"{float(x):.1f}s"+ except (TypeError, ValueError):+ return "—"+++def _span(a, z) -> str:+ try:+ return f"{float(a):.1f}–{float(z):.1f}s"+ except (TypeError, ValueError):+ return "—"+++# ------------------------------------------------------------------ sections --------------------------------------++def _head_md(b: dict) -> list[str]:+ s, src = b["summary"], b["source"]L = [T("# 视频拆解报告:{f}", "# Video breakdown: {f}", f=src["filename"]), "",T("**结论**:{v}", "**Verdict**: {v}", v=s["verdict"]), "",- T("- 时长 {d}s · {w}×{h} · {fps}fps · {ar}", "- {d}s · {w}×{h} · {fps}fps · {ar}",- d=src["duration"], w=src["width"], h=src["height"], fps=src["fps"], ar=src["aspect_ratio"]),- T("- 镜头 {n} 个,平均 {avg}s;转场:", "- {n} shots, {avg}s average; transitions: ", n=s["shots"], avg=s["avg_shot_s"])+ T("- 时长 {d}s · {w}×{h} · {fps}fps · {ar};镜头 {n} 个,平均 {avg}s;转场:", "- {d}s · {w}×{h} · {fps}fps · {ar}; {n} shots, {avg}s average; transitions: ",+ d=src["duration"], w=src["width"], h=src["height"], fps=src["fps"], ar=src["aspect_ratio"], n=s["shots"], avg=s["avg_shot_s"])+ join(f"{k}×{v}" for k, v in s["transitions"].items()),- T("- 判断置信度(按时长加权):{c:.0%};判定方式:{by}", "- Confidence (duration-weighted): {c:.0%}; decided by: {by}", c=s["confidence"], by=_decided_by(b)),- f"- {s.get('vlm') or vlm_note(b['analysis']['vlm'], b['analysis'].get('review'))}",- "", "", "", T("## 制作方式占比", "## Production mix"), "",- T("| 底层画面 | 时长 | 占比 |", "| Base picture | Duration | Share |"), "|---|---|---|"]- for m in s["production_mix"]:- L.append(f"| {m['label_zh']} | {m['seconds']}s | {m['ratio']:.0%} |")- L += production_md(b.get("production_plan") or {})- L += aspects.report_md(b)- prov = b.get("provenance", {})- if prov.get("hints") or prov.get("encoder"):- L += ["", T("## 元数据线索", "## Metadata clues"), ""]- if prov.get("encoder"):- L.append(T("- 编码器:`{e}`", "- Encoder: `{e}`", e=prov["encoder"]))- for k, v in (prov.get("hints") or {}).items():- L.append(f"- {k}{T(':', ': ')}{', '.join(v)}")+ T("- 判断置信度(按时长加权){c:.0%};判定方式:{by};{vlm}", "- Confidence (duration-weighted) {c:.0%}; decided by: {by}; {vlm}",+ c=s["confidence"], by=_decided_by(b), vlm=s.get("vlm") or vlm_note(b["analysis"]["vlm"], b["analysis"].get("review")))]+ if s.get("production"):+ L.append(T("- 复刻:{p}(方案见「复刻方案」)", "- Remake: {p} (see “Remake plan”)", p=s["production"]))+ qs = entities.open_questions(b)+ if qs:+ L.append(T("- ⚠️ 待确认 {n} 处,先看「不确定点」:{q}", "- ⚠️ {n} open questions, see “Open questions” first: {q}", n=len(qs),+ q=qs[0][:80] + ("…" if len(qs[0]) > 80 else "")))+ L += ["", _MIX_MARK] + _table([T("底层画面", "Base picture"), T("时长", "Duration"), T("占比", "Share")],+ [[m["label_zh"], f"{m['seconds']}s", f"{m['ratio']:.0%}"] for m in s["production_mix"]])+ L += ["", ""]+ return L+++def _content_md(b: dict) -> list[str]:+ w = b.get("whole_video_vlm") or {}+ lines = entities.script(b)+ L = ["", T("## 内容与结构", "## Content and structure"), ""]+ if not w and not lines:+ L.append(T("- 没有整片的内容概括(需要 VLM 或 agent 看完整片);字幕原文见「剪辑包装层」",+ "- No whole-video summary (needs the VLM or an agent watching the full video); subtitle text is under “Packaging layer”"))+ return L+ if w.get("summary"):+ L.append(T("- 概括:{s}", "- Summary: {s}", s=w["summary"]))+ bits = []+ if w.get("format"):+ bits.append(T("形式:{f}", "format: {f}", f=w["format"]))+ if w.get("hook"):+ bits.append(T("钩子:{h}", "hook: {h}", h=w["hook"]))+ if bits:+ L.append("- " + semi().join(bits))+ if w.get("overall_production"):+ L.append(T("- 整体制作:{o}", "- Overall production: {o}", o=w["overall_production"]))+ segs = [sg for sg in (w.get("segments") or []) if isinstance(sg, dict)][:30]+ if segs:+ L += ["", T("**结构时间轴**", "**Structure**")]+ L += _table([T("时间", "Time"), T("这一段在做什么", "Beat"), T("文案", "Copy"), T("声音", "Audio")],+ [[_span(sg.get("start"), sg.get("end")), sg.get("beat", ""), sg.get("copy", ""), sg.get("audio", "")] for sg in segs])+ if lines:+ n = w.get("narration") or {}+ head = T("**脚本**", "**Script**")+ if n.get("type") and n.get("type") != "none":+ head += T("({t}{v})", " ({t}{v})", t=NARR_ZH.get(n["type"], n["type"]), v=(T(",", ", ") + n["voice"]) if n.get("voice") else "")+ L += ["", head]+ L += _table([T("时间", "Time"), T("谁", "Who"), T("台词 / 旁白", "Line")],+ [[_span(ln["start"], ln["end"]), ln["speaker"] or T("旁白", "narration"), ln["text"]] for ln in lines], fold_title=T("全部 {n} 句", "all {n} lines", n=len(lines)))+ return L+++def _cast_md(b: dict) -> list[str]:+ c = entities.cast(b)+ L = ["", T("## 角色、场景与道具", "## Cast, scenes and props"), ""]+ if c["characters"]:+ L.append(T("复刻时每个角色固定一张参考图(`@图片`)贯穿所有生成单元,外观按下表写进首帧提示词,角色才不会一镜一个样。",+ "For the remake, give every character one reference image (`@image`) used across all generation units and copy the look below into the first-frame prompts, so the character stays the same from shot to shot."))+ L += _table([T("编号", "Id"), T("称呼", "Name"), T("类型", "Kind"), T("外观", "Look"), T("作用", "Role"), T("声音", "Voice"), T("出场", "Shots")],+ [[ch["id"], ch["name"], entities.KIND_ZH.get(ch["kind"], ch["kind"]), ch["look"], ch["role"], ch["voice"], _shots_str(ch["shots"])] for ch in c["characters"]])+ else:+ L.append(T("- 没有归纳出角色(需要 VLM 整片分析,或 agent 看图后在 `review_answers.json` 顶层 `cast` 里填)",+ "- No cast extracted (needs the VLM whole-video pass, or an agent filling top-level `cast` in `review_answers.json`)")+ + (T(";人脸检测器在这些镜头看到脸(真人或角色):{s}", "; shots where the face detector saw a face (person or character): {s}", s=_shots_str(c["face_shots"])) if c["face_shots"] else ""))+ if c["scenes"]:+ L += ["", T("**场景**", "**Scenes**")]+ L += _table([T("场景", "Scene"), T("地点", "Where"), T("时间", "When"), T("布景 / 光线", "Set / light"), T("镜头", "Shots")],+ [[sc["id"], sc["where"], sc["when"], sc["look"], _shots_str(sc["shots"])] for sc in c["scenes"]])+ if c["props"]:+ L += ["", T("**道具 / 商品 / Logo**", "**Props / products / logos**"), ""]+ for p in c["props"]:+ L.append(f"- {p['name']}" + (T("(镜头 {s})", " (shots {s})", s=_shots_str(p["shots"])) if p["shots"] else "") + (f"{_colon()}{p['note']}" if p.get("note") else ""))+ return L+++def _audio_md(b: dict) -> list[str]:a = b.get("audio", {})- if a.get("has_audio"):- L += ["", T("## 声音拆解", "## Audio breakdown"), "", "", "",- T("- 整体响度 {r} dBFS,峰值 {p} dBFS", "- Loudness {r} dBFS, peak {p} dBFS", r=a.get("rms_dbfs"), p=a.get("peak_dbfs"))]- v = a.get("voice", {})- L.append(T("- **人声**:{p},占 {r:.0%} 时长", "- **Voice**: {p}, {r:.0%} of the duration",- p=(T("有", "present") if v.get("present") else T("无/很少", "none / very little")), r=v.get("ratio", 0))- + (T(",基频约 {f}Hz({g})", ", pitch about {f}Hz ({g})", f=v.get("f0_median_hz"),- g=GENDER_ZH.get(v.get("gender_hint"), T("性别不确定", "gender unclear"))) if v.get("f0_median_hz") else ""))- mu = a.get("music", {})+ L = ["", T("## 声音", "## Sound"), ""]+ if not a.get("has_audio"):+ L.append(T("- 没有音轨", "- No audio track"))+ return L+ w = b.get("whole_video_vlm") or {}+ src = b.get("sound_sources") or {}+ tracks = {t["track"]: t for t in (b.get("audio_plan") or {}).get("plan", [])}+ L.append("")+ L.append("")+ over = [T("响度 {r} dBFS,峰值 {p} dBFS", "loudness {r} dBFS, peak {p} dBFS", r=a.get("rms_dbfs"), p=a.get("peak_dbfs"))]+ if w.get("mix"):+ over.append(T("混音:{m}", "mix: {m}", m=w["mix"]))+ pc = b.get("per_clip_audio") or {}+ if pc.get("ratio") is not None:+ over.append(T("每段画面自带声音(切点处背景声跳变 {a}dB,镜头内 {w}dB)", "each clip carries its own sound (background jumps {a}dB at cuts vs {w}dB within shots)", a=pc["at_cuts_db"], w=pc["within_shots_db"])+ if pc.get("resets_at_cuts") else+ T("声音跨切点连续,是后期整体铺的(切点处背景声变化 {a}dB,镜头内 {w}dB)", "sound runs across cuts, laid in post as one bed (background changes {a}dB at cuts vs {w}dB within shots)", a=pc["at_cuts_db"], w=pc["within_shots_db"]))+ L.append("- " + semi().join(over))+ if src.get("summary_zh"):+ L.append(T("- 来源判断:{s}", "- Sources: {s}", s=src["summary_zh"]))++ def _source_lines(k: str) -> list[str]:+ v = src.get(k) or {}+ if not v:+ return []+ probs = T(",", ", ").join(f"{kk} {vv:.0%}" for kk, vv in sorted(v["probs"].items(), key=lambda kv: -kv[1])[:3])+ out = [T("- 来源:{s}({p})", "- Source: {s} ({p})", s=v["source_zh"], p=probs)]+ out += [f" - {e}" for e in v.get("evidence", [])[:4]]+ out += [T(" - 确认方法:{h}", " - How to confirm: {h}", h=h) for h in v.get("how_to_confirm", [])[:2]]+ return out++ # voice+ v = a.get("voice", {})+ n = w.get("narration") or {}+ L += ["", T("**人声**", "**Voice**"), ""]+ if v.get("present"):+ bits = [T("占 {r:.0%} 时长", "{r:.0%} of the duration", r=v.get("ratio", 0))]+ if n.get("type") and n["type"] != "none":+ bits.append(NARR_ZH.get(n["type"], n["type"]) + (T(",{v}", ", {v}", v=n["voice"]) if n.get("voice") else "") + (T(",{s}", ", {s}", s=n["style"]) if n.get("style") else ""))+ if v.get("f0_median_hz"):+ bits.append(T("基频约 {f}Hz({g})", "pitch about {f}Hz ({g})", f=v["f0_median_hz"], g=GENDER_ZH.get(v.get("gender_hint"), T("性别不确定", "gender unclear"))))+ if v.get("sung"):+ bits.append(T("是唱的", "sung"))+ L.append("- " + semi().join(bits))+ L += _source_lines("voice")+ if tracks.get("voice"):+ L.append(T("- 复刻:{h}", "- Remake: {h}", h=tracks["voice"]["how"]))+ if entities.script(b):+ L.append(T("- 台词见「内容与结构」的脚本表", "- Lines are in the script table under “Content and structure”"))+ else:+ L.append(T("- 无 / 很少", "- None / very little"))++ # music+ mu = a.get("music", {})+ vm = w.get("music") or {}+ L += ["", T("**背景音乐**", "**Music**"), ""]+ if mu.get("present") or vm.get("present"):+ if vm.get("song_guess"):+ L.append(T("- 歌曲:{s}", "- Song: {s}", s=vm["song_guess"]))+ desc = [x for x in (vm.get("style"), vm.get("genre"), vm.get("mood")) if x]+ if vm.get("instruments"):+ desc.append(join(vm["instruments"][:5]))+ if vm.get("has_vocals") is not None:+ desc.append(T("有人声演唱", "with vocals") if vm.get("has_vocals") else T("纯音乐", "instrumental"))+ if desc:+ L.append(T("- 风格:", "- Style: ") + semi().join(desc))+ if vm.get("lyrics_excerpt"):+ L.append(T("- 歌词:{l}", "- Lyrics: {l}", l=str(vm["lyrics_excerpt"])[:120])+ + (T("(唱的就是画面内容)", " (the lyrics describe the video itself)") if vm.get("lyrics_match_content") else ""))+ tempo = []+ if mu.get("tempo_bpm"):+ tempo.append(T("{bpm} BPM(也可能是 {alt})", "{bpm} BPM (or {alt})", bpm=mu["tempo_bpm"], alt="/".join(str(t) for t in mu.get("tempo_alternatives", []))) if mu.get("tempo_alternatives")+ else f"{mu['tempo_bpm']} BPM")+ key = mu.get("key") or {}+ if key:+ tempo.append(T("调性 {t} {m}(置信 {c})", "key {t} {m} (confidence {c})", t=key.get("tonic"), m=key.get("mode"), c=key.get("confidence")))if mu.get("present"):- key = mu.get("key") or {}- L.append(T("- **背景音乐**:占 {r:.0%} 时长({s}–{e}s),约 {bpm} BPM(也可能是 {alt})",- "- **Music**: {r:.0%} of the duration ({s}–{e}s), about {bpm} BPM (or {alt})",- r=mu.get("ratio", 0), s=mu.get("start"), e=mu.get("end"), bpm=mu.get("tempo_bpm"),- alt="/".join(str(t) for t in mu.get("tempo_alternatives", [])))- + (T(",调性 {t} {m}(置信 {c})", ", key {t} {m} (confidence {c})", t=key.get("tonic"), m=key.get("mode"), c=key.get("confidence")) if key else "")- + (T(",段落变化点 {p}", ", section changes at {p}", p=", ".join(str(t) + "s" for t in mu.get("section_changes", [])[:8])) if mu.get("section_changes") else ""))- else:- L.append(T("- **背景音乐**:未检测到持续的音乐床", "- **Music**: no sustained music bed detected"))+ tempo.append(T("占 {r:.0%} 时长({s}–{e}s)", "{r:.0%} of the duration ({s}–{e}s)", r=mu.get("ratio", 0), s=mu.get("start"), e=mu.get("end")))+ if mu.get("section_changes"):+ tempo.append(T("段落变化点 {p}", "section changes at {p}", p=", ".join(str(t) + "s" for t in mu["section_changes"][:8])))+ ending = vm.get("ending") or (src.get("music") or {}).get("ending")+ if ending:+ tempo.append(T("片尾{e}", "ending: {e}", e=ENDING_ZH.get(ending, ending)))+ if tempo:+ L.append(T("- 节奏:", "- Tempo: ") + semi().join(tempo))if "cuts_on_beat_ratio" in a:- L.append(T("- **剪辑与节拍**:{r:.0%} 的切点落在节拍上(随机约 {c:.0%})", "- **Cuts vs beat**: {r:.0%} of cuts land on a beat (chance: about {c:.0%})",- r=a["cuts_on_beat_ratio"], c=a["cuts_on_beat_chance"]) + (T("→ **卡点剪辑**", " → **beat-synced edit**") if a.get("beat_synced_edit") else ""))- src = b.get("sound_sources") or {}- if src:- L += ["", T("**声音来源:AI 生成还是现成素材**", "**Sound sources: AI-generated or existing material**"), ""]- if src.get("summary_zh"):- L.append(T("- **结论**:{s}", "- **Verdict**: {s}", s=src["summary_zh"]))- st = b.get("stems") or {}- if st.get("ok"):- L.append(T("- **剥离出的音轨**:`stems/original.wav`(原声)、`stems/vocals.wav`(人声干声,瞬态音效也会落在这里)、`stems/music.wav`(配乐 + 环境声)",- "- **Separated stems**: `stems/original.wav` (original), `stems/vocals.wav` (dry voice; transient sound effects land here too), `stems/music.wav` (music + ambience)"))- ctx = src.get("format_context", {})- fmt_name = (T("音乐 MV", "music video") if ctx.get("music_mv") else- (T("疑似带唱歌曲/MV", "possibly a sung song / music video") if ctx.get("music_mv_maybe") else (ctx.get("format") or T("普通视频配乐", "regular video with music"))))- L.append(T("- 视频形式:{f};AI 画面占 {ai:.0%},实拍占 {live:.0%}", "- Format: {f}; AI picture {ai:.0%}, live footage {live:.0%}",- f=fmt_name, ai=ctx.get("ai_picture_share", 0), live=ctx.get("live_picture_share", 0)))- for k in ("music", "voice", "sfx"):- v = src.get(k)- if not v:- continue- probs = T(",", ", ").join(f"{kk} {vv:.0%}" for kk, vv in sorted(v["probs"].items(), key=lambda kv: -kv[1]))- L.append(f"- **{MODE_ZH[k]}**{T(':', ': ')}{v['source_zh']}({probs})" if lang() == "zh" else f"- **{MODE_ZH[k]}**: {v['source_zh']} ({probs})")- for e in v["evidence"]:- L.append(f" - {e}")- for h in v.get("how_to_confirm", []):- L.append(T(" - 确认方法:{h}", " - How to confirm: {h}", h=h))- pc = b.get("per_clip_audio") or {}- if pc.get("ratio") is not None:- L.append(T("- 逐段原生音频检测:切点处背景声变化 {a}dB,镜头内 {w}dB(比值 {r})",- "- Per-clip native audio check: background changes {a}dB at cuts vs {w}dB within shots (ratio {r})",- a=pc["at_cuts_db"], w=pc["within_shots_db"], r=pc["ratio"])- + (T("→ 每段画面自带声音", " → each clip carries its own sound") if pc.get("resets_at_cuts")- else T("→ 声音跨切点连续,是后期整体铺的", " → sound runs across cuts, laid in post as one bed")))- plan = b.get("audio_plan", {})- sfx = plan.get("sfx_merged", [])- if sfx:- L += ["", T("**音效**({n} 处;来源 vlm=大模型听出,deterministic=信号检测的候选,置信度低)",- "**Sound effects** ({n}; source vlm = heard by the model, deterministic = signal-detected candidate, low confidence)", n=len(sfx)), "",- T("| 时间 | 类型 | 描述 | 对应画面 | 来源 |", "| Time | Type | Description | On screen | Source |"), "|---|---|---|---|---|"]- for e in sfx[:40]:- on = (e.get("on") or {}).get("what") or e.get("sync_with", T("切点", "cut") if e.get("sync_with_visual") else "")- L.append(f"| {float(e.get('t', 0)):.2f}s | {e.get('type', '')} | {e.get('description', '') or e.get('anchor', '')} | "- f"{on} | {e.get('source', '')} |")- else:- L.append(T("- **音效**:信号层面未检出显著音效(在人声和音乐下面的轻音效需要 VLM 判断,见 --vlm)",- "- **Sound effects**: nothing prominent at the signal level (quiet effects under voice and music need the VLM, see --vlm)"))- if plan.get("plan"):- L += ["", T("**声音复刻方案**", "**Audio remake plan**"), ""]- for t in plan["plan"]:- L.append(f"- {t['track']}({t['rule']}):{t['what']} → {t['how']}" if lang() == "zh" else f"- {t['track']} ({t['rule']}): {t['what']} → {t['how']}")- if plan.get("mix"):- L.append(T("- 混音:{m}", "- Mix: {m}", m=plan["mix"]))- L += packaging_md(b)- w = b.get("whole_video_vlm")- if w:- L += ["", T("## 结构与文案(VLM)", "## Structure and copy (VLM)"), "", T("- 概括:{s}", "- Summary: {s}", s=w.get("summary", "")),- T("- 形式:{f};钩子:{h}", "- Format: {f}; hook: {h}", f=w.get("format", ""), h=w.get("hook", ""))]- n = w.get("narration") or {}- L.append(T("- 旁白:{t} {v};音乐:{m};字幕:{s}", "- Narration: {t} {v}; music: {m}; subtitles: {s}",- t=n.get("type", ""), v=n.get("voice", ""), m=(w.get("music") or {}).get("style", ""), s=(w.get("subtitles") or {}).get("style", "")))- L.append(T("- 整体判断:{o}", "- Overall: {o}", o=w.get("overall_production", "")))- for seg in w.get("segments", [])[:30]:- L.append(f" - {seg.get('start')}–{seg.get('end')}s · {seg.get('beat', '')} · {seg.get('copy', '')}")- rm = s.get("real_material") or {}- if rm.get("shots"):- L += ["", T("## 画面里的真实素材", "## Real material in the picture"), "",- T("共 {n} 个镜头、{s}s({r:.0%})的画面里有真实素材(录屏、截图、照片、嵌入视频),复刻时要拿到原文件,不能用模型生成替代:",- "{n} shots, {s}s ({r:.0%}) contain real material (screen recordings, screenshots, photos, embedded video). The remake needs the original files; a model cannot stand in for them:",- n=len(rm["shots"]), s=rm["seconds"], r=rm["ratio"]), ""]- for r in b["shots"]:- for a in r.get("replication", {}).get("user_assets", []):- L.append(T("- 镜头 #{i}({t}):{k},{w}", "- Shot #{i} ({t}): {k}, {w}", i=r["index"], t=fmt_time(r["start"]), k=a["kind_zh"], w=a["where"])- + (f"{T(',', ', ')}{a['description']}" if a.get("description") else ""))- if s.get("references"):- L += ["", T("## 复刻要准备的参考素材", "## Reference material to prepare for the remake"), "",- T("这些镜头的画面是生成或拍摄出来的,下面是画面里出现、复刻时应作为参考图 / 道具准备的东西(不是嵌入的真实像素):",- "These shots were generated or filmed; the items below appear in them and should be prepared as reference images / props for the remake (they are not embedded real pixels):"), ""]- for r in b["shots"]:- for a in (r.get("material") or {}).get("references", []):- L.append(T("- 镜头 #{i}({t}):{k}", "- Shot #{i} ({t}): {k}", i=r["index"], t=fmt_time(r["start"]), k=a["kind_zh"])- + (f"{T(',', ', ')}{a['description']}" if a.get("description") else ""))- L += ["", T("## 分镜表", "## Shot list"), "",- T("| # | 时间 | 时长 | 底层画面 | 置信度 | 素材来源 | 叠加层 | 运镜 | 复刻路线 |", "| # | Time | Length | Base picture | Confidence | Material | Overlays | Camera | Remake route |"),- "|---|---|---|---|---|---|---|---|---|"]- for r in b["shots"]:- base = r["base"]- L.append(f"| {r['index']} | {fmt_time(r['start'])} | {r['duration']:.2f}s | {base['label_zh']} | {base['confidence']:.0%} | {_origin(r)} | {_layers(r)} | "- f"{CAMERA_ZH.get(r['features'].get('camera', 'unknown'), '—')} | {r['replication']['rule']} → {r['replication']['executor']} |")- L += ["", T("## 逐镜详情", "## Shot by shot"), ""]- for r in b["shots"]:- base = r["base"]- L += [f"### #{r['index']} {fmt_time(r['start'])}–{fmt_time(r['end'])} · {r['verdict']}", "",- f"![{r['id']}]({r['assets']['sheet']})", ""]- probs = sorted(base["probs"].items(), key=lambda kv: -kv[1])[:3]- L.append(T("- 概率:", "- Probabilities: ") + T(",", ", ").join(f"{LABEL_ZH[k]} {v:.0%}" for k, v in probs) + f"({base['decided_by']})")- for key, name in (("uncertain", T("待确认", "To confirm")), ("disputed", T("有分歧", "Disputed"))):- if base.get(key):- L.append(f"- ⚠️ {name}{T(':', ': ')}{base[key]}")- if base.get("scene_text"):- L.append(T("- 画面里物体上的字(不是后期字幕):", "- Text on objects in the scene (not subtitles): ") + join(base["scene_text"][:6]))- if base.get("image_source"):- L.append(T("- 静帧来源:{s}", "- Still source: {s}", s=base["image_source"]))- L.append(T("- 素材来源:{o}", "- Material: {o}", o=_origin(r)))- for it in (r.get("material") or {}).get("items", []):- if it.get("real_material") and it.get("evidence"):- L.append(f" - {it['kind_zh']}{T(':', ': ')}{it['evidence']}")- if base.get("generator_guess") and base["generator_guess"] != "unknown":- L.append(T("- 可能的工具:{g}", "- Likely tool: {g}", g=base["generator_guess"]))- if r.get("beats"):- L.append(T("- 镜头内动效节拍:", "- Motion beats within the shot: ") + join(f"{t:.2f}s" for t in r["beats"]))- for e in base["evidence"][:8]:- L.append(f"- {e}")- v = r.get("vlm") or r.get("review") or {}- if v.get("description"):- L.append(T("- 画面:{d}", "- Picture: {d}", d=v["description"]))- cl = aspects.shot_text(r) if r["base"]["label"] in aspects.PHOTOGRAPHIC else ""- if cl:- L.append(T("- 拍法/打光:{c}", "- Camera / lighting: {c}", c=cl))- intrinsic = base["label"] in ("code_render", "screen_capture")- for tr in r.get("text", {}).get("tracks", [])[:4]:- kind = T("画面内容文字", "text in the picture") if intrinsic else KIND_ZH.get(tr["kind"], tr["kind"])- L.append(T("- 文字轨({k}/{b}):", "- Text track ({k}/{b}): ", k=kind, b=tr["band"]) + " / ".join(t[:40] for t in tr["texts"][:4]))- rep = r["replication"]- L.append(T("- 复刻:{n}", "- Remake: {n}", n=rep["note"]))- if rep.get("capsule", {}).get("image_prompt"):- L.append(T(" - 首帧图像提示词:{p}", " - First-frame image prompt: {p}", p=rep["capsule"]["image_prompt"]))- if rep.get("capsule", {}).get("prompt"):- L.append(T(" - 视频提示词:{p}", " - Video prompt: {p}", p=rep["capsule"]["prompt"]))+ L.append(T("- 剪辑与节拍:{r:.0%} 的切点落在节拍上(随机约 {c:.0%})", "- Cuts vs beat: {r:.0%} of cuts land on a beat (chance: about {c:.0%})",+ r=a["cuts_on_beat_ratio"], c=a["cuts_on_beat_chance"]) + (T(" → **卡点剪辑**", " → **beat-synced edit**") if a.get("beat_synced_edit") else ""))+ L += _source_lines("music")+ if tracks.get("music"):+ L.append(T("- 复刻:{h}", "- Remake: {h}", h=tracks["music"]["how"]))+ else:+ L.append(T("- 未检测到持续的音乐床", "- No sustained music bed detected"))++ # sfx+ sfx = (b.get("audio_plan") or {}).get("sfx_merged", [])+ L += ["", T("**音效**", "**Sound effects**") + (f"({len(sfx)})" if sfx and lang() == "zh" else (f" ({len(sfx)})" if sfx else "")), ""]+ if sfx:+ rows = []+ for e in sfx[:60]:+ on = (e.get("on") or {}).get("what") or e.get("sync_with", T("切点", "cut") if e.get("sync_with_visual") else "")+ rows.append([f"{float(e.get('t', 0)):.2f}s", e.get("type", ""), e.get("description", "") or e.get("anchor", ""), on, SFX_SRC_ZH.get(e.get("source"), e.get("source", ""))])+ L += _table([T("时间", "Time"), T("类型", "Type"), T("描述", "Description"), T("对应画面", "On screen"), T("依据", "Basis")], rows, fold_title=T("全部 {n} 处音效", "all {n} sound effects", n=len(rows)))L.append("")- L += [T("## 说明", "## Notes"), "",- T("- 确定性取证对「是否在动、是否整图推拉、是否渲染纹理、是否 24→30 帧率转换」很可靠;对实拍 / AI / 3D 的区分要依赖 VLM 与人工复核。",- "- Deterministic forensics is reliable on motion, whole-frame pan/zoom, rendered texture and 24→30 fps conversion; telling live action from AI from 3D relies on the VLM and human review."),- T("- 元数据经平台转码常被清除,缺失不代表没有。", "- Platform transcoding usually strips metadata; missing metadata proves nothing."), ""]- return "\n".join(L)+ L += _source_lines("sfx")+ if tracks.get("sfx"):+ L.append(T("- 复刻:{h}", "- Remake: {h}", h=tracks["sfx"]["how"]))+ else:+ L.append(T("- 信号层面未检出显著音效(人声和音乐下面的轻音效需要 VLM 听,见 --vlm)",+ "- Nothing prominent at the signal level (quiet effects under voice and music need the VLM, see --vlm)"))++ # ambience + files+ amb = w.get("ambience") or (tracks.get("ambience") or {}).get("what")+ if amb or tracks.get("ambience"):+ L += ["", T("**环境声**", "**Ambience**"), "", f"- {amb or '—'}" + (T(";复刻:{h}", "; remake: {h}", h=tracks["ambience"]["how"]) if tracks.get("ambience") else "")]+ st = b.get("stems") or {}+ if st.get("ok"):+ L += ["", T("- 分离出的音轨:`stems/original.wav`(原声)、`stems/vocals.wav`(人声干声,瞬态音效也会落在这里)、`stems/music.wav`(配乐 + 环境声)",+ "- Separated stems: `stems/original.wav` (original), `stems/vocals.wav` (dry voice; transient sound effects land here too), `stems/music.wav` (music + ambience)"),+ _STEMS_MARK]+ if (b.get("audio_plan") or {}).get("mix"):+ L.append(T("- 混音复刻:{m}", "- Mix for the remake: {m}", m=b["audio_plan"]["mix"]))+ return L+++def _visual_md(b: dict) -> list[str]:+ style = entities.cast(b).get("style")+ L = aspects.report_md(b)+ if not L and not style:+ return []+ if not L:+ L = ["", T("## 拍法、打光与剪辑", "## Camera, lighting and editing"), ""]+ if style:+ L.insert(3, T("- 视觉风格:{s}", "- Visual style: {s}", s=style))+ return Ldef packaging_md(b: dict) -> list[str]:@@ -262,22 +384,22 @@ def packaging_md(b: dict) -> list[str]:+ T("(SRT 是字幕时间轴;ASS 带颜色、描边、位置和入场动画,字体需要换成原片字体;timeline.json 是完整时间轴)"," (SRT is the subtitle timeline; ASS carries colour, outline, position and entrance animation, swap in the original font; timeline.json is the full timeline)"))if cues:- L += ["", T("| 时间 | 类型 | 文字 | 样式 | 入场 / 出场 | 音效 |", "| Time | Kind | Text | Style | In / out | SFX |"), "|---|---|---|---|---|---|"]sfx_by_ref: dict[str, list[str]] = {}for e in (b.get("audio_plan") or {}).get("sfx_merged", []):ref = (e.get("on") or {}).get("ref")if ref:sfx_by_ref.setdefault(ref, []).append(str(e.get("type", "")))+ rows = []for c in sorted(cues, key=lambda c: c["t0"])[:120]:anim = " / ".join(x for x in (ANIM_ZH.get((c.get("anim_in") or {}).get("kind"), ""), ANIM_ZH.get((c.get("anim_out") or {}).get("kind"), "")) if x)if c.get("mid_motion"):anim += T("(中途有弹跳/变色)", " (bounces / changes colour midway)")kind = c["kind_zh"] + (T("·跟随物体", " · follows an object") if c.get("follows") else "")- L.append(f"| {c['t0']:.2f}–{c['t1']:.2f}s | {kind} | {c['text'].replace('/', ' ⏎ ').replace('|', '|')[:40]} | "- f"{c.get('style_zh', '')} | {anim or '—'} | {join(sfx_by_ref.get(c['id'], [])) or '—'} |")+ rows.append([f"{c['t0']:.2f}–{c['t1']:.2f}s", kind, c["text"].replace("/", " ⏎ ")[:40], c.get("style_zh", ""), anim or "—", join(sfx_by_ref.get(c["id"], [])) or "—"])+ L += _table([T("时间", "Time"), T("类型", "Kind"), T("文字", "Text"), T("样式", "Style"), T("入场 / 出场", "In / out"), T("音效", "SFX")], rows,+ fold_title=T("文字时间轴({n} 条)", "text timeline ({n} rows)", n=len(rows)))if stickers:- L += ["", T("**贴纸 / 动图 / 画中画**", "**Stickers / GIFs / picture-in-picture**"), "",- T("| 时间 | 类型 | 位置 | 动态 | 置信 | 截图 |", "| Time | Kind | Position | Motion | Confidence | Crop |"), "|---|---|---|---|---|---|"]+ rows = []for st in stickers:where = (T("x{0:.0%} y{1:.0%} 宽{2:.0%} 高{3:.0%}", "x{0:.0%} y{1:.0%} w{2:.0%} h{3:.0%}").format(*st["bbox"]) if st.get("bbox") else (st.get("where") or "—"))dyn = (T("循环,周期 {p:.2f}s", "loops every {p:.2f}s", p=st["loop_period_s"]) if st.get("looping")@@ -287,17 +409,20 @@ def packaging_md(b: dict) -> list[str]:why.append(T("跨切镜不变", "unchanged across a cut"))if st.get("disappears_mid_shot"):why.append(T("镜头中途出现又消失", "appears and disappears mid-shot"))- conf = CONF_ZH.get(st.get("confidence"), st.get("confidence", ""))- L.append(f"| {st['t0']:.2f}–{st['t1']:.2f}s | {st['kind_zh']} | {where} | {dyn} | {conf}{('(' + join(why) + ')') if why else ''} | "- + (f"![{st['id']}]({st['image']})" if st.get("image") else "—") + " |")+ conf = CONF_ZH.get(st.get("confidence"), st.get("confidence", "")) + (("(" + join(why) + ")") if why else "")+ rows.append([f"{st['t0']:.2f}–{st['t1']:.2f}s", st["kind_zh"], where, dyn, conf, f"![{st['id']}]({st['image']})" if st.get("image") else "—"])+ L += ["", T("**贴纸 / 动图 / 画中画**", "**Stickers / GIFs / picture-in-picture**")]+ L += _table([T("时间", "Time"), T("类型", "Kind"), T("位置", "Position"), T("动态", "Motion"), T("置信", "Confidence"), T("截图", "Crop")], rows)dropped = [st for st in pack.get("stickers", []) if st.get("in_picture")]if dropped:L.append(T("- 另有 {n} 处画面里突然出现的东西没算作贴纸(3D/动画/版式画面里元素本来就会出现)","- {n} more things that pop up in the picture were not counted as stickers (elements appear on their own in 3D / animation / layout shots)", n=len(dropped)))if pack.get("vlm_text_effects"):- L += ["", T("**VLM 看到的文字特效**", "**Text effects seen by the VLM**"), ""]- for e in pack["vlm_text_effects"][:20]:+ fx = pack["vlm_text_effects"][:20]+ L += ["", f"<details><summary>{html.escape(T('VLM 看到的文字特效({n})', 'Text effects seen by the VLM ({n})', n=len(fx)))}</summary>", ""]+ for e in fx:L.append(f"- {e.get('t', '')}s {e.get('kind', '')}「{e.get('text', '')}」{e.get('style', '')} {e.get('animation', '')}")+ L += ["", "</details>"]L += ["", T("复刻:字幕和花字用 `packaging/overlays.ass` 直接压制(ffmpeg -vf ass=overlays.ass),或按 timeline.json 在剪映 / Remotion 里重建;""贴纸和动图要找同款素材(表情包库 / GIF 库),截图在 packaging/ 下。","Remake: burn subtitles and styled text in with `packaging/overlays.ass` (ffmpeg -vf ass=overlays.ass), or rebuild them from timeline.json in CapCut / Remotion; "@@ -305,140 +430,283 @@ def packaging_md(b: dict) -> list[str]:return L-def _packaging_html(b: dict) -> str:- pack = b.get("packaging")- if not pack:- return ""- esc = html.escape- parts = [f"<section class='shot'><h3 style='margin:4px 0'>{T('剪辑包装层', 'Packaging layer')}</h3>"]- parts += [f"<p>{esc(x)}</p>" for x in pack.get("summary_zh") or []]- stickers = [st for st in pack.get("stickers", []) if not st.get("in_picture") and st.get("image")]- if stickers:- parts.append("<div style='display:flex;gap:8px;flex-wrap:wrap'>" + "".join(- f"<figure style='margin:0'><img src='{esc(st['image'])}' style='max-height:90px;border-radius:6px'>"- f"<figcaption class='muted' style='font-size:12px'>{esc(st['kind_zh'])} {st['t0']:.1f}s</figcaption></figure>" for st in stickers) + "</div>")- files = pack.get("files") or {}- if files:- parts.append("<p class='muted'>" + " · ".join(f"<a href='{esc(v)}'>{esc(v)}</a>" for v in files.values()) + "</p>")- parts.append("</section>")- return "".join(parts)+def _remake_md(b: dict) -> list[str]:+ s = b["summary"]+ L = production_md(b.get("production_plan") or {})+ if not L:+ L = ["", T("## 复刻方案", "## Remake plan"), ""]+ rm = s.get("real_material") or {}+ if rm.get("shots"):+ L += ["", T("### 画面里的真实素材(必须拿到原文件)", "### Real material in the picture (the original files are needed)"), "",+ T("共 {n} 个镜头、{s}s({r:.0%})的画面里有真实素材(录屏、截图、照片、嵌入视频),模型生成替代不了:",+ "{n} shots, {s}s ({r:.0%}) contain real material (screen recordings, screenshots, photos, embedded video); a model cannot stand in for them:",+ n=len(rm["shots"]), s=rm["seconds"], r=rm["ratio"]), ""]+ for r in b["shots"]:+ for a in r.get("replication", {}).get("user_assets", []):+ L.append(T("- 镜头 #{i}({t}):{k},{w}", "- Shot #{i} ({t}): {k}, {w}", i=r["index"], t=fmt_time(r["start"]), k=a["kind_zh"], w=a["where"])+ + (f"{T(',', ', ')}{a['description']}" if a.get("description") else ""))+ if s.get("references"):+ L += ["", T("### 复刻要准备的参考素材", "### Reference material to prepare for the remake"), "",+ T("这些镜头的画面是生成或拍摄出来的,下面是画面里出现、复刻时应作为参考图 / 道具准备的东西(不是嵌入的真实像素):",+ "These shots were generated or filmed; the items below appear in them and should be prepared as reference images / props for the remake (they are not embedded real pixels):"), ""]+ for r in b["shots"]:+ for a in (r.get("material") or {}).get("references", []):+ L.append(T("- 镜头 #{i}({t}):{k}", "- Shot #{i} ({t}): {k}", i=r["index"], t=fmt_time(r["start"]), k=a["kind_zh"])+ + (f"{T(',', ', ')}{a['description']}" if a.get("description") else ""))+ return L-def html_report(b: dict) -> str:- s = b["summary"]- esc = html.escape+def _shotlist_md(b: dict) -> list[str]:+ units = _unit_of(b)rows = []for r in b["shots"]:base = r["base"]- c = "rgb(%d,%d,%d)" % LABEL_COLOR.get(base["label"], (80, 80, 80))- ev = "".join(f"<li>{esc(e)}</li>" for e in base["evidence"][:8])- desc = esc((r.get("vlm") or r.get("review") or {}).get("description", ""))- prompt = esc(r["replication"].get("capsule", {}).get("prompt", ""))- intrinsic = base["label"] in ("code_render", "screen_capture")- texts = "".join(f"<li>{esc(T('画面内容文字', 'text in the picture') if intrinsic else KIND_ZH.get(t['kind'], t['kind']))}·{esc(t['band'])}{T(':', ': ')}"- f"{esc(' / '.join(x[:40] for x in t['texts'][:4]))}</li>" for t in r.get("text", {}).get("tracks", [])[:4])- rows.append(f"""-<section class="shot">- <div class="head"><span class="badge" style="background:{c}">{esc(base['label_zh'])} {base['confidence']:.0%}</span>- <b>#{r['index']}</b> {fmt_time(r['start'])}–{fmt_time(r['end'])} · {r['duration']:.2f}s · {esc(r['verdict'])}- {('<span class="real">' + T('真实素材', 'real material') + '</span>') if (r.get('material') or {}).get('has_real_material') else ''}</div>- <img src="{esc(r['assets']['sheet'])}" loading="lazy">- <div class="cols"><div><h4>{T('证据', 'Evidence')}</h4><ul>{ev}</ul>{('<h4>' + T('文字轨', 'Text tracks') + '</h4><ul>' + texts + '</ul>') if texts else ''}</div>- <div><h4>{T('画面', 'Picture')}</h4><p>{desc or '—'}</p><h4>{T('复刻', 'Remake')}</h4><p>{esc(r['replication']['rule'])} → {esc(r['replication']['executor'])}<br>{esc(r['replication']['note'])}</p>- {('<p class="prompt">' + prompt + '</p>') if prompt else ''}</div></div>-</section>""")-- def _rgb(label: str) -> str:- return "rgb(%d,%d,%d)" % LABEL_COLOR.get(label, (80, 80, 80))-- mix = "".join(f"<div class='bar' style='flex:{m['ratio']};background:{_rgb(m['label'])}' title='{esc(m['label_zh'])}'>{esc(m['label_zh'])} {m['ratio']:.0%}</div>" for m in s["production_mix"])- rm = s.get("real_material") or {}- real_line = ""- if rm.get("shots"):- real_line = ("<p><b>" + T("用户真实素材:", "Real material: ") + "</b>"- + T("{n} 个镜头,{s}s({r:.0%})——画面里嵌入的真实素材,复刻时需要原文件", "{n} shots, {s}s ({r:.0%}) embed real material; the remake needs the original files",- n=len(rm["shots"]), s=rm["seconds"], r=rm["ratio"]) + "</p>")- return f"""<!doctype html><html lang="{lang()}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">-<title>{T('拆解:', 'Breakdown: ')}{esc(b['source']['filename'])}</title>-<style>-:root{{--bg:#fafaf9;--fg:#1c1917;--muted:#78716c;--card:#fff;--line:#e7e5e4}}-@media (prefers-color-scheme:dark){{:root{{--bg:#1c1917;--fg:#f5f5f4;--muted:#a8a29e;--card:#292524;--line:#44403c}}}}-body{{margin:0;padding:24px 16px;background:var(--bg);color:var(--fg);font:15px/1.6 -apple-system,"PingFang SC","Noto Sans CJK SC",sans-serif}}-main{{max-width:1100px;margin:auto}} h1{{font-size:22px}} .muted{{color:var(--muted)}}-.mix{{display:flex;height:30px;border-radius:6px;overflow:hidden;margin:12px 0}} .bar{{color:#fff;font-size:12px;padding:6px;white-space:nowrap;overflow:hidden}}-.shot{{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:12px;margin:14px 0}}-.shot img{{max-width:100%;border-radius:6px;margin:8px 0}} .badge{{color:#fff;border-radius:4px;padding:2px 8px;margin-right:8px;font-size:13px}}-.cols{{display:grid;grid-template-columns:1fr 1fr;gap:16px}} @media (max-width:700px){{.cols{{grid-template-columns:1fr}}}}-h4{{margin:6px 0 2px;font-size:13px;color:var(--muted)}} ul{{margin:0;padding-left:18px}} .prompt{{background:var(--bg);padding:8px;border-radius:6px;font-size:13px}}-img.sb{{max-width:100%;border-radius:8px}} .real{{background:#0d9488;color:#fff;border-radius:4px;padding:2px 8px;margin-left:8px;font-size:12px}}-</style></head><body><main>-<h1>{T('视频拆解:', 'Video breakdown: ')}{esc(b['source']['filename'])}</h1>-<p><b>{T('结论:', 'Verdict: ')}</b>{esc(s['verdict'])}</p>-{real_line}-<p class="muted">{b['source']['duration']}s · {b['source']['width']}×{b['source']['height']} · {b['source']['fps']}fps · {T('{n} 个镜头', '{n} shots', n=s['shots'])} · {T('置信度', 'confidence')} {s['confidence']:.0%} ·-{esc(s.get('vlm') or vlm_note(b['analysis']['vlm'], b['analysis'].get('review')))}</p>-<div class="mix">{mix}</div>-<img class="sb" src="storyboard.jpg">-{_production_html(b.get("production_plan") or {})}-{aspects.report_html(b)}-{_sound_html(b)}-{_packaging_html(b)}-{''.join(rows)}-</main></body></html>"""---def _shots(ids) -> str:- return join("#" + str(i) for i in ids)---def _production_html(plan: dict) -> str:- if not plan:- return ""- esc = html.escape- P = [f"<section class='shot'><h3 style='margin:4px 0'>{T('复刻方案', 'Remake plan')}</h3><p><b>{esc(plan['summary'])}</b></p>"]- if plan.get("engine_note"):- P.append(f"<p class='muted'>{esc(plan['engine_note'])}</p>")- if plan.get("audio_note"):- P.append(f"<p class='muted'>{T('声音:', 'Audio: ')}{esc(plan['audio_note'])}</p>")- for u in plan.get("units", []):- refs = "".join(f"<li><code>{esc(r['tag'])}</code> {esc(r['what'])}</li>" for r in u["refs"])- P.append(f"<h4>{esc(u['id'])} · {esc(u['label_zh'])} · {T('镜头', 'shots')} {esc(_shots(u['shots']))} · "- f"{u['start']:.1f}–{u['end']:.1f}s({u['duration']:.1f}s)</h4>"- + (f"<ul>{refs}</ul>" if refs else "")- + (f"<p class='muted'>{esc(u['continuity'])}</p>" if u.get("continuity") else "")- + "".join(f"<p class='muted'>{esc(u[k])}</p>" for k in ("note", "alt") if u.get(k))- + f"<pre class='prompt' style='white-space:pre-wrap'>{esc(u['prompt'])}</pre>")- for sc in plan.get("shoot", []):- rows = "".join(T("<li>机位 {size} · {sup}:镜头 {shots},成片 {scr}s,建议拍 {take}s</li>",- "<li>Setup {size} · {sup}: shots {shots}, {scr}s on screen, shoot about {take}s</li>",- size=esc(st["shot_size"]), sup=esc(st["support"]), shots=esc(_shots(st["shots"])), scr=st["screen_s"], take=st["take_s"]) for st in sc["setups"])- rows += "".join(T("<li>拍完后 #{s} 要 AI 加工:{k}", "<li>#{s} gets AI processing after the shoot: {k}", s=e["shot"], k=esc(e["kind_zh"]))- + (f" → {esc(e['how'])}" if e.get("how") else "") + "</li>" for e in sc.get("post", []))- P.append(T("<h4>场次 {id}:镜头 {shots}({scr}s)</h4>", "<h4>Scene {id}: shots {shots} ({scr}s)</h4>", id=esc(sc["id"]), shots=esc(_shots(sc["shots"])), scr=sc["screen_s"])- + (f"<p>{esc(sc['description'])}</p>" if sc.get("description") else "")- + (f"<p class='muted'>{T('布光:', 'Lighting: ')}{esc(sc['lighting'])}</p>" if sc.get("lighting") else "") + f"<ul>{rows}</ul>")- for c in plan.get("code", []):- P.append(T("<h4>{id} 代码合成:镜头 {shots}({d:.1f}s)</h4>", "<h4>{id} code render: shots {shots} ({d:.1f}s)</h4>", id=esc(c["id"]), shots=esc(_shots(c["shots"])), d=c["duration"]))- P.append("</section>")- return "".join(P)+ desc = ((r.get("vlm") or r.get("review") or {}).get("description") or "").replace("\n", " ")+ rows.append([r["index"], fmt_time(r["start"]), f"{r['duration']:.2f}s", f"{base['label_zh']} {base['confidence']:.0%}", _origin(r), _layers(r),+ CAMERA_ZH.get(r["features"].get("camera", "unknown"), "—"), desc[:40] + ("…" if len(desc) > 40 else ""), _route(r, units)])+ return ["", T("## 分镜表", "## Shot list")] + _table(+ ["#", T("时间", "Time"), T("时长", "Length"), T("底层画面", "Base picture"), T("素材来源", "Material"), T("叠加层", "Overlays"), T("运镜", "Camera"),+ T("画面", "Picture"), T("复刻", "Remake")], rows)-def _sound_html(b: dict) -> str:+def _questions_md(b: dict) -> list[str]:+ qs = entities.open_questions(b)+ L = ["", T("## 不确定点", "## Open questions"), ""]+ L += [f"- {q}" for q in qs] or [T("- 没有需要特别复核的地方", "- Nothing needs a second look")]+ return L+++def _shot_detail_md(r: dict) -> list[str]:+ base = r["base"]+ L = [f"![{r['id']}]({r['assets']['sheet']})", ""]+ probs = sorted(base["probs"].items(), key=lambda kv: -kv[1])[:3]+ L.append(T("- 概率:", "- Probabilities: ") + T(",", ", ").join(f"{LABEL_ZH[k]} {v:.0%}" for k, v in probs) + f"({base['decided_by']})")+ for key, name in (("uncertain", T("待确认", "To confirm")), ("disputed", T("有分歧", "Disputed"))):+ if base.get(key):+ L.append(f"- ⚠️ {name}{_colon()}{base[key]}")+ if base.get("scene_text"):+ L.append(T("- 画面里物体上的字(不是后期字幕):", "- Text on objects in the scene (not subtitles): ") + join(base["scene_text"][:6]))+ if base.get("image_source"):+ L.append(T("- 静帧来源:{s}", "- Still source: {s}", s=base["image_source"]))+ L.append(T("- 素材来源:{o}", "- Material: {o}", o=_origin(r)))+ for it in (r.get("material") or {}).get("items", []):+ if it.get("real_material") and it.get("evidence"):+ L.append(f" - {it['kind_zh']}{_colon()}{it['evidence']}")+ if base.get("generator_guess") and base["generator_guess"] != "unknown":+ L.append(T("- 可能的工具:{g}", "- Likely tool: {g}", g=base["generator_guess"]))+ if r.get("beats"):+ L.append(T("- 镜头内动效节拍:", "- Motion beats within the shot: ") + join(f"{t:.2f}s" for t in r["beats"]))+ L += [f"- {e}" for e in base["evidence"][:8]]+ v = r.get("vlm") or r.get("review") or {}+ if v.get("description"):+ L.append(T("- 画面:{d}", "- Picture: {d}", d=v["description"]))+ cl = aspects.shot_text(r) if base["label"] in aspects.PHOTOGRAPHIC else ""+ if cl:+ L.append(T("- 拍法/打光:{c}", "- Camera / lighting: {c}", c=cl))+ intrinsic = base["label"] in ("code_render", "screen_capture")+ for tr in r.get("text", {}).get("tracks", [])[:4]:+ kind = T("画面内容文字", "text in the picture") if intrinsic else KIND_ZH.get(tr["kind"], tr["kind"])+ L.append(T("- 文字轨({k}/{b}):", "- Text track ({k}/{b}): ", k=kind, b=tr["band"]) + " / ".join(t[:40] for t in tr["texts"][:4]))+ rep = r["replication"]+ L.append(T("- 复刻:{n}", "- Remake: {n}", n=rep["note"]))+ if rep.get("capsule", {}).get("image_prompt"):+ L.append(T(" - 首帧图像提示词:{p}", " - First-frame image prompt: {p}", p=rep["capsule"]["image_prompt"]))+ if rep.get("capsule", {}).get("prompt"):+ L.append(T(" - 视频提示词:{p}", " - Video prompt: {p}", p=rep["capsule"]["prompt"]))+ return L+++def _appendix_md(b: dict) -> list[str]:+ L = ["", T("## 附录", "## Appendix"), "", T("### 逐镜取证", "### Shot by shot"), "",+ T("每个镜头的证据、概率、文字轨和提示词。默认折叠,点开看。", "Evidence, probabilities, text tracks and prompts per shot. Folded by default."), ""]+ for r in b["shots"]:+ title = f"#{r['index']} {fmt_time(r['start'])}–{fmt_time(r['end'])} · {r['verdict']}"+ L += [f"<details><summary>{html.escape(title)}</summary>", ""] + _shot_detail_md(r) + ["", "</details>", ""]+ prov = b.get("provenance", {})+ if prov.get("hints") or prov.get("encoder"):+ L += [T("### 元数据线索", "### Metadata clues"), ""]+ if prov.get("encoder"):+ L.append(T("- 编码器:`{e}`", "- Encoder: `{e}`", e=prov["encoder"]))+ for k, v in (prov.get("hints") or {}).items():+ L.append(f"- {k}{_colon()}{', '.join(v)}")+ L.append("")+ L += [T("### 说明", "### Notes"), "",+ T("- 确定性取证对「是否在动、是否整图推拉、是否渲染纹理、是否 24→30 帧率转换」很可靠;对实拍 / AI / 3D 的区分要依赖 VLM 与人工复核。",+ "- Deterministic forensics is reliable on motion, whole-frame pan/zoom, rendered texture and 24→30 fps conversion; telling live action from AI from 3D relies on the VLM and human review."),+ T("- 元数据经平台转码常被清除,缺失不代表没有。", "- Platform transcoding usually strips metadata; missing metadata proves nothing."),+ T("- 完整数据在 `breakdown.json`;agent 用 `rea-video summary` 读紧凑版。", "- The full data is in `breakdown.json`; agents read the compact view with `rea-video summary`."), ""]+ return L+++def markdown(b: dict) -> str:+ L = _head_md(b) + _content_md(b) + _cast_md(b) + _audio_md(b) + _visual_md(b) + packaging_md(b) + _remake_md(b) + _shotlist_md(b) + _questions_md(b) + _appendix_md(b)+ return re.sub(r"\n{3,}", "\n\n", "\n".join(L)).strip() + "\n"+++# ------------------------------------------------------------------ HTML ------------------------------------------++_RE_IMG = re.compile(r"!\[([^\]]*)\]\(([^)\s]+)\)")+_RE_LINK = re.compile(r"\[([^\]]+)\]\(([^)\s]+)\)")+_RE_BOLD = re.compile(r"\*\*(.+?)\*\*")+_RE_CODE = re.compile(r"`([^`]+)`")+_RE_SEP = re.compile(r"^\|(\s*:?-+:?\s*\|)+\s*$")+++def _inline(s: str) -> str:+ s = html.escape(s, quote=False)+ s = _RE_CODE.sub(r"<code>\1</code>", s)+ s = _RE_BOLD.sub(r"<b>\1</b>", s)+ s = _RE_IMG.sub(r'<img src="\2" alt="\1" loading="lazy">', s)+ s = _RE_LINK.sub(r'<a href="\2">\1</a>', s)+ return s+++def _md_to_html(lines: list[str], b: dict) -> str:+ """Just enough Markdown for our own reports: headings, lists (2 levels), tables, fences, images, bold, code, raw <details>."""+ out: list[str] = []+ lists: list[tuple[str, int]] = [] # (tag, indent)+ table: list[str] = []+ para: list[str] = []+ in_code = False+ in_section = False+ skip_table = False++ def close_lists(to_indent: int = -1):+ while lists and lists[-1][1] > to_indent:+ out.append(f"</{lists.pop()[0]}>")++ def flush():+ nonlocal table, para, skip_table+ close_lists()+ if para:+ out.append("<p>" + "<br>".join(para) + "</p>")+ para = []+ if table:+ if not skip_table:+ head, *body = table+ out.append("<table><thead><tr>" + "".join(f"<th>{_inline(c.strip())}</th>" for c in head.strip().strip("|").split("|")) + "</tr></thead><tbody>"+ + "".join("<tr>" + "".join(f"<td>{_inline(c.strip())}</td>" for c in row.strip().strip("|").split("|")) + "</tr>" for row in body) + "</tbody></table>")+ table = []+ skip_table = False++ for raw in lines:+ line = raw.rstrip()+ if in_code:+ if line.startswith("```"):+ in_code = False+ out.append("</pre>")+ else:+ out.append(html.escape(line))+ continue+ if line.startswith("```"):+ flush()+ in_code = True+ out.append("<pre class='prompt'>")+ continue+ if line == _MIX_MARK:+ flush()+ out.append(_mix_bar(b))+ skip_table = True+ continue+ if line == _STEMS_MARK:+ flush()+ out.append(_stems_html(b))+ continue+ if line.startswith("<"): # details / summary / comments pass through+ flush()+ out.append(line)+ continue+ if not line.strip():+ flush()+ continue+ if line.startswith("#"):+ flush()+ level = len(line) - len(line.lstrip("#"))+ text = _inline(line[level:].strip())+ if level == 2:+ if in_section:+ out.append("</section>")+ out.append(f"<section class='card'><h2>{text}</h2>")+ in_section = True+ else:+ out.append(f"<h{level}>{text}</h{level}>")+ continue+ if line.lstrip().startswith("|"):+ if _RE_SEP.match(line.strip()):+ continue+ if para:+ flush()+ table.append(line)+ continue+ m = re.match(r"^(\s*)(?:[-*]|\d+\.)\s+(.*)$", line)+ if m:+ if table or para:+ flush()+ indent = len(m.group(1))+ tag = "ol" if re.match(r"^\s*\d+\.", line) else "ul"+ if lists and lists[-1][1] == indent:+ pass+ elif not lists or indent > lists[-1][1]:+ lists.append((tag, indent))+ out.append(f"<{tag}>")+ else:+ close_lists(indent)+ if not lists or lists[-1][1] != indent:+ lists.append((tag, indent))+ out.append(f"<{tag}>")+ out.append(f"<li>{_inline(m.group(2))}</li>")+ continue+ if table:+ flush()+ if _RE_IMG.fullmatch(line.strip()):+ flush()+ out.append(_inline(line.strip()).replace("<img ", "<img class='sb' "))+ continue+ close_lists()+ para.append(_inline(line.strip()))+ flush()+ if in_section:+ out.append("</section>")+ return "\n".join(out)+++def _mix_bar(b: dict) -> str:esc = html.escape- src = b.get("sound_sources") or {}- st = b.get("stems") or {}- if not src and not st.get("ok"):+ return "<div class='mix'>" + "".join(+ f"<div class='bar' style='flex:{m['ratio']};background:rgb({','.join(str(c) for c in LABEL_COLOR.get(m['label'], (80, 80, 80)))})' title='{esc(m['label_zh'])}'>{esc(m['label_zh'])} {m['ratio']:.0%}</div>"+ for m in b["summary"]["production_mix"]) + "</div>"+++def _stems_html(b: dict) -> str:+ if not (b.get("stems") or {}).get("ok"):return ""- parts = [f"<section class='shot'><h3 style='margin:4px 0'>{T('声音', 'Audio')}</h3>"]- if src.get("summary_zh"):- parts.append(f"<p><b>{esc(src['summary_zh'])}</b></p>")- if st.get("ok"):- for f, name in (("original.wav", T("原声", "original")), ("vocals.wav", T("人声干声", "dry voice")), ("music.wav", T("配乐 + 环境声", "music + ambience"))):- parts.append(f"<div>{name}{T(':', ': ')}<audio controls preload='none' src='stems/{f}'></audio></div>")- if (b.get("assets") or {}).get("audio_timeline") or b.get("audio", {}).get("has_audio"):- parts.append("<img class='sb' src='audio.png' onerror=\"this.remove()\">")- parts.append("</section>")- return "".join(parts)+ return "<div class='stems'>" + "".join(+ f"<div>{name}{_colon()}<audio controls preload='none' src='stems/{f}'></audio></div>"+ for f, name in (("original.wav", T("原声", "original")), ("vocals.wav", T("人声干声", "dry voice")), ("music.wav", T("配乐 + 环境声", "music + ambience")))) + "</div>"+++_CSS = """+:root{--bg:#fafaf9;--fg:#1c1917;--muted:#78716c;--card:#fff;--line:#e7e5e4;--accent:#0d9488}+@media (prefers-color-scheme:dark){:root{--bg:#1c1917;--fg:#f5f5f4;--muted:#a8a29e;--card:#292524;--line:#44403c}}+body{margin:0;padding:24px 16px;background:var(--bg);color:var(--fg);font:15px/1.6 -apple-system,"PingFang SC","Noto Sans CJK SC",sans-serif}+main{max-width:1100px;margin:auto} h1{font-size:22px} h2{font-size:18px;margin:4px 0 10px} h3{font-size:15px;margin:16px 0 6px} h4{font-size:13px;color:var(--muted);margin:10px 0 2px}+.card{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:14px 16px;margin:14px 0}+.mix{display:flex;height:30px;border-radius:6px;overflow:hidden;margin:12px 0} .bar{color:#fff;font-size:12px;padding:6px;white-space:nowrap;overflow:hidden}+img{max-width:100%;border-radius:6px} img.sb{display:block;margin:8px 0}+table{width:100%;border-collapse:collapse;font-size:13px;margin:8px 0;display:block;overflow-x:auto} th,td{border-bottom:1px solid var(--line);padding:5px 8px;text-align:left;vertical-align:top} th{color:var(--muted);font-weight:600}+td img{max-height:70px}+ul,ol{margin:4px 0;padding-left:20px} li{margin:2px 0} p{margin:6px 0}+pre.prompt{background:var(--bg);padding:10px;border-radius:6px;font-size:13px;white-space:pre-wrap;word-break:break-word}+code{background:var(--bg);padding:1px 4px;border-radius:4px;font-size:13px}+details{margin:8px 0;border:1px solid var(--line);border-radius:8px;padding:6px 12px} summary{cursor:pointer;color:var(--accent);font-weight:600}+.stems div{margin:4px 0} audio{vertical-align:middle;max-width:100%}+"""+++def html_report(b: dict) -> str:+ body = _md_to_html(markdown(b).split("\n"), b)+ return (f"<!doctype html><html lang=\"{lang()}\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">"+ f"<title>{T('拆解:', 'Breakdown: ')}{html.escape(b['source']['filename'])}</title><style>{_CSS}</style></head><body><main>\n{body}\n</main></body></html>")def write_reports(b: dict, out: Path) -> None:diff --git a/rea_video/review.py b/rea_video/review.pyindex 4864f6a..69e531e 100644--- a/rea_video/review.py+++ b/rea_video/review.py@@ -53,6 +53,10 @@ video_prompt(复刻该镜头的中文视频提示词:写清动作过程和拍摄方式(自拍/支架)、主光是什么光源、眼神光、轮廓光/背景灯、画面里可见的光源;和测量冲突时写明依据。最后在答案顶层的 aspects 里写整片:机位/场景、推测设备、整体布光、剪辑手法、视频形式。+答案顶层的 cast 写整片的角色、场景和道具(看 storyboard.jpg 和各镜截图):characters 每个主要角色一条(id 编号、name 称呼、kind person|animal|cartoon|avatar|product|other、+look 外观写到能据此再画出同一个角色、role 作用、voice 音色、shots 出场镜头号);同一个角色在不同镜头要认成同一个。scenes 每个地点一条(id、where、when、look、shots);+props 道具 / 商品 / Logo(name、note、shots);style 一句整体视觉风格与调色。+剪辑包装(tasks.packaging,有才做):- stickers:工具找到的贴纸 / 动图 / 画中画,看 image(贴纸截图)和 frame_cmd 抽的帧,在答案 packaging.stickers 里填is_overlay(true = 后期贴上去的;false = 画面本身的东西,例如 3D 里突然出现的物体)和 what(表情包 / GIF / emoji / 箭头 / 小窗里放的什么)。@@ -132,7 +136,9 @@ def build_tasks(breakdown: dict, out_dir: str) -> tuple[dict, dict]:"evidence": [], "description": "", "embedded_assets": [], "ai_edits": [],"replication": {"image_prompt": "", "video_prompt": "", "video_prompt_en": ""},"aspects": aspects.review_template()} for s in shots],- "aspects": aspects.review_template(video=True)}+ "aspects": aspects.review_template(video=True),+ "cast": {"style": "", "characters": [{"id": "A", "name": "", "kind": "", "look": "", "role": "", "voice": "", "shots": []}],+ "scenes": [{"id": "S1", "where": "", "when": "", "look": "", "shots": []}], "props": [{"name": "", "note": "", "shots": []}]}}if pk_answers:answers["packaging"] = pk_answersreturn tasks, answers@@ -223,6 +229,12 @@ def apply_answers(breakdown: dict, answers: dict, by: str | None = None) -> dictwhole = aspects.clean_answers(answers.get("aspects"), video=True)if whole:breakdown["review_aspects"] = whole+ from .entities import clean_cast++ cast = clean_cast(answers.get("cast"))+ if cast:+ cast["by"] = by+ breakdown["review_cast"] = castbreakdown.setdefault("analysis", {})["review"] = {"by": by, "shots": len(applied), "of": len(breakdown["shots"]),"time": time.strftime("%Y-%m-%d %H:%M"), "problems": problems}return {"applied": applied, "problems": problems, "before": dict(changes)}diff --git a/rea_video/vlm.py b/rea_video/vlm.pyindex 8d13e30..54dcbca 100644--- a/rea_video/vlm.py+++ b/rea_video/vlm.py@@ -236,7 +236,8 @@ WHOLE_PROMPT = """你是短视频拆解专家。完整观看并**仔细收听**每一个音效出现的时间点、类型,以及它对应画面上的什么事件。剪辑包装要拆全:字幕之外的花字、标题、章节牌、标签(含跟着物体走的标注)逐个列出时间、样式和动画;后期贴上去的表情包、GIF 动图、emoji、贴纸、画中画小窗、箭头圈注逐个列出出现/消失时间和位置(画面本身的内容不算)。-已检测到的镜头切分(秒):{shots}+角色要跨镜头认成同一个:给每个主要角色(人、动物、卡通形象、数字人、作为主角的商品)一个编号,外观写到能据此把同一个角色再画出来;场景同理(同一地点不同机位算一个场景);道具 / 商品 / Logo 单独列。+已检测到的镜头切分(秒,按顺序即镜头 #1、#2…):{shots}只返回 JSON:{{@@ -245,7 +246,7 @@ WHOLE_PROMPT = """你是短视频拆解专家。完整观看并**仔细收听**"hook": "开头 3 秒如何抓人","segments": [{{"start": 0.0, "end": 3.0, "beat": "这一段在叙事上的作用", "copy": "这一段的旁白/字幕文案", "audio": "人声/音乐/音效"}}],"narration": {{"type": "tts|human|none|mixed", "voice": "性别/年龄感/音色", "style": "语速、情绪、口癖", "language": "zh|en|...",- "lines": [{{"start": 0.0, "end": 2.0, "text": "台词/旁白原文"}}]}},+ "lines": [{{"start": 0.0, "end": 2.0, "speaker": "角色编号或 旁白", "text": "台词/旁白原文"}}]}},"music": {{"present": true, "segments": [{{"start": 0.0, "end": 10.0}}], "style": "风格", "genre": "流派", "mood": "情绪","instruments": ["主要乐器"], "bpm_estimate": 0, "has_vocals": false,"source_guess": "ai_generated|stock_library|popular_song|original|unknown", "song_guess": "若是知名歌曲写歌名,否则空",@@ -261,6 +262,12 @@ WHOLE_PROMPT = """你是短视频拆解专家。完整观看并**仔细收听**"animation": "弹出/缩放/抖动/打字机/逐字高亮/滑入/无"}}],"stickers": [{{"t0": 0.0, "t1": 1.0, "what": "表情包/GIF 动图/emoji/静态贴纸/画中画小窗/箭头圈注", "where": "画面位置","description": "贴的是什么", "animated": true}}],+ "style": "整体视觉风格与调色:画风、质感、色调、可参照的风格(如皮克斯 / 胶片感 / ins 风)",+ "characters": [{{"id": "A", "name": "称呼(角色名 / 商品名 / 主播 / 旁白者)", "kind": "person|animal|cartoon|avatar|product|other",+ "look": "外观:体型、发型或毛色、服装、配饰、标志性特征", "role": "在视频里的作用(主角 / 配角 / 被介绍的商品 / 旁白)",+ "voice": "有台词时的音色,没有留空", "shots": [1, 2]}}],+ "scenes": [{{"id": "S1", "where": "地点 / 环境", "when": "白天|夜晚|室内|不明", "look": "布景、色调、光线", "shots": [1, 2]}}],+ "props": [{{"name": "道具 / 商品 / Logo / 文件", "note": "出现在哪、起什么作用", "shots": [1]}}],"aspects": <<VIDEO_ASPECTS>>,"overall_production": "整体制作方式判断(实拍/AI生成/代码渲染/混合)与理由","warnings": []diff --git a/skills/rea-video/SKILL.md b/skills/rea-video/SKILL.mdindex d091e3e..3cb2d7b 100644--- a/skills/rea-video/SKILL.md+++ b/skills/rea-video/SKILL.md@@ -42,6 +42,7 @@ rea-video summary out/ref/breakdown.json```bashrea-video review out/ref # 写出 review_tasks.json(每镜要看的图、工具判断、优先级)和 review_answers.json(答案模板)# 读 review_tasks.json 的 instructions,逐镜看 images 里的图(priority=high 必看),把 label_probs / evidence / description / embedded_assets 填进 review_answers.json;若某镜头实为多刀合并(暗底图形与暗底口播交替时容易被合成一个长镜头),可加 split_suggestion(cuts 切点秒数 + labels 各段类别 + note),报告会在该镜头标注拆分建议,镜头边界本身不变+# 顶层 cast 填整片的角色 / 场景 / 道具(同一个角色跨镜头认成同一个,外观写到能据此复刻)和一句视觉风格;没开 VLM 时报告的「角色、场景与道具」一节全靠这里rea-video apply-review out/ref --by <你的名字> # 并入:重写 breakdown.json、report.md、report.html,打印改判了哪些镜头rea-video summary out/ref/breakdown.json # 用并入后的结果写回复```@@ -57,24 +58,25 @@ rea-video summary out/ref/breakdown.json # 用并入后的结果写回复- 打开 `shots/shot_XXX.jpg`(首、中、尾联系表)。- 必要时抽帧细看:`rea-video tiles ref.mp4 --start 12.3 --end 13.1 --every 0.1 -o out/ref/check.jpg`。- 按 `references/taxonomy.md` 的"易混对照表"逐条核对。-3. 声音按 `references/audio.md` 复核:先听 `stems/vocals.wav`(人声干声)和 `stems/music.wav`(配乐),再看 `rea-video summary` 里的"声音来源"一行(视频类型 → 人声 / 音乐 / 音效来源)。信号层面检出的音效只是**低置信候选**,音效清单以 VLM 听到的为准;没开 VLM 时要说明"轻音效可能漏检"。-4. **实拍(口播 / 桌拍 / vlog / 商品)**:`rea-video summary` 末尾按维度列出「取景 / 机位 / 打光 / 剪辑 / 形式」(`report.md`「拍法、打光与剪辑」一节,含复刻拍摄方案和器材)。+3. 角色与场景:`rea-video summary` 的「角色 / 场景」几行(`report.md`「角色、场景与道具」一节)。核对同一个角色有没有被 VLM 认成几个(逐镜描述里叫法不一致是常见问题),复刻时每个角色固定一张参考图贯穿所有生成单元;不对就在 `review_answers.json` 顶层 `cast` 里改。+4. 声音按 `references/audio.md` 复核:先听 `stems/vocals.wav`(人声干声)和 `stems/music.wav`(配乐),再看 `rea-video summary` 里的"声音来源"一行(视频类型 → 人声 / 音乐 / 音效来源)。信号层面检出的音效只是**低置信候选**,音效清单以 VLM 听到的为准;没开 VLM 时要说明"轻音效可能漏检"。+5. **实拍(口播 / 桌拍 / vlog / 商品)**:`rea-video summary` 末尾按维度列出「取景 / 机位 / 打光 / 剪辑 / 形式」(`report.md`「拍法、打光与剪辑」一节,含复刻拍摄方案和器材)。工具在画面主体上测量:有人脸用人脸,没有人脸(桌拍、商品、手)用画面里最清晰的区域,后者的景别是估算。看图时在 `review_answers.json` 每镜的 `aspects` 和顶层 `aspects` 里补像素测不出的:机位角度、自拍还是支架、主光是什么光源、眼神光、轮廓光/背景灯、画面里的光源、推测设备、视频形式。报告里测量、VLM、看图三个来源并列,不平均。注意:平台转码会压暗部,软硬和补光的测量偏保守。AI / 3D 画面也会给光影描述,但标明「不是拍摄方案」,只用于写生成提示词。-5. 真实素材按 `references/materials.md` 复核:代码模板里嵌入的截图和照片,确定性检测能找出大部分,但**暗色、半透明的背景照片会漏**。-6. 剪辑包装(`rea-video summary` 的「包装:」几行,`report.md`「剪辑包装层」一节,文件在 `packaging/`):+6. 真实素材按 `references/materials.md` 复核:代码模板里嵌入的截图和照片,确定性检测能找出大部分,但**暗色、半透明的背景照片会漏**。+7. 剪辑包装(`rea-video summary` 的「包装:」几行,`report.md`「剪辑包装层」一节,文件在 `packaging/`):- 字幕时间轴和样式是测出来的,一般可信;字体是什么要你看图补(工具只给颜色、描边、底框、字高)。- 贴纸:标了「需要看图确认」的,看 `packaging/sticker_XX.jpg` 和 `review_tasks.json` 里的 `frame_cmd`,在 `review_answers.json` 的 `packaging.stickers` 里填 `is_overlay` 和 `what`;工具漏掉的写进 `packaging.missed`。3D / 动画 / 版式画面里突然出现的物体工具不算贴纸,你看到是后期贴的再补。- 花字和标签分错类时在 `packaging.text` 里改 `kind`。- 音效「对应画面」一列是按时间就近对齐的,没开 VLM 时补出的候选(来源 `deterministic_anchored`)实测只有约四成是真音效,写成"可能"。-7. 如果你的判断和工具不同,以你的复核为准,在回复里写明理由;有价值的话,建议用户把这条视频加进评测集(仓库 `docs/dev/evaluation.md`)。+8. 如果你的判断和工具不同,以你的复核为准,在回复里写明理由;有价值的话,建议用户把这条视频加进评测集(仓库 `docs/dev/evaluation.md`)。用户指出判错或说出长期偏好时,按 `references/memory.md` 记下来(`rea-video correct` / `rea-video prefs`)。## 2. 交付给用户-按 `references/output-template.md` 回复:先一句话结论,再复刻方案(按生成单元 / 拍摄场次组织),然后分镜表、剪辑包装、声音、真实素材清单、不确定点,最后给 `report.html` 路径。不要把 breakdown.json 整段贴进对话。+按 `references/output-template.md` 回复:先一句话结论,再内容与角色(这条视频讲什么、主要角色和场景),然后复刻方案(按生成单元 / 拍摄场次组织)、分镜表、剪辑包装、声音、真实素材清单、不确定点,最后给 `report.html` 路径。不要把 breakdown.json 整段贴进对话。**报告和回复都用用户的语言。**语言的判断顺序:用户明确指定的语言(「用英文出报告」「report in Chinese」)> 用户提问所用的语言 > `rea-video memory` 里的 `lang` 偏好 > 中文。- 工具支持 `--lang zh` 和 `--lang en`:`decompose` 时就传对,报告文件(`report.html` / `report.md`)、`summary` 输出、VLM 的画面描述和提示词都会是该语言;忘了传可以在 `apply-review out/ref --lang en` 时补上(会重新生成结论和报告文字;VLM 已写好的描述和提示词保持原语言)。看图复核时,`review_answers.json` 里的 evidence / description / prompt 也用这个语言写。diff --git a/skills/rea-video/references/output-template.md b/skills/rea-video/references/output-template.mdindex 7894fff..302c6c7 100644--- a/skills/rea-video/references/output-template.md+++ b/skills/rea-video/references/output-template.md@@ -2,7 +2,7 @@## 原则-- 先给一句话结论(这条视频是怎么做出来的),再给**复刻方案**(`breakdown.json` 的 `production_plan`,报告里「复刻方案」一节),然后才是分镜表。+- 先给一句话结论(这条视频是怎么做出来的),再用两三行说内容和角色(讲什么、主要角色 / 场景 / 商品,`report.md`「角色、场景与道具」一节),再给**复刻方案**(`breakdown.json` 的 `production_plan`,报告里「复刻方案」一节),然后才是分镜表。- 复刻方案按实际制作的组织方式写,不按剪辑镜头逐个写:- AI 镜头 → **生成单元**:几个连续镜头一次生成、用哪个模型、参考素材(`@图片` 产品/人物、`@视频` 原片片段)、合并后的多镜头提示词、单元之间怎么衔接。默认引擎不支持一次多镜头时,照抄 `engine_note`,说明换模型能省几次调用。- 实拍镜头 → **拍摄场次**:哪些镜头是同一场景、同一机位,一起拍;每个场景的布光;先大景别后特写。分镜表本身仍然逐镜写细。@@ -13,12 +13,14 @@## 语言-报告语言跟 `--lang` 走(zh / en),回复语言跟用户走;两者的判断顺序见 SKILL.md「交付给用户」。下面的模板是中文版,英文回复用同样的结构:one-line verdict → remake plan → shot list → packaging → audio → material you must supply → open questions → report path。+报告语言跟 `--lang` 走(zh / en),回复语言跟用户走;两者的判断顺序见 SKILL.md「交付给用户」。下面的模板是中文版,英文回复用同样的结构:one-line verdict → content and cast → remake plan → shot list → packaging → audio → material you must supply → open questions → report path。## 回复模板(中文)**一句话结论**:混合制作——底层画面 AI 生成视频 62%、代码模板 30%、实拍 8%;全片字幕由代码叠加;引入了 2 段真实截图;女声 TTS + 110 BPM 流行 BGM,切镜卡在节拍上。+**内容与角色**:剧情短片,4 镜;主角 A「小黄」(黄色卡通小河马,粉色连体衣、斜挎粉包,全片出场)、B 男友(同款配色,#3–#4);场景 S1 白天城市街道。复刻时 A、B 各固定一张参考图贯穿所有生成单元。+**分镜表**| # | 时间 | 制作方式(置信度) | 素材来源 | 叠加层 | 关键证据 | 复刻路线 |@@ -29,7 +31,7 @@**剪辑包装**:字幕(几句、位置、颜色 / 描边 / 底框、关键词高亮、入场方式,SRT/ASS 文件路径);花字、标题、章节牌、跟随标签(时间、文字、样式、动画);贴纸 / GIF / 表情包 / 画中画(时间、位置、贴的是什么、是否循环);哪些音效卡在文字弹出或贴纸出现上。工具没测到、你看图补的写明。-**声音**:人声(TTS 还是真人、音色)/ BGM(风格、BPM、调性、来源、段落)/ 音效(时间点 → 对应画面事件)/ 混音(是否压低音乐)。+**声音**:人声(TTS 还是真人、音色,台词见报告脚本表)/ BGM(歌名猜测、风格、BPM、调性、来源与版权风险、段落)/ 音效(时间点 → 对应画面事件)/ 混音(是否压低音乐)。报告「声音」一节每一项是一张卡,照着抄即可。**需要你提供的真实素材**:镜头 #4 中部的 GitHub 页面截图……diff --git a/tests/test_report.py b/tests/test_report.pynew file mode 100644index 0000000..692a27f--- /dev/null+++ b/tests/test_report.py@@ -0,0 +1,138 @@+"""Report structure: reading order, cast / script / music cards, folded detail, and the HTML rendered from the Markdown."""+import json+import re++import pytest++from rea_video.entities import cast, clean_cast, open_questions, script+from rea_video.i18n import set_lang+from rea_video.pipeline import decompose, finalize+from rea_video.report import html_report, markdown+from rea_video.review import apply_answers, build_tasks++CAST = {"style": "扁平 UI,深色底",+ "characters": [{"id": "A", "name": "小黄", "kind": "cartoon", "look": "黄色圆滚滚的小河马,粉色连体衣,斜挎粉包", "role": "主角", "voice": "", "shots": [1, 2, 3]},+ {"id": "B", "name": "旁白", "kind": "person", "look": "", "role": "旁白", "voice": "青年男声", "shots": []},+ {"name": "", "look": "", "kind": "bogus"}],+ "scenes": [{"id": "S1", "where": "城市街道", "when": "白天", "look": "虚化街景,暖日光", "shots": [1, 2]}],+ "props": [{"name": "粉色小挎包", "note": "角色一直背着", "shots": [1, 3]}, {"note": "no name"}]}++[email protected](scope="module")+def breakdown(media, tmp_path_factory):+ out = tmp_path_factory.mktemp("rep") / "edit"+ b = decompose(media["edit"], out, use_vlm=False, ocr=False, stems=False)+ return b, out+++def _with_vlm(b: dict) -> dict:+ b = json.loads(json.dumps(b))+ b["whole_video_vlm"] = {+ "summary": "测试视频", "format": "知识讲解", "hook": "开头一张静帧", "overall_production": "代码渲染 + 静图",+ "segments": [{"start": 0, "end": 2, "beat": "铺垫", "copy": "你好", "audio": "音乐"}],+ "narration": {"type": "tts", "voice": "女声", "lines": [{"start": 0.0, "end": 1.0, "speaker": "A", "text": "你好"}, {"start": 1.0, "end": 2.0, "text": "再见"}]},+ "music": {"present": True, "style": "轻快", "genre": "pop", "mood": "开心", "instruments": ["钢琴"], "has_vocals": False,+ "song_guess": "测试歌", "source_guess": "stock_library", "ending": "fade_out"},+ "sfx": [], "ambience": "无", "mix": "人声在上", "subtitles": {"present": False}, **CAST}+ # the synthetic clip is silent; give it a measured audio layer so the voice / music cards render+ b["audio"] = {"has_audio": True, "rms_dbfs": -20.0, "peak_dbfs": -3.0, "voice": {"present": True, "ratio": 0.4, "f0_median_hz": 210.0, "gender_hint": "female"},+ "music": {"present": True, "ratio": 0.9, "start": 0.0, "end": 7.5, "tempo_bpm": 120.0, "tempo_alternatives": [60.0], "key": {"tonic": "C", "mode": "major", "confidence": 0.8},+ "section_changes": [4.0]}, "cuts_on_beat_ratio": 0.5, "cuts_on_beat_chance": 0.3, "beat_synced_edit": True}+ b["audio_plan"] = {"sfx_merged": [{"t": 1.0, "type": "pop", "description": "弹出音", "source": "vlm", "on": {"what": "文字弹出"}}], "plan": [], "mix": ""}+ return b+++def test_clean_cast_validates():+ c = clean_cast(CAST)+ assert [x["id"] for x in c["characters"]] == ["A", "B"] # the entry without name / look is dropped+ assert c["characters"][0]["shots"] == [1, 2, 3] and c["scenes"][0]["where"] == "城市街道"+ assert [p["name"] for p in c["props"]] == ["粉色小挎包"]+ assert clean_cast(None) == {} and clean_cast({"characters": [{}]}) == {}+++def test_cast_prefers_review_and_falls_back(breakdown):+ b, _ = breakdown+ set_lang("zh")+ c = cast(b)+ assert c["source"] is None and c["characters"] == []+ v = _with_vlm(b)+ assert cast(v)["source"] == "vlm" and cast(v)["style"] == "扁平 UI,深色底"+ v["review_cast"] = {"characters": [{"id": "X", "name": "复核角色", "kind": "person", "look": "看图填的", "shots": [2]}], "scenes": [], "props": [], "style": ""}+ c = cast(v)+ assert c["source"] == "review" and c["characters"][0]["name"] == "复核角色"+ assert c["props"][0]["name"] == "粉色小挎包" # review left props empty → VLM props stay+ rows = script(v)+ assert [r["speaker"] for r in rows] == ["A", ""] and rows[1]["text"] == "再见"+++def test_markdown_reading_order_and_cards(breakdown):+ b, _ = breakdown+ set_lang("zh")+ md = markdown(_with_vlm(b))+ heads = [l for l in md.splitlines() if l.startswith("## ")]+ want = ["## 内容与结构", "## 角色、场景与道具", "## 声音", "## 复刻方案", "## 分镜表", "## 不确定点", "## 附录"]+ idx = [heads.index(h) for h in want]+ assert idx == sorted(idx), heads+ assert md.index("## 内容与结构") < md.index("## 复刻方案") < md.index("### 逐镜取证")+ # cast table, scene table, props+ assert re.search(r"\| A \| 小黄 \| 卡通形象 \| 黄色圆滚滚的小河马.*\| #1、#2、#3 \|", md)+ assert "| S1 | 城市街道 | 白天 |" in md and "- 粉色小挎包(镜头 #1、#3):角色一直背着" in md+ # script and music card+ assert "**脚本**(TTS 合成,女声)" in md and "| 0.0–1.0s | A | 你好 |" in md and "| 1.0–2.0s | 旁白 | 再见 |" in md+ assert "- 歌曲:测试歌" in md and "- 风格:轻快;pop;开心;钢琴;纯音乐" in md+ # per-shot forensics folded, one per shot; no internal rule ids in prose+ assert md.count("<details><summary>#") == len(b["shots"])+ assert not re.search(r"\bR\d\d-[a-z]|\bS0\d\b|A0\d\)", md), "rule ids leaked into the report"+ assert "capsule_cinema" not in md and "code_render_spec" not in md+++def test_markdown_without_vlm_still_complete(breakdown):+ b, _ = breakdown+ set_lang("zh")+ md = markdown(b)+ assert "没有整片的内容概括" in md and "没有归纳出角色" in md and "## 不确定点" in md+ set_lang("en")+ try:+ md_en = markdown(b)+ assert "## Cast, scenes and props" in md_en and "## Open questions" in md_en and "<details><summary>#1 " in md_en+ finally:+ set_lang("zh")+++def test_html_is_rendered_from_markdown(breakdown):+ b, _ = breakdown+ set_lang("zh")+ h = html_report(_with_vlm(b))+ for tag in ("ul", "ol", "table", "section", "details", "pre"):+ assert h.count(f"<{tag}") == h.count(f"</{tag}>"), tag+ assert "<div class='mix'>" in h and h.count("<h2>") >= 7+ assert "<td>小黄</td>" in h and "<img" in h+ # no raw Markdown left behind+ body = h.split("<main>")[1]+ assert not re.search(r"^(\| |- |\*\*|#{1,3} )", body, re.M), "unrendered markdown in HTML"+ assert "<!--mix-->" not in h and "<!--stems-->" not in h+++def test_review_cast_flows_into_report(breakdown):+ b, out = breakdown+ set_lang("zh")+ b = json.loads(json.dumps(b))+ _, answers = build_tasks(b, out)+ assert "cast" in answers and answers["cast"]["characters"][0]["id"] == "A"+ answers["cast"] = CAST+ apply_answers(b, answers, by="tester")+ assert b["review_cast"]["by"] == "tester" and len(b["review_cast"]["characters"]) == 2+ b = finalize(b, out)+ md = (out / "report.md").read_text(encoding="utf-8")+ assert "| A | 小黄 |" in md+++def test_open_questions_collects_everything(breakdown):+ b, _ = breakdown+ set_lang("zh")+ b = json.loads(json.dumps(b))+ b["shots"][0]["base"]["disputed"] = "工具判 A、VLM 判 B"+ b["shots"][1]["base"]["confidence"] = 0.4+ b["sound_sources"] = {"music": {"source": "unknown", "source_zh": "来源待确认", "probs": {"a": 0.5, "b": 0.5}, "how_to_confirm": ["听歌识曲"]}}+ qs = open_questions(b)+ assert any("工具判 A" in q for q in qs) and any("#2" in q and "40%" in q for q in qs) and any("听歌识曲" in q for q in qs)