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
Tell remakes what to change: timing, position, spread, amount and colour
june7683a86b7cbb
diff --git a/docs/cli.md b/docs/cli.mdindex 1d77565..2bb94a0 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -105,7 +105,7 @@ rea-video capsule-draft out/ref/breakdown.json --capsule-root $CC --capsule-name| `pdf OUT_DIR` | 把 report.html 打印成 report.pdf(用本机的 Chrome / Chromium / Edge,`REA_CHROME` 可指定路径;正文的折叠内容展开,时间轴、逐镜取证这类查阅数据保持折叠) || `tiles VIDEO --start --end --every` | 按时间抽帧拼图,近距离复核 || `frames OUT_DIR [--every 0.25] [--points 4000] [--all]` | 代码渲染镜头按场景切分(画上去的东西整体换了位置或形状就算新场景),写出 `frames/`:每场景首 / 中 / 尾原尺寸帧、`scene_XX_layer.png`(画上去那一层的抠图,背景和文字已去掉)、`points/scene_XX.json`(这一层的采样点)、`scenes.json`(底色、背景光、前景颜色、块数、范围、重心随时间的轨迹);深底浅底都适用;decompose 遇到代码渲染镜头会自动跑 |-| `compare REF REMAKE [--scenes frames/scenes.json] [-o DIR]` | 逐帧比较复刻和原片画上去的那一层:落在哪、形状重合度、多少;两边各按自己的底色取前景,换了底色也能直接比;`-o` 写出 `compare.json` 和最差时刻的左右对比图 `compare_worst.jpg` |+| `compare REF REMAKE [--scenes frames/scenes.json] [-o DIR]` | 逐帧比较复刻和原片画上去的那一层:落在哪、形状重合度、多少;两边各按自己的底色取前景,换了底色也能直接比;并给出要改什么(整体早晚几秒、偏左偏右、铺开范围、多少、前景颜色和底色差多少),整段、每个场景、最差的几帧各一份;`-o` 写出 `compare.json` 和最差时刻的左右对比图 `compare_worst.jpg` || `eval labels.yaml` | 在带标注的样本上评测准确率和切点 F1 || `capsule breakdown.json` | 导出 capsule-cinema 的视频分析 JSON || `models [ID] [--plan OUT_DIR]` | 列出能力地图里的生成模型;带 id 时打印这个模型的提示词写法和关键帧要求(`models keyframes` 是关键帧通用做法);`--plan` 把已有拆解的复刻方案改按该模型重出 |diff --git a/rea_video/cli.py b/rea_video/cli.pyindex 9cefea6..22e711c 100644--- a/rea_video/cli.py+++ b/rea_video/cli.py@@ -353,7 +353,7 @@ def cmd_compare(args) -> int:raise SystemExit(f"rea-video: 找不到 {p}")res = compare(args.ref, args.remake, every=args.every, out=Path(args.out) if args.out else None,scenes=Path(args.scenes) if args.scenes else None, worst=args.worst)- brief = {k: res[k] for k in ("score", "place", "shape", "worst") if k in res}+ brief = {k: res[k] for k in ("score", "place", "shape", "offset", "advice", "worst") if k in res}if res.get("scenes"):brief["lowest_scenes"] = res["scenes"][:5]if res.get("sheet"):diff --git a/rea_video/layers.py b/rea_video/layers.pyindex f3c4584..4ddd0e6 100644--- a/rea_video/layers.py+++ b/rea_video/layers.py@@ -10,8 +10,9 @@ glow, the drawn colours and where the drawing sits. A remake can then place itsinstead of redrawing them from a description.`rea-video compare ref remake` scores a remake against the original frame by frame on the drawn layer (where it sits,-how well the shapes overlap, how much there is), so the remake is fixed where it is furthest off. Each video's layer is-taken against its own ground, so a remake on a different ground colour compares without extra steps.+how well the shapes overlap, how much there is) and says what to change: timing, position, spread, amount, drawn+colour and ground. Each video's layer is taken against its own ground, so a remake on a different ground colour+compares without extra steps."""from __future__ import annotations@@ -268,35 +269,143 @@ def scene_frames(out: Path, every: float = 0.25, n_points: int = 4000, all_shotsreturn res-def _score(fa: np.ndarray, fb: np.ndarray, k: np.ndarray) -> dict:- ma, mb = layer_mask(fa), layer_mask(fb)- place = 1.0 - 0.5 * float(np.abs(layout(ma) - layout(mb)).sum()) if ma.any() and mb.any() else float(ma.any() == mb.any())+def _lab_mean(lab: np.ndarray, m: np.ndarray) -> np.ndarray | None:+ return lab[m].mean(axis=0) if m.any() else None+++def _side(bgr: np.ndarray) -> dict:+ """One frame's drawn layer and what a remake can be told about it: where it sits, how spread out, how much,+ its mean colour and the ground's (Lab)."""+ m = layer_mask(bgr)+ lab = cv2.cvtColor(bgr, cv2.COLOR_BGR2LAB).astype(np.float32)+ lab[..., 0] *= 100.0 / 255.0 # OpenCV stores L as 0-255; colour distances below are in CIE units+ lab[..., 1:] -= 128.0+ g = cv2.cvtColor(ground(bgr).astype(np.uint8)[None, None], cv2.COLOR_BGR2LAB).astype(np.float32)[0, 0]+ g = np.array([g[0] * 100.0 / 255.0, g[1] - 128.0, g[2] - 128.0], np.float32)+ s = {"mask": m, "layout": layout(m), "cover": float(m.mean()), "ground": g, "colour": _lab_mean(lab, m)}+ if m.any():+ ys, xs = np.nonzero(m)+ h, w = m.shape+ s["centre"] = np.array([xs.mean() / w, ys.mean() / h])+ s["spread"] = np.array([xs.std() / w, ys.std() / h])+ return s+++def _score(sa: dict, sb: dict, k: np.ndarray) -> dict:+ ma, mb = sa["mask"], sb["mask"]+ place = 1.0 - 0.5 * float(np.abs(sa["layout"] - sb["layout"]).sum()) if ma.any() and mb.any() else float(ma.any() == mb.any())ua, ub = cv2.dilate(ma.astype(np.uint8), k) > 0, cv2.dilate(mb.astype(np.uint8), k) > 0hit_a = float((ma & ub).sum()) / max(1, int(ma.sum()))hit_b = float((mb & ua).sum()) / max(1, int(mb.sum()))shape = 2 * hit_a * hit_b / (hit_a + hit_b) if hit_a + hit_b else (1.0 if not ma.any() and not mb.any() else 0.0)- ca, cb = float(ma.mean()), float(mb.mean())+ ca, cb = sa["cover"], sb["cover"]amount = min(ca, cb) / max(ca, cb) if max(ca, cb) > 0 else 1.0# equal weight on where it sits and on the shapes themselves; how much is drawn counts half as muchreturn {"place": round(place, 3), "shape": round(shape, 3), "amount": round(amount, 3),"score": round(0.4 * place + 0.4 * shape + 0.2 * amount, 3)}+def _pair(sa: dict, sb: dict) -> dict:+ """Signed differences remake - original for one frame, None where one side has nothing drawn."""+ d: dict = {"cover": (sa["cover"], sb["cover"]), "ground": sb["ground"] - sa["ground"]}+ if sa["colour"] is not None and sb["colour"] is not None:+ d["colour"] = sb["colour"] - sa["colour"]+ if "centre" in sa and "centre" in sb:+ d["shift"] = sb["centre"] - sa["centre"]+ d["size"] = (sb["spread"] + 1e-6) / (sa["spread"] + 1e-6)+ return d+++# How far off counts as visibly off, for the advice only (the score does not use these): a twentieth of the frame,+# a quarter bigger or smaller, a colour difference of 10 (CIE Lab, plainly different side by side).+OFF_SHIFT, OFF_RATIO, OFF_COLOUR = 0.05, 1.25, 10.0+++def _advice(diffs: list[dict]) -> list[str]:+ """What to change in the remake over a stretch of frames, largest first."""+ if not diffs:+ return []+ tips: list[tuple[float, str]] = []+ sh = [d["shift"] for d in diffs if "shift" in d]+ if sh:+ dx, dy = np.median(np.array(sh), axis=0)+ for v, neg, pos in ((dx, ("偏左", "too far left"), ("偏右", "too far right")),+ (dy, ("偏上", "too high"), ("偏下", "too low"))):+ if abs(v) >= OFF_SHIFT:+ tips.append((abs(v) / OFF_SHIFT, T(f"{(pos if v > 0 else neg)[0]} {abs(v) * 100:.0f}% 画面",+ f"{(pos if v > 0 else neg)[1]} by {abs(v) * 100:.0f}% of the frame")))+ size = float(np.exp(np.median(np.log(np.array([d["size"].mean() for d in diffs if "size" in d])))))+ if max(size, 1 / size) >= OFF_RATIO:+ tips.append((max(size, 1 / size) / OFF_RATIO, T(f"铺开范围是原片的 {size:.1f} 倍", f"spread {size:.1f}x the original")))+ ca = float(np.mean([d["cover"][0] for d in diffs])); cb = float(np.mean([d["cover"][1] for d in diffs]))+ if ca > 0 and cb == 0:+ tips.append((9.0, T("画上去的东西没出来", "nothing drawn where the original has graphics")))+ elif cb > 0 and ca == 0:+ tips.append((9.0, T("原片这里没有画东西", "graphics where the original has none")))+ elif ca > 0:+ r = cb / ca+ if max(r, 1 / r) >= OFF_RATIO:+ tips.append((max(r, 1 / r) / OFF_RATIO, T(f"画上去的量是原片的 {r:.1f} 倍", f"{r:.1f}x as much drawn as the original")))+ for key, zh, en in (("colour", "前景颜色", "drawn colour"), ("ground", "底色", "ground")):+ cs = [d[key] for d in diffs if key in d]+ if not cs:+ continue+ dl, da, db = np.median(np.array(cs), axis=0)+ de = float(np.sqrt(dl * dl + da * da + db * db))+ if de >= OFF_COLOUR:+ how = []+ if abs(dl) >= OFF_COLOUR / 2:+ how.append(T("偏亮" if dl > 0 else "偏暗", "too light" if dl > 0 else "too dark"))+ hue = np.hypot(da, db)+ if hue >= OFF_COLOUR / 2:+ how.append(T("色相不对", "wrong hue"))+ tips.append((de / OFF_COLOUR, T(f"{zh}差 {de:.0f}({'、'.join(how) or '偏色'})",+ f"{en} off by {de:.0f} ({', '.join(how) or 'tinted'})")))+ return [t for _, t in sorted(tips, key=lambda x: -x[0])]+++def _lag(la: list, lb: list, every: float, max_s: float = 3.0) -> tuple[float, float]:+ """Time offset of the remake that best lines its layout up with the original's, and how much place agreement+ it gains. Positive: the remake runs late."""+ n = len(la)+ best, base = 0, None+ gains = {}+ for L in range(-int(max_s / every), int(max_s / every) + 1):+ idx = [(i, i + L) for i in range(n) if 0 <= i + L < n]+ if len(idx) < max(4, n // 2):+ continue+ v = float(np.mean([1.0 - 0.5 * np.abs(la[i] - lb[j]).sum() for i, j in idx]))+ gains[L] = v+ if L == 0:+ base = v+ if base is None or not gains:+ return 0.0, 0.0+ best = max(gains, key=lambda L: (gains[L], -abs(L)))+ return round(best * every, 2), round(gains[best] - base, 3)++def compare(ref: str, remake: str, every: float = 0.5, out: Path | None = None, scenes: Path | None = None,worst: int = 8) -> dict:- """Frame-by-frame score of a remake against the original on the drawn layer. Both videos are decoded side by- side and only the worst frames are kept, so memory does not grow with length."""+ """Frame-by-frame score of a remake against the original on the drawn layer, with what to change: position,+ spread, amount, drawn colour, ground and timing. Both videos are decoded side by side and only the worst frames+ are kept, so memory does not grow with length."""ri, mi = video_info(ref), video_info(remake)dur = min(ri.duration, mi.duration)k = np.ones((5, 5), np.uint8)rows: list[dict] = []+ la: list = []+ lb: list = []keep: list = [] # min-heap on -score: the `worst` lowest-scoring frames with their picturespairs = zip(iter_frames(ref, ri, WORK_W, start=0, duration=dur, fps=1.0 / every),iter_frames(remake, mi, WORK_W, start=0, duration=dur, fps=1.0 / every))for i, (fa, fb) in enumerate(pairs):fb = cv2.resize(fb, (fa.shape[1], fa.shape[0]))- r = {"t": round(i * every, 2), **_score(fa, fb, k)}+ sa, sb = _side(fa), _side(fb)+ r = {"t": round(i * every, 2), **_score(sa, sb, k)}rows.append(r)+ del sa["mask"], sb["mask"] # keep only the small numbers, so timing can be lined up afterwards+ la.append(sa)+ lb.append(sb)if out:item = (-r["score"], i, fa, fb)if len(keep) < worst:@@ -306,17 +415,32 @@ def compare(ref: str, remake: str, every: float = 0.5, out: Path | None = None,if not rows:raise ValueError(T("没有可比较的帧", "no frames to compare"))res: dict = {"ref": ref, "remake": remake, "every": every,- **{k2: round(float(np.mean([r[k2] for r in rows])), 3) for k2 in ("score", "place", "shape")}, "frames": rows}+ **{k2: round(float(np.mean([r[k2] for r in rows])), 3) for k2 in ("score", "place", "shape")}}+ lag, gain = _lag([a["layout"] for a in la], [b["layout"] for b in lb], every)+ shift = 0+ if lag and gain >= 0.05:+ shift = int(round(lag / every))+ res["offset"] = {"seconds": lag, "place_gain": gain,+ "advice": T(f"重做整体{'晚' if lag > 0 else '早'}了约 {abs(lag):g} 秒,先对齐时间;下面的建议已按对齐后算",+ f"the remake runs {abs(lag):g}s {'late' if lag > 0 else 'early'}; line up the timing first "+ "(the advice below is taken after lining it up)")}+ # the advice compares each original frame with the remake frame it lines up with+ diffs = [_pair(la[i], lb[i + shift]) if 0 <= i + shift < len(lb) else None for i in range(len(la))]+ res["advice"] = _advice([d for d in diffs if d])if scenes and Path(scenes).exists():per = []for sc in read_json(scenes).get("scenes", []):- rs = [r for r in rows if sc["start"] <= r["t"] < sc["end"]]- if rs:+ ix = [i for i, r in enumerate(rows) if sc["start"] <= r["t"] < sc["end"]]+ if ix:per.append({"id": sc["id"], "start": sc["start"], "end": sc["end"],- "score": round(float(np.mean([r["score"] for r in rs])), 3),- "shape": round(float(np.mean([r["shape"] for r in rs])), 3)})+ "score": round(float(np.mean([rows[i]["score"] for i in ix])), 3),+ "shape": round(float(np.mean([rows[i]["shape"] for i in ix])), 3),+ "advice": _advice([diffs[i] for i in ix if diffs[i]])})res["scenes"] = sorted(per, key=lambda x: x["score"])res["worst"] = sorted(r["t"] for r in sorted(rows, key=lambda r: r["score"])[:worst])+ for i in sorted(range(len(rows)), key=lambda i: rows[i]["score"])[:worst]:+ rows[i]["advice"] = _advice([diffs[i]] if diffs[i] else [])+ res["frames"] = rowsif out:out.mkdir(parents=True, exist_ok=True)cells = []diff --git a/skills/rea-video/references/remake.md b/skills/rea-video/references/remake.mdindex 2e27d55..d117f56 100644--- a/skills/rea-video/references/remake.md+++ b/skills/rea-video/references/remake.md@@ -15,7 +15,7 @@- **静态图推拉、静帧**:本地按测得的运动参数重建。- **代码渲染**:用 Remotion 重建,或在 ChatCut 里生成动效图形。用 Remotion 时,把报告「代码合成」一节(每镜做法、逐镜动效时间轴、色值)连同 `shots/` 里的元素截图、关键帧条和 `packaging/overlays.ass` 一起交给写代码的人或 LLM;按时间轴的时间和位置写动画,按截图重画图形,图标 / Logo / 插画这类画不出来的直接抠图用。- 拆片包的 `frames/` 里每个场景有原尺寸帧、画上去那一层的抠图(`scene_XX_layer.png`)和采样点(`points/`,x、y 为 0–1 坐标):粒子、线条、图形照着摆或描,不要照文字描述去猜形状。旧目录没有 `frames/` 时运行 `rea-video frames out/ref`。- - 做完用 `rea-video compare 原片 成片 --scenes out/ref/frames/scenes.json -o 对比目录` 打分,先改 `compare_worst.jpg` 里分数最低的时刻。+ - 做完用 `rea-video compare 原片 成片 --scenes out/ref/frames/scenes.json -o 对比目录` 打分,按输出里的 `advice`(时间早晚、位置、范围、多少、颜色)先改分数最低的场景,对照 `compare_worst.jpg` 看。- **真实素材**:列清单让用户提供;拿到后用 `rea-video assemble` 拼回原时间线,或放进 ChatCut 按原片节奏剪。- **声音**:TTS、BGM(按 BPM / 调性 / 情绪)、音效(按时间点)三条轨分别准备。- **剪辑包装(字幕、花字、贴纸)**:不进生成。生成模型只出干净的人和画面,包装层最后按「剪辑包装层」的时间轴叠上去,这样字不会被模型画糊,换文案时也只改包装层。diff --git a/tests/test_layers.py b/tests/test_layers.pyindex dfe7b97..544933b 100644--- a/tests/test_layers.py+++ b/tests/test_layers.py@@ -134,3 +134,16 @@ def test_scene_table_text():"colours": [{"hex": "#4e747c"}], "pieces": 286, "box": [0.4, 0.03, 0.6, 0.78]}}]))assert "| scene_01 | #1 | 0.0–5.2s | #000000 | #507c87" in md and "rea-video compare" in md and "scene_XX_layer.png" in mdassert layer_scenes_md([]) == []+++def test_compare_says_what_to_change(tmp_path):+ moving = [_glow(_dots(0, cx=100 + 15 * i)) for i in range(24)]+ ref = _video(tmp_path / "ref.mp4", moving)+ late = compare(str(ref), str(_video(tmp_path / "late.mp4", [moving[0]] * 4 + moving[:-4])))+ assert late["offset"]["seconds"] == 1.0 and late["advice"] == [] # lined up first, nothing else is off+ still = _video(tmp_path / "still.mp4", [_glow(_dots())] * 12)+ left = compare(str(still), str(_video(tmp_path / "left.mp4", [_glow(_dots(cx=150))] * 12)))+ assert "offset" not in left and any("偏左" in a for a in left["advice"])+ pale = compare(str(still), str(_video(tmp_path / "pale.mp4", [_dots(light=True)] * 12)))+ assert any(a.startswith("底色") and "偏亮" in a for a in pale["advice"])+ assert compare(str(still), str(still))["advice"] == []