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

Generalize scene frames to the drawn layer of rendered shots

june298f0a43ece9
diff --git a/docs/cli.md b/docs/cli.md
index 78b5a74..1d77565 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -104,8 +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` |
+| `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` |
| `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.md
index 9086454..2b4d783 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/`、`frames/`(粒子镜头才有)、`storyboard.jpg`、`audio.png` | 完整数据和媒体文件,地图里都列着 |
+| `breakdown.json`、`shots/`、`stems/`、`sfx/`、`packaging/`、`frames/`(有代码渲染镜头时才有)、`storyboard.jpg`、`audio.png` | 完整数据和媒体文件,地图里都列着 |
没有内容的主题文件不生成。
diff --git a/eval/RESULTS.md b/eval/RESULTS.md
index 602f506..79542fb 100644
--- a/eval/RESULTS.md
+++ b/eval/RESULTS.md
@@ -168,7 +168,7 @@
2. 暗色/半透明的背景照片、暗色主题网页截图漏检;实拍或 AI 画面上叠加的商品图和 Logo 不做确定性检测,依赖 VLM。
3. 嵌入图片是真实照片还是 AI 图,确定性层判断不了。
4. 加看图模型和 agent 复核的分数是把缓存的答案重新融合得到的,还没有在从头解码的特征上重测;只开看图模型、不做 agent 复核时在留出集上曾低于只用工具。
-5. 暗底粒子:粒子背后有大圈柔光的规则(`fine_glow`)阈值按 `particles.yaml` 的 halo 样本定,halo 样本属于开发集,能认出它不说明能推广到其他带柔光的粒子视频;大颗失焦光斑漂在暗底上的(bokeh 样本)还会被判成 3D 渲染。星空、夜景灯光、暗色界面没有专门的样本,这条规则只在暗底且有柔光时生效,但误判成代码渲染的可能没有排除。
+5. 暗底细碎图形(粒子、点云、细线):同一组阈值既在原画面上测,也在去掉平滑背景(画面尺度的柔光、暗角、渐变,不含物体本身的明暗)后的画面上测,所以背后有柔光也能认出;阈值来自开发集(`particles.yaml` 文件头有说明),halo 样本也是开发集。大颗失焦光斑漂在暗底上的(bokeh 样本)还认不出。星空、夜景灯光、暗色界面没有专门的样本,误判成代码渲染的可能没有排除。
6. 音乐来源:普通视频里的 AI 生成 BGM 判断不出来(见上);AI MV 样本只有 1 条。
## 复现
diff --git a/rea_video/classify.py b/rea_video/classify.py
index dcc6a72..14f3c27 100644
--- a/rea_video/classify.py
+++ b/rea_video/classify.py
@@ -104,12 +104,8 @@ 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},
+ # measured twice with the same bounds: on the picture, and on its detail layer (the picture minus its smooth
+ # background), so a soft glow or gradient behind the graphics does not hide them
# 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},
@@ -246,25 +242,25 @@ def deterministic(f: dict, overlay: dict | None = None, text: dict | None = None
area=f.get('face_area', 0), faces=faces))
graphic *= bf["graphic_factor"]
fd = RULES["fine_dark"]
- fine_dark = 0.0
- if 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)
+
+ def _fine(ratio: float, smooth: float, peaks: float) -> float:
+ if ratio <= fd["lit_min"]:
+ return 0.0
+ return (_sig((f.get("dark_ratio", 0.0) - fd["dark"]) / 0.05) * _sig((fd["smooth"] - smooth) / 0.05)
+ * _sig((peaks - fd["peaks"]) / 1.0) * _sig((fd["lit_max"] - ratio) / 0.04))
+
+ plain = _fine(f.get("lit_ratio", 0.0), f.get("lit_smooth", 1.0), f.get("lit_peaks", 0.0))
+ detail = _fine(f.get("detail_ratio", 0.0), f.get("detail_smooth", 1.0), f.get("detail_peaks", 0.0))
+ by_detail = detail > plain
+ fine_dark = max(plain, detail)
facts["fine_dark"] = round(fine_dark, 3)
if fine_dark > 0.5:
- 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))
+ sm, pk = (f.get("detail_smooth", 0.0), f.get("detail_peaks", 0.0)) if by_detail 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 ({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=sm, pk=pk, halo=T("去掉背后的柔光后,", "with the soft halo behind them taken out, ") if by_glow else ""))
+ sm=sm, pk=pk, halo=T("去掉平滑背景后,", "with the smooth background taken out, ") if by_detail 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 art
diff --git a/rea_video/cli.py b/rea_video/cli.py
index 96ce083..9cefea6 100644
--- a/rea_video/cli.py
+++ b/rea_video/cli.py
@@ -327,7 +327,7 @@ def cmd_tiles(args) -> int:
def cmd_frames(args) -> int:
- from .particles import scene_frames
+ from .layers import scene_frames
if args.every <= 0:
raise SystemExit("rea-video: --every 必须大于 0")
@@ -336,7 +336,7 @@ def cmd_frames(args) -> int:
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)"))
+ print(T("没有代码渲染镜头(加 --all 对所有镜头取帧)", "no code-rendered 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))
@@ -344,16 +344,16 @@ def cmd_frames(args) -> int:
def cmd_compare(args) -> int:
- from .particles import compare
+ from .layers 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,
+ 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", "inverted", "worst") if k in res}
+ brief = {k: res[k] for k in ("score", "place", "shape", "worst") if k in res}
if res.get("scenes"):
brief["lowest_scenes"] = res["scenes"][:5]
if res.get("sheet"):
@@ -673,18 +673,17 @@ 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 = 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.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 = 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")
diff --git a/rea_video/features.py b/rea_video/features.py
index 299406a..72405b5 100644
--- a/rea_video/features.py
+++ b/rea_video/features.py
@@ -49,16 +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
+DETAIL = 25 # how far a pixel must stand out from its smooth background to count as drawn detail
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."""
+ """The smooth background of a gray picture (float32): what is left on the scale of the frame rather than of the
+ things in it, a Gaussian blur with a radius of 1/20 of the long side (smaller radii also take away the shading of
+ faces and surfaces, which is what tells a filmed picture from drawn graphics). 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)
+ return cv2.resize(cv2.GaussianBlur(small, (0, 0), max(h, w) / 80.0), (w, h), interpolation=cv2.INTER_LINEAR)
def spatial_features(bgr: np.ndarray) -> dict:
@@ -103,17 +105,10 @@ def spatial_features(bgr: np.ndarray) -> dict:
gf = gray.astype(np.float32)
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 lit detail layer: what stands out above the picture's smooth background (a glow, vignette or gradient behind
+ # the graphics), measured like the lit part above, so a soft background does not hide fine graphics drawn on it
+ detail = (gf - halo_blur(gf)) > DETAIL
+ n_detail = int(detail.sum())
# the same on the inverted picture: thin dark lines / dots / small text on a light ground (line art, documents)
inv = 255 - gray
ink_mask = inv > 50
@@ -144,10 +139,9 @@ 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,
+ "detail_ratio": n_detail / float(h * w),
+ "detail_smooth": float(((mag < 40) & detail).sum()) / n_detail if n_detail else 1.0,
+ "detail_peaks": 100.0 * float((bumps & detail).sum()) / n_detail if n_detail 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/layers.py
similarity index 54%
rename from rea_video/particles.py
rename to rea_video/layers.py
index 73c9940..f3c4584 100644
--- a/rea_video/particles.py
+++ b/rea_video/layers.py
@@ -1,31 +1,35 @@
-"""Particle / point-cloud pictures on a dark ground, measured for a code remake.
+"""The drawn layer of rendered shots, 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.
+A code-rendered picture is a smooth background (flat colour, gradient, glow, vignette) with something drawn on it
+(particles, lines, shapes, charts, text). The drawn layer is whatever stands out from the smooth background, away from
+the ground colour, in any direction: light on dark, dark on light, or another colour of the same brightness.
-`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.
+`rea-video frames out/ref` splits rendered shots into scenes (the drawn layer rearranges without a cut), saves
+full-size frames, a cut-out of the drawn layer and samples of it per scene, and measures the ground, the background
+glow, the drawn colours and where the drawing sits. A remake can then place its graphics on the original's shapes
+instead 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.
"""
from __future__ import annotations
+import heapq
from pathlib import Path
import cv2
import numpy as np
-from .features import SPARK, halo_blur
+from .features import DETAIL, 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
+WORK_W = 480 # measuring width; positions are written as 0-1 of the frame, so this only sets precision
+GRID = (16, 9) # cells of the layout map (x, y)
+SCENE_WIN = 1.5 # seconds compared on each side of a candidate scene change; also the shortest scene kept
+SCENE_MOVE = 0.25 # share of the drawn layer that has to move elsewhere in the frame for a new scene
def _hex(bgr) -> str:
@@ -33,11 +37,25 @@ def _hex(bgr) -> str:
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
+def ground(bgr: np.ndarray) -> np.ndarray:
+ """Background colour: the median of the frame border."""
+ border = np.concatenate([bgr[0], bgr[-1], bgr[:, 0], bgr[:, -1]])
+ return np.median(border, axis=0)
+
+
+def contrast(bgr: np.ndarray) -> np.ndarray:
+ """How far each pixel stands out from the smooth background, away from the ground: its colour distance to the
+ ground colour minus the smooth background's (Lab). Light dots on a dark glow, dark ink on paper, a white road or a
+ blue river on a pale map all stand out; the dark gaps between dots inside a glow (closer to the ground) do not."""
+ lab = cv2.cvtColor(bgr, cv2.COLOR_BGR2LAB).astype(np.float32)
+ g = cv2.cvtColor(ground(bgr).astype(np.uint8)[None, None], cv2.COLOR_BGR2LAB).astype(np.float32)[0, 0]
+ smooth = np.dstack([halo_blur(np.ascontiguousarray(lab[..., c])) for c in range(3)])
+ return np.linalg.norm(lab - g, axis=2) - np.linalg.norm(smooth - g, axis=2)
+
+
+def layer_mask(bgr: np.ndarray, text_boxes: list | None = None) -> np.ndarray:
+ """The drawn layer. text_boxes (0-1 x, y, w, h) are blanked, so subtitles and labels are left out."""
+ m = contrast(bgr) > DETAIL
h, w = m.shape
for x, y, bw, bh in text_boxes or []:
pad = 0.01
@@ -47,7 +65,8 @@ def spark_mask(bgr: np.ndarray, text_boxes: list | None = None) -> np.ndarray:
return m
-def density(mask: np.ndarray) -> np.ndarray:
+def layout(mask: np.ndarray) -> np.ndarray:
+ """Where the drawn layer sits: share of it in each grid cell."""
d = cv2.resize(mask.astype(np.float32), GRID, interpolation=cv2.INTER_AREA)
s = float(d.sum())
return d / s if s > 0 else d
@@ -69,25 +88,24 @@ def _colours(pixels: np.ndarray, k: int = 3) -> list[dict]:
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."""
+ """Ground, background glow (colour, centre, radius), drawn colours, how many separate pieces and how big, where
+ the drawing sits and how much of the frame it covers. 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)
+ g = ground(bgr)
+ out: dict = {"ground": _hex(g)}
+ gl = float(cv2.cvtColor(g.astype(np.uint8)[None, None], cv2.COLOR_BGR2GRAY)[0, 0])
+ lift = np.abs(halo_blur(gf) - gl) # the smooth background's departure from the ground: glow, vignette, gradient
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)
+ blur = cv2.resize(cv2.GaussianBlur(cv2.resize(bgr, (max(1, w // 4), max(1, h // 4))), (0, 0), max(h, w) / 80.0), (w, h))
+ out["glow"] = {"colour": _hex(blur[peak]), "centre": [round(float((xs * wts).sum() / wts.sum()) / w, 3),
+ round(float((ys * wts).sum() / wts.sum()) / h, 3)],
+ "radius": round(float(np.sqrt(on.sum() / np.pi)) / w, 3)}
+ m = layer_mask(bgr, text_boxes)
n = int(m.sum())
out["cover"] = round(n / float(h * w), 4)
if n < 10:
@@ -100,33 +118,38 @@ def measure(bgr: np.ndarray, text_boxes: list | None = None) -> dict:
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)]
+ out["pieces"] = int(n_cc - 1)
+ out["piece_area"] = round(float(np.median(areas)) / float(h * w), 6) # median piece, share of the frame
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)
+ """Up to n pixels of the drawn layer as [x, y, r, g, b, a] (x, y 0-1; colour 0-255; a = how strongly the pixel
+ stands out, 0-1), picked with probability by that strength: targets to place particles, dots or strokes on."""
+ c = contrast(bgr)
+ m = layer_mask(bgr, text_boxes)
ys, xs = np.nonzero(m)
if not len(xs):
return []
- wts = lift[ys, xs]
+ wts = c[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)
+ h, w = c.shape
+ top = float(wts.max()) or 1.0
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)]
+ round(float(wts[i]) / top, 2)] for i in pick]
+
+
+def cutout(bgr: np.ndarray, text_boxes: list | None = None) -> np.ndarray:
+ """The drawn layer as an RGBA image (BGRA for OpenCV): the frame's colours, alpha by how strongly each pixel
+ stands out from the smooth background; text left out."""
+ c = np.clip(contrast(bgr) / 100.0, 0, 1)
+ c[~cv2.dilate(layer_mask(bgr, text_boxes).astype(np.uint8), np.ones((3, 3), np.uint8)).astype(bool)] = 0
+ return np.dstack([bgr, (c * 255).astype(np.uint8)])
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)."""
+ """Where text sits and when: every OCR read stored on the shots, plus the packaging timeline once it is written
+ (decompose measures the layer before that 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"
@@ -136,47 +159,51 @@ def _text_boxes(out: Path, b: dict) -> list[tuple[float, float, list]]:
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
+ """Text boxes on screen at t (or at any time in t..until): OCR misses text 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."""
+def split_scenes(maps: np.ndarray, times: np.ndarray, start: float, end: float) -> list[tuple[float, float]]:
+ """Scene changes inside one shot: where the layout before and after differs (share of the drawn layer that sits
+ elsewhere) by more than SCENE_MOVE beyond how much it varies within each side. maps: one flattened layout 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]
+ a, b = maps[i - win:i], maps[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:
+ if score[i] < SCENE_MOVE:
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):
+ if t - start < SCENE_WIN or end - t < SCENE_WIN or any(abs(t - c) < SCENE_WIN for c in cuts):
continue
- lo, hi = max(0, i - near), min(len(score), i + near + 1)
+ lo, hi = max(0, i - win), min(len(score), i + win + 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 shot_label(shot: dict) -> str | None:
+ """The shot's current label: after review / correction when there is one, else the measured one."""
+ base = (shot.get("base") or {}).get("label")
+ if base:
+ return base
+ probs = (shot.get("deterministic") or {}).get("probs") or {}
+ return max(probs, key=probs.get) if probs else None
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"]:
+ """Drop what an earlier run wrote, so a rerun with fewer scenes leaves no stale files behind."""
+ for p in [*fdir.glob("scene_*.jpg"), *fdir.glob("scene_*.png"), *(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()):
@@ -184,8 +211,9 @@ def _clear(fdir: Path) -> None:
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)."""
+ """Scenes, full-size frames, a cut-out of the drawn layer, measurements and samples for the rendered shots of a
+ breakdown (all shots with all_shots). Frames are measured as they are decoded, so 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")
@@ -193,7 +221,7 @@ def scene_frames(out: Path, every: float = 0.25, n_points: int = 4000, all_shots
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)]
+ shots = [s for s in b.get("shots", []) if all_shots or shot_label(s) == "code_render"]
if not shots:
return {"video": video, "every": every, "scenes": []}
info = video_info(video)
@@ -203,19 +231,19 @@ def scene_frames(out: Path, every: float = 0.25, n_points: int = 4000, all_shots
scenes: list[dict] = []
for s in shots:
st, en = float(s["start"]), float(s["end"])
- descs, times, track = [], [], []
+ maps, 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())
+ m = layer_mask(f, _boxes_at(boxes, t))
+ maps.append(layout(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
+ if len(xs) >= 10: # how the drawing moves: 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):
+ for a, z in split_scenes(np.array(maps), 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": {}}
@@ -223,10 +251,12 @@ def scene_frames(out: Path, every: float = 0.25, n_points: int = 4000, all_shots
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)
+ full = cv2.imread(str(fdir / f"{sid}_mid.jpg"))
+ if full is not None:
in_scene = _boxes_at(boxes, a, z)
+ cv2.imwrite(str(fdir / f"{sid}_layer.png"), cutout(full, in_scene))
+ rec["frames"]["layer"] = f"frames/{sid}_layer.png"
+ img = cv2.resize(full, (WORK_W, max(1, round(full.shape[0] * WORK_W / full.shape[1]))), interpolation=cv2.INTER_AREA)
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)})
@@ -238,50 +268,34 @@ def scene_frames(out: Path, every: float = 0.25, n_points: int = 4000, all_shots
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())
+ 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())
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
+ # equal weight on where it sits and on the shapes themselves; how much is drawn counts half as much
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
-
+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."""
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)}
+ 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)}
rows.append(r)
if out:
item = (-r["score"], i, fa, fb)
@@ -291,10 +305,8 @@ def compare(ref: str, remake: str, every: float = 0.5, invert: str = "auto", out
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}
+ 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}
if scenes and Path(scenes).exists():
per = []
for sc in read_json(scenes).get("scenes", []):
@@ -304,8 +316,7 @@ def compare(ref: str, remake: str, every: float = 0.5, invert: str = "auto", out
"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"])]
+ res["worst"] = sorted(r["t"] for r in sorted(rows, key=lambda r: r["score"])[:worst])
if out:
out.mkdir(parents=True, exist_ok=True)
cells = []
@@ -322,9 +333,9 @@ def compare(ref: str, remake: str, every: float = 0.5, invert: str = "auto", out
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]
+def drawn_colours(frames: list[np.ndarray]) -> list[str]:
+ """Colours of the drawn layer of a shot (ground and smooth background left out), most common first."""
+ px = [f[layer_mask(f)] for f in frames if f is not None]
px = [p for p in px if len(p)]
if not px:
return []
diff --git a/rea_video/pipeline.py b/rea_video/pipeline.py
index 375333f..0af5e2a 100644
--- a/rea_video/pipeline.py
+++ b/rea_video/pipeline.py
@@ -199,10 +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
+ from .layers import drawn_colours
- motion["dots"] = lit_palette(sframes)
+ # the drawn layer's own colours: a frame average is mostly ground when the drawing is thin or small
+ motion["drawn"] = drawn_colours(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
@@ -350,15 +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
+ from .layers import scene_frames, shot_label
- LOG.info("particle shots: scenes, full-size frames and target points (frames/)")
+ if any(shot_label(r) == "code_render" for r in shot_records):
+ LOG.info("rendered shots: scenes, full-size frames and the drawn layer (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"])}
+ breakdown["layer_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)
+ LOG.warning("scene frames 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 breakdown
diff --git a/rea_video/plan.py b/rea_video/plan.py
index 46db5fa..b366f94 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]], "dots": motion.get("dots") or [],
+ "background": pal.get("background"), "palette": [c["hex"] for c in pal.get("colours", [])[:5]], "drawn": motion.get("drawn") 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.py
index 43119ba..79e33e1 100644
--- a/rea_video/production.py
+++ b/rea_video/production.py
@@ -115,11 +115,10 @@ def code_motion_md(scenes: list[dict]) -> list[str]:
L.append("")
if sc.get("strip"):
L += [f"![{head}]({sc['strip']})", ""]
- 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"):
+ if 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 "—"))
+ c=" ".join(c for c in sc.get("palette") or [] if c != sc["background"]) or "—")
+ + (T(";前景(画上去的那层){d}", "; drawn layer {d}", d=" ".join(sc["drawn"])) if sc.get("drawn") else ""))
if sc.get("elements_sheet"):
L += [T("元素截图(编号对应下面的动效;L 是持续运动层的镜头中段和结尾,S 是整镜不动的元素),原分辨率单张在 `shots/` 里:",
"Element crops (numbers match the motion list below; L = the continuously moving layer mid-shot and at the end, "
@@ -609,13 +608,13 @@ def production_plan(b: dict, out: Path, engine: str = "seedance2.0") -> dict:
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():
+ # only shots still in the code build: a review that relabels a shot drops its scenes from the plan
+ code_shots = {sh for c in code for sh in c["shots"]}
+ if code_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]
+ plan["layer_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", "glow", "colours", "pieces", "box")}}
+ for sc in json.loads(ps.read_text(encoding="utf-8")).get("scenes", []) if sc.get("shot") in code_shots]
except (OSError, ValueError, TypeError):
pass
plan["local"] = [{"shot": r["index"], "label_zh": r["base"]["label_zh"], "duration": r["duration"]}
@@ -705,31 +704,37 @@ 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."""
+def layer_scenes_md(scenes: list[dict]) -> list[str]:
+ """Rendered shots split into scenes (the drawing rearranges without a cut), with the measured look and where to
+ find the drawn layer of each."""
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) |"),
- "|---|---|---|---|---|---|---|"]
+ L = ["", T("**画面场景**(镜头内画上去的东西整体换了位置或形状就算新场景。`frames/` 里每个场景有首 / 中 / 尾原尺寸帧,"
+ "`scene_XX_layer.png` 是中间帧画上去的那一层(背景和文字已去掉,透明度按突出程度),"
+ "`frames/points/scene_XX.json` 是从这一层取的采样点,每行 `x y r g b a`,x、y 是 0–1 坐标;"
+ "按这些摆粒子、描线或重画图形,不用照文字描述去猜形状。`frames/scenes.json` 的 `track` 是这一层的重心和散开程度随时间的变化)",
+ "**Picture scenes** (a new scene whenever what is drawn moves or changes shape as a whole inside a shot. `frames/` holds first / "
+ "middle / last full-size frames per scene, `scene_XX_layer.png` the drawn layer of the middle frame (background and text "
+ "removed, alpha by how strongly it stands out), `frames/points/scene_XX.json` samples of that layer, one `x y r g b a` per row "
+ "with x, y in 0–1. Place particles, trace lines or redraw shapes from these instead of guessing from a description. `track` in "
+ "`frames/scenes.json` follows the layer's centre and spread over time)"), "",
+ T("| 场景 | 镜头 | 时间 | 底色 | 背景光 | 前景颜色 | 块数 | 范围 (x0 y0 x1 y1) |",
+ "| Scene | Shot | Time | Ground | Background glow | Drawn colours | Pieces | 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 "—")
+ gl = m.get("glow") or {}
+ gw = (T("{c},中心 ({x:.2f}, {y:.2f}),半径 {r:.2f}", "{c}, centre ({x:.2f}, {y:.2f}), radius {r:.2f}", c=gl["colour"],
+ x=gl["centre"][0], y=gl["centre"][1], r=gl["radius"]) if gl 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 对比目录` 打分(浅底复刻会自动反相再比),"
+ L.append(f"| {sc['id']} | #{sc['shot']} | {sc['start']:.1f}–{sc['end']:.1f}s | {m.get('ground') or '—'} | {gw} | {cols} | "
+ f"{m.get('pieces') 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`.")]
+ "When built, score it with `rea-video compare original remake --scenes frames/scenes.json -o dir` (each side's drawn layer "
+ "is taken against its own ground, so a new ground colour still compares) and fix the lowest-scoring scenes first, from "
+ "`compare_worst.jpg`.")]
return L
@@ -873,12 +878,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"]) + " · " + (T("粒子 ", "dots ") + " ".join(sc["dots"]) if sc.get("dots") else
- " ".join(c for c in sc["palette"] if c != sc["background"]))
+ cols = (T("底 {bg}", "ground {bg}", bg=sc["background"]) + " · " + " ".join(c for c in sc["palette"] if c != sc["background"])
+ + (T(" · 前景 ", " · drawn ") + " ".join(sc["drawn"]) if sc.get("drawn") else "")
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 += layer_scenes_md(plan.get("layer_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.py
index 9f176ba..28c51db 100644
--- a/rea_video/videomd.py
+++ b/rea_video/videomd.py
@@ -320,8 +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")),
+ ("frames/", T("画面场景:每场景原尺寸帧、画上去那一层的抠图和采样点、测量值", "picture scenes: full-size frames, the drawn layer cut out and sampled, measurements"),
+ T("复刻代码渲染画面", "remaking rendered 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.md
index b9fb037..ca54cf5 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(粒子镜头按 `frames/points/` 摆点,做完用 `rea-video compare` 对原片打分);用户自己的素材用 `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/` 里的抠图和采样点做,做完用 `rea-video compare` 对原片打分);用户自己的素材用 `rea-video assemble` 拼回原时间线。代码渲染和用户自己的素材也可以在 ChatCut 里做。
## 参考文件
diff --git a/skills/rea-video/references/remake.md b/skills/rea-video/references/remake.md
index 854b796..2e27d55 100644
--- a/skills/rea-video/references/remake.md
+++ b/skills/rea-video/references/remake.md
@@ -14,8 +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` 里分数最低的时刻。
+ - 拆片包的 `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 assemble` 拼回原时间线,或放进 ChatCut 按原片节奏剪。
- **声音**:TTS、BGM(按 BPM / 调性 / 情绪)、音效(按时间点)三条轨分别准备。
- **剪辑包装(字幕、花字、贴纸)**:不进生成。生成模型只出干净的人和画面,包装层最后按「剪辑包装层」的时间轴叠上去,这样字不会被模型画糊,换文案时也只改包装层。
diff --git a/tests/test_layers.py b/tests/test_layers.py
new file mode 100644
index 0000000..dfe7b97
--- /dev/null
+++ b/tests/test_layers.py
@@ -0,0 +1,136 @@
+"""The drawn layer of rendered shots: scenes, cut-outs, samples and remake scores, on dark and light grounds."""
+import cv2
+import numpy as np
+
+from rea_video.layers import compare, cutout, layer_mask, layout, measure, sample_points, scene_frames, split_scenes
+from rea_video.production import layer_scenes_md
+
+
+def _dots(seed=0, cx=240, light=False):
+ """Dots on an ellipse: light dots on black, or dark dots on white."""
+ rng = np.random.default_rng(seed)
+ img = np.full((270, 480, 3), 245 if light else 0, np.uint8)
+ for _ in range(1500):
+ a, r = rng.uniform(0, 2 * np.pi), rng.uniform(0, 1) ** 0.5
+ cv2.circle(img, (int(cx + 90 * r * np.cos(a)), int(135 + 60 * r * np.sin(a))), 1,
+ (60, 40, 30) if light else (230, 220, 60), -1)
+ return img
+
+
+def _strokes(x0, light=True):
+ """A small line chart: a few strokes in one half of the frame."""
+ img = np.full((270, 480, 3), 245 if light else 10, np.uint8)
+ ink = (40, 40, 40) if light else (240, 240, 240)
+ pts = np.array([[x0 + 20 * i, 200 - int(60 * np.sin(i / 2))] for i in range(9)], np.int32)
+ cv2.polylines(img, [pts], False, ink, 2)
+ cv2.line(img, (x0, 220), (x0 + 170, 220), ink, 1)
+ return img
+
+
+def _glow(img, colour=(140, 120, 40), radius=150):
+ 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))
+ return np.clip(img.astype(np.float32) + g[..., None] * np.array(colour, np.float32), 0, 255).astype(np.uint8)
+
+
+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 test_layer_follows_the_drawing_on_either_ground():
+ for img in (_glow(_dots()), _dots(light=True)):
+ m = measure(img)
+ 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
+ xs = np.array([p[0] for p in sample_points(img, 500)])
+ assert len(xs) == 500 and xs.min() > 0.25 and xs.max() < 0.75
+ assert measure(_glow(_dots()))["glow"]["radius"] > 0.05
+ assert measure(_dots(light=True))["ground"] in ("#f5f5f5", "#f4f4f4")
+ m = measure(_strokes(40))
+ assert m["box"][2] < 0.5 # the chart sits in the left half
+ assert not sample_points(_dots(), 50, text_boxes=[[0.0, 0.0, 1.0, 1.0]]) # text boxes are blanked
+ rgba = cutout(_dots(light=True))
+ assert rgba.shape[2] == 4 and rgba[..., 3][0, 0] == 0 and rgba[..., 3].max() > 0
+
+
+def test_split_scenes_finds_a_rearrangement_without_a_cut():
+ for a, b in ((_dots(cx=120), _dots(cx=360)), (_strokes(20), _strokes(280))):
+ frames = [a] * 20 + [b] * 20
+ maps = np.array([layout(layer_mask(f)).ravel() for f in frames])
+ times = np.arange(40) * 0.25
+ sc = split_scenes(maps, times, 0.0, 10.0)
+ assert len(sc) == 2 and abs(sc[0][1] - 5.0) <= 0.25
+ assert split_scenes(maps[:20], times[:20], 0.0, 5.0) == [(0.0, 5.0)]
+
+
+def test_compare_ranks_remakes_and_ignores_the_ground_colour(tmp_path):
+ ref = _video(tmp_path / "ref.mp4", [_glow(_dots())] * 12)
+ good = _video(tmp_path / "good.mp4", [_dots(1, light=True)] * 12) # same shape, dark on a light ground
+ bad = np.full((270, 480, 3), 230, np.uint8)
+ cv2.circle(bad, (420, 60), 30, (40, 40, 40), -1)
+ bad = _video(tmp_path / "bad.mp4", [bad] * 12)
+ g = compare(str(ref), str(good), out=tmp_path / "cmp")
+ b = compare(str(ref), str(bad))
+ assert g["score"] > 0.6 > b["score"]
+ assert (tmp_path / "cmp" / "compare_worst.jpg").exists() and (tmp_path / "cmp" / "compare.json").exists()
+ assert compare(str(ref), str(ref))["score"] > 0.99
+
+
+def test_scene_frames_covers_rendered_shots_and_clears_old_files(tmp_path):
+ video = _video(tmp_path / "v.mp4", [_strokes(20)] * 20 + [_strokes(280)] * 20)
+ shot = {"index": 1, "start": 0.0, "end": 10.0, "deterministic": {"probs": {"code_render": 0.9, "cg_3d": 0.1}}}
+ b = {"source": {"path": str(video)}, "shots": [shot]}
+ out = tmp_path / "out"
+ stale = out / "frames" / "points" / "scene_09.json"
+ stale.parent.mkdir(parents=True)
+ stale.write_text("{}")
+ res = scene_frames(out, breakdown=b)
+ assert [s["id"] for s in res["scenes"]] == ["scene_01", "scene_02"] and not stale.exists()
+ sc = res["scenes"][0]
+ assert sc["measure"]["box"][2] < 0.5 and sc["track"]
+ assert (out / sc["points"]).exists() and (out / sc["frames"]["layer"]).exists()
+ shot["base"] = {"label": "cg_3d"} # relabelled after review: nothing left to write, no empty folder
+ assert scene_frames(out, breakdown=b)["scenes"] == []
+ assert not (out / "frames").exists()
+
+
+def test_layer_step_failure_keeps_the_breakdown(tmp_path, monkeypatch):
+ import rea_video.layers as layers
+ from rea_video.pipeline import decompose
+
+ def boom(*a, **k):
+ raise RuntimeError("decode failed")
+
+ monkeypatch.setattr(layers, "scene_frames", boom)
+ video = _video(tmp_path / "dots.mp4", [_dots(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 "layer_scenes" not in b
+ assert (out / "report.html").exists() and (out / "breakdown.json").exists()
+
+
+def test_scene_table_follows_the_shot_labels(tmp_path):
+ from rea_video.memory import correct
+ from rea_video.pipeline import decompose, finalize
+
+ video = _video(tmp_path / "dots.mp4", [_dots(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("layer_scenes", {}).get("count", 0) >= 1
+ assert b["production_plan"].get("layer_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("layer_scenes")
+
+
+def test_scene_table_text():
+ md = "\n".join(layer_scenes_md([{"id": "scene_01", "shot": 1, "start": 0.0, "end": 5.2, "points": "frames/points/scene_01.json",
+ "measure": {"ground": "#000000", "glow": {"colour": "#507c87", "centre": [0.5, 0.52], "radius": 0.15},
+ "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 md
+ assert layer_scenes_md([]) == []
diff --git a/tests/test_particles.py b/tests/test_particles.py
index 7685258..6d3c89c 100644
--- a/tests/test_particles.py
+++ b/tests/test_particles.py
@@ -66,165 +66,24 @@ def test_code_scene_and_report_table(tmp_path):
def _halo(img, colour=(140, 120, 40), radius=150):
- """Lay a large soft glow behind the picture, as particle explainers often do."""
+ """Lay a large soft glow behind the picture."""
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)
+ return np.clip(img.astype(np.float32) + g[..., None] * np.array(colour, np.float32), 0, 255).astype(np.uint8)
-def test_particles_on_a_soft_halo_still_read_as_particles():
+def test_a_smooth_background_does_not_hide_fine_graphics():
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
+ assert f["lit_smooth"] > 0.3 # on the plain picture the glow makes the lit part look shaded
+ assert f["detail_smooth"] < 0.3 and f["detail_peaks"] > 4 # the same bounds hold once the glow is taken out
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)
+ 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
+ # big soft lights on a glow (night street, bokeh) are not fine graphics
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")
+ _, _, facts_l = deterministic(_feat(_halo(cv2.GaussianBlur(img, (0, 0), 3))))
+ assert facts_l["fine_dark"] < 0.5