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
Measure particle scenes and score remakes
june51af00ab4482
diff --git a/docs/cli.md b/docs/cli.mdindex d2d4502..e6c41bc 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -104,6 +104,8 @@ rea-video capsule-draft out/ref/breakdown.json --capsule-root $CC --capsule-name| `videomd OUT_DIR --check` | 校验目录是否符合拆片包规范,不合格时逐条列出问题 || `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/`:每场景首 / 中 / 尾原尺寸帧、`scenes.json`(光晕颜色和位置、粒子颜色、粒子数、范围、重心随时间的轨迹)、`points/scene_XX.json`(从原片取的粒子目标点);decompose 遇到粒子镜头会自动跑 |+| `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/docs/videomd.md b/docs/videomd.mdindex 2057d21..9086454 100644--- a/docs/videomd.md+++ b/docs/videomd.md@@ -29,7 +29,7 @@| `video/packaging.md` | 字幕、花字、贴纸、画中画的时间和样式 || `video/remake.md` | 复刻方案:生成单元、拍摄场次、代码合成、要准备的真实素材 || `video/shots/<编号>.md` | 每镜的 `inferred`(制作方式、概率、次选、由谁判定、有没有真实素材)、`flags`、`frames`;正文是看得到的、推断和依据、提示词 |-| `breakdown.json`、`shots/`、`stems/`、`sfx/`、`packaging/`、`storyboard.jpg`、`audio.png` | 完整数据和媒体文件,地图里都列着 |+| `breakdown.json`、`shots/`、`stems/`、`sfx/`、`packaging/`、`frames/`(粒子镜头才有)、`storyboard.jpg`、`audio.png` | 完整数据和媒体文件,地图里都列着 |没有内容的主题文件不生成。diff --git a/eval/RESULTS.md b/eval/RESULTS.mdindex 22096bc..602f506 100644--- a/eval/RESULTS.md+++ b/eval/RESULTS.md@@ -152,15 +152,15 @@| `labels.yaml`(缺 11 条) | 100% || `holdout.yaml`(缺 3 条) | 100% || `holdout2.yaml`(缺 4 条) | 100% |-| `articles.yaml` 文章视频(转码) | 96.5% |+| `articles.yaml` 文章视频(转码) | 97.2% || `daihuo.yaml` 带货 | 63.2% || `koubo.yaml` 口播 | 93.3% |-| `film.yaml` 影视混剪 | 15.4% |+| `film.yaml` 影视混剪 | 15.8% || `code_videos.yaml` | 94.8% || `code_videos_holdout.yaml` | 100% |-| `particles.yaml` | 100% |+| `particles.yaml`(3 条) | 66.7%(集合从 1 条扩到 3 条;新增的 bokeh 样本没认出,原有样本仍然判对) |-和前面记录的只用工具的分数比,没有一组下降:文章视频 88.6% → 96.5%,带货 46.4% → 63.2%,口播 75.5% → 93.3%,影视混剪 15% → 15.4%。带货和影视混剪只用工具仍然不够,要靠看图复核(第 5、6 节)。+和前面记录的只用工具的分数比,没有一组下降:文章视频 88.6% → 97.2%,带货 46.4% → 63.2%,口播 75.5% → 93.3%,影视混剪 15% → 15.8%。带货和影视混剪只用工具仍然不够,要靠看图复核(第 5、6 节)。## 已知局限@@ -168,7 +168,8 @@2. 暗色/半透明的背景照片、暗色主题网页截图漏检;实拍或 AI 画面上叠加的商品图和 Logo 不做确定性检测,依赖 VLM。3. 嵌入图片是真实照片还是 AI 图,确定性层判断不了。4. 加看图模型和 agent 复核的分数是把缓存的答案重新融合得到的,还没有在从头解码的特征上重测;只开看图模型、不做 agent 复核时在留出集上曾低于只用工具。-5. 音乐来源:普通视频里的 AI 生成 BGM 判断不出来(见上);AI MV 样本只有 1 条。+5. 暗底粒子:粒子背后有大圈柔光的规则(`fine_glow`)阈值按 `particles.yaml` 的 halo 样本定,halo 样本属于开发集,能认出它不说明能推广到其他带柔光的粒子视频;大颗失焦光斑漂在暗底上的(bokeh 样本)还会被判成 3D 渲染。星空、夜景灯光、暗色界面没有专门的样本,这条规则只在暗底且有柔光时生效,但误判成代码渲染的可能没有排除。+6. 音乐来源:普通视频里的 AI 生成 BGM 判断不出来(见上);AI MV 样本只有 1 条。## 复现diff --git a/rea_video/classify.py b/rea_video/classify.pyindex 4c57072..dcc6a72 100644--- a/rea_video/classify.py+++ b/rea_video/classify.py@@ -104,6 +104,12 @@ RULES = {# shaded pixels and many small bright peaks. Eval photo / 3D / AI frames on dark ground keep lit_smooth >= 0.47# and lit_peaks <= 10; a particle explainer video sits at lit_smooth 0.01-0.22, lit_peaks 5-67"fine_dark": {"dark": 0.4, "smooth": 0.3, "peaks": 4.0, "lit_max": 0.4, "lit_min": 0.002},+ # the same with a soft halo lit behind the dots (measured on the "spark" layer, the glow blurred out): a glowing+ # particle explainer sits at spark_smooth 0.03-0.17, spark_peaks 12-62, spark_ratio <= 0.03; eval AI / 3D / photo+ # frames keep spark_smooth >= 0.31+ # glow_min: the halo must be there (share of the frame lit by the blurred picture; 0.16-0.36 on the particle video),+ # so dark pictures without one (star fields, dark UI) stay with fine_dark above+ "fine_glow": {"smooth": 0.24, "peaks": 8.0, "spark_max": 0.08, "glow_min": 0.08},# thin dark lines / dots on a light ground: fine_dark on the inverted picture, with a looser smoothness bound# (anti-aliased dark strokes shade more than glowing dots)"fine_light": {"smooth": 0.35},@@ -244,13 +250,21 @@ def deterministic(f: dict, overlay: dict | None = None, text: dict | None = Noneif fd["lit_min"] < f.get("lit_ratio", 0.0):fine_dark = (_sig((f.get("dark_ratio", 0.0) - fd["dark"]) / 0.05) * _sig((fd["smooth"] - f.get("lit_smooth", 1.0)) / 0.05)* _sig((f.get("lit_peaks", 0.0) - fd["peaks"]) / 1.0) * _sig((fd["lit_max"] - f.get("lit_ratio", 0.0)) / 0.04))+ fg = RULES["fine_glow"]+ glow_fine = 0.0+ if fd["lit_min"] < f.get("spark_ratio", 0.0) and f.get("glow_ratio", 0.0) >= fg["glow_min"]:+ glow_fine = (_sig((f.get("dark_ratio", 0.0) - fd["dark"]) / 0.05) * _sig((fg["smooth"] - f.get("spark_smooth", 1.0)) / 0.03)+ * _sig((f.get("spark_peaks", 0.0) - fg["peaks"]) / 1.5) * _sig((fg["spark_max"] - f.get("spark_ratio", 0.0)) / 0.01))+ by_glow = glow_fine > fine_dark+ fine_dark = max(fine_dark, glow_fine)facts["fine_dark"] = round(fine_dark, 3)if fine_dark > 0.5:- ev.append(T("暗底上的亮部几乎全是细碎亮点/细线(亮部平滑过渡只占 {sm:.0%},每百个亮像素 {pk:.0f} 个亮峰):粒子/点云/线框类图形,"+ sm, pk = (f.get("spark_smooth", 0.0), f.get("spark_peaks", 0.0)) if by_glow else (f.get("lit_smooth", 0.0), f.get("lit_peaks", 0.0))+ ev.append(T("暗底上的亮部几乎全是细碎亮点/细线({halo}亮部平滑过渡只占 {sm:.0%},每百个亮像素 {pk:.0f} 个亮峰):粒子/点云/线框类图形,""不是有明暗过渡的实拍、3D 表面或 AI 画面",- "On a dark ground the lit part is almost all fine dots / thin lines (only {sm:.0%} of lit pixels shade gently, "+ "On a dark ground the lit part is almost all fine dots / thin lines ({halo}only {sm:.0%} of lit pixels shade gently, ""{pk:.0f} bright peaks per 100 lit pixels): particle / point-cloud / wireframe graphics, not a shaded photo, 3D surface or AI picture",- sm=f.get("lit_smooth", 0.0), pk=f.get("lit_peaks", 0.0)))+ sm=sm, pk=pk, halo=T("去掉背后的柔光后,", "with the soft halo behind them taken out, ") if by_glow else ""))graphic = max(graphic, fine_dark)# the same on a light ground: thin dark lines / dots (line art, generative ink, dot matrices). Pages of small text# are left to the screenshot cues (RULES["ui_text"]), they are a document rather than line artdiff --git a/rea_video/cli.py b/rea_video/cli.pyindex fec3770..70547d6 100644--- a/rea_video/cli.py+++ b/rea_video/cli.py@@ -314,6 +314,42 @@ def cmd_tiles(args) -> int:return 0+def cmd_frames(args) -> int:+ from .particles import scene_frames++ if args.every <= 0:+ raise SystemExit("rea-video: --every 必须大于 0")+ out = Path(args.out_dir)+ if not (out / "breakdown.json").is_file():+ raise SystemExit(f"rea-video: {out} 下没有 breakdown.json,先运行 decompose")+ res = scene_frames(out, every=args.every, n_points=args.points, all_shots=args.all)+ if not res["scenes"]:+ print(T("没有粒子镜头(加 --all 对所有镜头取帧)", "no particle shots (add --all to cover every shot)"))+ return 0+ print(json.dumps({"scenes": len(res["scenes"]), "file": str(out / "frames" / "scenes.json"),+ "cuts": [s["start"] for s in res["scenes"]]}, ensure_ascii=False))+ return 0+++def cmd_compare(args) -> int:+ from .particles import compare++ if args.every <= 0:+ raise SystemExit("rea-video: --every 必须大于 0")+ for p in (args.ref, args.remake):+ if not Path(p).is_file():+ raise SystemExit(f"rea-video: 找不到 {p}")+ res = compare(args.ref, args.remake, every=args.every, invert=args.invert, 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", "inverted", "worst") if k in res}+ if res.get("scenes"):+ brief["lowest_scenes"] = res["scenes"][:5]+ if res.get("sheet"):+ brief["sheet"] = res["sheet"]+ print(json.dumps(brief, ensure_ascii=False, indent=1))+ return 0++def cmd_summary(args) -> int:"""Compact, agent-friendly view of a breakdown (instead of reading the whole JSON)."""from .i18n import T, join@@ -624,6 +660,23 @@ def main(argv: list[str] | None = None) -> int:t.add_argument("-o", "--out", default="out/tiles.jpg")t.set_defaults(func=cmd_tiles)+ fr = sub.add_parser("frames", help="粒子镜头按场景切分,取原尺寸帧、测光晕 / 粒子颜色 / 粒子数,并从原片取粒子目标点(decompose 遇到粒子镜头会自动跑)")+ fr.add_argument("out_dir", help="decompose 的输出目录")+ fr.add_argument("--every", type=float, default=0.25, help="采样间隔秒数(默认 0.25)")+ fr.add_argument("--points", type=int, default=4000, help="每个场景取多少个目标点(默认 4000)")+ fr.add_argument("--all", action="store_true", help="所有镜头都做,不只是粒子镜头")+ fr.set_defaults(func=cmd_frames)++ cp = sub.add_parser("compare", help="逐帧给复刻打分(粒子 / 图形落在哪、形状重合度),列出最差的时刻并拼对比图")+ cp.add_argument("ref", help="原片")+ cp.add_argument("remake", help="复刻成片")+ cp.add_argument("--every", type=float, default=0.5, help="采样间隔秒数(默认 0.5)")+ cp.add_argument("--invert", choices=["auto", "yes", "no"], default="auto", help="复刻换了深浅底时先反相再比(默认自动判断)")+ cp.add_argument("--scenes", help="frames/scenes.json:按场景汇总分数")+ cp.add_argument("--worst", type=int, default=8, help="对比图里放几个最差时刻(默认 8)")+ cp.add_argument("-o", "--out", help="输出目录:compare.json 和 compare_worst.jpg")+ cp.set_defaults(func=cmd_compare)+sm = sub.add_parser("summary", help="紧凑打印拆解结果(低置信镜头会被标出来)")sm.add_argument("breakdown")sm.set_defaults(func=cmd_summary)diff --git a/rea_video/features.py b/rea_video/features.pyindex cbe1d00..299406a 100644--- a/rea_video/features.py+++ b/rea_video/features.py@@ -49,6 +49,18 @@ def noise_sigma(gray: np.ndarray) -> float:return float(math.sqrt(math.pi / 2.0) * conv[mask].mean() / 6.0)+SPARK = 25 # how far a pixel must stand out above the halo to count as a dot / line+++def halo_blur(gf: np.ndarray) -> np.ndarray:+ """The soft glow of a gray picture (float32): a Gaussian blur with a radius of 1/40 of the long side, done at a+ quarter size since nothing that wide needs full resolution."""+ h, w = gf.shape+ sh, sw = max(1, h // 4), max(1, w // 4)+ small = cv2.resize(gf, (sw, sh), interpolation=cv2.INTER_AREA)+ return cv2.resize(cv2.GaussianBlur(small, (0, 0), max(h, w) / 160.0), (w, h), interpolation=cv2.INTER_LINEAR)++def spatial_features(bgr: np.ndarray) -> dict:gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)h, w = gray.shape@@ -89,7 +101,19 @@ def spatial_features(bgr: np.ndarray) -> dict:lit_mask = gray > 50n_lit = int(lit_mask.sum())gf = gray.astype(np.float32)- peaks = (gf >= cv2.dilate(gf, np.ones((3, 3), np.uint8))) & (gf - cv2.blur(gf, (7, 7)) > 18) & lit_mask+ bumps = (gf >= cv2.dilate(gf, np.ones((3, 3), np.uint8))) & (gf - cv2.blur(gf, (7, 7)) > 18)+ peaks = bumps & lit_mask+ # the same with the soft glow behind the graphics taken out: particle explainers often light a large radial+ # halo behind the dots, which is smooth and lit and hides the dots from lit_smooth / lit_peaks. "spark" = what+ # stands out above the heavily blurred picture. Only dark pictures can be particles on black, so the rest skip it+ glow_ratio, n_spark, spark_smooth, spark_peaks = 0.0, 0, 1.0, 0+ if dark_ratio > 0.3:+ glow = halo_blur(gf)+ spark = (gf - glow) > SPARK+ n_spark = int(spark.sum())+ glow_ratio = float((glow > 28).mean())+ spark_smooth = float(((mag < 40) & spark).sum()) / n_spark if n_spark else 1.0+ spark_peaks = int((bumps & spark).sum())# the same on the inverted picture: thin dark lines / dots / small text on a light ground (line art, documents)inv = 255 - grayink_mask = inv > 50@@ -120,6 +144,10 @@ def spatial_features(bgr: np.ndarray) -> dict:"lit_ratio": n_lit / float(h * w),"lit_smooth": float(((mag < 40) & lit_mask).sum()) / n_lit if n_lit else 1.0,"lit_peaks": 100.0 * float(peaks.sum()) / n_lit if n_lit else 0.0,+ "glow_ratio": glow_ratio,+ "spark_ratio": n_spark / float(h * w),+ "spark_smooth": spark_smooth,+ "spark_peaks": 100.0 * spark_peaks / n_spark if n_spark else 0.0,"light_ratio": float((bmean > 227).mean()),"ink_ratio": n_ink / float(h * w),"ink_smooth": float(((mag < 40) & ink_mask).sum()) / n_ink if n_ink else 1.0,diff --git a/rea_video/particles.py b/rea_video/particles.pynew file mode 100644index 0000000..73c9940--- /dev/null+++ b/rea_video/particles.py@@ -0,0 +1,331 @@+"""Particle / point-cloud pictures on a dark ground, measured for a code remake.++`rea-video frames out/ref` splits each particle shot into scenes (the dots regroup into a new shape without a cut),+saves full-resolution frames per scene, measures what a renderer needs (ground, halo, dot colours, dot size and count,+where the dots sit) and samples the lit dots of each scene's middle frame as target points, so a remake can place its+particles on the original shapes instead of guessing them from a description.++`rea-video compare ref.mp4 remake.mp4` scores a remake against the original frame by frame (where the dots are and how+dense, with the halo and colours left out) and puts the worst moments side by side, so the remake can be fixed where it+is furthest off rather than where it looks off at a glance.+"""+from __future__ import annotations++from pathlib import Path++import cv2+import numpy as np++from .features import SPARK, halo_blur+from .i18n import T+from .media import extract_frame, iter_frames, video_info+from .util import read_json, write_json++WORK_W = 480 # measuring width; the remake reads positions as 0-1 of the frame, so this only sets precision+GRID = (16, 9) # density map cells (x, y)+SCENE_WIN = 1.5 # seconds compared on each side of a candidate scene change+SCENE_MIN = 1.5 # shortest scene kept+SCENE_JUMP = 0.25 # density-map change (half L1, 0-1) that starts a new scene+++def _hex(bgr) -> str:+ b, g, r = (int(round(float(v))) for v in bgr)+ return f"#{r:02x}{g:02x}{b:02x}"+++def spark_mask(bgr: np.ndarray, text_boxes: list | None = None) -> np.ndarray:+ """Pixels that stand out above the soft halo: the dots and thin lines themselves. text_boxes (0-1 x, y, w, h) are+ blanked, so subtitles and labels do not count as particles."""+ gf = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY).astype(np.float32)+ m = (gf - halo_blur(gf)) > SPARK+ h, w = m.shape+ for x, y, bw, bh in text_boxes or []:+ pad = 0.01+ x0, y0 = int(max(0, x - pad) * w), int(max(0, y - pad) * h)+ x1, y1 = int(min(1, x + bw + pad) * w + 1), int(min(1, y + bh + pad) * h + 1)+ m[y0:y1, x0:x1] = False+ return m+++def density(mask: np.ndarray) -> np.ndarray:+ d = cv2.resize(mask.astype(np.float32), GRID, interpolation=cv2.INTER_AREA)+ s = float(d.sum())+ return d / s if s > 0 else d+++def _colours(pixels: np.ndarray, k: int = 3) -> list[dict]:+ """Main colours of a set of BGR pixels, as hex with their share."""+ if len(pixels) < 10:+ return []+ px = pixels.astype(np.float32)+ if len(px) > 6000:+ px = px[np.random.default_rng(0).choice(len(px), 6000, replace=False)]+ k = min(k, len(np.unique(px, axis=0)))+ cv2.setRNGSeed(0)+ _, lbl, centers = cv2.kmeans(px, k, None, (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 1.0), 2,+ cv2.KMEANS_PP_CENTERS)+ share = np.bincount(lbl.ravel(), minlength=k) / len(lbl)+ return [{"hex": _hex(centers[i]), "share": round(float(share[i]), 2)} for i in np.argsort(-share) if share[i] >= 0.05]+++def measure(bgr: np.ndarray, text_boxes: list | None = None) -> dict:+ """What a particle renderer needs from one frame: ground, halo (colour, centre, radius), dot colours, dot size,+ rough dot count, where the dots sit and how much of the frame they cover. Positions are 0-1 of the frame."""+ h, w = bgr.shape[:2]+ gf = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY).astype(np.float32)+ halo = halo_blur(gf)+ border = np.concatenate([bgr[0], bgr[-1], bgr[:, 0], bgr[:, -1]])+ ground = np.median(border, axis=0)+ out: dict = {"ground": _hex(ground)}+ lift = np.clip(halo - float(np.median(cv2.cvtColor(border[None], cv2.COLOR_BGR2GRAY))), 0, None)+ if lift.max() > 6:+ on = lift > lift.max() * 0.5+ ys, xs = np.nonzero(on)+ wts = lift[on]+ cx, cy = float((xs * wts).sum() / wts.sum()) / w, float((ys * wts).sum() / wts.sum()) / h+ blur = cv2.GaussianBlur(bgr, (0, 0), max(h, w) / 40.0)+ peak = np.unravel_index(int(np.argmax(lift)), lift.shape)+ out["halo"] = {"colour": _hex(blur[peak]), "centre": [round(cx, 3), round(cy, 3)],+ "radius": round(float(np.sqrt(on.sum() / np.pi)) / w, 3), "lift": round(float(lift.max()), 1)}+ m = spark_mask(bgr, text_boxes)+ n = int(m.sum())+ out["cover"] = round(n / float(h * w), 4)+ if n < 10:+ return out+ out["colours"] = _colours(bgr[m])+ ys, xs = np.nonzero(m)+ out["box"] = [round(float(np.percentile(xs, 2)) / w, 3), round(float(np.percentile(ys, 2)) / h, 3),+ round(float(np.percentile(xs, 98)) / w, 3), round(float(np.percentile(ys, 98)) / h, 3)]+ out["centre"] = [round(float(xs.mean()) / w, 3), round(float(ys.mean()) / h, 3)]+ n_cc, _, stats, _ = cv2.connectedComponentsWithStats(m.astype(np.uint8), connectivity=8)+ areas = stats[1:, cv2.CC_STAT_AREA]+ if len(areas):+ out["dots"] = int(n_cc - 1)+ out["dot_px"] = round(float(np.median(areas)) * (1.0 / w) ** 2 * 1e6, 1) # median dot area, per million of frame+ out["lines"] = round(float((areas > 40).sum()) / len(areas), 2) # share of blobs long enough to be lines / clumps+ out["density"] = [[round(float(v), 3) for v in row] for row in density(m)]+ return out+++def sample_points(bgr: np.ndarray, n: int = 4000, text_boxes: list | None = None) -> list[list[float]]:+ """Up to n lit dots of the frame as [x, y, r, g, b, a] (x, y 0-1; colour 0-255; a = how far the pixel stands out+ above the halo, 0-1), picked with probability by brightness: targets a particle system can be laid onto."""+ gf = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY).astype(np.float32)+ lift = gf - halo_blur(gf)+ m = spark_mask(bgr, text_boxes)+ ys, xs = np.nonzero(m)+ if not len(xs):+ return []+ wts = lift[ys, xs]+ pick = np.random.default_rng(0).choice(len(xs), size=min(n, len(xs)), replace=False, p=wts / wts.sum())+ h, w = gf.shape+ a = np.clip(wts[pick] / 255.0 * 2, 0, 1)+ return [[round(float(xs[i] + 0.5) / w, 4), round(float(ys[i] + 0.5) / h, 4), *[int(v) for v in bgr[ys[i], xs[i]][::-1]],+ round(float(al), 2)] for i, al in zip(pick, a)]+++def _text_boxes(out: Path, b: dict) -> list[tuple[float, float, list]]:+ """Where text sits and when: the packaging timeline when it is written, plus every OCR read stored on the shots+ (decompose measures particles before the timeline file exists)."""+ boxes = [(float(it["t"]) - 0.6, float(it["t"]) + 0.6, it["bbox"]) for s in b.get("shots", [])+ for it in (s.get("text") or {}).get("items", []) if it.get("bbox") and it.get("t") is not None]+ tl = out / "packaging" / "timeline.json"+ if tl.exists():+ boxes += [(float(x["t0"]), float(x["t1"]), x["bbox"]) for x in read_json(tl).get("text", []) if x.get("bbox")]+ return boxes+++def _boxes_at(boxes, t: float, until: float | None = None) -> list:+ """Text boxes on screen at t (or at any time in t..until): OCR misses a label on some frames, so a scene blanks+ every box seen during it."""+ z = t if until is None else until+ return [b for t0, t1, b in boxes if t0 - 0.3 <= z and t <= t1 + 0.3]+++def split_scenes(descs: np.ndarray, times: np.ndarray, start: float, end: float) -> list[tuple[float, float]]:+ """Scene changes inside one shot: where the density map before and after differ by more than they vary inside+ each side. descs: one density map (flattened) per sampled time."""+ if len(times) < 2:+ return [(start, end)]+ step = float(np.median(np.diff(times)))+ win = max(1, int(round(SCENE_WIN / step)))+ score = np.zeros(len(times))+ for i in range(win, len(times) - win + 1):+ a, b = descs[i - win:i], descs[i:i + win]+ spread = 0.5 * (0.5 * np.abs(a - a.mean(0)).sum(1).mean() + 0.5 * np.abs(b - b.mean(0)).sum(1).mean())+ score[i] = 0.5 * np.abs(a.mean(0) - b.mean(0)).sum() - spread+ cuts: list[float] = []+ near = max(1, int(round(SCENE_MIN / step)))+ for i in np.argsort(-score):+ if score[i] < SCENE_JUMP:+ break+ t = float(times[i])+ if t - start < SCENE_MIN or end - t < SCENE_MIN or any(abs(t - c) < SCENE_MIN for c in cuts):+ continue+ lo, hi = max(0, i - near), min(len(score), i + near + 1)+ if score[i] >= score[lo:hi].max():+ cuts.append(t)+ edges = [start, *sorted(cuts), end]+ return list(zip(edges[:-1], edges[1:]))+++def _is_particles(shot: dict) -> bool:+ facts = (shot.get("deterministic") or {}).get("facts") or {}+ return facts.get("fine_dark", 0.0) > 0.5+++def _clear(fdir: Path) -> None:+ """Drop what an earlier run wrote, so a rerun with fewer scenes leaves no stale scene files behind."""+ for p in [*fdir.glob("scene_*.jpg"), *(fdir / "points").glob("scene_*.json"), fdir / "scenes.json"]:+ p.unlink(missing_ok=True)+ for d in (fdir / "points", fdir):+ if d.is_dir() and not any(d.iterdir()):+ d.rmdir()+++def scene_frames(out: Path, every: float = 0.25, n_points: int = 4000, all_shots: bool = False, breakdown: dict | None = None) -> dict:+ """Scenes, full-resolution frames, measurements and target points for the particle shots of a breakdown.+ Frames are measured as they are decoded (memory does not grow with shot length)."""+ out = Path(out)+ b = breakdown if breakdown is not None else read_json(out / "breakdown.json")+ video = (b.get("source") or {}).get("path")+ if not video or not Path(video).exists():+ raise FileNotFoundError(T("找不到原视频 {p}(breakdown.json 的 source.path)", "source video not found: {p} (source.path in breakdown.json)", p=video))+ fdir = out / "frames"+ _clear(fdir)+ shots = [s for s in b.get("shots", []) if all_shots or _is_particles(s)]+ if not shots:+ return {"video": video, "every": every, "scenes": []}+ info = video_info(video)+ boxes = _text_boxes(out, b)+ (fdir / "points").mkdir(parents=True, exist_ok=True)+ full_w = min(1080, info.display_size[0] or 1080)+ scenes: list[dict] = []+ for s in shots:+ st, en = float(s["start"]), float(s["end"])+ descs, times, track = [], [], []+ for i, f in enumerate(iter_frames(video, info, WORK_W, start=st, duration=en - st, fps=1.0 / every)):+ t = st + i * every+ m = spark_mask(f, _boxes_at(boxes, t))+ descs.append(density(m).ravel())+ times.append(t)+ ys, xs = np.nonzero(m)+ if len(xs) >= 10: # how the dots move: centre, horizontal spread and cover over time+ track.append([round(t, 2), round(float(xs.mean()) / f.shape[1], 3), round(float(ys.mean()) / f.shape[0], 3),+ round(float(xs.std()) / f.shape[1], 3), round(float(m.mean()), 4)])+ if not times:+ continue+ for a, z in split_scenes(np.array(descs), np.array(times), st, en):+ sid = f"scene_{len(scenes) + 1:02d}"+ mid = (a + z) / 2+ rec = {"id": sid, "shot": s.get("index"), "start": round(a, 2), "end": round(z, 2), "frames": {}}+ for tag, t in (("start", a + min(0.15, (z - a) / 4)), ("mid", mid), ("end", max(a, z - min(0.15, (z - a) / 4)))):+ p = fdir / f"{sid}_{tag}.jpg"+ extract_frame(video, t, p, full_w)+ rec["frames"][tag] = f"frames/{p.name}"+ img = cv2.imread(str(fdir / f"{sid}_mid.jpg"))+ if img is not None:+ img = cv2.resize(img, (WORK_W, max(1, round(img.shape[0] * WORK_W / img.shape[1]))), interpolation=cv2.INTER_AREA)+ in_scene = _boxes_at(boxes, a, z)+ rec["measure"] = measure(img, in_scene)+ write_json(fdir / "points" / f"{sid}.json", {"time": round(mid, 2), "format": "x y r g b a",+ "points": sample_points(img, n_points, in_scene)})+ rec["points"] = f"frames/points/{sid}.json"+ rec["track"] = [r for r in track if a <= r[0] < z]+ scenes.append(rec)+ res = {"video": video, "every": every, "track_format": "t cx cy spread cover", "scenes": scenes}+ write_json(fdir / "scenes.json", res)+ return res+++def _prep(bgr: np.ndarray, invert: bool) -> np.ndarray:+ return 255 - bgr if invert else bgr+++def _is_light(path: str, info, n: int = 20) -> bool:+ """Light ground or dark ground, from a few small frames spread over the video."""+ fps = max(n / max(info.duration, 0.1), 0.01)+ lum = [float(f.mean()) for f in iter_frames(path, info, 64, fps=fps)][:n]+ return bool(lum) and float(np.median(lum)) >= 90+++def _score(fa: np.ndarray, fb: np.ndarray, k: np.ndarray) -> dict:+ ma, mb = spark_mask(fa), spark_mask(fb)+ da, db = density(ma), density(mb)+ place = 1.0 - 0.5 * float(np.abs(da - db).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) > 0+ hit_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())+ amount = min(ca, cb) / max(ca, cb) if max(ca, cb) > 0 else 1.0+ return {"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 compare(ref: str, remake: str, every: float = 0.5, invert: str = "auto", out: Path | None = None,+ scenes: Path | None = None, worst: int = 8) -> dict:+ """Frame-by-frame score of a remake against the original: where the dots are (density-map overlap) and the dot+ masks themselves (overlap with a few pixels of slack). invert: 'auto' flips a light-ground remake of a dark-ground+ original before measuring; 'yes' / 'no' force it. Both videos are decoded side by side and only the worst frames+ are kept, so memory does not grow with length."""+ import heapq++ ri, mi = video_info(ref), video_info(remake)+ dur = min(ri.duration, mi.duration)+ flip = (_is_light(ref, ri) != _is_light(remake, mi)) if invert == "auto" else invert == "yes"+ k = np.ones((5, 5), np.uint8)+ rows: list[dict] = []+ keep: list = [] # min-heap on -score: the `worst` lowest-scoring frames with their pictures+ pairs = 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_raw) in enumerate(pairs):+ fb = cv2.resize(fb_raw, (fa.shape[1], fa.shape[0]))+ r = {"t": round(i * every, 2), **_score(fa, _prep(fb, flip), k)}+ rows.append(r)+ if out:+ item = (-r["score"], i, fa, fb)+ if len(keep) < worst:+ heapq.heappush(keep, item)+ elif item[0] > keep[0][0]:+ heapq.heapreplace(keep, item)+ if not rows:+ raise ValueError(T("没有可比较的帧", "no frames to compare"))+ res: dict = {"ref": ref, "remake": remake, "inverted": bool(flip), "every": every,+ "score": round(float(np.mean([r["score"] for r in rows])), 3),+ "place": round(float(np.mean([r["place"] for r in rows])), 3),+ "shape": round(float(np.mean([r["shape"] for r in rows])), 3), "frames": rows}+ 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:+ 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)})+ res["scenes"] = sorted(per, key=lambda x: x["score"])+ low = sorted(rows, key=lambda r: r["score"])[:worst]+ res["worst"] = [r["t"] for r in sorted(low, key=lambda r: r["t"])]+ if out:+ out.mkdir(parents=True, exist_ok=True)+ cells = []+ for _, i, fa, fb in sorted(keep, key=lambda x: x[1]):+ r = rows[i]+ row = np.hstack([fa, np.full((fa.shape[0], 6, 3), 128, np.uint8), fb])+ cv2.putText(row, f"{r['t']:.1f}s score {r['score']:.2f} (place {r['place']:.2f} shape {r['shape']:.2f})", (8, 20),+ cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1, cv2.LINE_AA)+ cells.append(row)+ if cells:+ cv2.imwrite(str(out / "compare_worst.jpg"), np.vstack(cells), [cv2.IMWRITE_JPEG_QUALITY, 88])+ res["sheet"] = str(out / "compare_worst.jpg")+ write_json(out / "compare.json", res)+ return res+++def lit_palette(frames: list[np.ndarray]) -> list[str]:+ """Dot colours of a particle shot (lit dots only, the black ground and halo left out), most common first."""+ px = [f[spark_mask(f)] for f in frames if f is not None]+ px = [p for p in px if len(p)]+ if not px:+ return []+ return [c["hex"] for c in _colours(np.concatenate(px), k=4)]diff --git a/rea_video/pipeline.py b/rea_video/pipeline.pyindex bb7d8a7..375333f 100644--- a/rea_video/pipeline.py+++ b/rea_video/pipeline.py@@ -199,6 +199,10 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,shot_sheet(sframes, stimes, out / "shots" / f"{sid}_strip.jpg", n=len(sframes), cell_w=200)motion["palette"] = palette(sframes[-1])motion["palette_start"] = palette(sframes[0])+ if facts.get("fine_dark", 0.0) > 0.5: # particles: the frame average is the black ground, keep the dots' own colours+ from .particles import lit_palette++ motion["dots"] = lit_palette(sframes)sheet = element_crops(video, info, s.start, s.end, motion, out / "shots", sid, min(1080, info.display_size[0] or 1080))if sheet:motion["elements_sheet"] = sheet@@ -346,6 +350,15 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,n = reapply(breakdown)if n:LOG.info("re-applied %d earlier user correction(s) for this file", n)+ if any(((r.get("deterministic") or {}).get("facts") or {}).get("fine_dark", 0.0) > 0.5 for r in shot_records):+ from .particles import scene_frames++ LOG.info("particle shots: scenes, full-size frames and target points (frames/)")+ try: # an extra for the remake: a failure here must not lose the breakdown and report+ sc = scene_frames(out, breakdown=breakdown)+ breakdown["particle_scenes"] = {"file": "frames/scenes.json", "count": len(sc["scenes"])}+ except Exception as exc: # noqa: BLE001+ LOG.warning("particle scenes skipped (%s: %s); rerun with `rea-video frames %s`", type(exc).__name__, exc, out)finalize(breakdown, out, engine=engine)LOG.info("done in %.1fs -> %s", time.time() - t0, out)return breakdowndiff --git a/rea_video/plan.py b/rea_video/plan.pyindex 1c9e0aa..46db5fa 100644--- a/rea_video/plan.py+++ b/rea_video/plan.py@@ -174,7 +174,7 @@ def code_scene(shot: dict) -> dict:pal = motion.get("palette") or {}return {"picture": str(desc), "particles": facts.get("fine_dark", 0.0) > 0.5, "style": code_style(shot),"move": _move_words(shot.get("features") or {}), "on_screen_text": words[:6],- "background": pal.get("background"), "palette": [c["hex"] for c in pal.get("colours", [])[:5]],+ "background": pal.get("background"), "palette": [c["hex"] for c in pal.get("colours", [])[:5]], "dots": motion.get("dots") or [],"events": motion.get("events", []), "sequences": motion.get("sequences", []), "layer": motion.get("layer"),"static": motion.get("static", []), "elements_sheet": motion.get("elements_sheet"),"strip": (shot.get("assets") or {}).get("strip"), "transition_in": shot.get("transition_in"),diff --git a/rea_video/production.py b/rea_video/production.pyindex 792aeb2..43119ba 100644--- a/rea_video/production.py+++ b/rea_video/production.py@@ -12,6 +12,7 @@ from __future__ import annotationsfrom .i18n import LangDict, T, join, lang, model_name, semi, shot_ids+import jsonimport refrom pathlib import Path@@ -114,7 +115,9 @@ def code_motion_md(scenes: list[dict]) -> list[str]:L.append("")if sc.get("strip"):L += [f"", ""]- if sc.get("background"):+ if sc.get("background") and sc.get("dots"):+ L.append(T("- 背景 {bg};粒子颜色 {c}", "- Ground {bg}; dot colours {c}", bg=sc["background"], c=" ".join(sc["dots"])))+ elif sc.get("background"):L.append(T("- 背景 {bg};其他主色 {c}", "- Ground {bg}; other main colours {c}", bg=sc["background"],c=" ".join(c for c in sc.get("palette") or [] if c != sc["background"]) or "—"))if sc.get("elements_sheet"):@@ -605,6 +608,16 @@ def production_plan(b: dict, out: Path, engine: str = "seedance2.0") -> dict:if (x.get("assets") or {}).get(k)])} for x in cur]})cur = []plan["code"] = code+ ps = out / "frames" / "scenes.json"+ # only shots still built as particles: a review that relabels a shot drops its scenes from the plan+ particle_shots = {sc["shot"] for c in code for sc in c["scenes"] if sc.get("style") == "particles"}+ if particle_shots and ps.exists():+ try:+ plan["particle_scenes"] = [{k: sc.get(k) for k in ("id", "shot", "start", "end", "points", "frames")} | {"measure": {+ k: (sc.get("measure") or {}).get(k) for k in ("ground", "halo", "colours", "dots", "dot_px", "box")}}+ for sc in json.loads(ps.read_text(encoding="utf-8")).get("scenes", []) if sc.get("shot") in particle_shots]+ except (OSError, ValueError, TypeError):+ passplan["local"] = [{"shot": r["index"], "label_zh": r["base"]["label_zh"], "duration": r["duration"]}for r in shots if r["base"]["label"] in LOCAL_LABELS]plan["avatar"] = [r["index"] for r in shots if r["base"]["label"] == "avatar"]@@ -692,6 +705,34 @@ def report_parts(plan: dict) -> dict[str, list[str]]:return {k: v for k, v in parts.items() if any(x.strip() for x in v)}+def particle_scenes_md(scenes: list[dict]) -> list[str]:+ """Particle shots split into scenes (the dots regroup without a cut), with the measured look and the target points."""+ if not scenes:+ return []+ L = ["", T("**粒子场景**(镜头内粒子重组成新形状就算一个新场景;`frames/` 里每个场景有首 / 中 / 尾原尺寸帧,"+ "`frames/points/scene_XX.json` 是从原片中间帧取的亮点,每行 `x y r g b a`,x、y 是 0–1 坐标:粒子直接摆到这些点上就是原片的形状,"+ "不用照描述去猜;`frames/scenes.json` 的 `track` 是粒子重心和散开程度随时间的变化)",+ "**Particle scenes** (a new scene whenever the dots regroup into a new shape inside a shot; `frames/` holds first / middle / last "+ "full-size frames per scene, `frames/points/scene_XX.json` the lit dots of the original's middle frame, one `x y r g b a` per row "+ "with x, y in 0–1: put the particles on these points and you have the original shape, no guessing from a description; "+ "`track` in `frames/scenes.json` follows the dots' centre and spread over time)"), "",+ T("| 场景 | 镜头 | 时间 | 光晕 | 粒子颜色 | 粒子数 | 范围 (x0 y0 x1 y1) |", "| Scene | Shot | Time | Halo | Dot colours | Dots | Area (x0 y0 x1 y1) |"),+ "|---|---|---|---|---|---|---|"]+ for sc in scenes:+ m = sc.get("measure") or {}+ halo = m.get("halo") or {}+ hw = (T("{c},中心 ({x:.2f}, {y:.2f}),半径 {r:.2f}", "{c}, centre ({x:.2f}, {y:.2f}), radius {r:.2f}", c=halo["colour"],+ x=halo["centre"][0], y=halo["centre"][1], r=halo["radius"]) if halo else "—")+ cols = " ".join(c["hex"] for c in m.get("colours") or []) or "—"+ box = " ".join(f"{v:.2f}" for v in m.get("box") or []) or "—"+ L.append(f"| {sc['id']} | #{sc['shot']} | {sc['start']:.1f}–{sc['end']:.1f}s | {hw} | {cols} | {m.get('dots') or '—'} | {box} |")+ L += ["", T("做完用 `rea-video compare 原片 成片 --scenes frames/scenes.json -o 对比目录` 打分(浅底复刻会自动反相再比),"+ "按 `compare_worst.jpg` 先改分数最低的场景。",+ "When built, score it with `rea-video compare original remake --scenes frames/scenes.json -o dir` (a light-ground remake is "+ "inverted before comparing) and fix the lowest-scoring scenes first, from `compare_worst.jpg`.")]+ return L++def report_md(plan: dict) -> list[str]:if not plan:return []@@ -832,10 +873,12 @@ def report_md(plan: dict) -> list[str]:for sc in scenes:pic = sc["picture"].replace("|", "/").replace("\n", " ") or T("(待看图补:画面元素拼成什么、怎么动)","(to fill from the images: what the elements form and how they move)")- cols = (T("底 {bg}", "ground {bg}", bg=sc["background"]) + " · " + " ".join(c for c in sc["palette"] if c != sc["background"])+ cols = (T("底 {bg}", "ground {bg}", bg=sc["background"]) + " · " + (T("粒子 ", "dots ") + " ".join(sc["dots"]) if sc.get("dots") else+ " ".join(c for c in sc["palette"] if c != sc["background"]))if sc.get("background") else T('、', ', ').join(sc['colours']) or '—')L.append(f"| #{sc['shot']} | {sc['start']:.1f}–{sc['end']:.1f}s | {styles[sc.get('style', 'shapes')][0]} | {pic} | {sc['move']} | "f"{cols} | {' / '.join(w.replace('|', '/') for w in sc['on_screen_text']) or '—'} |")+ L += particle_scenes_md(plan.get("particle_scenes") or [])L += code_motion_md(scenes)if plan["local"]:L += ["", T("### 本地重建", "### Local rebuild"), "", "- " + semi().join(f"#{x['shot']} {x['label_zh']} {x['duration']:.1f}s" for x in plan["local"])diff --git a/rea_video/videomd.py b/rea_video/videomd.pyindex 3fd1dba..9f176ba 100644--- a/rea_video/videomd.py+++ b/rea_video/videomd.py@@ -320,6 +320,8 @@ def write(b: dict, out: Path) -> Path:("stems/", T("人声、配乐、音效分轨", "voice, music and effects stems"), T("听声音、复刻配音配乐", "listening, remaking the sound")),("sfx/", T("每处音效的试听片段", "a clip of each sound effect"), T("找同款音效", "finding matching effects")),("packaging/", T("字幕文件、包装时间轴、贴纸截图", "subtitle files, packaging timeline, sticker frames"), T("复刻字幕和包装", "remaking subtitles and packaging")),+ ("frames/", T("粒子场景:每场景原尺寸帧、测量值、取自原片的粒子目标点", "particle scenes: full-size frames, measurements and target points taken from the original"),+ T("复刻粒子画面", "remaking particle pictures")),("audio.png", T("声音波形和节拍图", "waveform and beat chart"), T("看节奏", "seeing the rhythm"))):if (out / rel.rstrip("/")).exists():files.append((rel, what, when, 0))diff --git a/skills/rea-video/SKILL.md b/skills/rea-video/SKILL.mdindex 2dedd34..7e63578 100644--- a/skills/rea-video/SKILL.md+++ b/skills/rea-video/SKILL.md@@ -94,7 +94,7 @@ rea-video summary out/ref/breakdown.json # 用并入后的结果写回复## 3. 复刻(需要时)-见 `references/remake.md`;可用的工具和方式(capsule-cinema、ChatCut、自己动手)和各自的特点列在 `references/remake-tools.md`。在本工具里直接跑:AI 镜头走 capsule-cinema(会计费,先 `rea-video remake-run --dry-run` 并征得用户同意);实拍给拍摄方案;代码渲染用 Remotion;用户自己的素材用 `rea-video assemble` 拼回原时间线。代码渲染和用户自己的素材也可以在 ChatCut 里做。+见 `references/remake.md`;可用的工具和方式(capsule-cinema、ChatCut、自己动手)和各自的特点列在 `references/remake-tools.md`。在本工具里直接跑:AI 镜头走 capsule-cinema(会计费,先 `rea-video remake-run --dry-run` 并征得用户同意);实拍给拍摄方案;代码渲染用 Remotion(粒子镜头按 `frames/points/` 摆点,做完用 `rea-video compare` 对原片打分);用户自己的素材用 `rea-video assemble` 拼回原时间线。代码渲染和用户自己的素材也可以在 ChatCut 里做。## 参考文件diff --git a/skills/rea-video/references/remake.md b/skills/rea-video/references/remake.mdindex 4f951f8..854b796 100644--- a/skills/rea-video/references/remake.md+++ b/skills/rea-video/references/remake.md@@ -14,6 +14,8 @@- **AI 类镜头**:用原镜头首尾帧加 VLM 提示词,通过 [capsule-cinema](https://github.com/JuneYaooo/capsule-cinema) 生成(会计费,先 `--dry-run`,并征得用户同意)。- **静态图推拉、静帧**:本地按测得的运动参数重建。- **代码渲染**:用 Remotion 重建,或在 ChatCut 里生成动效图形。用 Remotion 时,把报告「代码合成」一节(每镜做法、逐镜动效时间轴、色值)连同 `shots/` 里的元素截图、关键帧条和 `packaging/overlays.ass` 一起交给写代码的人或 LLM;按时间轴的时间和位置写动画,按截图重画图形,图标 / Logo / 插画这类画不出来的直接抠图用。+ - 粒子 / 点云镜头:拆片包的 `frames/` 里每个场景有原尺寸帧、光晕和粒子颜色,`frames/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 assemble` 拼回原时间线,或放进 ChatCut 按原片节奏剪。- **声音**:TTS、BGM(按 BPM / 调性 / 情绪)、音效(按时间点)三条轨分别准备。- **剪辑包装(字幕、花字、贴纸)**:不进生成。生成模型只出干净的人和画面,包装层最后按「剪辑包装层」的时间轴叠上去,这样字不会被模型画糊,换文案时也只改包装层。diff --git a/tests/test_particles.py b/tests/test_particles.pyindex 1f065c1..7685258 100644--- a/tests/test_particles.py+++ b/tests/test_particles.py@@ -63,3 +63,168 @@ def test_code_scene_and_report_table(tmp_path):"scenes": [{"shot": 1, "start": 0.0, "end": 3.0, **sc, "colours": ["青"]}]}]}md = "\n".join(report_md(plan))assert "Three.js" in md and "| #1 | 0.0–3.0s | 粒子/点云 | 青色粒子拼成的胶囊 |" in md+++def _halo(img, colour=(140, 120, 40), radius=150):+ """Lay a large soft glow behind the picture, as particle explainers often do."""+ yy, xx = np.mgrid[0:img.shape[0], 0:img.shape[1]]+ g = np.exp(-((xx - 240) ** 2 + (yy - 135) ** 2) / (2 * (radius / 2) ** 2))+ glow = (g[..., None] * np.array(colour, np.float32)).astype(np.float32)+ return np.clip(img.astype(np.float32) + glow, 0, 255).astype(np.uint8)+++def test_particles_on_a_soft_halo_still_read_as_particles():+ f = _feat(_halo(_particles()))+ assert f["lit_smooth"] > 0.3 # the halo hides the dots from the plain lit-pixel measure+ assert f["spark_smooth"] < 0.24 and f["spark_peaks"] > 8+ probs, ev, facts = deterministic(f)+ assert facts["fine_dark"] > 0.5 and max(probs, key=probs.get) == "code_render"+ assert any("柔光" in e for e in ev)+ _, _, facts_s = deterministic(_feat(_halo(_shaded()))) # a shaded ball on a glow stays a shaded surface+ assert facts_s["fine_dark"] < 0.1+++def test_measure_and_points_follow_the_dots():+ from rea_video.particles import measure, sample_points++ img = _halo(_particles())+ m = measure(img)+ assert m["ground"] in ("#000000", "#000101") and m["halo"]["radius"] > 0.05+ assert abs(m["centre"][0] - 0.5) < 0.05 and abs(m["centre"][1] - 0.5) < 0.05+ assert m["box"][0] > 0.25 and m["box"][2] < 0.75 # the ellipse spans x 150-330 of 480+ pts = sample_points(img, 500)+ assert len(pts) == 500+ xs = np.array([p[0] for p in pts])+ assert xs.min() > 0.25 and xs.max() < 0.75+ # text boxes are blanked+ assert not sample_points(img, 50, text_boxes=[[0.0, 0.0, 1.0, 1.0]])+++def test_split_scenes_finds_a_regroup_without_a_cut():+ from rea_video.particles import density, spark_mask, split_scenes++ left, right = np.zeros((270, 480, 3), np.uint8), np.zeros((270, 480, 3), np.uint8)+ rng = np.random.default_rng(1)+ for _ in range(800):+ cv2.circle(left, (int(rng.uniform(40, 200)), int(rng.uniform(60, 210))), 1, (255, 255, 255), -1)+ cv2.circle(right, (int(rng.uniform(280, 440)), int(rng.uniform(60, 210))), 1, (255, 255, 255), -1)+ frames = [left] * 20 + [right] * 20+ times = np.arange(40) * 0.25+ descs = np.array([density(spark_mask(f)).ravel() for f in frames])+ sc = split_scenes(descs, times, 0.0, 10.0)+ assert len(sc) == 2 and abs(sc[0][1] - 5.0) <= 0.25+ assert split_scenes(descs[:20], times[:20], 0.0, 5.0) == [(0.0, 5.0)]+++def test_compare_scores_a_good_remake_above_a_bad_one(tmp_path):+ from rea_video.particles import compare++ def write(path, frames):+ vw = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), 4, (480, 270))+ for f in frames:+ vw.write(f)+ vw.release()++ ref = _halo(_particles())+ good = 255 - cv2.GaussianBlur(_particles(1), (3, 3), 0) // 2 # same shape, dark dots on a light ground+ bad = np.full((270, 480, 3), 230, np.uint8)+ cv2.circle(bad, (420, 60), 30, (40, 40, 40), -1)+ write(tmp_path / "ref.mp4", [ref] * 12)+ write(tmp_path / "good.mp4", [good] * 12)+ write(tmp_path / "bad.mp4", [bad] * 12)+ g = compare(str(tmp_path / "ref.mp4"), str(tmp_path / "good.mp4"), out=tmp_path / "cmp")+ b = compare(str(tmp_path / "ref.mp4"), str(tmp_path / "bad.mp4"))+ assert g["inverted"] and g["score"] > 0.6 > b["score"]+ assert (tmp_path / "cmp" / "compare_worst.jpg").exists() and (tmp_path / "cmp" / "compare.json").exists()+++def test_report_lists_particle_scenes():+ from rea_video.production import particle_scenes_md++ md = "\n".join(particle_scenes_md([{"id": "scene_01", "shot": 1, "start": 0.0, "end": 5.2, "points": "frames/points/scene_01.json",+ "measure": {"halo": {"colour": "#507c87", "centre": [0.5, 0.52], "radius": 0.15},+ "colours": [{"hex": "#4e747c"}], "dots": 286, "box": [0.4, 0.03, 0.6, 0.78]}}]))+ assert "| scene_01 | #1 | 0.0–5.2s | #507c87" in md and "rea-video compare" in md and "frames/points/scene_XX.json" in md+ assert particle_scenes_md([]) == []+++def _video(path, frames, fps=4):+ vw = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), fps, (frames[0].shape[1], frames[0].shape[0]))+ for f in frames:+ vw.write(f)+ vw.release()+ return path+++def _two_shapes():+ rng = np.random.default_rng(1)+ left, right = np.zeros((270, 480, 3), np.uint8), np.zeros((270, 480, 3), np.uint8)+ for _ in range(800):+ cv2.circle(left, (int(rng.uniform(40, 200)), int(rng.uniform(60, 210))), 1, (255, 255, 255), -1)+ cv2.circle(right, (int(rng.uniform(280, 440)), int(rng.uniform(60, 210))), 1, (255, 255, 255), -1)+ return left, right+++def test_halo_layer_only_on_dark_pictures_and_needs_a_halo():+ bright = np.full((270, 480, 3), 200, np.uint8)+ f = spatial_features(bright)+ assert f["glow_ratio"] == 0.0 and f["spark_ratio"] == 0.0 and f["spark_smooth"] == 1.0+ # big soft lights on a glow (night street, bokeh) are not fine dots+ img = np.zeros((270, 480, 3), np.uint8)+ for x, y in [(100, 80), (220, 150), (330, 100), (400, 200)]:+ cv2.circle(img, (x, y), 14, (200, 210, 230), -1)+ img = _halo(cv2.GaussianBlur(img, (0, 0), 3))+ _, _, facts = deterministic(_feat(img))+ assert facts["fine_dark"] < 0.5+++def test_scene_frames_clears_old_files_and_skips_without_particles(tmp_path):+ from rea_video.particles import scene_frames++ left, right = _two_shapes()+ video = _video(tmp_path / "p.mp4", [left] * 20 + [right] * 20)+ b = {"source": {"path": str(video)}, "shots": [{"index": 1, "start": 0.0, "end": 10.0, "deterministic": {"facts": {"fine_dark": 0.9}}}]}+ out = tmp_path / "out"+ stale = out / "frames" / "points" / "scene_09.json"+ stale.parent.mkdir(parents=True)+ stale.write_text("{}")+ (out / "frames" / "scene_09_mid.jpg").write_bytes(b"x")+ res = scene_frames(out, breakdown=b)+ assert [s["id"] for s in res["scenes"]] == ["scene_01", "scene_02"]+ assert not stale.exists() and not (out / "frames" / "scene_09_mid.jpg").exists()+ sc = res["scenes"][0]+ assert sc["measure"]["box"][2] < 0.5 and sc["track"] and (out / sc["points"]).exists()+ b["shots"][0]["deterministic"]["facts"]["fine_dark"] = 0.0 # relabelled: nothing left to write+ assert scene_frames(out, breakdown=b)["scenes"] == []+ assert not (out / "frames").exists()+++def test_particle_step_failure_keeps_the_breakdown(tmp_path, monkeypatch):+ import rea_video.particles as particles+ from rea_video.pipeline import decompose++ def boom(*a, **k):+ raise RuntimeError("decode failed")++ monkeypatch.setattr(particles, "scene_frames", boom)+ video = _video(tmp_path / "dots.mp4", [_particles(i % 3) for i in range(24)], fps=8)+ out = tmp_path / "o"+ b = decompose(video, out, use_vlm=False, ocr=False, stems=False, asr=False, speakers=False)+ assert any(((s.get("deterministic") or {}).get("facts") or {}).get("fine_dark", 0) > 0.5 for s in b["shots"])+ assert "particle_scenes" not in b+ assert (out / "report.html").exists() and (out / "breakdown.json").exists()+++def test_particle_scenes_follow_the_shot_labels(tmp_path):+ from rea_video.memory import correct+ from rea_video.pipeline import decompose, finalize++ video = _video(tmp_path / "dots.mp4", [_particles(i % 3) for i in range(24)], fps=8)+ out = tmp_path / "o"+ b = decompose(video, out, use_vlm=False, ocr=False, stems=False, asr=False, speakers=False)+ assert b.get("particle_scenes", {}).get("count", 0) >= 1 and (out / "frames" / "scenes.json").exists()+ assert b["production_plan"].get("particle_scenes")+ assert "粒子场景" in (out / "video" / "remake.md").read_text(encoding="utf-8")+ correct(b, label="cg_3d", shots="1", record=False) # the user says it is a 3D render after all+ finalize(b, out)+ assert not b["production_plan"].get("particle_scenes")