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

Make remake runs more reliable

june90eae960d136
diff --git a/rea_video/cli.py b/rea_video/cli.py
index 9d22085..d41bd26 100644
--- a/rea_video/cli.py
+++ b/rea_video/cli.py
@@ -389,6 +389,7 @@ def cmd_capsule_draft(args) -> int:
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 []
+ argv += ["--keep-source-text"] if args.keep_source_text else []
return _run_integration("to_capsule.py", _capsule_python(args.python, root), argv)
@@ -923,6 +924,7 @@ def main(argv: list[str] | None = None) -> int:
cd.add_argument("--write-capsule", action="store_true", help="落盘到 capsule-cinema 的 capsules/")
cd.add_argument("--overwrite-capsule", action="store_true")
cd.add_argument("--python", help="capsule-cinema 的 Python;默认同 remake-run")
+ cd.add_argument("--keep-source-text", action="store_true", help="保留原片台词、画面文字和镜头描述(只用于你有权使用的视频)")
cd.set_defaults(func=cmd_capsule_draft)
a = sub.add_parser("assemble", help="交给 Capsule Cinema:把复刻结果按原时间线拼回,并输出对比视频")
diff --git a/rea_video/cli_en.py b/rea_video/cli_en.py
index 68bab12..d3c08e2 100644
--- a/rea_video/cli_en.py
+++ b/rea_video/cli_en.py
@@ -53,6 +53,7 @@ HELP = {
"capsule-draft": "draft a capsule-cinema capsule from a breakdown",
"capsule-draft.capsule_root": _CAPSULE_ROOT,
"capsule-draft.write_capsule": "write it to capsules/ in capsule-cinema",
+ "capsule-draft.keep_source_text": "keep the source's spoken lines, on-screen text and shot descriptions (only for videos you have the rights to)",
"capsule-draft.python": "capsule-cinema Python; same default as remake-run",
"assemble": "through Capsule Cinema: put remade shots back on the original timeline and output a comparison video",
"assemble.results": "results.json from remake-run (or your own file in the same format)",
diff --git a/rea_video/drive.py b/rea_video/drive.py
index 72db58b..a142817 100644
--- a/rea_video/drive.py
+++ b/rea_video/drive.py
@@ -121,6 +121,24 @@ def erase(frame: np.ndarray, mask: np.ndarray | None) -> np.ndarray:
return out
+def _strokes(frame: np.ndarray, mask: np.ndarray) -> np.ndarray:
+ """The text's own pixels inside the overlay boxes, so a caption over a face or a body takes only its letters with it.
+ Falls back to the whole box when no letters stand out from their surroundings."""
+ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
+ k = max(15, frame.shape[0] // 40) | 1
+ hit = (cv2.absdiff(gray, cv2.medianBlur(gray, k)) > 32) & (mask > 0)
+ if hit.sum() < 0.02 * (mask > 0).sum():
+ return mask
+ return cv2.dilate(hit.astype(np.uint8) * 255, np.ones((3, 3), np.uint8), iterations=2) & mask
+
+
+def scene_text(b: dict, t: float) -> list[str]:
+ """Words visible at t that are not erased from a reference: lettering on things, which only a clean image can remove."""
+ gone = {tuple(x["bbox"]) for x in overlays(b, persistent=True)}
+ return [str(c["text"]) for c in (b.get("packaging") or {}).get("text_cues") or []
+ if c.get("text") and c.get("bbox") and c["t0"] <= t <= c["t1"] and tuple(c["bbox"]) not in gone]
+
+
def motion_curve(path: str | Path, info, a: float, z: float, boxes: list[dict]) -> tuple[np.ndarray, np.ndarray]:
"""(times, motion) at CURVE_FPS: mean absolute change from the previous frame, overlay boxes left out."""
prev, ts, es = None, [], []
@@ -281,7 +299,9 @@ def clean_frame(b: dict, t: float, path: Path, width: int = 1080) -> Path:
w, _ = scaled_size(info, min(width, info.width or width))
for f in iter_frames(src, info, w, start=t, duration=0.1):
path.parent.mkdir(parents=True, exist_ok=True)
- write_image(path, erase(f, _mask(boxes, t, f.shape[1], f.shape[0]) if boxes else None))
+ m = _mask(boxes, t, f.shape[1], f.shape[0]) if boxes else None
+ # a still is looked at closely: fill at full size, letters only
+ write_image(path, f if m is None else cv2.inpaint(f, _strokes(f, m), 3, cv2.INPAINT_TELEA))
break
return path
diff --git a/rea_video/integrations/capsule_cinema.py b/rea_video/integrations/capsule_cinema.py
index a1f0054..9bb0cc5 100644
--- a/rea_video/integrations/capsule_cinema.py
+++ b/rea_video/integrations/capsule_cinema.py
@@ -55,9 +55,14 @@ def _shot_copy(s: dict) -> str:
return " / ".join(out[:6])
-def export_capsule_analysis(b: dict, out_path: Path) -> Path:
+def export_capsule_analysis(b: dict, out_path: Path, keep_source_text: bool = False) -> Path:
+ """Analyzer JSON for a capsule draft. A capsule is a reusable recipe, so by default it carries the source's form only:
+ no spoken or on-screen words, scene descriptions, or file path, any of which can name a brand, a person or a licence."""
s = b["summary"]
- whole = b.get("whole_video_vlm") or {}
+ whole = dict(b.get("whole_video_vlm") or {})
+ if not keep_source_text:
+ for k in ("segments", "hook", "summary"):
+ whole.pop(k, None)
shots = b["shots"]
mix_txt = "、".join(f"{m['label_zh']} {m['ratio']:.0%}" for m in s["production_mix"])
segments = []
@@ -65,7 +70,7 @@ def export_capsule_analysis(b: dict, out_path: Path) -> Path:
for sh in shots:
v = sh.get("vlm") or {}
f = sh["features"]
- copy = _shot_copy(sh)
+ copy = _shot_copy(sh) if keep_source_text else ""
literals += [t for t in copy.split(" / ") if len(t) >= 2]
motion = CAMERA_ZH.get(f.get("camera", "unknown"), "")
if sh["base"]["label"] == "still_motion":
@@ -73,7 +78,7 @@ def export_capsule_analysis(b: dict, out_path: Path) -> Path:
segments.append({
"start_time": _mmss(sh["start"]), "end_time": _mmss(sh["end"]),
"beat": f"镜头 {sh['index']}({sh['duration']:.1f}s)",
- "visuals": f"[{sh['base']['label_zh']} {sh['base']['confidence']:.0%}] " + (v.get("description") or sh["verdict"]),
+ "visuals": f"[{sh['base']['label_zh']} {sh['base']['confidence']:.0%}] " + ((v.get("description") or sh["verdict"]) if keep_source_text else "按原片的景别和机位重新设计内容"),
"material": (sh.get("material") or {}).get("origin_zh", ""),
"motion": motion, "copy": copy,
"audio": "",
@@ -202,7 +207,7 @@ def export_capsule_analysis(b: dict, out_path: Path) -> Path:
"content_scope": content_scope,
"warnings": [] if b["analysis"]["vlm"].get("used") else ["未启用 VLM:镜头描述与文案较少,建议用 --vlm 重新拆解"],
"rea_video": {"verdict": s["verdict"], "production_mix": s["production_mix"], "confidence": s["confidence"],
- "source": b["source"]["path"]},
+ **({"source": b["source"]["path"]} if keep_source_text else {})},
}
write_json(out_path, data)
return out_path
@@ -291,13 +296,14 @@ def write_handoff(b: dict, bdir: Path, jobs: list[dict]) -> Path:
return out
-GEN_TYPE = {"remix": "multimodal", "keyframes": "image_to_video", "frames": "first_last_frame", "text": "text_to_video"}
+GEN_TYPE = {"remix": "multimodal", "keyframes": "multimodal", "frames": "first_last_frame", "text": "text_to_video"}
def _unit_jobs(b: dict, bdir: Path, run_dir: Path, plan: dict, prompts: dict[str, str]) -> list[dict]:
"""One job per call of each unit, fed as the plan says: the source stretch as reference video (remix), one source
frame per shot (keyframes), the shot's first / last frame (frames) or nothing but text; the user's images first; the
final 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 unit_images
spec = plan.get("spec") or {}
@@ -327,9 +333,14 @@ def _unit_jobs(b: dict, bdir: Path, run_dir: Path, plan: dict, prompts: dict[str
else:
params.update(generation_type="image_to_video", image_path=first)
jid = u["id"] if len(parts) == 1 else f"{u['id']}-{part}"
+ times = [r["t"] for r in u["refs"] if r.get("keyframe")] + ([u["start"] + 0.05, u["end"] - 0.08] if u["strategy"] == "frames" else [])
+ 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
jobs.append({"shot": u["shots"][0], "id": jid, "unit": u["id"], "part": part, "parts": len(parts), "shots": u["shots"],
"executor": "capsule_cinema", "label": u["label"], "strategy": u["strategy"], "images": images,
- "params": params, "trim_to": round(secs, 3), "prompt_source": "final" if u["id"] in prompts else "draft"})
+ "params": params, "trim_to": round(secs, 3), "prompt_source": "final" if u["id"] in prompts else "draft",
+ **({"warning": warning} if warning else {})})
return jobs
diff --git a/rea_video/integrations/run_remake.py b/rea_video/integrations/run_remake.py
index 958f252..1f88182 100644
--- a/rea_video/integrations/run_remake.py
+++ b/rea_video/integrations/run_remake.py
@@ -6,7 +6,9 @@ Writes results.json next to jobs.json; rea-video `assemble` consumes it."""
from __future__ import annotations
import argparse
+import inspect
import json
+import os
import re
import sys
import time
@@ -30,6 +32,12 @@ def _video_path(res) -> str | None:
return None
+def _routes() -> dict[str, str]:
+ """Local engine routes from the environment, as `plan-engine=run-engine,...`: the plan and reports keep the model name."""
+ pairs = (x.split("=", 1) for x in os.getenv("REA_VIDEO_ENGINE_ROUTES", "").split(",") if "=" in x)
+ return {a.strip(): b.strip() for a, b in pairs}
+
+
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--jobs", required=True)
@@ -93,23 +101,44 @@ def main() -> None:
from custom_tools.video_generation import video_generation_tool as vgt # noqa: E402
tool = vgt.UniversalVideoGenerationTool()
+ routes = {vgt.normalize_video_engine(a): vgt.normalize_video_engine(b) for a, b in _routes().items()}
failed = []
for j in todo:
Path(j["params"]["output_dir"]).mkdir(parents=True, exist_ok=True)
t0 = time.time()
label = j["id"] if j.get("unit") else f"shot {j['shot']}"
print(f"{label}: {j['params']['generation_type']} via {j['params']['engine']} ...", flush=True)
+ if j.get("warning"):
+ print(f" ! {j['warning']}", flush=True)
+ key = j["id"] if j.get("unit") else str(j["shot"]) # a unit's clip covers several shots: assemble splits it
+ before = results["results"].get(key) or {}
+
+ def keep_task(task_id: str) -> None: # saved the moment the task exists, so a crash cannot lose a paid result
+ results["results"][key] = {**before, "id": j["id"], "video": None, "task_id": task_id}
+ results_path.write_text(json.dumps(results, ensure_ascii=False, indent=2, default=str), encoding="utf-8")
+
try:
if j.get("unit"): # a unit's references go straight to the engine's own tool
p = {k: v for k, v in j["params"].items() if k != "engine"}
- res = vgt._tool_for_engine(vgt.normalize_video_engine(j["params"]["engine"]))._run(**p)
+ eng = vgt.normalize_video_engine(j["params"]["engine"])
+ unit_tool = vgt._tool_for_engine(routes.get(eng, eng))
+ accepts = inspect.signature(unit_tool._run).parameters
+ if "on_task_id" in accepts:
+ p["on_task_id"] = keep_task
+ if before.get("task_id"):
+ p["resume_task_id"] = before["task_id"]
+ print(" resuming the saved task, no new submission", flush=True)
+ if "output_path" in accepts:
+ p["output_path"] = str(Path(p["output_dir"]) / f"{j['id']}.mp4")
+ res = unit_tool._run(**p)
else:
res = tool._run(**j["params"])
except Exception as exc: # keep going, record the failure
res = {"error": str(exc)}
video = _video_path(res)
- key = j["id"] if j.get("unit") else str(j["shot"]) # a unit's clip covers several shots: assemble splits it
+ task_id = res.get("task_id") if isinstance(res, dict) else None
results["results"][key] = {"id": j["id"], "video": video, "raw": res if not video else None,
+ **({"task_id": task_id} if task_id and not video and res.get("resumable") else {}),
"seconds": round(time.time() - t0, 1), "trim_to": j["trim_to"],
**({k: j[k] for k in ("unit", "part", "parts", "shots")} if j.get("unit") else {})}
results_path.write_text(json.dumps(results, ensure_ascii=False, indent=2, default=str), encoding="utf-8")
diff --git a/rea_video/integrations/to_capsule.py b/rea_video/integrations/to_capsule.py
index 9b3a120..b77b7ef 100644
--- a/rea_video/integrations/to_capsule.py
+++ b/rea_video/integrations/to_capsule.py
@@ -24,6 +24,7 @@ def main() -> None:
ap.add_argument("--capsule-display-name", default="")
ap.add_argument("--write-capsule", action="store_true")
ap.add_argument("--overwrite-capsule", action="store_true")
+ ap.add_argument("--keep-source-text", action="store_true")
args = ap.parse_args()
from rea_video.integrations.capsule_cinema import export_capsule_analysis
@@ -31,7 +32,7 @@ def main() -> None:
bpath = Path(args.breakdown).expanduser().resolve()
b = read_json(bpath)
- analysis_path = export_capsule_analysis(b, bpath.with_name("capsule_analysis.json"))
+ analysis_path = export_capsule_analysis(b, bpath.with_name("capsule_analysis.json"), keep_source_text=args.keep_source_text)
analysis = json.loads(analysis_path.read_text(encoding="utf-8"))
root = Path(args.capsule_root).expanduser().resolve()
@@ -50,6 +51,7 @@ def main() -> None:
capsule_display_name=args.capsule_display_name,
write_capsule=args.write_capsule,
overwrite_capsule=args.overwrite_capsule,
+ output_base_dir=bpath.parent / "capsule_draft",
tool_factory=lambda _name: ReaVideoAnalyzer(),
)
print(json.dumps(result, ensure_ascii=False, indent=2))