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: 可变帧率视频按真实时间戳算切点;换语言重出报告时包装层标签跟着换
june0478976a3097
diff --git a/eval/RESULTS.md b/eval/RESULTS.mdindex 0cee842..8caad92 100644--- a/eval/RESULTS.md+++ b/eval/RESULTS.md@@ -422,3 +422,10 @@ issue #8 的口红带货片(抖音转码,HEVC 1080x1920 30fps,98 秒 38| daihuo(2 条) | 0.464 | 一致;+ Gemini 0.703 / 真实素材 0.926,+ agent 复核 0.975,均与 11-04 一致 |8 条案例视频的镜头切点在改动前后逐条一致。++### 同日追加:可变帧率切点、换语言重出报告++- 可变帧率视频(录屏、手机暗光)的镜头时间原来按「帧序号 / 平均帧率」算,会错位:30fps + 10fps + 30fps 各 2 秒的片子,切点报成 2.571s / 3.429s。现在读容器里每帧的时间戳(不解码,每条约 0.04 秒),和均匀时间差超过半帧时才改用,切点为 2.0s / 4.0s。案例和评测集里的视频都是恒定帧率,不走这条路。+- `--lang` 换语言重出报告时,包装层里存下来的文字类型、动画、颜色、字高说明按新语言重新生成;VLM 和复核者写的描述保持原文。++回归:6 个集合 + daihuo 的 Gemini / agent 复核两组分数与上表一致;8 条案例视频切点逐条一致。diff --git a/rea_video/features.py b/rea_video/features.pyindex 64f9813..e3f20ca 100644--- a/rea_video/features.py+++ b/rea_video/features.py@@ -165,7 +165,7 @@ def collect_samples(path: str, info: VideoInfo, shot: Shot, n_frames: int = 16,out.sharpness.append(float(cv2.Laplacian(gray, cv2.CV_32F).var()))if i in keep:out.frames.append(bgr.copy())- out.frame_times.append(shot.start + i / shot.fps)+ out.frame_times.append(shot.t(shot.start_frame + i))if prev_gray is not None and i - 1 >= lo:d = cv2.absdiff(gray, prev_gray)out.pair_mad.append(float(d.mean()))diff --git a/rea_video/media.py b/rea_video/media.pyindex c0bd2b3..fd48ead 100644--- a/rea_video/media.py+++ b/rea_video/media.py@@ -139,6 +139,26 @@ def scaled_size(info: VideoInfo, width: int) -> tuple[int, int]:return width, max(2, height)+def frame_times(path: str | Path, n: int, fps: float) -> np.ndarray | None:+ """Real timestamps (s, from 0) of the n frames iter_frames passes through, read from packet pts+ (no decoding). None when they match frame / fps to within half a frame (constant frame rate; the+ caller keeps index / fps) or when the packet count does not line up with the decoded frames."""+ if n < 2 or fps <= 0:+ return None+ try:+ out = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "packet=pts_time",+ "-of", "csv=p=0", str(path)], capture_output=True, text=True, timeout=120).stdout+ pts = sorted(float(x.strip().rstrip(",")) for x in out.split() if x.strip().rstrip(",") not in ("", "N/A"))+ except (OSError, ValueError, subprocess.SubprocessError):+ return None+ if len(pts) != n:+ return None+ t = np.asarray(pts) - pts[0]+ if np.max(np.abs(t - np.arange(n) / fps)) <= 0.5 / fps:+ return None+ return t++def iter_frames(path: str | Path,info: VideoInfo,diff --git a/rea_video/packaging.py b/rea_video/packaging.pyindex 3f7e033..4c2dcf5 100644--- a/rea_video/packaging.py+++ b/rea_video/packaging.py@@ -1396,6 +1396,28 @@ def merge_vlm(pack: dict, whole: dict | None) -> None:pack["vlm_text_effects"] = [e for e in (whole.get("text_effects") or []) if isinstance(e, dict)][:60]+def relocalize(pack: dict, frame_h: int | None) -> None:+ """Display labels (kind_zh, style_zh, colour names) are stored in the language of the first run.+ Re-derive them from their codes so a report re-rendered with another --lang is not half one, half the other.+ Free text from a VLM or reviewer (VLM / agent stickers) stays as written."""+ name_to_code = {name: code for code in COLOR_ZH for name in (COLOR_ZH._zh[code], COLOR_ZH._en.get(code))}+ for c in pack.get("text_cues", []):+ if c.get("kind") in KIND_ZH:+ c["kind_zh"] = KIND_ZH[c["kind"]]+ for k in ("anim_in", "anim_out"):+ if isinstance(c.get(k), dict) and c[k].get("kind") in ANIM_ZH:+ c[k]["kind_zh"] = ANIM_ZH[c[k]["kind"]]+ st = c.get("style")+ if isinstance(st, dict):+ for k in ("fill_name", "stroke_name", "box_name", "highlight_name"):+ if st.get(k) in name_to_code:+ st[k] = COLOR_ZH[name_to_code[st[k]]]+ c["style_zh"] = style_text(st, c.get("line_h"), frame_h)+ for st in pack.get("stickers", []):+ if st.get("source") not in ("vlm", "agent") and st.get("kind") in STICKER_ZH:+ st["kind_zh"] = STICKER_ZH[st["kind"]]++def apply_review(pack: dict) -> None:"""An agent's look at the stickers and text kinds (rea-video review / apply-review) overrides the pixel pass."""rv = pack.get("review")diff --git a/rea_video/pipeline.py b/rea_video/pipeline.pyindex 17ebc07..63c9e59 100644--- a/rea_video/pipeline.py+++ b/rea_video/pipeline.py@@ -51,7 +51,7 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,track = build_track(str(video), info)shots = detect_shots(track)LOG.info("detected %d shots", len(shots))- marks = [b / s.fps for s in shots for b in s.beats]+ marks = [s.t(b) for s in shots for b in s.beats]audio = analyze_audio(str(video), [s.start for s in shots[1:]], marks) if info.has_audio else {"has_audio": False}stem_info: dict = {}if info.has_audio and stems: # strip the soundtrack: original.wav / vocals.wav / music.wav@@ -390,6 +390,10 @@ def finalize(breakdown: dict, out: Path, engine: str | None = None) -> dict:from .packaging import apply_review as apply_pack_reviewapply_pack_review(pack)+ from .packaging import relocalize++ src = breakdown["source"]+ relocalize(pack, src.get("width") if src.get("rotation") in (90, 270) else src.get("height"))vctx = video_context(shot_records, prov, breakdown["source"].get("fps"))breakdown["video_context"] = vctxfor rec in shot_records:diff --git a/rea_video/shots.py b/rea_video/shots.pyindex dc6bd20..ca54faa 100644--- a/rea_video/shots.py+++ b/rea_video/shots.py@@ -10,7 +10,7 @@ from dataclasses import dataclass, fieldimport cv2import numpy as np-from .media import VideoInfo, iter_frames+from .media import VideoInfo, frame_times, iter_framesTHUMB_W = 96@@ -24,6 +24,7 @@ class FrameTrack:luma: np.ndarray # mean luma 0..255thumbs: list[np.ndarray] = field(repr=False, default_factory=list) # small gray thumbs, uint8 (for dissolve check)hists: list[np.ndarray] = field(repr=False, default_factory=list)+ times: np.ndarray | None = field(repr=False, default=None) # per-frame pts (s) for variable frame rate; None = i / fps@propertydef n(self) -> int:@@ -39,24 +40,35 @@ class Shot:transition_in: str = "cut"boundary_score: float = 0.0beats: list[int] = field(default_factory=list) # frame indices of MG/slide beat changes inside the shot+ times: np.ndarray | None = field(repr=False, default=None) # FrameTrack.times++ def t(self, frame: int) -> float:+ """Time of a frame index. Variable-frame-rate video uses the real pts; past the last frame,+ one median frame interval after it."""+ if self.times is None:+ return frame / self.fps+ if frame < len(self.times):+ return float(self.times[frame])+ step = float(np.median(np.diff(self.times))) if len(self.times) > 1 else 1 / self.fps+ return float(self.times[-1]) + step * (frame - len(self.times) + 1)@propertydef start(self) -> float:- return self.start_frame / self.fps+ return self.t(self.start_frame)@propertydef end(self) -> float:- return self.end_frame / self.fps+ return self.t(self.end_frame)@propertydef duration(self) -> float:- return (self.end_frame - self.start_frame) / self.fps+ return self.end - self.startdef to_dict(self) -> dict:return {"index": self.index, "start": round(self.start, 3), "end": round(self.end, 3),"duration": round(self.duration, 3), "start_frame": self.start_frame, "end_frame": self.end_frame,"transition_in": self.transition_in, "boundary_score": round(self.boundary_score, 3),- "beats": [round(b / self.fps, 3) for b in self.beats]}+ "beats": [round(self.t(b), 3) for b in self.beats]}def _hist(bgr: np.ndarray) -> np.ndarray:@@ -88,7 +100,7 @@ def build_track(path: str, info: VideoInfo) -> FrameTrack:prev_h, prev_g = h, gfps = info.fps if info.fps > 0 else 30.0return FrameTrack(fps=fps, hist_dist=np.array(hist_d), pix_diff=np.array(pix_d), changed=np.array(chg), luma=np.array(luma),- thumbs=thumbs, hists=hists)+ thumbs=thumbs, hists=hists, times=frame_times(path, len(luma), fps))def _local_median(x: np.ndarray, radius: int) -> np.ndarray:@@ -182,7 +194,8 @@ def detect_shots(track: FrameTrack, min_shot_s: float = 0.35, cut_threshold: floif b == n and shots and b - start < min_len:shots[-1].end_frame = nbreak- shots.append(Shot(index=len(shots) + 1, start_frame=start, end_frame=b, fps=fps, transition_in=trans, boundary_score=bscore))+ shots.append(Shot(index=len(shots) + 1, start_frame=start, end_frame=b, fps=fps, transition_in=trans, boundary_score=bscore,+ times=track.times))if b < n:trans, bscore = boundaries[b]start = bdiff --git a/tests/test_robustness.py b/tests/test_robustness.pyindex 9175860..d989626 100644--- a/tests/test_robustness.py+++ b/tests/test_robustness.py@@ -95,3 +95,41 @@ def test_srt_timestamp_carries_into_seconds():def test_tiles_cmd_quotes_paths():assert "'/a/my video.mp4'" in _tiles_cmd("/a/my video.mp4", 1, 2, 0.2, "out/c.jpg")+++def test_relocalize_rewrites_stored_labels():+ from rea_video.i18n import set_lang+ from rea_video.packaging import relocalize++ pack = {"text_cues": [{"kind": "subtitle", "kind_zh": "字幕", "line_h": 0.05,+ "style": {"fill_name": "白", "stroke": True, "stroke_name": "黑"}, "style_zh": "白字、黑描边",+ "anim_in": {"kind": "pop", "kind_zh": "缩放弹出"}}],+ "stickers": [{"kind": "static_sticker", "kind_zh": "静态贴纸/图片", "source": "pixels"},+ {"kind": "static_sticker", "kind_zh": "一只猫的贴纸", "source": "vlm"}]}+ try:+ set_lang("en")+ relocalize(pack, 1920)+ finally:+ set_lang("zh")+ c = pack["text_cues"][0]+ assert c["kind_zh"] == "subtitle" and c["anim_in"]["kind_zh"] == "scale pop"+ assert c["style"]["fill_name"] == "white" and "black outline" in c["style_zh"] and "line height" in c["style_zh"]+ assert pack["stickers"][0]["kind_zh"] == "static sticker / image"+ assert pack["stickers"][1]["kind_zh"] == "一只猫的贴纸" # free text from the VLM is kept+++def test_variable_frame_rate_cuts_use_real_timestamps(tmp_path):+ """30 fps + 10 fps + 30 fps segments, 2 s each: cuts at 2 s and 4 s, not at frame / average-fps."""+ from rea_video.shots import build_track, detect_shots++ srcs = ["testsrc2=s=160x120:r=30:d=2", "mandelbrot=s=160x120:r=10", "testsrc2=s=160x120:r=30:d=2"]+ for k, src in enumerate(srcs):+ vf = ["-vf", "hue=h=180,vflip"] if k == 2 else []+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", src, "-t", "2", *vf, "-c:v", "libx264",+ "-pix_fmt", "yuv420p", "-video_track_timescale", "90000", str(tmp_path / f"{k}.mp4")], check=True)+ (tmp_path / "list.txt").write_text("".join(f"file {k}.mp4\n" for k in range(3)))+ vfr = tmp_path / "vfr.mp4"+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-f", "concat", "-i", str(tmp_path / "list.txt"), "-c", "copy", str(vfr)], check=True)+ shots = detect_shots(build_track(str(vfr), video_info(vfr)))+ assert [round(s.start, 2) for s in shots] == [0.0, 2.0, 4.0]+ assert abs(shots[-1].end - 6.0) < 0.05