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
Tighten model answers and remake frames
june4a8dcded6a57
diff --git a/docs/capsule-cinema.md b/docs/capsule-cinema.mdindex d7cbc01..50ba745 100644--- a/docs/capsule-cinema.md+++ b/docs/capsule-cinema.md@@ -1,6 +1,6 @@# capsule-cinema 对接-`remake`、`remake-run`、`assemble`(在已安装 capsule-cinema 时)会调用 `<capsule-root>/scripts/remake_reference.py`,`capsule-draft` 会用 **capsule-cinema 自己的 Python 环境**运行 `rea_video/integrations/to_capsule.py`(读取它的 `.env`)。未安装 capsule-cinema 时,`remake` 和 `assemble` 自动回退到本地 DIY 复刻(静图推拉重建、代码重画、`mine.json` 素材拼回)。解释器按 `--python` > `$CAPSULE_CINEMA_PYTHON` > `<capsule-root>/.venv/bin/python` 的顺序找。rea-video 本身只依赖 numpy/opencv/pillow/pyyaml。+`remake`、`remake-run`、`assemble` 会调用 `<capsule-root>/scripts/remake_reference.py`,`capsule-draft` 会用 **capsule-cinema 自己的 Python 环境**运行 `rea_video/integrations/to_capsule.py`(读取它的 `.env`)。解释器按 `--python` > `$CAPSULE_CINEMA_PYTHON` > `<capsule-root>/.venv/bin/python` 的顺序找。rea-video 本身只依赖 numpy/opencv/pillow/pyyaml。```bashCC=~/code/github/capsule-cinema # capsule-cinema 仓库diff --git a/eval/RESULTS.md b/eval/RESULTS.mdindex aba8634..eb36663 100644--- a/eval/RESULTS.md+++ b/eval/RESULTS.md@@ -159,7 +159,6 @@| `code_videos.yaml` | 94.8% || `code_videos_holdout.yaml` | 100% || `particles.yaml`(3 条) | 66.7%(集合从 1 条扩到 3 条;新增的 bokeh 样本没认出,原有样本仍然判对) |-| `magic.yaml`(1 条,12fps 藏剪辑) | 100%(切点 F1 1.00,2/2;无剪断局部突变召回 2/2,共 5 个候选) |和前面记录的只用工具的分数比,除了 holdout 那一个短镜头,没有一组下降:文章视频 88.6% → 97.2%,带货 46.4% → 63.2%,口播 75.5% → 93.3%,影视混剪 15% → 15.8%。带货和影视混剪只用工具仍然不够,要靠看图复核(第 5、6 节)。diff --git a/eval/magic.yaml b/eval/magic.yamlindex fa907b3..89ac7a2 100644--- a/eval/magic.yaml+++ b/eval/magic.yaml@@ -1,13 +1,13 @@# 魔术 / 藏剪辑评测集:画面里东西凭空出现的短视频。视频不入库(eval/media/ 已 gitignore)。-# 真值来源:人工逐帧目测(2026-11-20),「存疑」:素材是平台转出的 12fps 无声 GIF,手法本身没有原片确认。+# 真值来源:人工逐帧目测。素材是平台转出的 12fps 无声 GIF,手法本身没有原片确认。# cuts:硬切 / 跳剪。sudden:没有剪断、局部一帧内出现东西的位置,box 是 x0,y0,x1,y1(0-1)。videos:- id: mukbang_hidden_editpath: eval/media/mukbang_hidden_edit.mp4label: [live_action, ai_video] # 人和场景像实拍,食物出现的方式未确认- source: 用户实测案例,X 上转发的吃播片段(4.6 秒 GIF),人工逐帧目测,存疑+ source: 平台转出的短 GIF,人工逐帧目测cuts: [1.67, 3.50]cut_tolerance: 0.1sudden:- - {t: 0.29, box: [0.25, 0.50, 0.80, 0.85]} # 螺旋薯塔从只有面的碗里出现- - {t: 2.00, box: [0.25, 0.50, 0.80, 0.85]} # 蟹排出现,旁边的薯塔不动+ - {t: 0.29, box: [0.25, 0.50, 0.80, 0.85]} # 碗里出现新的食物+ - {t: 2.00, box: [0.25, 0.50, 0.80, 0.85]} # 又出现一样食物,旁边的不动diff --git a/rea_video/cli.py b/rea_video/cli.pyindex 1f56674..0ee855b 100644--- a/rea_video/cli.py+++ b/rea_video/cli.py@@ -417,27 +417,11 @@ def cmd_capsule_draft(args) -> int:return _run_integration("to_capsule.py", _capsule_python(args.python, root), argv)-def _has_capsule_script(args) -> bool:- from .memory import capsule_root-- root = capsule_root(getattr(args, "capsule_root", None))- return (root / "scripts" / "remake_reference.py").is_file()--def cmd_assemble(args) -> int:- if getattr(args, "capsule_root", None) or _has_capsule_script(args):- pkg = Path(args.breakdown).expanduser().resolve().parent- argv = ["assemble", str(pkg), "--results", str(Path(args.results).expanduser().resolve())]- argv += ["-o", str(Path(args.out).expanduser().resolve())] if args.out else []- return _capsule_command(args, argv + ([] if args.overlays else ["--no-overlays"]))- from .remake import assemble-- bpath = Path(args.breakdown).expanduser().resolve()- out_dir = Path(args.out).expanduser().resolve() if args.out else (bpath.parent / "remake")- code_mp4 = bpath.parent / "code" / "remake.mp4"- print(assemble(bpath, Path(args.results).expanduser().resolve(), out_dir, overlays=args.overlays,- code_video=code_mp4 if code_mp4.is_file() else None))- return 0+ pkg = Path(args.breakdown).expanduser().resolve().parent+ argv = ["assemble", str(pkg), "--results", str(Path(args.results).expanduser().resolve())]+ argv += ["-o", str(Path(args.out).expanduser().resolve())] if args.out else []+ return _capsule_command(args, argv + ([] if args.overlays else ["--no-overlays"]))def cmd_tiles(args) -> int:@@ -550,33 +534,27 @@ def cmd_compare(args) -> int:def cmd_remake(args) -> int:- """The plan is rea-video's; Capsule Cinema takes it from there when installed, else local DIY remake runs."""+ """The plan is rea-video's; Capsule Cinema takes it from there (stills, clips in, assembly, status, check)."""out = Path(args.out_dir).expanduser().resolve()if not (out / "breakdown.json").is_file():raise SystemExit(U(f"rea-video: {out} 下没有 breakdown.json,先运行 decompose", f"rea-video: no breakdown.json in {out}, run decompose first"))- if getattr(args, "capsule_root", None) or _has_capsule_script(args):- if args.code:- from .code_remake import code_remake-- b = read_json(out / "breakdown.json")- if any(sh["base"]["label"] == "code_render" for sh in b["shots"]) and not (out / "code" / "remake.mp4").is_file():- try:- code_remake(out)- except (ValueError, OSError, RuntimeError) as exc:- print(f"rea-video: code-remake: {exc}", file=sys.stderr)- args.breakdown = str(out / "breakdown.json")- args.capsule_root = getattr(args, "capsule_root", None)- root = _capsule_root(args)- args.capsule_root = str(root)- rc = cmd_remake_plan(args)- if rc:- return rc- return _capsule_command(args, ["assemble", str(out)] + (["--no-overlays"] if args.no_overlays else []))- from .remake import remake-- res = remake(out, code=args.code, overlays=not args.no_overlays)- print(json.dumps(res, ensure_ascii=False, indent=2))- return 0+ if args.code:+ from .code_remake import code_remake++ b = read_json(out / "breakdown.json")+ if any(sh["base"]["label"] == "code_render" for sh in b["shots"]) and not (out / "code" / "remake.mp4").is_file():+ try:+ code_remake(out)+ except (ValueError, OSError, RuntimeError) as exc:+ print(f"rea-video: code-remake: {exc}", file=sys.stderr)+ args.breakdown = str(out / "breakdown.json")+ args.capsule_root = getattr(args, "capsule_root", None)+ root = _capsule_root(args)+ args.capsule_root = str(root)+ rc = cmd_remake_plan(args)+ if rc:+ return rc+ return _capsule_command(args, ["assemble", str(out)] + (["--no-overlays"] if args.no_overlays else []))def cmd_code_remake(args) -> int:diff --git a/rea_video/drive.py b/rea_video/drive.pyindex 702d97c..c182f2c 100644--- a/rea_video/drive.py+++ b/rea_video/drive.py@@ -22,6 +22,7 @@ from pathlib import Pathimport cv2import numpy as np+from .readings import shot_overlay_textfrom . import dancefrom .i18n import T, semi, shot_idsfrom .media import iter_frames, scaled_size, video_info@@ -70,8 +71,6 @@ def overlays(b: dict, persistent: bool = False) -> list[dict]:continueif int(c.get("samples") or 0) < MIN_SAMPLES:continue # a flicker read: printing on a dancer's clothes, caught for a frame or two as it turns past- from .pipeline import shot_overlay_text-mid = (c["t0"] + c["t1"]) / 2r = next((r for r in b.get("shots", []) if r["start"] <= mid < r["end"]), None) or {}said = shot_overlay_text(r)diff --git a/rea_video/gemini.py b/rea_video/gemini.pyindex 12d0f24..a8c74a1 100644--- a/rea_video/gemini.py+++ b/rea_video/gemini.py@@ -21,7 +21,7 @@ from . import __version__from .util import LOGAPI = "https://generativelanguage.googleapis.com"-DEFAULT_MODEL = "gemini-3.5-flash"+DEFAULT_MODEL = "gemini-3.7-flash"INLINE_MAX = 14 * 1024 * 1024 # base64 adds 33%: 14 MB raw -> ~18.7 MB body, under Gemini's 20 MB inline limitCLIP_FPS = ((30.0, 10.0), (120.0, 4.0)) # (clips up to s, frames a second); longer: Gemini's default (1)diff --git a/rea_video/generation.py b/rea_video/generation.pyindex a710caa..68eb053 100644--- a/rea_video/generation.py+++ b/rea_video/generation.py@@ -26,6 +26,7 @@ from pathlib import Pathimport yaml+from .readings import shot_descriptionfrom . import performancefrom .classify import LABEL_ZHfrom .i18n import T, join, lang, model_name, semi, shot_ids@@ -209,8 +210,6 @@ def _clips(ranges: list[list[float]], each: float) -> list[list[list[float]]]:# ---------------------------------------------------------------- one unitdef _shot_text(r: dict) -> str:"""What happens in the shot, in the report's language when the reader wrote it in both."""- from .pipeline import shot_description-p = shot_prompts(r)if lang() == "en" and p.get("video_prompt_en"):return p["video_prompt_en"]@@ -218,8 +217,6 @@ def _shot_text(r: dict) -> str:def _brief(seg: list[dict], keyframe_tag: dict[int, str]) -> list[dict]:- from .pipeline import shot_description-out, acc = [], 0.0for r in seg:act = performance.of(r)@@ -449,13 +446,21 @@ def redrawn_frame(out: Path, name: str) -> Path | None:return next((f for ext in ("png", "jpg", "jpeg", "webp") if (f := Path(out) / REDRAWN_DIR / f"{name}.{ext}").is_file()), None)+def part_frame_name(u: dict, part: int, key: str) -> str:+ """The name of a frames unit's first / last frame; a unit generated in several calls has a pair per call."""+ return f"{u['id']}_{key}" if int(u.get("calls") or 1) <= 1 else f"{u['id']}_p{part}_{key}"+++def wants_last_frame(u: dict) -> bool:+ return any(x["kind"] == "last_frame" and x["need"] != "no" for x in u.get("inputs") or [])++def source_frame_names(u: dict) -> list[str]:"""The frames this unit takes from the source, by the name a redrawn version goes under."""names = [f"shot{int(r['keyframe']):03d}" for r in u.get("refs") or [] if r.get("keyframe")]if u.get("strategy") == "frames":- names.append(f"{u['id']}_first")- if any(x["kind"] == "last_frame" and x["need"] != "no" for x in u.get("inputs") or []):- names.append(f"{u['id']}_last")+ keys = ("first", "last") if wants_last_frame(u) else ("first",)+ names += [part_frame_name(u, part, key) for part in range(1, int(u.get("calls") or 1) + 1) for key in keys]return names@@ -482,8 +487,8 @@ def checks(plan: dict, intent: dict, prompts: dict[str, str], notes: dict | Noneif spec.get("multi_ref") and not spec.get("images_stated"):add("warn", T("能力地图没写这个模型最多几张参考图,按 {n} 张排的;查到实际数后补进模型资料", "the capability map has no image limit for this model; planned for {n}, add the real one", n=UNKNOWN_IMAGES))if spec.get("exclusive") and plan.get("strategy") == "frames" and any(s.get("image") for s in intent.get("swaps") or []):- add("warn", T("当前模型在首尾帧模式下不接收额外参考图:先把替换主体画进每段首帧(remake/redrawn/<单元>_first.png)再生成",- "in first/last-frame mode this model takes no extra reference images: redraw each unit's first frame (remake/redrawn/<unit>_first.png) with the swapped subject first"))+ add("warn", T("当前模型在首尾帧模式下不接收额外参考图:先把替换主体画进每段的参考帧(存进 remake/redrawn/,文件名见各单元的提示)再生成",+ "in first/last-frame mode this model takes no extra reference images: redraw each part's reference frames with the swapped subject first (into remake/redrawn/, named in each unit's warning)"))for u in units:n_img, n_vid = len(unit_images(u)), len({r["tag"] for r in u["refs"] if r["tag"].startswith("@视频")})if spec.get("images") is not None and n_img > max(spec["images"], 0) and (n_img or spec.get("multi_ref")):diff --git a/rea_video/integrations/capsule_cinema.py b/rea_video/integrations/capsule_cinema.pyindex 33ad5bd..1421b8a 100644--- a/rea_video/integrations/capsule_cinema.py+++ b/rea_video/integrations/capsule_cinema.py@@ -12,6 +12,7 @@ import refrom datetime import datetimefrom pathlib import Path+from ..readings import shot_descriptionfrom ..classify import LABEL_ZHfrom ..i18n import T, join, semifrom ..util import fmt_time, write_json@@ -67,8 +68,6 @@ def export_capsule_analysis(b: dict, out_path: Path, keep_source_text: bool = Famix_txt = "、".join(f"{m['label_zh']} {m['ratio']:.0%}" for m in s["production_mix"])segments = []literals: list[str] = []- from ..pipeline import shot_description-for sh in shots:f = sh["features"]copy = _shot_copy(sh) if keep_source_text else ""@@ -305,7 +304,7 @@ def _unit_jobs(b: dict, bdir: Path, run_dir: Path, plan: dict, prompts: dict[strframe per shot (keyframes), the shot's first / last frame (frames) or nothing but text; the user's images first; thefinal prompt from remake/prompts.json, else the draft. Everything taken from the source has its subtitles erased."""from ..drive import scene_text- from ..generation import redrawn_frame, unit_images+ from ..generation import part_frame_name, redrawn_frame, unit_imagesspec = plan.get("spec") or {}lo, hi = int(spec.get("min") or 1), int(spec.get("max") or 15)@@ -328,7 +327,7 @@ def _unit_jobs(b: dict, bdir: Path, run_dir: Path, plan: dict, prompts: dict[strif images:params["image_paths"] = [x["path"] for x in images]if u["strategy"] == "frames":- first, last = files.get((part, "first")) or files.get((1, "first")), files.get((part, "last")) or files.get((1, "last"))+ first, last = files.get((part, "first")), files.get((part, "last"))if last:params.update(start_image_path=first, end_image_path=last)else:@@ -336,12 +335,7 @@ def _unit_jobs(b: dict, bdir: Path, run_dir: Path, plan: dict, prompts: dict[strjid = u["id"] if len(parts) == 1 else f"{u['id']}-{part}"times = [r["t"] for r in u["refs"] if r.get("keyframe") and not redrawn_frame(bdir, f"shot{int(r['keyframe']):03d}")]if u["strategy"] == "frames":- span = max(0.0, u["end"] - u["start"])- ps0 = u["start"] + span * (part - 1) / max(1, len(parts))- ps1 = u["start"] + span * part / max(1, len(parts))- pd = max(0.0, ps1 - ps0)- t_first, t_last = min(ps1, ps0 + min(0.05, pd / 4)), max(ps0, ps1 - min(0.08, pd / 4))- times += [t for name, t in ((f"{u['id']}_first", t_first), (f"{u['id']}_last", t_last)) if not redrawn_frame(bdir, name)]+ times += [t for key, t in _part_frame_times(u, part) if not redrawn_frame(bdir, part_frame_name(u, part, key))]words = list(dict.fromkeys(w for t in times for w in scene_text(b, t)))warning = T("参考帧里还有画面内文字({w}),模型可能照着生成:换成干净图,或确认有授权", "the reference frames still show text in the picture ({w}), which the model may copy: use a clean image or confirm you have the rights",w=join(words[:6])) if words else None@@ -352,12 +346,20 @@ def _unit_jobs(b: dict, bdir: Path, run_dir: Path, plan: dict, prompts: dict[strreturn jobs+def _part_frame_times(unit: dict, part: int) -> tuple[tuple[str, float], tuple[str, float]]:+ """Where one call of a frames unit takes its first and last frame from: just inside its share of the unit."""+ n = max(1, int(unit.get("calls") or 1))+ span = max(0.0, unit["end"] - unit["start"])+ a, z = unit["start"] + span * (part - 1) / n, unit["start"] + span * part / n+ return ("first", min(z, a + min(0.05, (z - a) / 4))), ("last", max(a, z - min(0.08, (z - a) / 4)))++def ref_clips(b: dict, bdir: Path, unit: dict) -> dict[tuple[int, str], str]:"""What one unit takes from the source, subtitles and laid-on text erased, written once into remake/refs/:reference clips ({(part, "@视频1"): path}), per-shot keyframes ({(1, "@图片3"): path}) and the first / last frame of- a frames unit ({(1, "first"): path, (1, "last"): path}). Files are named by span, so a re-plan never reuses a stale one."""+ a frames unit, per call ({(part, "first"): path, (part, "last"): path}). Files are named by span, so a re-plan never reuses a stale one."""from ..drive import clean_clip, clean_frame- from ..generation import redrawn_frame+ from ..generation import part_frame_name, redrawn_frame, wants_last_framed = bdir / "remake" / "refs"out = {}@@ -374,18 +376,12 @@ def ref_clips(b: dict, bdir: Path, unit: dict) -> dict[tuple[int, str], str]:clean_clip(b, r["ranges"], f)out[(r.get("part", 1), r["tag"])] = str(f.resolve())if unit.get("strategy") == "frames":- s0, s1 = unit["start"], unit["end"]- n_parts = max(1, int(unit.get("calls") or 1))- want_last = any(x["kind"] == "last_frame" and x["need"] != "no" for x in unit.get("inputs") or [])- for part in range(1, n_parts + 1):- ps0 = s0 + (s1 - s0) * (part - 1) / n_parts- ps1 = s0 + (s1 - s0) * part / n_parts- pd = max(0.0, ps1 - ps0)- for key, t in (("first", min(ps1, ps0 + min(0.05, pd / 4))), ("last", max(ps0, ps1 - min(0.08, pd / 4)))):- if key == "last" and not want_last:+ for part in range(1, max(1, int(unit.get("calls") or 1)) + 1):+ for key, t in _part_frame_times(unit, part):+ if key == "last" and not wants_last_frame(unit):continue- red = redrawn_frame(bdir, f"{unit['id']}_{key}" if n_parts == 1 else f"{unit['id']}_p{part}_{key}") or (redrawn_frame(bdir, f"{unit['id']}_{key}") if part == 1 else None)- f = red or d / f"{unit['id']}_p{part}_{key}_{t:.2f}.jpg" if n_parts > 1 else (red or d / f"{unit['id']}_{key}_{t:.2f}.jpg")+ name = part_frame_name(unit, part, key)+ f = redrawn_frame(bdir, name) or d / f"{name}_{t:.2f}.jpg"if not f.is_file():clean_frame(b, t, f)out[(part, key)] = str(f.resolve())diff --git a/rea_video/packaging.py b/rea_video/packaging.pyindex 70d8e71..cb25689 100644--- a/rea_video/packaging.py+++ b/rea_video/packaging.py@@ -21,6 +21,7 @@ Everything here is deterministic and best effort: styles and animations are measor the agent's look at the frames still settles fine typography (font family) and odd cases."""from __future__ import annotations+from .readings import shot_overlay_textfrom .i18n import LangDict, T, joinimport re@@ -1892,8 +1893,6 @@ def finalize_pack(breakdown: dict, out: Path) -> dict | None:if not pack:return Noneout = Path(out)- from .pipeline import shot_overlay_text-labels = {r["id"]: r["base"]["label"] for r in breakdown["shots"]}for c in pack.get("text_cues", []):mid = (c["t0"] + c["t1"]) / 2diff --git a/rea_video/pipeline.py b/rea_video/pipeline.pyindex 3f56917..5330422 100644--- a/rea_video/pipeline.py+++ b/rea_video/pipeline.py@@ -18,6 +18,7 @@ from .media import cut_clip, extract_frame, extract_frames, require_tools, videofrom .overlay import ocr_frames, persistent_template, shot_ocr_frames, shot_ocr_items, static_overlays, summarize_textfrom .plan import Plannerfrom .probe import provenance+from .readings import shot_description, shot_overlay_text # noqa: F401from .motion import element_crops, motion_events, palette, strip_framesfrom .shots import build_track, detect_shotsfrom .util import LOG, fmt_time, read_image, read_json, round_floats, write_json@@ -63,7 +64,7 @@ def vlm_units(records: list[dict], max_calls: int) -> list[list[dict]]:# modules that only run in finalize(): a change there needs no new decode. Everything else measures the video._FINALIZE_ONLY = {"classify.py", "report.py", "plan.py", "production.py", "entities.py", "narrative.py", "review.py", "cli.py",- "evaluate.py", "remake.py", "memory.py", "i18n.py", "visual.py", "__init__.py"}+ "evaluate.py", "remake.py", "memory.py", "i18n.py", "visual.py", "readings.py", "__init__.py"}_DECODE_FP: str | None = None@@ -622,20 +623,6 @@ def _user_real(material: dict, real: bool) -> None:material["user_corrected"] = True-def shot_description(rec: dict) -> str:- """Description of a shot's picture: an agent review overrides the VLM when non-empty."""- return ((rec.get("review") or {}).get("description") or (rec.get("vlm") or {}).get("description") or "").strip()---def shot_overlay_text(rec: dict) -> list[str] | None:- """Post-production overlay words listed by an image reader: agent review overrides VLM when given."""- rv = (rec.get("review") or {}).get("overlay_text")- if isinstance(rv, list):- return rv- vl = (rec.get("vlm") or {}).get("overlay_text")- return vl if isinstance(vl, list) else None--def visual_opinion(rec: dict) -> dict | None:"""What a model saw in the shot: the VLM answer, an agent's review (rea-video apply-review), or both averaged;with neither, the survey's look at the whole video (how this stretch was made, from the overview)."""diff --git a/rea_video/probe.py b/rea_video/probe.pyindex b565d66..2aacc56 100644--- a/rea_video/probe.py+++ b/rea_video/probe.py@@ -147,7 +147,9 @@ def provenance(info: VideoInfo) -> dict:if short in CAMERA_KEYS:hints["camera"].append(f"{short}={value}")is_aigc_key = any(a in short for a in AIGC_KEYS)- parsed = parse_aigc(value) if (is_aigc_key or (short not in FREE_TEXT_KEYS and re.search(r"\baigc\b", value, re.I))) else None+ parsed = parse_aigc(value) if is_aigc_key or re.search(r"\baigc\b", value, re.I) else None+ if parsed and not is_aigc_key and short in FREE_TEXT_KEYS and parsed["label"] not in ("1", "2", "3"):+ parsed = None # typed text that mentions AIGC; a real label in a comment tag carries a valid valueif parsed or is_aigc_key:cand = parsed or {"label": "", "meaning": T("无法解析", "could not be parsed"), "raw": value[:200]}strong = cand.get("label") in ("1", "2", "3")diff --git a/rea_video/production.py b/rea_video/production.pyindex 05ac5f8..9128b18 100644--- a/rea_video/production.py+++ b/rea_video/production.py@@ -10,6 +10,7 @@ Edit shots (cut detection) are the facts; making them is organised differently:"""from __future__ import annotations+from .readings import shot_descriptionfrom .i18n import LangDict, T, join, lang, model_name, semi, shot_idsimport json@@ -288,8 +289,6 @@ def _setups(shots: list[dict], sig: dict, thr: float, b: dict) -> list[dict]:cam = (a.get("camera") or {}).get("result") or {}support = SUPPORT_ZH.get(cam.get("support"), cam.get("support_zh") or "—")groups.setdefault((size, support), []).append(r)- from .pipeline import shot_description-light = (((sc[0].get("aspects") or {}).get("lighting") or {}).get("result") or {})desc = shot_description(sc[0])if named:diff --git a/rea_video/readings.py b/rea_video/readings.pynew file mode 100644index 0000000..4318866--- /dev/null+++ b/rea_video/readings.py@@ -0,0 +1,16 @@+"""What the image readers said about a shot: an agent review takes precedence over the VLM."""+from __future__ import annotations+++def shot_description(rec: dict) -> str:+ """Description of a shot's picture."""+ return ((rec.get("review") or {}).get("description") or (rec.get("vlm") or {}).get("description") or "").strip()+++def shot_overlay_text(rec: dict) -> list[str] | None:+ """The post-production words a reader listed; [] means it saw none, None that no reader said."""+ rv = (rec.get("review") or {}).get("overlay_text")+ if isinstance(rv, list):+ return rv+ vl = (rec.get("vlm") or {}).get("overlay_text")+ return vl if isinstance(vl, list) else Nonediff --git a/rea_video/report.py b/rea_video/report.pyindex 9914983..7d7030d 100644--- a/rea_video/report.py+++ b/rea_video/report.py@@ -11,6 +11,7 @@ import htmlimport refrom pathlib import Path+from .readings import shot_description, shot_overlay_textfrom . import aspects, entities, narrative, performance, playbookfrom .classify import LABEL_ZHfrom .i18n import LangDict, T, join, lang, semi, shot_ids@@ -949,8 +950,6 @@ def _clock(t: float) -> str:def _shotlist_md(b: dict) -> list[str]:- from .pipeline import shot_description-told = narrative.shot_roles(b)mixed = len({r["base"]["label"] for r in b["shots"]}) > 1 # one kind throughout is already said at the toprows = []@@ -977,8 +976,6 @@ def _questions_md(b: dict) -> list[str]:def _shot_detail_md(r: dict) -> list[str]:- from .pipeline import shot_description, shot_overlay_text-base = r["base"]seen, measured = list(base.get("seen") or []), list(base.get("measured") or [])L = [f"![{r['id']}]({r['assets']['sheet']})", ""]diff --git a/rea_video/stems.py b/rea_video/stems.pyindex 7cf8a84..72cf511 100644--- a/rea_video/stems.py+++ b/rea_video/stems.py@@ -176,22 +176,24 @@ def _without_effect_hits(inst: np.ndarray, effects_wav: str | Path) -> np.ndarrafx = np.frombuffer(r.stdout, np.float32)n = inst.shape[1]fx = np.pad(fx, (0, max(0, n - len(fx))))[:n]- sub = np.zeros_like(inst)- w = np.hanning(441).astype(np.float32)- w /= w.sum()- for e in hits:+ spans: list[list[int]] = []+ for e in sorted(hits, key=lambda e: e["t"]):a, z = max(0, int((e["t"] - 0.03) * SR)), min(n, int((e["t"] + e["dur"] + 0.08) * SR))if z <= a:continue+ if spans and a <= spans[-1][1]: # effects that overlap are one stretch, with one gain+ spans[-1][1] = max(spans[-1][1], z)+ else:+ spans.append([a, z])+ sub = np.zeros_like(inst)+ w = np.hanning(441).astype(np.float32)+ w /= w.sum()+ for a, z in spans:seg = fx[a:z]denom = float(np.dot(seg, seg)) + 1e-8- gate = np.zeros(z - a, np.float32)- gate[:] = 1.0- if len(gate) > len(w):- gate = np.convolve(gate, w, "same").astype(np.float32)+ gate = np.convolve(np.ones(z - a, np.float32), w, "same").astype(np.float32) if z - a > len(w) else 1.0 # 10 ms edgesfor c in range(inst.shape[0]):- gain = float(np.clip(np.dot(inst[c, a:z], seg) / denom, 0.0, 1.5))- sub[c, a:z] = np.where(gate > 0, gain * gate * seg, sub[c, a:z])+ sub[c, a:z] = float(np.clip(np.dot(inst[c, a:z], seg) / denom, 0.0, 1.5)) * gate * segreturn inst - subdiff --git a/rea_video/videomd.py b/rea_video/videomd.pyindex 0cfa13a..1cf34f3 100644--- a/rea_video/videomd.py+++ b/rea_video/videomd.py@@ -19,6 +19,7 @@ from pathlib import Pathimport yaml+from .readings import shot_descriptionfrom . import entities, narrative, performancefrom .classify import LABEL_ZHfrom .i18n import T, join@@ -110,7 +111,6 @@ def _transition_in(r: dict) -> dict:def timeline_line(r: dict, roles: dict, units: dict) -> str:- from .pipeline import shot_descriptionfrom .report import CAMERA_ZH, _layers, _origin, _routebase = r["base"]@@ -347,8 +347,6 @@ def _description(b: dict) -> str: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, whatthe shots show, the opening lines, the file's title. Empty only when none of them says anything."""- from .pipeline import shot_description-whole = _one_line((b.get("review_story") or {}).get("summary") or (b.get("whole_video_vlm") or {}).get("summary"), 600)if whole:return wholediff --git a/rea_video/vlm.py b/rea_video/vlm.pyindex 167a87a..2271c8e 100644--- a/rea_video/vlm.py+++ b/rea_video/vlm.py@@ -150,25 +150,24 @@ def _data_uri(path: Path, mime: str) -> str:def parse_json(text: str) -> dict:+ """The answer object in a model's reply: the last complete top-level one, after any reasoning or example.+ A reply cut off inside an object is an error, so the call is retried instead of keeping a fragment of it."""text = re.sub(r"<think>[\s\S]*?</think>", "", text or "", flags=re.I).strip()text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text)dec = json.JSONDecoder()+ found = Nonepos = text.find("{")while pos != -1:try:- out, _ = dec.raw_decode(text, pos)- if isinstance(out, dict):- return out+ found, end = dec.raw_decode(text, pos)+ pos = text.find("{", end)except ValueError:- pass- pos = text.find("{", pos + 1)- m = re.search(r"\{[\s\S]*\}", text)- if not m:+ if re.match(r"\{\s*\"", text[pos:]):+ raise ValueError("incomplete JSON object in VLM response") from None+ pos = text.find("{", pos + 1) # a stray brace in the prose+ if found is None:raise ValueError("no JSON object in VLM response")- out = json.loads(m.group(0))- if not isinstance(out, dict):- raise ValueError("VLM answer is not a JSON object")- return out+ return foundclass VLMClient: