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
Keep remake segments on the original's frames
june92b9f6cee579
diff --git a/rea_video/drive.py b/rea_video/drive.pyindex a3292f0..72db58b 100644--- a/rea_video/drive.py+++ b/rea_video/drive.py@@ -408,7 +408,7 @@ def readme(res: dict, plan_units: list[dict]) -> list[str]:def join(out: Path, results: Path | None = None) -> dict:"""Generated segments -> per-shot clips in remake/mine.json. A shot is filled only when every segment over it is in."""- from .remake import _fit_clip, _original_segment+ from .remake import _fit_clip, _original_segment, frame_boundsb = read_json(out / "breakdown.json")ddir = out / "drive"@@ -442,17 +442,19 @@ def join(out: Path, results: Path | None = None) -> dict:fitted = []for s in blk:f = jdir / f"{s['id']}_fit.mp4"- _fit_clip(paths[s["id"]], f, s["duration"], (w, h), fps)+ _fit_clip(paths[s["id"]], f, max(1, int(round(s["end"] * fps)) - int(round(s["start"] * fps))), (w, h), fps)fitted.append(f)lst = jdir / f"block_{k:02d}.txt"lst.write_text("".join(f"file '{f.resolve()}'\n" for f in fitted), encoding="utf-8")whole = jdir / f"block_{k:02d}.mp4"_ff(["-f", "concat", "-safe", "0", "-i", str(lst), "-c", "copy", str(whole)])a, z = blk[0]["start"], blk[-1]["end"]+ bounds = frame_bounds(b["shots"], fps)for r in b["shots"]:if r["start"] >= a - 1e-3 and r["end"] <= z + 1e-3:clip = jdir / f"shot_{int(r['index']):03d}.mp4"- _original_segment(whole, clip, r["start"] - a, r["duration"], (w, h), fps)+ first, n = bounds[r["index"]]+ _original_segment(whole, clip, first - int(round(a * fps)), n, (w, h), fps)res[str(r["index"])] = {"video": str(clip.resolve())}filled.append(r["index"])mine_p.parent.mkdir(parents=True, exist_ok=True)diff --git a/rea_video/pipeline.py b/rea_video/pipeline.pyindex 7f0f754..646b502 100644--- a/rea_video/pipeline.py+++ b/rea_video/pipeline.py@@ -260,7 +260,7 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,rec = {**({"survey_look": {"label_probs": {k: float(look["p"].get(k, 0.0)) for k in LABEL_ZH}, "answer": look["answer"],"_by": look.get("by") or "agent", "evidence": []}} if look else {}),- "id": sid, **s.to_dict(), "keyframes": [{k: r[k] for k in ("t", "role", "by", "p") if k in r} for r in kf],+ "id": sid, **s.to_dict(), "keyframes": [{k: r[k] for k in ("t", "frame", "role", "by", "p") if k in r} for r in kf],"features": round_floats(feats), "faces": round(faces, 3),"aspects": round_floats(asp), "overlay": round_floats(ov), "text": text, "layers": layers, "embedded_assets": round_floats(embedded),"deterministic": {"probs": round_floats(probs), "evidence": evidence, "facts": facts},diff --git a/rea_video/remake.py b/rea_video/remake.pyindex 5f63f38..76bfa4f 100644--- a/rea_video/remake.py+++ b/rea_video/remake.py@@ -78,19 +78,38 @@ def _clip_seconds(src: Path) -> float:return 0.0-def _fit_clip(src: Path, out: Path, duration: float, size: tuple[int, int], fps: float) -> Path:+def frame_bounds(shots: list[dict], fps: float) -> dict[int, tuple[int, int]]:+ """{shot index: (first frame, frame count)} on the original's frame grid. Every segment of a remake is cut to+ exactly its count, so a cut lands on the original's frame and the lengths never add up to a drift against the+ original sound (seconds rounded per segment lose or gain a frame each, a few tenths of a second by the end)."""+ starts = [int(round(sh["start"] * fps)) for sh in shots]+ ends = starts[1:] + [int(round(shots[-1]["end"] * fps))] if shots else []+ return {sh["index"]: (a, max(1, z - a)) for sh, a, z in zip(shots, starts, ends)}+++def _exact(fps: float, frames: int) -> tuple[str, list[str]]:+ """The tail of a filter chain and the output flags that make a segment exactly `frames` frames at `fps`: the last+ frame held when the source runs short, the rest cut off."""+ return (f"fps={fps},tpad=stop_mode=clone:stop_duration={frames / fps + 1:.3f}",+ ["-frames:v", str(frames), "-r", f"{fps}"])+++def _fit_clip(src: Path, out: Path, frames: int, size: tuple[int, int], fps: float) -> Path:w, h = size- speed = fit_speed(_clip_seconds(src), duration)- vf = (f"setpts=PTS/{speed:.4f},scale={w}:{h}:force_original_aspect_ratio=increase,crop={w}:{h},fps={fps},"- f"tpad=stop_mode=clone:stop_duration={duration:.3f},trim=duration={duration:.3f},setpts=PTS-STARTPTS")- _ff(["-i", str(src), "-an", "-vf", vf, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", str(out)])+ speed = fit_speed(_clip_seconds(src), frames / fps)+ tail, flags = _exact(fps, frames)+ vf = f"setpts=PTS/{speed:.4f},scale={w}:{h}:force_original_aspect_ratio=increase,crop={w}:{h},{tail}"+ _ff(["-i", str(src), "-an", "-vf", vf, *flags, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", str(out)])return out-def _original_segment(src: Path, out: Path, start: float, duration: float, size: tuple[int, int], fps: float) -> Path:+def _original_segment(src: Path, out: Path, first: int, frames: int, size: tuple[int, int], fps: float) -> Path:+ """Frames first .. first + frames - 1 of src: seeking half a frame early, so the first one is never skipped, and+ its time reset to zero, so the frame-rate filter does not repeat it (which would shift the whole segment a frame)."""w, h = size- _ff(["-ss", f"{start:.4f}", "-i", str(src), "-t", f"{duration:.4f}", "-an",- "-vf", f"scale={w}:{h},fps={fps}", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", str(out)])+ tail, flags = _exact(fps, frames)+ _ff(["-ss", f"{max(0.0, (first - 0.5) / fps):.6f}", "-i", str(src), "-an",+ "-vf", f"setpts=PTS-STARTPTS,scale={w}:{h},{tail}", *flags, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", str(out)])return out@@ -134,7 +153,8 @@ def overlay_cues(b: dict, spans: list[tuple[float, float]]) -> tuple[list[dict],return cues, stickers-def unit_shots(b: dict, results: dict, udir: Path, size: tuple[int, int], fps: float) -> dict:+def unit_shots(b: dict, results: dict, udir: Path, size: tuple[int, int], fps: float,+ bounds: dict[int, tuple[int, int]] | None = None) -> dict:"""Generation-unit clips (one call made several shots: results keyed "G2", or "G4-1", "G4-2" for the parts of along shot) -> one clip per shot. The parts are fitted to their lengths and joined; the shots are then cut at thesource's own cut points, because the model was given the source stretch and follows its timing.@@ -146,6 +166,7 @@ def unit_shots(b: dict, results: dict, udir: Path, size: tuple[int, int], fps: fif not by_unit:return {}by_index = {r["index"]: r for r in b["shots"]}+ bounds = bounds or frame_bounds(b["shots"], fps)out: dict[str, dict] = {}udir.mkdir(parents=True, exist_ok=True)for uid, got in by_unit.items():@@ -155,7 +176,7 @@ def unit_shots(b: dict, results: dict, udir: Path, size: tuple[int, int], fps: ffitted = []for v in got:f = udir / f"{uid}_p{v.get('part', 1)}.mp4"- _fit_clip(Path(v["video"]), f, float(v["trim_to"]), size, fps)+ _fit_clip(Path(v["video"]), f, max(1, int(round(float(v["trim_to"]) * fps))), size, fps)fitted.append(f)whole = fitted[0]if len(fitted) > 1:@@ -163,15 +184,15 @@ def unit_shots(b: dict, results: dict, udir: Path, size: tuple[int, int], fps: flst.write_text("".join(f"file '{f.resolve()}'\n" for f in fitted), encoding="utf-8")whole = udir / f"{uid}.mp4"_ff(["-f", "concat", "-safe", "0", "-i", str(lst), "-c", "copy", str(whole)])- t = 0.0+ at = 0for i in got[0].get("shots") or []:- r = by_index.get(i)- if not r:+ if i not in by_index or i not in bounds:continueclip = udir / f"shot_{int(i):03d}.mp4"- _original_segment(whole, clip, t, r["duration"], size, fps)+ n = bounds[i][1]+ _original_segment(whole, clip, at, n, size, fps)out[str(i)] = {"video": str(clip), "unit": uid}- t += r["duration"]+ at += nreturn out@@ -195,18 +216,21 @@ def assemble(breakdown_path: Path, results_path: Path, out_dir: Path | None = Nofps = float(b["source"]["fps"]) if b["source"]["fps"] and b["source"]["fps"] <= 60 else 30.0results = {**results, **{str(k): v for k, v in (extra or {}).items()}}# unit clips (one call, several shots) become per-shot clips; a shot's own clip, given later, still wins- results = {**unit_shots(b, results, seg_dir / "units", (w, h), fps), **{k: v for k, v in results.items() if not (isinstance(v, dict) and v.get("unit"))}}+ bounds = frame_bounds(b["shots"], fps)+ results = {**unit_shots(b, results, seg_dir / "units", (w, h), fps, bounds),+ **{k: v for k, v in results.items() if not (isinstance(v, dict) and v.get("unit"))}}parts, legend = [], []for sh in b["shots"]:- dur = sh["duration"]+ first, n = bounds[sh["index"]]+ dur = n / fpsseg = seg_dir / f"shot_{int(sh['index']):03d}.mp4" # 不用 JSON 里的 id 拼路径,防 ../res = results.get(str(sh["index"])) or {}job = jobs.get(sh["index"], {})if res.get("video") and Path(res["video"]).is_file():- _fit_clip(Path(res["video"]), seg, dur, (w, h), fps)+ _fit_clip(Path(res["video"]), seg, n, (w, h), fps)legend.append((sh["index"], "generated"))elif code_video and sh["base"]["label"] == "code_render" and Path(code_video).is_file():- _original_segment(Path(code_video), seg, sh["start"], dur, (w, h), fps)+ _original_segment(Path(code_video), seg, first, n, (w, h), fps)legend.append((sh["index"], "code"))elif job.get("executor") == "local_ffmpeg" or sh["base"]["label"] in ("still_motion", "static_hold"):m = sh["replication"].get("local", {})@@ -215,7 +239,7 @@ def assemble(breakdown_path: Path, results_path: Path, out_dir: Path | None = Nom.get("pan_dir_deg", 0.0), m.get("analysis_width", 480))legend.append((sh["index"], "local_still"))else:- _original_segment(src, seg, sh["start"], dur, (w, h), fps)+ _original_segment(src, seg, first, n, (w, h), fps)legend.append((sh["index"], "original"))parts.append(seg)lst = seg_dir / "concat.txt"diff --git a/rea_video/videomd.py b/rea_video/videomd.pyindex d63d6f9..046875e 100644--- a/rea_video/videomd.py+++ b/rea_video/videomd.py@@ -220,6 +220,15 @@ def rhythm_md(b: dict) -> list[str]:if not rh and not any(r.get("keyframes") for r in b.get("shots", [])):return []out = [T("# 节奏与关键帧", "# Rhythm and key frames"), ""]+ fps = float((b.get("source") or {}).get("fps") or 0)+ if fps:+ out += [T("帧率 {f:g}fps。时间后面的 @数字 是原片帧号(从 0 起):复刻时按帧号对齐切点和关键帧,秒数四舍五入会差一帧。",+ "{f:g} fps. The @number after a time is the original's frame number (from 0): line cuts and key frames up by "+ "frame number, rounded seconds can be a frame off.", f=fps), ""]++ def at(t: float, frame=None) -> str:+ f = frame if frame is not None else (int(round(t * fps)) if fps else None)+ return f"{t:.3f}s" + (f" @{f}" if f is not None else "")if rh:out += [T("每分钟 {n} 刀,平均镜头 {m}s;镜头长度:{l}", "{n} cuts a minute, mean shot {m}s; shot lengths: {l}",n=rh.get("cuts_per_min"), m=rh.get("mean_shot_s"), l=" ".join(f"{x:.1f}" for x in rh.get("shot_lengths", []))), ""]@@ -240,18 +249,19 @@ def rhythm_md(b: dict) -> list[str]:return f" → {got[-1]}"ends = [c["t"] for c in sv["cuts"]] + [1e9]if (first := named(0.0, ends[0])):- out.append(f"- 0.00s{first}")+ out.append(f"- {at(0.0, 0)}{first}")for k, c in enumerate(sv["cuts"]):span = c.get("span") or [c["t"], c["t"]]dur = f" {span[1] - span[0]:.2f}s" if span[1] > span[0] and c.get("kind", "cut") not in ("cut", "jump") else ""- out.append(f"- {c['t']:.2f}s {c.get('kind', 'cut')}{dur}" + (T("(待确认)", " (to confirm)") if c.get("unsure") else "")+ dur = f" {span[1] - span[0]:.2f}s ({at(span[0])} – {at(span[1])})" if dur else ""+ out.append(f"- {at(c['t'], c.get('frame'))} {c.get('kind', 'cut')}{dur}" + (T("(待确认)", " (to confirm)") if c.get("unsure") else "")+ named(span[0], ends[k + 1]))out.append("")rows = [(r["index"], r["keyframes"]) for r in b.get("shots", []) if r.get("keyframes")]if rows:out += [T("## 每镜关键帧", "## Key frames per shot"), ""]for i, kf in rows:- out.append(f"- #{i}: " + ", ".join(f"{k['t']:.2f}s {T(*KEY_ROLE_WORDS.get(k.get('role', ''), (k.get('role', ''), k.get('role', ''))))}" for k in kf))+ out.append(f"- #{i}: " + ", ".join(f"{at(k['t'], k.get('frame'))} {T(*KEY_ROLE_WORDS.get(k.get('role', ''), (k.get('role', ''), k.get('role', ''))))}" for k in kf))return out