Skip to content

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 格式输出。

Hand remakes to Capsule Cinema and keep packages portable

june865888a1ef43
diff --git a/docs/cli.md b/docs/cli.md
index db499c7..4b82260 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -81,9 +81,9 @@ rea-video stems ref.mp4 -o out/ref
```bash
CC=~/code/github/capsule-cinema # capsule-cinema 仓库;也可以设 CAPSULE_CINEMA_ROOT,或 rea-video prefs capsule_root $CC 设一次,之后不用再带 --capsule-root
rea-video plan out/ref --model seedance-2.5 # 按 remake/intent.yaml 和模型出复刻方案(报告第二部分)并检查
-rea-video remake-plan out/ref/breakdown.json --capsule-root $CC # 方案里的生成单元 → 生成任务(检查有错误时不出)
-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 # 按原时间线拼回 + 对比片;加 --overlays 把字幕和花字叠回换掉的镜头
+rea-video remake-plan out/ref/breakdown.json --capsule-root $CC # 方案里的生成单元 → 生成任务和交接文件(检查有错误时不出)
+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 # 转交 capsule-cinema 拼回并验收;加 --overlays 把字幕和花字叠回换掉的镜头
rea-video capsule-draft out/ref/breakdown.json --capsule-root $CC --capsule-name my_remake
```
@@ -120,8 +120,9 @@ rea-video capsule-draft out/ref/breakdown.json --capsule-root $CC --capsule-name
| `capsule breakdown.json` | 导出 capsule-cinema 的视频分析 JSON |
| `models [ID]` | 列出能力地图里的生成模型;带 id 时打印这个模型的提示词写法和关键帧要求(`models keyframes` 是关键帧通用做法);`~/.rea-video/capabilities/models/*.yaml` 里补充的模型也会列出 |
| `plan OUT_DIR [--model ID] [--generate ai\|all]` | 按复刻意图 `remake/intent.yaml`(模型、整条重做还是只做 AI 镜头、换什么)出报告第二部分:生成单元、每次喂什么、提示词草稿和方案检查;`remake/prompts.json` 里按模型写好的最终提示词会做格式检查;拆解结果不变 |
-| `remake-plan` / `assemble` | 把方案里的生成单元写成任务、拼回成片 |
-| `remake-run JOBS [--dry-run] [--only G2\|2,5\|shot_002] [--capsule-root]` | 用 capsule-cinema 执行复刻任务(会计费);有任务没生成出视频时退出码非 0 |
+| `remake-plan` | 把方案里的生成单元写成任务和交接文件 |
+| `remake` / `assemble` | 转交 capsule-cinema 拼回成片并验收 |
+| `remake-run JOBS [--dry-run] [--only G2\|2,5\|shot_002] [--capsule-root]` | 转交 capsule-cinema 执行复刻任务(会计费);有任务没生成出视频时退出码非 0 |
| `capsule-draft breakdown.json` | 生成 capsule-cinema 胶囊草稿 |
## 工作流(设计目标;目前完成到拆解和 AI 镜头复刻)
@@ -153,3 +154,5 @@ Ingest ─► Decompose ─► Video IR ─► Plan ─► Reconstruct ─► Ve
- **adapt(创意改编)**:保留原片"为什么有效"的关系,比如钩子、揭示、节奏,内容按新主题重写。
两种模式可以按层混用。例如节奏和运镜走 fidelity,人物和文案走 adapt。
+
+`rea-video clean-paths <dir> [--apply]`:清掉旧拆解包里的本机路径,方便分享;默认只报告。生成任务等运行时还要用的路径会保留并列出。
diff --git a/pyproject.toml b/pyproject.toml
index 63a6712..f5e77dc 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -14,7 +14,7 @@ dependencies = [
"opencv-python-headless>=4.8,<5",
"Pillow>=9.0",
"PyYAML>=6.0",
- "videomd>=1.1", # VIDEO.md 拆片包的校验和读取(https://github.com/videomd/videomd)
+ "videomd>=1.2", # VIDEO.md 拆片包的校验和读取(https://github.com/videomd/videomd)
"onnxruntime>=1.16", # 人声/配乐/音效分离(UVR MDX-Net 约 67 MB + BandIt v2 约 149 MB,首次运行自动下载)
]
diff --git a/rea_video/clean_paths.py b/rea_video/clean_paths.py
new file mode 100644
index 0000000..0c4473b
--- /dev/null
+++ b/rea_video/clean_paths.py
@@ -0,0 +1,127 @@
+"""Take this machine's paths out of breakdown packages written before packages became portable.
+
+Report by default; `apply=True` rewrites. The source video stays findable through $REA_VIDEO_HOME/sources.json.
+Paths a later step still opens (the user's swap images, remake/ run files) are kept and listed: do not share those as is.
+"""
+from __future__ import annotations
+
+import json
+import os
+import shlex
+from pathlib import Path
+from typing import Any
+
+from .util import BREAKDOWN, _portable_breakdown, _sources_file, _source_key, dumps_rows
+
+TEXT = {".json", ".md", ".html", ".txt", ".vtt", ".yaml", ".yml", ".csv", ".ass", ".srt", ".jsonl"}
+
+
+def _command(cmd: str) -> str:
+ """A `rea-video tiles` command that runs from the package root."""
+ try:
+ t = shlex.split(cmd)
+ except ValueError:
+ return cmd
+ if t[:2] != ["rea-video", "tiles"] or len(t) < 3:
+ return cmd
+ t[2] = "."
+ if "-o" in t[:-1]:
+ t[t.index("-o") + 1] = Path(t[t.index("-o") + 1]).name
+ return " ".join(x if "{" in x else shlex.quote(x) for x in t)
+
+
+def _clean_review(d: dict) -> dict:
+ d = dict(d)
+ if d.get("video"):
+ d["video"] = Path(str(d["video"])).name
+ if d.get("zoom_cmd"):
+ d["zoom_cmd"], d["zoom_cmd_cwd"] = _command(d["zoom_cmd"]), "package root"
+ if isinstance(d.get("shots"), list):
+ d["shots"] = [{**s, "zoom_cmd": _command(s["zoom_cmd"])} if isinstance(s, dict) and s.get("zoom_cmd") else s for s in d["shots"]]
+ pack = d.get("packaging")
+ if isinstance(pack, dict) and isinstance(pack.get("stickers"), list):
+ d["packaging"] = {**pack, "stickers": [{**s, "frame_cmd": _command(s["frame_cmd"])} if isinstance(s, dict) and s.get("frame_cmd") else s
+ for s in pack["stickers"]]}
+ return d
+
+
+def _clean_named(d: dict, *keys: str) -> dict:
+ d = dict(d)
+ for k in keys:
+ if k == "source.path" and isinstance(d.get("source"), dict) and d["source"].get("path"):
+ d["source"] = {**d["source"], "path": Path(str(d["source"]["path"])).name}
+ elif k == "video" and d.get("video"):
+ d["video"] = Path(str(d["video"])).name
+ return d
+
+
+def _dump(data: Any, old: str, rows: bool) -> str:
+ if rows:
+ return dumps_rows(data)
+ if "\n" not in old.strip():
+ return json.dumps(data, ensure_ascii=False, separators=(",", ":")) + "\n"
+ return json.dumps(data, ensure_ascii=False, indent=2) + "\n"
+
+
+def _replace(path: Path, text: str) -> None:
+ tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")
+ tmp.write_text(text, encoding="utf-8")
+ tmp.replace(path)
+
+
+def _remembered(src: dict) -> bool:
+ try:
+ return bool(json.loads(_sources_file().read_text(encoding="utf-8")).get(_source_key(src)))
+ except (OSError, ValueError):
+ return False
+
+
+def clean_package(root: Path, home: str, apply: bool = False) -> dict:
+ root = Path(root)
+ p = root / BREAKDOWN
+ old = p.read_text(encoding="utf-8")
+ b = json.loads(old)
+ src = b.get("source") or {}
+ res: dict[str, Any] = {"package": str(root), "cleaned": [], "kept": [], "error": None}
+ source_is_local = Path(str(src.get("path") or "")).is_absolute()
+ jobs: list[tuple[Path, str, Any, bool]] = []
+ if source_is_local or (isinstance(b.get("stems"), dict) and Path(str(b["stems"].get("effects") or "")).is_absolute()):
+ res["cleaned"].append(BREAKDOWN)
+ if apply:
+ new = _portable_breakdown(b, root) # also records where the video is
+ if source_is_local and Path(src["path"]).is_file() and not _remembered(src):
+ res["error"] = f"could not record the source video in {_sources_file()}; package left as it was"
+ res["cleaned"] = []
+ return res
+ jobs.append((p, old, new, False))
+ for rel, fix, rows in (("review_tasks.json", _clean_review, True),
+ ("frames/scenes.json", lambda d: _clean_named(d, "video"), False),
+ ("survey/survey.json", lambda d: _clean_named(d, "source.path"), False),
+ ("survey/timeline.json", lambda d: _clean_named(d, "source.path"), False)):
+ f = root / rel
+ if not f.is_file():
+ continue
+ text = f.read_text(encoding="utf-8")
+ if home not in text:
+ continue
+ res["cleaned"].append(rel)
+ if apply:
+ jobs.append((f, text, fix(json.loads(text)), rows))
+ for f, text, data, rows in jobs:
+ _replace(f, _dump(data, text, rows))
+ for f in sorted(root.rglob("*")):
+ if f.is_file() and f.suffix.lower() in TEXT:
+ rel = str(f.relative_to(root))
+ try:
+ has = home in f.read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError):
+ continue
+ if has and (apply or rel not in res["cleaned"]):
+ res["kept"].append(rel)
+ return res
+
+
+def clean_paths(start: Path, apply: bool = False, home: str | None = None) -> list[dict]:
+ home = home or str(Path.home())
+ return [clean_package(f.parent, home, apply) for f in sorted(Path(start).expanduser().resolve().rglob(BREAKDOWN))
+ if (f.parent / "VIDEO.md").is_file()]
diff --git a/rea_video/cli.py b/rea_video/cli.py
index 2c9bd3c..6473912 100644
--- a/rea_video/cli.py
+++ b/rea_video/cli.py
@@ -282,6 +282,25 @@ def cmd_videomd(args) -> int:
return 0
+def cmd_clean_paths(args) -> int:
+ from .clean_paths import clean_paths
+
+ rows = clean_paths(Path(args.dir), apply=args.apply)
+ changed = [r for r in rows if r["cleaned"]]
+ kept = [r for r in rows if r["kept"]]
+ for r in changed:
+ print(f"{'cleaned' if args.apply else 'would clean'} {r['package']}: {', '.join(r['cleaned'])}")
+ for r in kept:
+ print(f"still has local paths {r['package']}: {', '.join(r['kept'])}")
+ for r in rows:
+ if r["error"]:
+ print(f"failed {r['package']}: {r['error']}", file=sys.stderr)
+ print(T("{n} 个包,{c} 个{v},{k} 个仍含运行时要用的本机路径(分享前别带上这些文件)",
+ "{n} packages, {c} {v}, {k} still hold local paths a later step needs (leave those files out when sharing)",
+ n=len(rows), c=len(changed), v=T("已清理", "cleaned") if args.apply else T("待清理(加 --apply 执行)", "to clean (add --apply)"), k=len(kept)))
+ return 1 if any(r["error"] for r in rows) else 0
+
+
def cmd_pdf(args) -> int:
from .pdf import write_pdf
@@ -341,14 +360,26 @@ def _run_integration(script: str, python: str, argv: list[str]) -> int:
return subprocess.call([python, str(path), *argv])
+def _capsule_command(args, argv: list[str]) -> int:
+ """Generation, assembly and checks belong to Capsule Cinema: run its command in its own environment."""
+ import subprocess
+
+ from .memory import capsule_root
+
+ # capsule-root 只认命令行和用户配置(jobs.json 可能是别人给的,不能让它决定跑哪个解释器、import 哪里的代码)
+ root = capsule_root(getattr(args, "capsule_root", None))
+ script = root / "scripts" / "remake_reference.py"
+ if not script.is_file():
+ raise SystemExit(T("生成、拼接和验收由 Capsule Cinema 负责,但没找到它:{r}。安装 https://github.com/JuneYaooo/capsule-cinema ,"
+ "再用 --capsule-root 指定,或运行 rea-video prefs capsule_root <路径>",
+ "Capsule Cinema does the generation, assembly and checks, but it was not found at {r}. Install "
+ "https://github.com/JuneYaooo/capsule-cinema , then pass --capsule-root or run: rea-video prefs capsule_root <path>", r=root))
+ return subprocess.call([_capsule_python(getattr(args, "python", None), root), str(script), *argv], cwd=root)
+
+
def cmd_remake_run(args) -> int:
jobs = Path(args.jobs).expanduser().resolve()
- # capsule-root 只认命令行(jobs.json 可能是别人给的,不能让它决定跑哪个解释器、import 哪里的代码)
- 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)
- return _run_integration("run_remake.py", python, argv)
+ return _capsule_command(args, ["run", str(jobs)] + (["--only", args.only] if args.only else []) + (["--dry-run"] if args.dry_run else []))
def cmd_capsule_draft(args) -> int:
@@ -362,10 +393,10 @@ def cmd_capsule_draft(args) -> int:
def cmd_assemble(args) -> int:
- from .remake import assemble
-
- print(assemble(Path(args.breakdown), Path(args.results), Path(args.out) if args.out else None, overlays=args.overlays))
- 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:
@@ -379,6 +410,8 @@ def cmd_tiles(args) -> int:
# bad numbers used to die deep inside numpy / PIL with a traceback, or silently print an empty result
if args.every <= 0:
raise SystemExit("rea-video: --every 必须大于 0(两次抽帧的间隔秒数)")
+ if Path(args.video).is_dir() and (Path(args.video) / "breakdown.json").is_file():
+ args.video = read_json(Path(args.video) / "breakdown.json")["source"]["path"] # a package: its source video
if args.start < 0:
raise SystemExit("rea-video: --start 不能小于 0")
if args.cols < 1:
@@ -466,13 +499,27 @@ def cmd_compare(args) -> int:
def cmd_remake(args) -> int:
- from .remake import remake
-
- out = Path(args.out_dir)
+ """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(f"rea-video: {out} 下没有 breakdown.json,先运行 decompose")
- print(json.dumps(remake(out, code=args.code, overlays=not args.no_overlays), ensure_ascii=False, indent=1))
- 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:
@@ -840,7 +887,7 @@ def main(argv: list[str] | None = None) -> int:
r.add_argument("--capsule-root", help="capsule-cinema 仓库;默认 $CAPSULE_CINEMA_ROOT、prefs capsule_root,再退到 ~/code/github/capsule-cinema")
r.set_defaults(func=cmd_remake_plan)
- rr = sub.add_parser("remake-run", help="用 capsule-cinema 执行 remake-plan 生成的任务(会计费,先 --dry-run)")
+ 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", help="须与 remake-plan 时一致;默认同 remake-plan")
rr.add_argument("--dry-run", action="store_true", help="只列出任务和参数,不调用模型")
@@ -858,10 +905,11 @@ def main(argv: list[str] | None = None) -> int:
cd.add_argument("--python", help="capsule-cinema 的 Python;默认同 remake-run")
cd.set_defaults(func=cmd_capsule_draft)
- a = sub.add_parser("assemble", help="把复刻结果按原时间线拼回,并输出对比视频")
+ a = sub.add_parser("assemble", help="交给 Capsule Cinema:把复刻结果按原时间线拼回,并输出对比视频")
a.add_argument("breakdown")
a.add_argument("results", help="remake-run 输出的 results.json(或自己写的同格式文件)")
a.add_argument("-o", "--out")
+ a.add_argument("--capsule-root", help="capsule-cinema 仓库;默认 $CAPSULE_CINEMA_ROOT、prefs capsule_root,再退到 ~/code/github/capsule-cinema")
a.add_argument("--overlays", action="store_true",
help="把测得的字幕 / 花字 / 标题按原样式叠回换掉的镜头(保留原片的镜头本来就有);贴纸只列出来,要自己找素材")
a.set_defaults(func=cmd_assemble)
@@ -895,10 +943,11 @@ def main(argv: list[str] | None = None) -> int:
cp.add_argument("-o", "--out", help="输出目录:compare.json 和 compare_worst.jpg")
cp.set_defaults(func=cmd_compare)
- rm = sub.add_parser("remake", help="一条命令出复刻:静图按运动重建(代码渲染镜头默认原片占位,加 --code 出快速草稿)、已生成 / 你给的镜头剪进去,其余原片占位;输出成片、对比视频和逐镜进度(remake/status.md)")
+ rm = sub.add_parser("remake", help="交给 Capsule Cinema 出复刻:静图按运动重建(代码渲染镜头默认原片占位,加 --code 出快速草稿)、已生成 / 你给的镜头剪进去,其余原片占位;输出成片、对比视频和逐镜进度(remake/status.md)")
rm.add_argument("out_dir", help="decompose 的输出目录")
rm.add_argument("--code", action="store_true", help="用 code-remake 给代码渲染镜头出快速草稿(粒子 / 数据可视化类画面接近原片;插画动画建议交给 HyperFrames 等 HTML 视频框架)")
rm.add_argument("--no-overlays", action="store_true", help="换掉的镜头上不叠回字幕 / 花字")
+ rm.add_argument("--capsule-root", help="capsule-cinema 仓库;默认 $CAPSULE_CINEMA_ROOT、prefs capsule_root,再退到 ~/code/github/capsule-cinema")
rm.set_defaults(func=cmd_remake)
cr = sub.add_parser("code-remake", help="代码渲染镜头的第一版复刻:按场景的采样点 / 抠图、运动和背景光写出可改的工程(code/spec.json + render.py),对齐原片后渲染并打分")
@@ -927,6 +976,11 @@ def main(argv: list[str] | None = None) -> int:
rl.add_argument("--check", action="store_true", help="只校验目录是否符合 VIDEO.md 规范(https://github.com/videomd/videomd),不重写")
rl.set_defaults(func=cmd_videomd)
+ cl = sub.add_parser("clean-paths", help="清掉旧拆解包里的本机路径,方便分享;默认只报告,加 --apply 才改")
+ cl.add_argument("dir", help="拆解包目录,或包含多个包的上级目录")
+ cl.add_argument("--apply", action="store_true", help="真正改写文件")
+ cl.set_defaults(func=cmd_clean_paths)
+
pd = sub.add_parser("pdf", help="把 report.html 打印成 report.pdf(用本机的 Chrome / Chromium / Edge,折叠内容全部展开)")
pd.add_argument("out_dir")
pd.set_defaults(func=cmd_pdf)
diff --git a/rea_video/integrations/capsule_cinema.py b/rea_video/integrations/capsule_cinema.py
index 687ad2f..a1f0054 100644
--- a/rea_video/integrations/capsule_cinema.py
+++ b/rea_video/integrations/capsule_cinema.py
@@ -241,12 +241,56 @@ def build_remake_jobs(b: dict, bdir: Path, capsule_root: Path) -> Path:
jobs.append({"shot": sh["index"], "id": sh["id"], "shots": [sh["index"]], "executor": "keep_original", "label": lab,
"reason": rep.get("note", ""), "user_assets": rep.get("user_assets", [])})
jobs.sort(key=lambda j: (j["shot"], j.get("part", 0)))
+ write_handoff(b, bdir, jobs)
out = bdir / "remake" / "jobs.json"
write_json(out, {"breakdown": str((bdir / "breakdown.json").resolve()), "capsule_root": str(capsule_root),
"run_dir": str(run_dir), "engine": plan.get("model"), "strategy": plan.get("strategy"), "jobs": jobs})
return out
+HANDOFF_SCHEMA = "rea_video.remake_handoff.v1"
+
+
+def write_handoff(b: dict, bdir: Path, jobs: list[dict]) -> Path:
+ """What Capsule Cinema needs to generate, assemble and check the remake, with package-relative paths only. rea-video
+ knows the shots' measured moves, the text to lay back on and what each shot still needs; the doing is Capsule's."""
+ from ..packaging import fit_ass_sizes, to_ass
+ from ..remake import _needs, _next_step, overlay_cues
+
+ src = b["source"]
+ w, h = src["width"], src["height"]
+ if src.get("rotation") in (90, 270):
+ w, h = h, w
+ w, h = w - w % 2, h - h % 2
+ rdir = bdir / "remake"
+ rdir.mkdir(parents=True, exist_ok=True)
+ duration = float(src.get("duration") or (b["shots"][-1]["end"] if b["shots"] else 0))
+ pack = b.get("packaging") or {} # a cue without text has nothing to lay back on
+ readable = {**b, "packaging": {**pack, "text_cues": [c for c in pack.get("text_cues", []) if c.get("text")]}}
+ cues, stickers = overlay_cues(readable, [(0.0, duration)])
+ ass = None
+ if cues:
+ f = rdir / "overlays_all.ass"
+ f.write_text(to_ass(cues, w, h), encoding="utf-8")
+ try:
+ fit_ass_sizes(f)
+ except (OSError, RuntimeError, ValueError):
+ pass # the measured sizes stay; only the font-metric correction is lost
+ ass = "remake/overlays_all.ass"
+ plan = b.get("production_plan") or {}
+ executor = {j["shot"]: j["executor"] for j in jobs}
+ shots = [{"index": sh["index"], "start": sh["start"], "end": sh["end"], "label": sh["base"]["label"],
+ "first_frame": (sh.get("assets") or {}).get("first_frame"), "local": (sh.get("replication") or {}).get("local") or {},
+ "executor": executor.get(sh["index"], "keep_original"), "next": _next_step(sh, plan), "needs": _needs(sh)}
+ for sh in b["shots"]]
+ code = bdir / "code" / "remake.mp4"
+ out = rdir / "handoff.json"
+ write_json(out, {"schema": HANDOFF_SCHEMA, "width": w, "height": h, "fps": src["fps"], "duration": duration,
+ "has_audio": bool(src.get("has_audio")), "shots": shots,
+ "overlays": {"ass": ass, "stickers": stickers}, "code_video": "code/remake.mp4" if code.is_file() else None})
+ return out
+
+
GEN_TYPE = {"remix": "multimodal", "keyframes": "image_to_video", "frames": "first_last_frame", "text": "text_to_video"}
diff --git a/rea_video/moments.py b/rea_video/moments.py
index 8e4262a..024d245 100644
--- a/rea_video/moments.py
+++ b/rea_video/moments.py
@@ -392,12 +392,13 @@ def _screen_text(b: dict, t0: float = 0.0, t1: float = 1e9, cap: int = 300) -> l
def _zoom_cmd(video: str, out: Path) -> str:
- return (f"rea-video tiles '{video}' --start {{start}} --end {{end}} --every {{every}} --cell 320 [--focus x0,y0,x1,y1 --cell 480] "
- f"-o '{out / 'moments' / 'look' / 'zoom' / '{name}.jpg'}'")
+ # run from the package directory: `tiles .` finds the video, so the task files carry no local path
+ return ("rea-video tiles . --start {start} --end {end} --every {every} --cell 320 [--focus x0,y0,x1,y1 --cell 480] "
+ "-o 'moments/look/zoom/{name}.jpg'")
def _grid_cmd(video: str, out: Path) -> str:
- return f"rea-video tiles '{video}' --start {{t}} --end {{t_end}} --every 1 --cols 1 --cell 960 --grid -o '{out / 'moments' / 'look' / 'zoom' / 'grid_{{t}}.jpg'}'"
+ return "rea-video tiles . --start {t} --end {t_end} --every 1 --cols 1 --cell 960 --grid -o 'moments/look/zoom/grid_{t}.jpg'"
def find_task(b: dict, out: Path, info) -> dict:
@@ -605,7 +606,8 @@ def _answer(out: Path, tid: str) -> dict | None:
def _put(out: Path, task: dict) -> None:
tp, ap = _paths(out, task["id"])
- write_json(tp, task)
+ st = task.get("state") or {}
+ write_json(tp, {**task, "state": {**st, "video": Path(st["video"]).name}} if st.get("video") else task) # no local path on disk
if not ap.is_file():
write_json(ap, {**task["answer_template"], "filled": False})
@@ -629,6 +631,9 @@ def _task_clips(task: dict, clip_dir: Path) -> list[tuple[Path, str]]:
st = task.get("state") or {}
video = st.get("video")
+ if video and not Path(video).is_file(): # task files name the video only: the package knows where it is
+ pkg = next((d for d in Path(clip_dir).resolve().parents if (d / "breakdown.json").is_file()), None)
+ video = read_json(pkg / "breakdown.json")["source"]["path"] if pkg else None
if not video or not Path(video).is_file():
return []
clip_dir.mkdir(parents=True, exist_ok=True)
diff --git a/rea_video/remake.py b/rea_video/remake.py
index 16df45e..3ff3950 100644
--- a/rea_video/remake.py
+++ b/rea_video/remake.py
@@ -449,8 +449,8 @@ def _next_step(sh: dict, plan: dict | None = None) -> str:
if lab in GENERATED:
if unit:
return T("生成 {u}:用报告「生成单元」{u} 的提示词生成", "generate {u}: use the prompt of generation unit {u} in the report", u=unit["id"]) + tail
- return T("生成:用报告「生成单元」的提示词在网页上手动生成,或 remake-plan + remake-run(计费,先 --dry-run)",
- "generate: paste the report's generation-unit prompt into a video model, or remake-plan + remake-run (paid; --dry-run first)") + tail
+ return T("生成:用报告「生成单元」的提示词在网页上手动生成,或交给 Capsule Cinema 生成(计费,先 --dry-run)",
+ "generate: paste the report's generation-unit prompt into a video model, or have Capsule Cinema generate it (paid; --dry-run first)") + tail
if lab == "live_action":
if scene:
return T("拍摄 {s}:按报告「拍摄场次」{s} 拍", "shoot {s}: follow shooting scene {s} in the report", s=scene["id"]) + tail
diff --git a/rea_video/review.py b/rea_video/review.py
index 1e2f56a..50bb0e1 100644
--- a/rea_video/review.py
+++ b/rea_video/review.py
@@ -7,6 +7,7 @@ from __future__ import annotations
import re
import shlex
import time
+from pathlib import Path
from .classify import LABEL_ZH, LABELS, top
from . import aspects, narrative, performance
@@ -193,8 +194,10 @@ def build_tasks(breakdown: dict, out_dir: str) -> tuple[dict, dict]:
instructions = INSTRUCTIONS.replace("<PROMPT_LANG>", "英文" if breakdown.get("lang") == "en" else "中文")
if breakdown.get("lang") == "en":
instructions += "\n\n报告语言是英文:evidence、description、image_prompt、video_prompt 和其他自由文本都用英文写(video_prompt_en 可以和 video_prompt 相同)。"
- tasks = {"instructions": instructions, "video": video, "storyboard": "storyboard.jpg",
- "zoom_cmd": _tiles_cmd(video, 0, 0, 0.2, f"{out_dir}/check_ID.jpg")
+ # run from the package directory: `tiles .` finds the video, so this file carries no local path
+ tasks = {"instructions": instructions, "video": Path(str(video)).name, "storyboard": "storyboard.jpg",
+ "zoom_cmd_cwd": "package root",
+ "zoom_cmd": _tiles_cmd(".", 0, 0, 0.2, "check_ID.jpg")
.replace("--start 0.00 --end 0.00", "--start {start} --end {end}").replace("check_ID.jpg", "check_{id}.jpg"),
"shot_aspects_template": aspects.review_template(),
"video_context": {k: ctx.get(k) for k in ("transcoded", "platform", "native30", "film_hint_share") if k in ctx},
diff --git a/rea_video/survey.py b/rea_video/survey.py
index f75e2bb..ea1d279 100644
--- a/rea_video/survey.py
+++ b/rea_video/survey.py
@@ -367,7 +367,13 @@ def _gap_bars(track: FrameTrack, times: list[float], score: np.ndarray, cut_fram
# ------------------------------------------------------------------ rounds -----------------------------------------
def _source(video: str, info: VideoInfo) -> dict:
- return {"path": str(video), "duration": round(info.duration, 3), "size": [info.width, info.height], "fps": round(info.fps, 3)}
+ # the file name only: this lands in the package, which gets shared
+ return {"path": Path(str(video)).name, "duration": round(info.duration, 3), "size": [info.width, info.height], "fps": round(info.fps, 3)}
+
+
+def _same_source(a: dict | None, b: dict) -> bool:
+ """Older packages stored the full path: they still count as the same video."""
+ return bool(a) and {**a, "path": Path(str(a.get("path") or "")).name} == b
def overview_every(track: FrameTrack, shots: list[Shot], dur: float) -> float:
@@ -784,7 +790,7 @@ def run(video: str | Path, out: Path, track: FrameTrack, shots: list[Shot], info
src = _source(video, info)
meta_p = sdir / "survey.json"
meta = read_json(meta_p) if meta_p.is_file() else {}
- if meta.get("source") != src or meta.get("version") != VERSION:
+ if not _same_source(meta.get("source"), src) or meta.get("version") != VERSION:
_reset(sdir)
meta = {"version": VERSION, "source": src, "rounds": [["overview"]]}
_write_task(sdir, overview_task(video, info, track, shots, sdir))
@@ -1065,7 +1071,7 @@ def load_timeline(out: Path, video: str | Path, info: VideoInfo) -> dict | None:
tl = read_json(p)
except (OSError, ValueError):
return None
- return tl if tl.get("source") == _source(str(video), info) and tl.get("version") == VERSION else None
+ return tl if _same_source(tl.get("source"), _source(str(video), info)) and tl.get("version") == VERSION else None
# ------------------------------------------------------------------ VLM ------------------------------------------
diff --git a/rea_video/util.py b/rea_video/util.py
index f384ad8..322c393 100644
--- a/rea_video/util.py
+++ b/rea_video/util.py
@@ -22,6 +22,8 @@ def write_json(path: Path, data: Any, compact: bool = False) -> Path:
"""compact=True: no indentation (about half the size; for large machine-read files like breakdown.json)."""
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
+ if path.name == BREAKDOWN:
+ data = _portable_breakdown(data, path.parent)
text = (json.dumps(data, ensure_ascii=False, separators=(",", ":"), default=_json_default) if compact
else json.dumps(data, ensure_ascii=False, indent=2, default=_json_default))
path.write_text(text + "\n", encoding="utf-8")
@@ -51,7 +53,83 @@ def dumps_rows(data: dict) -> str:
def read_json(path: Path) -> Any:
- return json.loads(Path(path).read_text(encoding="utf-8"))
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
+ return _local_breakdown(data, Path(path).parent) if Path(path).name == BREAKDOWN else data
+
+
+# A package gets shared, so breakdown.json must not carry where the video sits on this machine (a home directory names
+# the user). The file keeps the video's name; the local path lives in $REA_VIDEO_HOME/sources.json and comes back on read.
+BREAKDOWN = "breakdown.json"
+
+
+def _sources_file() -> Path:
+ return Path(os.getenv("REA_VIDEO_HOME", str(Path.home() / ".rea-video"))).expanduser() / "sources.json"
+
+
+def _source_key(src: dict) -> str:
+ return str(src.get("sha256_head") or f"{src.get('filename')}:{src.get('duration')}")
+
+
+_SOURCES_SEEN: dict[str, str] = {} # this process's own videos, found even when the index cannot be written or read
+
+
+def _remember_source(src: dict, path: str) -> None:
+ _SOURCES_SEEN[_source_key(src)] = path
+ f = _sources_file()
+ try:
+ known = json.loads(f.read_text(encoding="utf-8")) if f.is_file() else {}
+ if known.get(_source_key(src)) == path:
+ return
+ known[_source_key(src)] = path
+ f.parent.mkdir(parents=True, exist_ok=True)
+ tmp = f.with_name(f"{f.name}.{os.getpid()}.tmp")
+ tmp.write_text(json.dumps(known, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
+ tmp.replace(f)
+ except (OSError, ValueError) as exc: # only the convenience of finding the video later is lost
+ LOG.warning("could not remember where the source video is: %s", exc)
+
+
+def _portable_breakdown(data: Any, root: Path) -> Any:
+ """A copy to write: the source path reduced to the file name, paths inside the package made relative."""
+ if not isinstance(data, dict) or not isinstance(data.get("source"), dict):
+ return data
+ src = dict(data["source"])
+ path = str(src.get("path") or "")
+ if path and (Path(path).is_absolute() or Path(path).is_file()):
+ _remember_source(src, str(Path(path).resolve()))
+ if path:
+ src["path"] = src.get("filename") or Path(path).name
+ out = {**data, "source": src}
+ stems = data.get("stems")
+ if isinstance(stems, dict) and Path(str(stems.get("effects") or "")).is_absolute():
+ try:
+ rel = Path(stems["effects"]).resolve().relative_to(Path(root).resolve() / "stems")
+ out["stems"] = {**stems, "effects": str(rel)}
+ except ValueError:
+ out["stems"] = {**stems, "effects": Path(stems["effects"]).name}
+ return out
+
+
+def _local_breakdown(data: Any, root: Path) -> Any:
+ """The source path back as a usable local path: the remembered one, else next to the package."""
+ if not isinstance(data, dict) or not isinstance(data.get("source"), dict):
+ return data
+ src = data["source"]
+ path = str(src.get("path") or "")
+ if not path or Path(path).is_absolute():
+ return data
+ candidates = [Path(_SOURCES_SEEN[_source_key(src)])] if _source_key(src) in _SOURCES_SEEN else []
+ try:
+ f = _sources_file()
+ remembered = json.loads(f.read_text(encoding="utf-8")).get(_source_key(src)) if f.is_file() else None
+ if remembered:
+ candidates.append(Path(remembered))
+ except (OSError, ValueError):
+ pass
+ root = Path(root).resolve()
+ candidates += [root / path, root.parent / path, root.parent / "videos" / path, root.parent.parent / path]
+ found = next((c for c in candidates if c.is_file()), root / path)
+ return {**data, "source": {**src, "path": str(found)}}
def _json_default(value: Any) -> Any:
diff --git a/rea_video/videomd.py b/rea_video/videomd.py
index 7031490..4f01712 100644
--- a/rea_video/videomd.py
+++ b/rea_video/videomd.py
@@ -162,12 +162,41 @@ def _legend() -> list[str]:
# ------------------------------------------------------------------ per-shot files ---------------------------------
-def _shot_file(r: dict) -> str:
+def _beats(r: dict) -> list[dict]:
+ """The shot's key frames as the spec's `beats`: moments worth finding without splitting a long shot."""
+ out = []
+ for k in r.get("keyframes") or []:
+ t = k.get("t")
+ role = k.get("role", "")
+ if t is None or role in ("first", "last") or not r["start"] <= t <= r["end"]:
+ continue
+ out.append({"time": [round(t, 3), round(t, 3)], "what": T(*KEY_ROLE_WORDS.get(role, (role or "画面变化", role or "change")))})
+ return out
+
+
+def _pip_layers(r: dict, stickers: list[dict]) -> list[dict]:
+ """A composite picture, when a picture-in-picture window covers at least half of the shot."""
+ span = max(1e-3, r["end"] - r["start"])
+ pips = [s for s in stickers if s.get("kind") == "pip" and s.get("confidence") != "low" and s.get("bbox")
+ and not s.get("in_picture") and (min(s["t1"], r["end"]) - max(s["t0"], r["start"])) / span >= 0.5]
+ if not pips:
+ return []
+ layers = [{"id": "main", "role": "base", "region": [0, 0, 1, 1]}]
+ for n, s in enumerate(pips, 1):
+ x, y, w, h = (max(0.0, min(1.0, float(v))) for v in s["bbox"])
+ layers.append({"id": f"pip{n}", "role": "pip", "region": [x, y, min(w, round(1 - x, 4)), min(h, round(1 - y, 4))],
+ **({"seen": _one_line(s["what"], 60)} if s.get("what") else {})})
+ return layers
+
+
+def _shot_file(r: dict, *, scene: int | None = None, stickers: list[dict] | None = None) -> str:
from .report import _shot_detail_md
base = r["base"]
probs = sorted(base["probs"].items(), key=lambda kv: -kv[1])
assets = r.get("assets") or {}
+ beats = _beats(r)
+ layers = _pip_layers(r, stickers or [])
meta = {
FORMAT: VERSION, "part": "shot", "shot": r["index"], "time": [round(r["start"], 3), round(r["end"], 3)],
"camera": (r.get("features") or {}).get("camera", "unknown"),
@@ -176,6 +205,9 @@ def _shot_file(r: dict) -> str:
"alternatives": dict([(k, v) for k, v in probs if k != base["label"] and v > 0][:2]),
"decided_by": DECIDED_BY.get(base["decided_by"], base["decided_by"]), "real_material": bool((r.get("material") or {}).get("has_real_material"))},
"flags": [k for k in ("uncertain", "disputed") if base.get(k)] + (["low_confidence"] if base["confidence"] < 0.6 and base["decided_by"] != "user" else []),
+ **({"scene": scene} if scene else {}),
+ **({"beats": beats} if beats else {}),
+ **({"layers": layers} if layers else {}),
**({"transition_in": _transition_in(r)} if _transition_in(r) else {}),
**({"keyframes": [[k["t"], k.get("role", "")] for k in r["keyframes"]]} if r.get("keyframes") else {}),
"frames": {k: v for k, v in (("sheet", assets.get("sheet")), ("first", assets.get("first_frame")), ("last", assets.get("last_frame"))) if v},
@@ -273,7 +305,7 @@ def _has_body(text: str) -> bool:
# ------------------------------------------------------------------ entry (L0 + L1) -----------------------------------
-def _card(b: dict) -> dict:
+def _card(b: dict, *, scenes: int = 0, transcript: str | None = None) -> dict:
s, src = b["summary"], b["source"]
from . import __version__
@@ -287,7 +319,8 @@ def _card(b: dict) -> dict:
source.update({"duration": src["duration"], "size": f"{src['width']}x{src['height']}", "fps": src["fps"], "aspect": src["aspect_ratio"]})
return {
FORMAT: VERSION, "name": slug(Path(src["filename"]).stem), "description": _description(b),
- "source": source, "shots": len(b["shots"]), "lang": b.get("lang", "zh"),
+ "source": source, "shots": len(b["shots"]), **({"scenes": scenes} if scenes else {}),
+ **({"tracks": {"transcript": transcript}} if transcript else {}), "lang": b.get("lang", "zh"),
"made_mix": {m["label"]: m["ratio"] for m in s["production_mix"]}, "confidence": s["confidence"],
"readers": readers, "open_questions": len(entities.open_questions(b)),
"generator": {"name": "rea-video", "version": __version__},
@@ -302,12 +335,78 @@ def slug(stem: str) -> str:
def _description(b: dict) -> str:
"""What the video is about first, then how it was made: an agent picks a package by this line."""
- about = _one_line((b.get("whole_video_vlm") or {}).get("summary"), 600)
+ about = _about(b)
made = join(f"{m['label_zh']} {m['ratio']:.0%}" for m in b["summary"]["production_mix"])
made = T("制作方式(推断):{m}", "Made with (inferred): {m}", m=made)
return _one_line(f"{about} {made}" if about else made, 1000)
+def _about(b: dict) -> str:
+ """What the video shows or says, from the best source this run has: the whole-video read, the story beats, what
+ the shots show, the opening lines, the file's title. Empty only when none of them says anything."""
+ whole = _one_line((b.get("whole_video_vlm") or {}).get("summary"), 600)
+ if whole:
+ return whole
+ points = [p for st in narrative.beats(b) for p in st.get("points") or []][:3]
+ if points:
+ return _one_line(T(";", "; ").join(points), 600)
+ seen = [d for d in ((r.get("vlm") or r.get("review") or {}).get("description") for r in b.get("shots", [])) if d][:2]
+ if seen:
+ return _one_line(T(";", "; ").join(seen), 400)
+ said = [str(ln.get("text") or "").strip() for ln in ((b.get("speech") or {}).get("lines") or [])[:3]]
+ said = [x for x in said if x]
+ if said:
+ return T("开场台词:「{x}」。", "Opens with: “{x}”.", x=_one_line(" ".join(said), 160))
+ title = re.sub(r"[_\-\s]*\d{6,}[_\-\s\d]*", " ", Path(str((b.get("source") or {}).get("filename") or "")).stem).strip(" _-")
+ return T("《{t}》。", "“{t}”.", t=_one_line(title, 80)) if re.search(r"[^\W\d_]", title) else ""
+
+
+LONG_VIDEO_S = 120.0 # past this, a reader wants the parts of the video before its timeline
+
+
+def _scenes(b: dict) -> list[dict]:
+ """The story beats as the spec's scenes, for a long video. Nothing unless they cover every shot once, in order."""
+ shots = b.get("shots") or []
+ if float((b.get("source") or {}).get("duration") or 0) < LONG_VIDEO_S or len(shots) < 2:
+ return []
+ steps = narrative.beats(b)
+ if len(steps) < 2 or [i for st in steps for i in st["shots"]] != [r["index"] for r in shots]:
+ return []
+ by = {r["index"]: r for r in shots}
+ return [{"n": n, "first": st["shots"][0], "last": st["shots"][-1], "shots": st["shots"],
+ "start": by[st["shots"][0]]["start"], "end": by[st["shots"][-1]]["end"],
+ "story": _one_line(join(x for x in (st.get("role_zh"), (st.get("points") or [""])[0]) if x), 60)}
+ for n, st in enumerate(steps, 1)]
+
+
+def _scenes_md(scenes: list[dict]) -> str:
+ lines = [f"#S{s['n']:02d} {s['start']:.3f}-{s['end']:.3f} | shots {s['first']}-{s['last']}" + (f" | story {s['story']}" if s["story"] else "")
+ for s in scenes]
+ body = "\n".join([T("# 场景", "# Scenes"), "", T("长视频先读这里,再打开对应镜头。", "For a long video, read this first, then open the shots you need."),
+ "", "```videomd-scenes", *lines, "```"])
+ return _sized({FORMAT: VERSION, "part": "scenes", "scenes": len(scenes)}, body)
+
+
+def _vtt_time(t: float) -> str:
+ ms = int(round(max(0.0, float(t)) * 1000))
+ h, ms = divmod(ms, 3_600_000)
+ m, ms = divmod(ms, 60_000)
+ s, ms = divmod(ms, 1000)
+ return f"{h:02d}:{m:02d}:{s:02d}.{ms:03d}"
+
+
+def _transcript(b: dict) -> str:
+ """Who says what, when, as WebVTT. Empty when no speech was recognised."""
+ out = ["WEBVTT", ""]
+ for ln in (b.get("speech") or {}).get("lines") or []:
+ text = html.escape(_one_line(ln.get("text"), 500), quote=False) if isinstance(ln, dict) else ""
+ if not text or ln.get("start") is None or ln.get("end") is None or float(ln["end"]) <= float(ln["start"]):
+ continue
+ who = re.sub(r"[<>&\n]", "", str(ln.get("speaker") or "")).strip()
+ out += [f"{_vtt_time(ln['start'])} --> {_vtt_time(ln['end'])}", f"<v {who}>{text}" if who else text, ""]
+ return "\n".join(out) if len(out) > 2 else ""
+
+
def _sha256(path) -> str | None:
"""sha256 of the whole source file, when it is still where the breakdown found it."""
import hashlib
@@ -328,8 +427,8 @@ def _next_steps(b: dict) -> list[str]:
if not (b.get("analysis") or {}).get("review") and not ((b.get("analysis") or {}).get("vlm") or {}).get("used"):
L.append(T("没开 VLM:能看图就先复核,`rea-video review <本目录>` → 填 `review_answers.json` → `rea-video apply-review <本目录>`",
"No VLM ran: if you can see images, review first: `rea-video review <this dir>` → fill `review_answers.json` → `rea-video apply-review <this dir>`"))
- L.append(T("复刻:`rea-video remake <本目录>`,能自动做的先做掉,其余原片占位;`remake/status.md` 逐镜写了还要做什么。拿到新镜头写进 `remake/mine.json` 再跑一次",
- "Remake: `rea-video remake <this dir>` does what can be done automatically and keeps the original elsewhere; `remake/status.md` "
+ L.append(T("复刻:生成、拼接和验收由 Capsule Cinema 负责。`rea-video remake <本目录>` 会交给它,能自动做的先做掉,其余原片占位;`remake/status.md` 逐镜写了还要做什么。拿到新镜头写进 `remake/mine.json` 再跑一次",
+ "Remake: Capsule Cinema does the generation, assembly and checks. `rea-video remake <this dir>` hands over to it, does what can be done automatically and keeps the original elsewhere; `remake/status.md` "
"says per shot what is left. Add incoming clips to `remake/mine.json` and run it again"))
if "code_render" in labels:
L.append(T("代码渲染镜头建议交给 HTML 视频框架(如 HyperFrames)按 `video/rhythm.md` 的节奏和关键帧重做;"
@@ -347,8 +446,8 @@ def _next_steps(b: dict) -> list[str]:
"Dance / action shots are not generated from first / last frames: `rea-video drive <this dir>` writes caption-free drive clips cut at calm moments, "
"and `--join` puts the generated segments back; routes and prompts under “Motion drive” in `video/remake.md`"))
if labels & {"ai_video", "cg_3d", "anim_2d", "stop_motion", "avatar"}:
- L.append(T("AI 类镜头:提示词在 `video/remake.md` 的「生成单元」;要自动生成跑 `rea-video remake-plan` + `remake-run --dry-run`,会计费,先问用户",
- "AI shots: prompts are in the generation units of `video/remake.md`; for automatic generation run `rea-video remake-plan` + `remake-run --dry-run` (paid: ask the user first)"))
+ L.append(T("AI 类镜头:提示词在 `video/remake.md` 的「生成单元」;要自动生成用 Capsule Cinema:`scripts/remake_reference.py prepare <本目录>`,再 `run <jobs.json> --dry-run`,会计费,先问用户",
+ "AI shots: prompts are in the generation units of `video/remake.md`; for automatic generation use Capsule Cinema: `scripts/remake_reference.py prepare <this dir>`, then `run <jobs.json> --dry-run` (paid: ask the user first)"))
return L
@@ -407,13 +506,25 @@ def write(b: dict, out: Path) -> Path:
body = "\n".join([T("# 时间线", "# Timeline"), ""] + _legend() + ["", f"```{BLOCK}"] + lines + ["```"])
put(f"{DIR}/timeline.md", _sized({FORMAT: VERSION, "part": "timeline", "shots": len(lines)}, body),
T("时间线:一行一个镜头", "Timeline: one line per shot"), T("想知道某段讲什么、哪镜要复核、某镜怎么做", "what a stretch says, which shots need review, how a shot was made"))
+ scenes = _scenes(b)
+ if scenes:
+ put(f"{DIR}/scenes.md", _scenes_md(scenes), T("场景:长视频的分段", "Scenes: the parts of a long video"),
+ T("长视频先读这里,再打开对应镜头", "read first for a long video, then open the shots you need"))
for stem, title, when, section in _topics(b):
text = _plain(section)
if _has_body(text):
put(f"{DIR}/{stem}.md", _sized({FORMAT: VERSION, "part": stem}, text), title, when)
+ transcript_rel = None
+ transcript = _transcript(b)
+ if transcript:
+ transcript_rel = f"{DIR}/transcript.vtt"
+ put(transcript_rel, transcript, T("台词轨:谁在什么时候说了什么", "Transcript: who says what, when"),
+ T("引用台词、做字幕和配音", "quoting speech, subtitles and voice-over"))
+ scene_of = {i: s["n"] for s in scenes for i in s["shots"]}
+ stickers = (b.get("packaging") or {}).get("stickers") or []
shot_tokens = 0
for r in b["shots"]:
- text = _shot_file(r)
+ text = _shot_file(r, scene=scene_of.get(r["index"]), stickers=stickers)
(d / "shots" / f"{_shot_name(r['index'])}.md").write_text(text, encoding="utf-8")
shot_tokens += tokens(text)
files.append((f"{DIR}/shots/*.md", T("逐镜细节,token 是每个文件的平均值", "Per-shot detail, tokens per file on average"),
@@ -434,7 +545,8 @@ def write(b: dict, out: Path) -> Path:
if (out / rel.rstrip("/")).exists():
files.append((rel, what, when, 0))
entry = out / ENTRY
- entry.write_text(_front(_card(b), _overview(b, files)), encoding="utf-8")
+ card = _card(b, scenes=len(scenes), transcript=transcript_rel)
+ entry.write_text(_front(card, _overview(b, files)), encoding="utf-8")
return entry
diff --git a/skills/rea-video/references/capsule-cinema.md b/skills/rea-video/references/capsule-cinema.md
index 8778f3f..1c88955 100644
--- a/skills/rea-video/references/capsule-cinema.md
+++ b/skills/rea-video/references/capsule-cinema.md
@@ -4,7 +4,7 @@
## 能做什么
-按拆解结果逐镜生成 AI 镜头,拼回原时间线;`rea-video remake-plan` / `remake-run` 直接对接。
+rea-video 负责拆解和复刻方案,capsule-cinema 负责生成、拼接和验收。`rea-video remake` / `remake-run` / `assemble` 会转交给它。
## 费用
@@ -22,16 +22,17 @@
## 怎么跑
-`remake-plan` 照报告第二部分的方案出任务(一个单元的每次调用一个任务,用 `remake/prompts.json` 里的最终提示词),方案检查有 ❌ 时不出任务;`remake-run` 交给 capsule-cinema 跑完,`remake` 按原片切点拆回各镜头。方案不迁就执行端:capsule-cinema 还没接的模型会在 `remake-run` 时报错,这时把提示词和 `remake/refs/` 里的参考交给用户在模型自己的平台上生成。
+`prepare` 调 `rea-video remake-plan` 照报告第二部分的方案出任务和交接文件 `remake/handoff.json`(一个单元的每次调用一个任务,用 `remake/prompts.json` 里的最终提示词),方案检查有 ❌ 时不出任务;`run` 生成,`assemble` 按原片切点拆回各镜头、拼回并验收结构。方案不迁就执行端:capsule-cinema 还没接的模型会在 `remake-run` 时报错,这时把提示词和 `remake/refs/` 里的参考交给用户在模型自己的平台上生成。
生成要用 capsule-cinema 自己的 Python 环境。`rea-video remake-run` / `capsule-draft` 会自动找 `$CAPSULE_CINEMA_PYTHON` 或 `<capsule-root>/.venv/bin/python`,也可以用 `--python` 指定。
```bash
CC=$CAPSULE_CINEMA_ROOT # capsule-cinema 仓库路径
-rea-video remake-plan out/ref/breakdown.json --capsule-root $CC # 照报告第二部分的方案出任务
-rea-video remake-run out/ref/remake/jobs.json --dry-run # 先给用户看任务和费用;--only G2 只跑一个单元
-rea-video remake-run out/ref/remake/jobs.json # 用户确认后再跑
-rea-video assemble out/ref/breakdown.json out/ref/remake/results.json # 拼回原时间线 + compare.mp4
+cd $CC
+python3.12 scripts/remake_reference.py prepare /abs/out/ref # 出任务和交接文件,不计费
+python3.12 scripts/remake_reference.py run /abs/out/ref/remake/jobs.json --dry-run # 先给用户看任务;--only G2 只跑一个单元
+python3.12 scripts/remake_reference.py run /abs/out/ref/remake/jobs.json # 用户确认后再跑(计费)
+python3.12 scripts/remake_reference.py assemble /abs/out/ref # 拼回原时间线 + compare.mp4 + 结构验收
rea-video capsule-draft out/ref/breakdown.json --capsule-root $CC --capsule-name xxx [--write-capsule]
```