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
fix: remake-run --only 接受 shot_003、生成失败时非 0 退出;capsule-cinema 路径可用 prefs 设置并在不存在时提示;找不到文件不再打印堆栈;评测汇总字幕召回为空时不崩溃
june6f0c46dab646
diff --git a/docs/capsule-cinema.md b/docs/capsule-cinema.mdindex b1824c5..98624bf 100644--- a/docs/capsule-cinema.md+++ b/docs/capsule-cinema.md@@ -22,5 +22,5 @@ rea-video assemble out/ref/breakdown.json out/ref/remake/results.json- AI 视频 / 3D / 实拍 / 数字人镜头:默认用原镜头的**首尾帧 + VLM 提示词**做 `first_last_frame` 生成(`--mode image_to_video` 只用首帧)。- 静态图推拉、静帧:不调模型,`assemble` 用测得的缩放/平移参数在本地重建。- 代码渲染、录屏镜头:默认保留原片(`keep_original`),重建请按报告中的文字轨/版式用 Remotion 实现。-- 只复刻部分镜头:`remake-run ... --only 2,5`。-- capsule-cinema 不在默认路径时,`remake-run` 也要带上和 `remake-plan` 一样的 `--capsule-root`;jobs.json 里记录的路径对不上会拒绝执行。+- 只复刻部分镜头:`remake-run ... --only 2,5`(也可以写镜头 id:`--only shot_002,shot_005`)。有镜头没生成出视频时,命令以非 0 退出,失败详情在 results.json。+- capsule-cinema 不在默认路径(`~/code/github/capsule-cinema`)时,用 `rea-video prefs capsule_root <路径>` 设一次;或者每次都带 `--capsule-root`,`remake-run` 要和 `remake-plan` 一致;jobs.json 里记录的路径对不上会拒绝执行。diff --git a/docs/cli.md b/docs/cli.mdindex 259fa03..904f7b8 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -13,6 +13,9 @@ rea-video --helpbash scripts/install_skill.sh # 可选:装 CLI 并把 skill 链接到 ~/.claude/skills、~/.codex/skills、~/.agents/skills```+手动装了 `[ocr]` 时,OCR 依赖会再装一套 `opencv-python`,和 rea-video 用的 `opencv-python-headless` 抢同一个 `cv2` 目录。装完跑一次:+`pip uninstall -y opencv-python && pip install --force-reinstall --no-deps "opencv-python-headless>=4.8,<5"`(`install_skill.sh` 会自动做)。+Claude Code 也可以按插件装 skill(CLI 仍需 `pip install`,skill 第一步会检查):```text@@ -65,7 +68,7 @@ rea-video stems ref.mp4 -o out/ref## 和 capsule-cinema 一起复刻```bash-CC=~/code/github/capsule-cinema # capsule-cinema 仓库,也可以设 CAPSULE_CINEMA_ROOT+CC=~/code/github/capsule-cinema # capsule-cinema 仓库;也可以设 CAPSULE_CINEMA_ROOT,或 rea-video prefs capsule_root $CC 设一次,之后不用再带 --capsule-rootrea-video remake-plan out/ref/breakdown.json --capsule-root $CC # AI 类镜头 → 首尾帧生成任务rea-video remake-run out/ref/remake/jobs.json # 调 capsule-cinema 生成(会计费,可先 --dry-run)rea-video assemble out/ref/breakdown.json out/ref/remake/results.json # 按原时间线拼回 + 对比片@@ -94,7 +97,7 @@ rea-video capsule-draft out/ref/breakdown.json --capsule-root $CC --capsule-name| `eval labels.yaml` | 在带标注的样本上评测准确率和切点 F1 || `capsule breakdown.json` | 导出 capsule-cinema 的视频分析 JSON || `remake-plan` / `assemble` | 生成复刻任务、拼回成片 |-| `remake-run JOBS [--dry-run] [--only] [--capsule-root]` | 用 capsule-cinema 执行复刻任务(会计费) |+| `remake-run JOBS [--dry-run] [--only 2,5\|shot_002] [--capsule-root]` | 用 capsule-cinema 执行复刻任务(会计费);有镜头没生成出视频时退出码非 0 || `capsule-draft breakdown.json` | 生成 capsule-cinema 胶囊草稿 |## 工作流(设计目标;目前完成到拆解和 AI 镜头复刻)diff --git a/rea_video/cli.py b/rea_video/cli.pyindex 4d5a0b5..148a701 100644--- a/rea_video/cli.py+++ b/rea_video/cli.py@@ -12,7 +12,6 @@ from .i18n import LANGS, T, set_langfrom .classify import LABELSfrom .vlm import vlm_note-DEFAULT_CAPSULE_ROOT = os.getenv("CAPSULE_CINEMA_ROOT", str(Path.home() / "code/github/capsule-cinema"))def _env(args) -> None:@@ -111,6 +110,8 @@ def cmd_apply_review(args) -> int:(":" + ", ".join(f"{i} {a}→{c}" for i, a, c in changed) if changed else ""))print(f"结论: {b['summary']['verdict']}")print(f"VLM: {b['summary']['vlm']}")+ if not log["applied"] and not log["problems"]:+ print("答案文件里没有可并入的镜头(先按 review_tasks.md 填 review_answers.json)")return 0 if log["applied"] else 1@@ -154,11 +155,22 @@ def cmd_capsule(args) -> int:return 0+def _capsule_root(args, check: bool = True) -> Path:+ from .memory import capsule_root++ root = capsule_root(args.capsule_root)+ if check and not root.is_dir():+ raise SystemExit(T(f"找不到 capsule-cinema 仓库:{root}。用 --capsule-root 指定,或 rea-video prefs capsule_root <路径> 设成默认",+ f"capsule-cinema repo not found: {root}. Pass --capsule-root, or set it once with: rea-video prefs capsule_root <path>"))+ return root++def cmd_remake_plan(args) -> int:from .integrations.capsule_cinema import build_remake_jobsbdir = Path(args.breakdown).parent- jobs = build_remake_jobs(read_json(Path(args.breakdown)), bdir, capsule_root=Path(args.capsule_root),+ root = _capsule_root(args)+ jobs = build_remake_jobs(read_json(Path(args.breakdown)), bdir, capsule_root=root,engine=args.engine, # None: keep the engine chosen at decompose timemode=args.mode, labels=args.labels.split(",") if args.labels else None)print(jobs)@@ -183,7 +195,7 @@ def _run_integration(script: str, python: str, argv: list[str]) -> int:def cmd_remake_run(args) -> int:jobs = Path(args.jobs).expanduser().resolve()# capsule-root 只认命令行(jobs.json 可能是别人给的,不能让它决定跑哪个解释器、import 哪里的代码)- root = Path(args.capsule_root).expanduser().resolve()+ root = _capsule_root(args, check=not args.dry_run)argv = ["--jobs", str(jobs), "--capsule-root", str(root)] + (["--only", args.only] if args.only else []) + (["--dry-run"] if args.dry_run else [])# 试跑不调用 capsule-cinema,用当前解释器即可python = sys.executable if args.dry_run and not args.python else _capsule_python(args.python, root)@@ -191,12 +203,13 @@ def cmd_remake_run(args) -> int:def cmd_capsule_draft(args) -> int:- argv = ["--breakdown", str(Path(args.breakdown).expanduser().resolve()), "--capsule-root", args.capsule_root]+ root = _capsule_root(args)+ argv = ["--breakdown", str(Path(args.breakdown).expanduser().resolve()), "--capsule-root", str(root)]argv += ["--capsule-name", args.capsule_name] if args.capsule_name else []argv += ["--capsule-display-name", args.capsule_display_name] if args.capsule_display_name else []argv += ["--write-capsule"] if args.write_capsule else []argv += ["--overwrite-capsule"] if args.overwrite_capsule else []- return _run_integration("to_capsule.py", _capsule_python(args.python, Path(args.capsule_root)), argv)+ return _run_integration("to_capsule.py", _capsule_python(args.python, root), argv)def cmd_assemble(args) -> int:@@ -414,15 +427,15 @@ def main(argv: list[str] | None = None) -> int:r = sub.add_parser("remake-plan", help="为 AI 类镜头生成 capsule-cinema 复刻任务")r.add_argument("breakdown")- r.add_argument("--capsule-root", default=DEFAULT_CAPSULE_ROOT)+ r.add_argument("--capsule-root", help="capsule-cinema 仓库;默认 $CAPSULE_CINEMA_ROOT、prefs capsule_root,再退到 ~/code/github/capsule-cinema")r.add_argument("--engine", help="换用另一个视频引擎;默认沿用拆解时的引擎")r.add_argument("--mode", default="first_last_frame", choices=["first_last_frame", "image_to_video", "text_to_video"])- r.add_argument("--labels", default="", help="只复刻这些底层类别(逗号分隔),默认 ai_video,cg_3d,live_action,avatar")+ r.add_argument("--labels", default="", help="只复刻这些底层类别(逗号分隔),默认 ai_video,cg_3d,live_action,avatar,anim_2d,stop_motion")r.set_defaults(func=cmd_remake_plan)rr = sub.add_parser("remake-run", help="用 capsule-cinema 执行 remake-plan 生成的任务(会计费,先 --dry-run)")rr.add_argument("jobs", help="remake-plan 输出的 jobs.json")- rr.add_argument("--capsule-root", default=DEFAULT_CAPSULE_ROOT, help="须与 remake-plan 时一致")+ rr.add_argument("--capsule-root", help="须与 remake-plan 时一致;默认同 remake-plan")rr.add_argument("--dry-run", action="store_true", help="只列出任务和参数,不调用模型")rr.add_argument("--only", default="", help="只跑这些镜头(逗号分隔)")rr.add_argument("--python", help="capsule-cinema 的 Python;默认 $CAPSULE_CINEMA_PYTHON 或 <capsule-root>/.venv/bin/python")@@ -430,7 +443,7 @@ def main(argv: list[str] | None = None) -> int:cd = sub.add_parser("capsule-draft", help="用拆解结果生成 capsule-cinema 胶囊草稿")cd.add_argument("breakdown")- cd.add_argument("--capsule-root", default=DEFAULT_CAPSULE_ROOT)+ cd.add_argument("--capsule-root", help="capsule-cinema 仓库;默认 $CAPSULE_CINEMA_ROOT、prefs capsule_root,再退到 ~/code/github/capsule-cinema")cd.add_argument("--capsule-name", default="")cd.add_argument("--capsule-display-name", default="")cd.add_argument("--write-capsule", action="store_true", help="落盘到 capsule-cinema 的 capsules/")@@ -512,6 +525,11 @@ def main(argv: list[str] | None = None) -> int:if args.verbose:raisereturn 2+ except FileNotFoundError as exc: # wrong path to a video / breakdown.json / answers file+ if args.verbose:+ raise+ print(f"rea-video: " + T(f"找不到文件:{exc.filename}", f"file not found: {exc.filename}"), file=sys.stderr)+ return 2if __name__ == "__main__":diff --git a/rea_video/evaluate.py b/rea_video/evaluate.pyindex c7654f2..738ce53 100644--- a/rea_video/evaluate.py+++ b/rea_video/evaluate.py@@ -12,7 +12,9 @@ from .util import LOG, read_json, round_floats, write_jsondef _expand(path: str) -> str:- root = os.getenv("CAPSULE_CINEMA_ROOT", str(Path.home() / "code/github/capsule-cinema"))+ from .memory import capsule_root++ root = str(capsule_root())p = os.path.expanduser(path.replace("${CAPSULE}", root))if not os.path.isabs(p): # relative paths are relative to the repo rootp = str(Path(__file__).resolve().parents[1] / p)@@ -305,8 +307,9 @@ def evaluate(labels_path: Path, out: Path, use_vlm: bool = False, ocr: bool = Trtot = sum(x["truth"] for x in subs)summary["packaging"] = {"videos": len(packs), "subtitle_lines": tot,- "subtitle_recall": round(sum(x["recall"] * x["truth"] for x in subs) / tot, 3) if tot else None,- "subtitle_precision_mean": round(sum(x["precision"] or 0 for x in subs) / len(subs), 3),+ "subtitle_recall": round(sum((x["recall"] or 0) * x["truth"] for x in subs) / tot, 3) if tot else None,+ "subtitle_precision_mean": (round(sum(x["precision"] for x in precs) / len(precs), 3)+ if (precs := [x for x in subs if x["precision"] is not None]) else None),"start_err_median_s": {r["id"]: r["packaging"]["subtitles"]["start_err_median_s"] for r in rows if r.get("packaging")},"end_err_median_s": {r["id"]: r["packaging"]["subtitles"]["end_err_median_s"] for r in rows if r.get("packaging")},"other_text_found": f"{sum(p_[k]['found'] for p_ in packs for k in ('titles', 'cards', 'labels', 'stickers') if k in p_)}/"diff --git a/rea_video/integrations/run_remake.py b/rea_video/integrations/run_remake.pyindex f860f87..37361c3 100644--- a/rea_video/integrations/run_remake.py+++ b/rea_video/integrations/run_remake.py@@ -7,6 +7,7 @@ from __future__ import annotationsimport argparseimport json+import reimport sysimport timefrom pathlib import Path@@ -32,14 +33,22 @@ def _video_path(res) -> str | None:def main() -> None:ap = argparse.ArgumentParser()ap.add_argument("--jobs", required=True)- ap.add_argument("--only", default="", help="comma-separated shot indices")+ ap.add_argument("--only", default="", help="comma-separated shots: 3,5 or shot_003,shot_005")ap.add_argument("--capsule-root", required=True)ap.add_argument("--dry-run", action="store_true")args = ap.parse_args()jobs_path = Path(args.jobs).expanduser().resolve()spec = json.loads(jobs_path.read_text(encoding="utf-8"))- only = {int(x) for x in args.only.split(",") if x.strip()}+ only = set()+ for x in args.only.split(","):+ x = x.strip()+ if not x:+ continue+ m = re.fullmatch(r"(?:shot_?)?0*(\d+)", x, re.I)+ if not m:+ sys.exit(f"--only 看不懂 {x!r}:写镜头序号(3)或镜头 id(shot_003),逗号分隔")+ only.add(int(m.group(1)))results_path = jobs_path.with_name("results.json")results = json.loads(results_path.read_text(encoding="utf-8")) if results_path.is_file() else {"results": {}}@@ -54,6 +63,9 @@ def main() -> None:sys.exit(f"shot {j.get('shot')}: output_dir 不在 {out_root} 下,拒绝执行")todo = [j for j in spec["jobs"] if j["executor"] == "capsule_cinema" and (not only or j["shot"] in only)]+ if only and not todo:+ have = sorted(j["shot"] for j in spec["jobs"] if j["executor"] == "capsule_cinema")+ sys.exit(f"--only {args.only} 里没有需要生成的镜头;可生成的镜头序号:{have}")print(f"{len(todo)} generation job(s); run dir {spec['run_dir']}")if args.dry_run:for j in todo:@@ -70,6 +82,7 @@ def main() -> None:from custom_tools.video_generation.video_generation_tool import UniversalVideoGenerationTool # noqa: E402tool = UniversalVideoGenerationTool()+ failed = []for j in todo:Path(j["params"]["output_dir"]).mkdir(parents=True, exist_ok=True)t0 = time.time()@@ -83,7 +96,11 @@ def main() -> None:"seconds": round(time.time() - t0, 1), "trim_to": j["trim_to"]}results_path.write_text(json.dumps(results, ensure_ascii=False, indent=2, default=str), encoding="utf-8")print(f" -> {video or res}", flush=True)+ if not video:+ failed.append(str(j["shot"]))print(f"results: {results_path}")+ if failed:+ sys.exit(f"{len(failed)}/{len(todo)} 个镜头没生成出视频:{', '.join(failed)}(详情见 results.json)")if __name__ == "__main__":diff --git a/rea_video/memory.py b/rea_video/memory.pyindex efc0c99..42c24c2 100644--- a/rea_video/memory.py+++ b/rea_video/memory.py@@ -28,6 +28,7 @@ PREF_KEYS = {"stems": "decompose 是否默认做人声/配乐分离:on / off","reviewer": "apply-review 默认的复核者名字","ocr_lang": "字幕/花字 OCR 的语言:zh(中英,默认)/ ja(日文,首次使用自动下载约 10 MB 识别模型)",+ "capsule_root": "capsule-cinema 仓库位置(remake-plan / remake-run / capsule-draft 的 --capsule-root;也可设 $CAPSULE_CINEMA_ROOT)","lang": "报告和结论的语言:zh(默认)/ en;agent 应按用户提问的语言选,用户明确指定时以指定为准",}ON_OFF = ("on", "off")@@ -59,7 +60,7 @@ def set_pref(key: str, value: str | None) -> dict:raise ValueError(f"{key} 只能是 on / off")if value is not None and key == "ocr_lang" and value not in OCR_LANGS:raise ValueError(f"ocr_lang 只能是 {' / '.join(OCR_LANGS)}")- if value is not None and key == "env_file":+ if value is not None and key in ("env_file", "capsule_root"):value = str(Path(value).expanduser().resolve())prefs = load_prefs()if value is None:@@ -93,6 +94,12 @@ def pref(key: str, default=None):return load_prefs().get(key, default)+def capsule_root(explicit: str | None = None) -> Path:+ """capsule-cinema 仓库:命令行 > $CAPSULE_CINEMA_ROOT > prefs capsule_root > ~/code/github/capsule-cinema。"""+ raw = explicit or os.getenv("CAPSULE_CINEMA_ROOT") or pref("capsule_root") or str(Path.home() / "code/github/capsule-cinema")+ return Path(raw).expanduser().resolve()++# ---------------- corrections ----------------------------------------------------------------------def load_corrections() -> list[dict]:diff --git a/skills/rea-video/references/memory.md b/skills/rea-video/references/memory.mdindex a3dcdeb..fa9246a 100644--- a/skills/rea-video/references/memory.md+++ b/skills/rea-video/references/memory.md@@ -3,5 +3,5 @@- 用户指出某个镜头判错("这是定格动画不是 AI"、"这段是我自己拍的素材"):运行`rea-video correct out/ref --shots 3,5 --label still_motion --note "<用户原话>"`(也可用 `--start/--end` 指定时间段,`--shots all` 表示整条;真实素材用 `--real yes|no`)。这会立刻改结论和报告,并记入 `~/.rea-video/corrections.jsonl`;以后拆同一个文件会自动套用,同类镜头会在复核任务里提示。-- 用户说出长期偏好:能对应参数的用 `rea-video prefs engine kling2.1`、`prefs vlm on`、`prefs env_file <路径>`、`prefs reviewer <名字>`;其余的用 `rea-video prefs --note "报告尽量短,重点写复刻方案"` 记下,下次 `rea-video memory` 会显示,按它调整回复。+- 用户说出长期偏好:能对应参数的用 `rea-video prefs engine kling2.1`、`prefs vlm on`、`prefs env_file <路径>`、`prefs reviewer <名字>`、`prefs capsule_root <capsule-cinema 路径>`;其余的用 `rea-video prefs --note "报告尽量短,重点写复刻方案"` 记下,下次 `rea-video memory` 会显示,按它调整回复。- 只记用户明确说的,不要把你自己的猜测写成纠正。纠正不会自动改分类权重;积累到几条以后,用 `rea-video memory --export-labels eval/user_labels.yaml` 导出成评测样本,再按开发约定评测、改规则(仓库 `docs/dev/evaluation.md`)。diff --git a/tests/test_security.py b/tests/test_security.pyindex f27c863..9b6e43a 100644--- a/tests/test_security.py+++ b/tests/test_security.py@@ -34,9 +34,11 @@ def test_cwd_env_is_not_loaded(tmp_path, monkeypatch):assert "REA_TEST_FROM_CWD" not in os.environ-def _run_remake(jobs: Path, root: Path) -> subprocess.CompletedProcess:- script = Path(__file__).resolve().parent.parent / "rea_video/integrations/run_remake.py"- return subprocess.run([sys.executable, str(script), "--jobs", str(jobs), "--capsule-root", str(root), "--dry-run"],+RUN_REMAKE = Path(__file__).resolve().parent.parent / "rea_video/integrations/run_remake.py"+++def _run_remake(jobs: Path, root: Path, *extra: str) -> subprocess.CompletedProcess:+ return subprocess.run([sys.executable, str(RUN_REMAKE), "--jobs", str(jobs), "--capsule-root", str(root), "--dry-run", *extra],capture_output=True, text=True)@@ -64,3 +66,17 @@ def test_face_model_checksum_rejects_tampered_download(tmp_path, monkeypatch):monkeypatch.setattr(faces.urllib.request, "urlretrieve", lambda url, dst: open(dst, "wb").write(b"evil"))assert faces._ensure_model() is Noneassert list(tmp_path.iterdir()) == []+++def test_run_remake_only_accepts_shot_ids(tmp_path):+ root = tmp_path / "capsule"+ jobs_list = [{"executor": "capsule_cinema", "shot": i, "label": "ai_video",+ "params": {"prompt": f"p{i}", "output_dir": str(root / f"output/{i}")}} for i in (1, 3)]+ jobs = tmp_path / "jobs.json"+ jobs.write_text(json.dumps({"capsule_root": str(root), "run_dir": "r", "jobs": jobs_list}))+ for only in ("3", "shot_003", "SHOT_3"):+ r = _run_remake(jobs, root, "--only", only)+ assert r.returncode == 0 and r.stdout.startswith("1 generation job") and '"p3"' in r.stdout, (only, r.stderr)+ for bad in ("abc", "7"):+ r = _run_remake(jobs, root, "--only", bad)+ assert r.returncode != 0 and "--only" in r.stderr