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

fix: 各类代码渲染画面判为代码渲染,代码镜头给逐镜动效时间轴和元素截图

june1983f47c673e
diff --git a/.gitignore b/.gitignore
index 2bdcb45..4812425 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,3 +12,8 @@ eval/media/
.env
.env.*
!.env.example
+eval/code_videos.yaml
+eval/code_videos_holdout.yaml
+eval/particles.yaml
+eval/codegen/
+scripts/roundtrip_compare.py
diff --git a/rea_video/aspects/framing.py b/rea_video/aspects/framing.py
index af53341..0261a55 100644
--- a/rea_video/aspects/framing.py
+++ b/rea_video/aspects/framing.py
@@ -43,7 +43,7 @@ class Framing(Aspect):
if not subs:
return {}
kinds = [s["kind"] for s in subs]
- kind = max(set(kinds), key=kinds.count)
+ kind = max(dict.fromkeys(kinds), key=kinds.count)
use = [s for s in subs if s["kind"] == kind]
hs = [s["box"][3] for s in use]
cx = float(np.median([s["box"][0] + s["box"][2] / 2 for s in use]))
diff --git a/rea_video/aspects/lighting.py b/rea_video/aspects/lighting.py
index 3d64212..d722d85 100644
--- a/rea_video/aspects/lighting.py
+++ b/rea_video/aspects/lighting.py
@@ -308,13 +308,13 @@ class Lighting(Aspect):
kinds.append(s["kind"])
if not per:
return {}
- out = {"subject": max(set(kinds), key=kinds.count), "frames": len(per)}
+ out = {"subject": max(dict.fromkeys(kinds), key=kinds.count), "frames": len(per)}
for k in MEASURES:
vals = [m[k] for m in per if m.get(k) is not None]
if vals:
out[k] = round(float(np.median(vals)), 3)
sides = [m["key_side"] for m in per]
- out["key_side"] = max(set(sides), key=sides.count)
+ out["key_side"] = max(dict.fromkeys(sides), key=sides.count)
return out
def interpret(self, shot: dict) -> dict:
diff --git a/rea_video/classify.py b/rea_video/classify.py
index a99b2a0..acff454 100644
--- a/rea_video/classify.py
+++ b/rea_video/classify.py
@@ -89,6 +89,25 @@ RULES = {
"ui_text": {"height": 0.02, "mid": 4.5, "width": 0.7},
# an avatar is a fixed frame; a moving / shaking camera argues for someone filming
"avatar_moving_camera": 0.3,
+ # fine graphics on black (particles, point clouds, thin lines, small text): the lit part has almost no gently
+ # 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},
+ # 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},
+ # pictures made of vector fills, gradients and glows (no material texture). tex_fine = share of pixels with
+ # fine detail left after a median filter and removing the smooth component (high-pass), so gradients and glows
+ # count as zero and light film grain is mostly removed. Eval photo / AI shots >= 0.12 except one compressed
+ # night street shot at 0.066; Blender plush >= 0.073 (plain walls, nearly colourless: sat_p90 <= 0.35); code
+ # gradients 0.006-0.04, glass / neon / dashboards 0.03-0.13. The gradient test cuts at 0.06 and needs colour,
+ # the colour-field and neon tests cut at 0.12 and need saturated colour. dark_guard: a rendered dark ground is
+ # exactly flat (dark_flat >= 0.85 in the code sets); night footage keeps grain (dark_flat <= 0.77).
+ # Procedural colour fields (fractals, shaders) are textured but almost all vivid (> 0.9) and either rainbow
+ # (plasma: 8 hue bands) or very cleanly curving (fractal zoom 0.93). Vivid AI cartoons (capybara / lulukong in
+ # holdout) reach vivid 0.97 but keep 2-3 hue bands and grad_clean <= 0.86
+ "vector_fill": {"tex": 0.06, "grad": 0.12, "sat": 0.3, "vivid": 0.3, "vivid_tex": 0.12, "dark_flat": 0.8,
+ "neon_dark": 0.6, "neon_sat": 0.8, "neon_tex": 0.12, "rainbow": 0.85, "hues": 4.5, "clean": 0.9},
}
@@ -186,6 +205,63 @@ def deterministic(f: dict, overlay: dict | None = None, text: dict | None = None
"A face covers {area:.0%} of the frame and appears in {faces:.0%} of sampled frames: a close-up of a person, flat colour blocks mostly come from walls / clothing, rendered-texture cues down-weighted",
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))
+ facts["fine_dark"] = round(fine_dark, 3)
+ if fine_dark > 0.5:
+ ev.append(T("暗底上的亮部几乎全是细碎亮点/细线(亮部平滑过渡只占 {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, "
+ "{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)))
+ 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
+ ut = RULES["ui_text"]
+ small_lines = sum(1 for tr in (text or {}).get("tracks", []) if tr.get("text_height", 1.0) < ut["height"])
+ fl = RULES["fine_light"]
+ fine_light = 0.0
+ if fd["lit_min"] < f.get("ink_ratio", 0.0):
+ fine_light = (_sig((f.get("light_ratio", 0.0) - fd["dark"]) / 0.05) * _sig((fl["smooth"] - f.get("ink_smooth", 1.0)) / 0.05)
+ * _sig((f.get("ink_peaks", 0.0) - fd["peaks"]) / 1.0) * _sig((fd["lit_max"] - f.get("ink_ratio", 0.0)) / 0.04)
+ * (1.0 - _sig((small_lines - ut["mid"]) / ut["width"])))
+ facts["fine_light"] = round(fine_light, 3)
+ if fine_light > 0.5:
+ ev.append(T("浅色底上的深色部分几乎全是细线/细点(平滑过渡只占 {sm:.0%}):线稿、生成式线条或点阵图形,不是有明暗的实拍或 3D 表面",
+ "On a light ground the dark part is almost all thin lines / dots (only {sm:.0%} shade gently): line art, generative strokes "
+ "or dot graphics, not a shaded photo or 3D surface", sm=f.get("ink_smooth", 0.0)))
+ graphic = max(graphic, fine_light)
+ vf = RULES["vector_fill"]
+ tex = f.get("tex_fine", 1.0)
+ # a rendered dark ground is one exact colour; dark parts of night footage keep grain after transcoding
+ dark_guard = 1.0 - min(1.0, f.get("dark_ratio", 0.0) / 0.3) * (1.0 - _sig((f.get("dark_flat", 0.0) - vf["dark_flat"]) / 0.03))
+ vec_parts = {
+ # smooth coloured gradients with no texture at all (mesh-gradient backgrounds, CSS cards, UI)
+ "gradient": _sig((vf["tex"] - tex) / 0.01) * _sig((f.get("grad_share", 0.0) - vf["grad"]) / 0.04)
+ * _sig((f.get("sat_p90", 0.0) - vf["sat"]) / 0.06),
+ # large saturated colour fields with little texture (flat illustration, glassmorphism, brand colour blocks)
+ "colour_fields": _sig((f.get("vivid", 0.0) - vf["vivid"]) / 0.08) * _sig((vf["vivid_tex"] - tex) / 0.02),
+ # saturated glow on a dark ground (neon text, glowing lines)
+ "neon": _sig((f.get("dark_ratio", 0.0) - vf["neon_dark"]) / 0.08) * _sig((f.get("sat_p90", 0.0) - vf["neon_sat"]) / 0.05)
+ * _sig((vf["neon_tex"] - tex) / 0.02),
+ # procedural rainbow colour fields (fractal zooms, plasma / noise shaders)
+ "procedural": _sig((f.get("vivid", 0.0) - vf["rainbow"]) / 0.02)
+ * max(_sig((f.get("hue_n", 0.0) - vf["hues"]) / 0.3), _sig((f.get("grad_clean", 0.0) - vf["clean"]) / 0.01)),
+ }
+ vector = max(vec_parts.values()) * dark_guard * (1.0 - (0.8 if big_face else 0.0))
+ facts["vector_fill"] = round(vector, 3)
+ kind = max(vec_parts, key=vec_parts.get)
+ facts["vector_kind"] = kind if vector > 0.5 else None
+ if vector > 0.5:
+ what = {"gradient": T("平滑彩色渐变", "smooth colour gradients"), "colour_fields": T("大块饱和纯色", "large saturated colour fields"),
+ "neon": T("暗底上的饱和辉光", "saturated glow on a dark ground"), "procedural": T("程序生成的彩虹色场(分形/着色器)", "procedural rainbow colour fields (fractal / shader)")}[kind]
+ ev.append(T("画面由{what}构成、几乎没有材质纹理(细纹理像素 {tex:.0%};实拍、AI 和 3D 渲染的布料/皮肤/噪点都会留下纹理):代码绘制的矢量/渐变图形",
+ "The picture is {what} with almost no material texture ({tex:.0%} fine-texture pixels; footage, AI and 3D renders keep fabric / skin / noise texture): vector / gradient graphics drawn by code",
+ what=what, tex=tex))
+ graphic = max(graphic, vector)
# (overlay text is a separate layer, so OCR coverage does not count toward the base)
photo = 1.0 - graphic
# fine high-frequency detail on flat ground = small text / UI (screenshots, docs, code cards)
@@ -309,7 +385,8 @@ def deterministic(f: dict, overlay: dict | None = None, text: dict | None = None
s["code_render"] += 1.6 * graphic * (1 + 0.5 * rsb) * (1 - 0.5 * text_like * _sig((0.12 - f.get("saturation", 0.3)) / 0.04))
s["screen_capture"] += 1.5 * graphic * text_like * (0.3 + _sig((0.12 - f.get("saturation", 0.3)) / 0.04))
s["static_hold"] += 0.5 * photo
- s["cg_3d"] += 0.4 * graphic * (1 - text_like)
+ s["cg_3d"] += 0.4 * graphic * (1 - text_like) * (1 - 0.8 * max(fine_dark, fine_light, vector))
+ s["code_render"] += 1.2 * graphic * max(fine_dark, fine_light, vector)
s["ai_video"] += 0.8 * photo * (1.4 if pulldown else 1.0)
s["live_action"] += 0.3 * photo * live_hint
else:
@@ -318,8 +395,9 @@ def deterministic(f: dict, overlay: dict | None = None, text: dict | None = None
# cards, dark editors), not shaded 3D renders: shading spreads colours, product 3D is coloured
ui_gray = _sig((0.04 - f.get("saturation", 0.3)) / 0.01) * _sig((20 - pal) / 3)
facts["ui_gray"] = round(ui_gray, 3)
- s["code_render"] += 1.5 * graphic * (0.3 + 1.2 * rsb + 1.0 * text_like + 0.8 * ui_gray) * axis_f
- s["cg_3d"] += 1.5 * graphic * max(0.0, 1.1 - rsb - 0.8 * text_like) * (1 - 0.8 * ui_gray) * (1 - 0.8 * ui_text)
+ code_cue = max(fine_dark, fine_light, vector)
+ s["code_render"] += 1.5 * graphic * (0.3 + 1.2 * rsb + 1.0 * text_like + 0.8 * ui_gray + 1.2 * code_cue) * axis_f
+ s["cg_3d"] += 1.5 * graphic * max(0.0, 1.1 - rsb - 0.8 * text_like) * (1 - 0.8 * ui_gray) * (1 - 0.8 * ui_text) * (1 - 0.8 * code_cue)
s["screen_capture"] += 1.2 * graphic * ui_text
if ui_gray > 0.5 and graphic > 0.6:
ev.append(T("画面几乎无彩色(饱和度 {sat:.2f})、只用 {pal} 种颜色:界面/文档类平面画面,不是有光影的 3D 渲染",
diff --git a/rea_video/cli.py b/rea_video/cli.py
index 148a701..2e4358f 100644
--- a/rea_video/cli.py
+++ b/rea_video/cli.py
@@ -283,7 +283,10 @@ def cmd_summary(args) -> int:
+ (T(" ← 有分歧:{d}", " ← disputed: {d}", d=base["disputed"]) if base.get("disputed") else "")
+ (T(" ← 用户纠正过素材来源", " ← material origin corrected by the user") if (r.get("material") or {}).get("user_corrected") else "")
+ (f" ← {past}" if past else "")
- + (f" | {shot_text(r)}" if r["base"]["label"] in ("live_action", "avatar") and shot_text(r) else ""))
+ + (f" | {shot_text(r)}" if r["base"]["label"] in ("live_action", "avatar") and shot_text(r) else "")
+ + (T(" | 动效 {n} 个,元素截图 {f}", " | {n} motion events, element crops {f}", n=len(r["motion"].get("events", [])),
+ f=r["motion"]["elements_sheet"]) if r["base"]["label"] in ("code_render", "screen_capture")
+ and (r.get("motion") or {}).get("elements_sheet") else ""))
if s.get("aspects"):
lines += [""] + s["aspects"]
from .entities import cast
diff --git a/rea_video/evaluate.py b/rea_video/evaluate.py
index 738ce53..6b3188b 100644
--- a/rea_video/evaluate.py
+++ b/rea_video/evaluate.py
@@ -156,7 +156,7 @@ def packaging_check(truth_path: str | Path, pack: dict, sfx: list[dict] | None =
cand = [c for c in others if overlap(g["t0"], g["t1"], c["t0"], c["t1"]) > 0 and _similar(g["text"], c["text"]) >= 0.5]
if cand:
found += 1
- kind_ok += any(c["kind"] == kind for c in cand)
+ kind_ok += any(c["kind"] == kind or (kind == "label" and c["kind"] == "counter") for c in cand)
out[key] = {"truth": len(items), "found": found, "kind_ok": kind_ok}
out["image_stickers_false"] = sum(1 for st in pack.get("stickers", []) if not st.get("in_picture"))
if sfx is not None and sfx_truth is not None:
diff --git a/rea_video/features.py b/rea_video/features.py
index e3f20ca..44de783 100644
--- a/rea_video/features.py
+++ b/rea_video/features.py
@@ -84,8 +84,46 @@ def spatial_features(bgr: np.ndarray) -> dict:
axis = float(((ang < 4) | (ang > 86)).mean())
else:
axis = 0.0
+ # what the lit part is made of: shaded surfaces (photo, 3D, AI) have gentle gradients; particles, point clouds,
+ # thin lines and small text on black are all fine detail, many small bright peaks per lit pixel
+ lit_mask = gray > 50
+ n_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
+ # 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
+ n_ink = int(ink_mask.sum())
+ fi = inv.astype(np.float32)
+ ink_peaks = (fi >= cv2.dilate(fi, np.ones((3, 3), np.uint8))) & (fi - cv2.blur(fi, (7, 7)) > 18) & ink_mask
hsv = cv2.cvtColor(bgr, cv2.COLOR_BGR2HSV)
+ # material texture: cameras, generators and 3D renders put fine texture (fabric, skin, foliage, noise) almost
+ # everywhere; vector shapes, gradients, glows and text drawn by code have none. Median-filtered first so a
+ # film-grain overlay on a flat design does not count as texture.
+ # The detail left after removing the smooth component (high-pass), so smooth gradients and glows count as zero.
+ dn = cv2.medianBlur(gray, 5).astype(np.float32)
+ hp = dn - cv2.GaussianBlur(dn, (0, 0), 1.5)
+ hp_e = np.sqrt(np.maximum(cv2.blur(hp * hp, (5, 5)), 0))
+ # gentle slopes (gradients, shading) and whether they curve cleanly (synthetic ramps) or noisily (surfaces)
+ slope = (mag > 2) & (mag < 30)
+ curv = np.abs(cv2.Laplacian(cv2.GaussianBlur(gf, (0, 0), 1.0), cv2.CV_32F))
+ sat, val = hsv[..., 1], hsv[..., 2]
+ vivid = (sat > 90) & (val > 60)
+ hues = np.bincount((hsv[..., 0][vivid] // 15).ravel(), minlength=12) if vivid.any() else np.zeros(12)
return {
+ "tex_fine": float(((hp_e > 0.6) & (hp_e < 6)).mean()),
+ "grad_share": float(slope.mean()),
+ "grad_clean": float((curv[slope] < 1.0).mean()) if slope.any() else 0.0,
+ "vivid": float(vivid.mean()),
+ "hue_n": float((hues / max(1, hues.sum()) > 0.08).sum()),
+ "sat_p90": float(np.percentile(sat, 90)) / 255.0,
+ "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,
+ "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,
+ "ink_peaks": 100.0 * float(ink_peaks.sum()) / n_ink if n_ink else 0.0,
"noise_sigma": noise_sigma(gray),
"flat_ratio": flat_ratio,
"dark_ratio": dark_ratio,
diff --git a/rea_video/integrations/capsule_cinema.py b/rea_video/integrations/capsule_cinema.py
index 494ecf2..45eda68 100644
--- a/rea_video/integrations/capsule_cinema.py
+++ b/rea_video/integrations/capsule_cinema.py
@@ -28,6 +28,14 @@ def _aspect(b: dict) -> str:
return ar if ar in ("9:16", "16:9", "1:1") else "unknown"
+TRANS_ZH = {"cut": "硬切", "flash": "闪亮切", "fade": "淡入淡出", "dissolve": "叠化", "mg_transition": "版式切换", "start": "开场"}
+
+
+def _top_tr(s: dict) -> str:
+ tr = {k: v for k, v in s["transitions"].items() if k != "start"} or s["transitions"]
+ return max(tr, key=tr.get)
+
+
def _mmss(t: float) -> str:
return fmt_time(t)
@@ -95,7 +103,7 @@ def export_capsule_analysis(b: dict, out_path: Path) -> Path:
lens = [x["duration"] for x in shots]
structure_rules = [
f"全片约 {s['duration']:.0f}s,{s['shots']} 个镜头,平均每镜 {s['avg_shot_s']}s(最短 {min(lens):.1f}s,最长 {max(lens):.1f}s)",
- f"转场以 {max(s['transitions'], key=s['transitions'].get)} 为主:" + "、".join(f"{k}×{v}" for k, v in s["transitions"].items()),
+ f"转场以 {TRANS_ZH.get(_top_tr(s), _top_tr(s))} 为主:" + "、".join(f"{TRANS_ZH.get(k, k)}×{v}" for k, v in s["transitions"].items() if k != "start"),
]
if whole.get("hook"):
structure_rules.append(f"开头钩子:{whole['hook']}")
diff --git a/rea_video/motion.py b/rea_video/motion.py
new file mode 100644
index 0000000..5412b8b
--- /dev/null
+++ b/rea_video/motion.py
@@ -0,0 +1,476 @@
+"""Motion events of a rendered (code / motion-graphics) shot: what changes where, when, how, in what colour.
+
+A remake of a code-drawn video needs every element's entrance time, place, direction and easing, which a few key
+frames do not give. Here the shot is decoded small, every cell that changes is stamped with the frame it starts and
+stops changing, and cells are grouped first by start time (staggered entrances become separate events) and then by
+place. Cells that keep changing through most of the shot (drifting gradients, particle flows, glow breathing) form
+one "continuous layer" instead of events."""
+from __future__ import annotations
+
+from pathlib import Path
+
+import cv2
+import numpy as np
+
+from .i18n import T
+from .media import VideoInfo, iter_frames
+
+W = 180 # analysis width
+CELL = 4 # px per cell at that width
+DIFF = 12 # per-channel change that counts (8-bit)
+MAX_FPS = 15.0
+CONT = 0.7 # a cell active in more than this share of the shot belongs to the continuous layer
+GAP_S = 0.12 # start times further apart than this split an event
+MIN_AREA = 0.002 # events smaller than this share of the frame are dropped
+MAX_EVENTS = 20
+
+
+def _hex(bgr) -> str:
+ b, g, r = (int(x) for x in bgr)
+ return f"#{r:02x}{g:02x}{b:02x}"
+
+
+def _frames(path: str | Path, info: VideoInfo, start: float, dur: float) -> tuple[np.ndarray, float]:
+ fps = min(info.fps or 30.0, MAX_FPS)
+ fr = list(iter_frames(path, info, W, start=start, duration=dur, fps=fps))
+ return (np.stack(fr) if fr else np.zeros((0, 1, W, 3), np.uint8)), fps
+
+
+def _easing(act: np.ndarray) -> str:
+ """Shape of an event's activity over its life: where the change happens."""
+ if len(act) < 4 or act.sum() <= 0:
+ return "instant"
+ c = np.cumsum(act) / act.sum()
+ half = c[len(c) // 2 - (1 if len(c) % 2 == 0 else 0)]
+ if half > 0.68:
+ return "ease_out"
+ if half < 0.32:
+ return "ease_in"
+ cv = float(act.std() / (act.mean() + 1e-6))
+ return "linear" if cv < 0.45 else "ease_in_out"
+
+
+def _direction(on: np.ndarray, ys: np.ndarray, xs: np.ndarray) -> str | None:
+ """Start time sweeping across the region: a wipe / grow / draw-on along that direction."""
+ if len(on) < 12 or on.std() < 1e-6:
+ return None
+ best, axis = 0.0, None
+ for coord, pos, neg in ((xs, "right", "left"), (ys, "down", "up")):
+ if coord.std() < 1e-6:
+ continue
+ r = float(np.corrcoef(coord, on)[0, 1])
+ if abs(r) > abs(best):
+ best, axis = r, (pos if r > 0 else neg)
+ return axis if abs(best) > 0.6 else None
+
+
+def motion_events(path: str | Path, info: VideoInfo, start: float, dur: float, text_items: list[dict] | None = None) -> dict:
+ fr, fps = _frames(path, info, start, dur)
+ n = len(fr)
+ if n < 3:
+ return {"fps": fps, "events": [], "layer": None, "sequences": []}
+ h, w = fr.shape[1:3]
+ gh, gw = h // CELL, w // CELL
+ f = fr[:, : gh * CELL, : gw * CELL].astype(np.int16)
+ d = np.abs(np.diff(f, axis=0)).max(axis=3) > DIFF # (n-1, H, W) changed pixels
+ act = d.reshape(n - 1, gh, CELL, gw, CELL).mean(axis=(2, 4)) > 0.12 # (n-1, gh, gw) active cells
+ count = act.sum(axis=0)
+ ever = count > 0
+ cont = count > CONT * (n - 1)
+ # slow drifts (gradients, blurred blobs, glow) change by 1-3 levels between neighbouring frames: compare 1 s apart
+ lag = max(1, int(round(1.0 * fps)))
+ if n > lag + 2:
+ slow = (np.abs(f[lag:] - f[:-lag]).max(axis=3) > 8).reshape(n - lag, gh, CELL, gw, CELL).mean(axis=(2, 4)) > 0.3
+ cont |= slow.mean(axis=0) > 0.6
+ out: dict = {"fps": round(fps, 2), "events": [], "layer": None, "sequences": []}
+ if cont.mean() > 0.01:
+ ys, xs = np.nonzero(cont)
+ out["layer"] = {"share": round(float(cont.mean()), 3),
+ "box": [round(xs.min() / gw, 3), round(ys.min() / gh, 3), round((xs.max() + 1 - xs.min()) / gw, 3),
+ round((ys.max() + 1 - ys.min()) / gh, 3)]}
+ # over a moving ground (drifting gradient, particle field) "unchanged" pieces are just patches of that ground
+ out["static"] = _static_elements(fr, ever | cont, text_items or []) if cont.mean() < 0.4 else []
+ if not ever.any():
+ return out
+ onset = np.where(ever, act.argmax(axis=0), -1)
+ last = np.where(ever, n - 2 - act[::-1].argmax(axis=0), -1)
+ trans = ever & ~cont
+ texts = text_items or []
+ # elements: what is on screen at the end that was not at the start, at rest (staggered entrances that sweep
+ # through each other's place, like springing icons or lines sliding up, are apart once they settle)
+ settled = np.abs(f[-1] - f[0]).max(axis=2) > DIFF
+ settled = settled.reshape(gh, CELL, gw, CELL).mean(axis=(1, 3)) > 0.12
+ settled &= trans
+ # where an element finally comes to rest, its own entrance is the last burst of change there (something else may
+ # have swept through the spot earlier)
+ arrive = last.copy()
+ for t in range(n - 2, -1, -1):
+ hit = act[t] & (arrive - t <= 3) & (t < arrive)
+ arrive[hit] = t
+ k, lab = cv2.connectedComponents(cv2.dilate(settled.astype(np.uint8), np.ones((1, 3), np.uint8)), connectivity=8)
+ covered = np.zeros_like(trans)
+ for j in range(1, k):
+ region = (lab == j) & settled
+ if region.sum() / (gh * gw) < MIN_AREA:
+ continue
+ covered |= cv2.dilate(region.astype(np.uint8), np.ones((5, 5), np.uint8)).astype(bool)
+ for cm in _split_by_start(region, arrive, fps):
+ if cm.sum() / (gh * gw) >= MIN_AREA:
+ out["events"].append(_event(cm, fr, act, arrive, last, start, fps, gh, gw, texts))
+ # the rest: things that come and go within the shot, or move without staying; split where start times jump
+ rest = trans & ~covered
+ k, lab = cv2.connectedComponents(cv2.dilate(rest.astype(np.uint8), np.ones((1, 3), np.uint8)), connectivity=8)
+ for j in range(1, k):
+ for cm in _split_by_start(((lab == j) & rest), onset, fps):
+ if cm.sum() / (gh * gw) >= MIN_AREA:
+ out["events"].append(_event(cm, fr, act, onset, last, start, fps, gh, gw, texts))
+ # whole-picture changes (camera moves, particle fields) and specks of jitter are not elements
+ long_ = 0.8 * dur # changing through (almost) the whole shot: twinkling star fields, flicker -> part of the layer
+ out["events"] = [e for e in out["events"] if not (e["kind"] == "change" and (e["box"][2] * e["box"][3] > 0.5 or e["area"] < 0.01
+ or e["t1"] - e["t0"] > long_))]
+ out["events"] = _chain(out["events"])
+ out["events"] = sorted(sorted(out["events"], key=lambda e: -e.pop("_rank"))[:MAX_EVENTS], key=lambda e: (e["t0"], e["box"][1]))
+ out["sequences"] = _sequences(out["events"])
+ return out
+
+
+def _static_elements(fr: np.ndarray, moving_cells: np.ndarray, texts: list[dict], most: int = 8) -> list[dict]:
+ """Shapes that are on screen for the whole shot and never move (axis lines, fixed cards, frames, logos): the
+ motion timeline never mentions them, and a remake built from it alone would leave them out."""
+ last = fr[-1].astype(np.int16)
+ h, w = last.shape[:2]
+ border = np.concatenate([last[0], last[-1], last[:, 0], last[:, -1]])
+ bg = np.median(border, axis=0)
+ fg = np.abs(last - bg).max(axis=2) > 2 * DIFF
+ fg &= (np.abs(fr[0].astype(np.int16) - last).max(axis=2) <= DIFF) # same at the start: never changed
+ gh, gw = moving_cells.shape
+ moving_px = cv2.resize(moving_cells.astype(np.uint8), (gw * CELL, gh * CELL), interpolation=cv2.INTER_NEAREST).astype(bool)
+ fg[: gh * CELL, : gw * CELL] &= ~cv2.dilate(moving_px.astype(np.uint8), np.ones((3, 3), np.uint8)).astype(bool)
+ k, lab, stats, _ = cv2.connectedComponentsWithStats(cv2.dilate(fg.astype(np.uint8), np.ones((3, 3), np.uint8)), connectivity=8)
+ items = []
+ for j in range(1, k):
+ x, y, bw, bh, area = stats[j]
+ if area < 30 or bw * bh > 0.6 * w * h:
+ continue
+ m = (lab == j) & fg
+ box = [round(x / w, 3), round(y / h, 3), round(bw / w, 3), round(bh / h, 3)]
+ shape = "hline" if bw > 8 * bh else "vline" if bh > 8 * bw else "block"
+ px = fr[-1][m].astype(np.int16)
+ far = np.abs(px - bg).max(axis=1)
+ core = px[far >= np.percentile(far, 60)] # glyph / line cores, not their anti-aliased edges
+ ev = {"box": box, "shape": shape, "colour": _hex(np.median(core, axis=0)), "_a": int(area)}
+ words = _words(box, texts)
+ if words:
+ ev["text"] = words
+ items.append(ev)
+ items = sorted(items, key=lambda e: -e.pop("_a"))[:most]
+ return sorted(items, key=lambda e: (e["box"][1], e["box"][0]))
+
+
+def _split_by_start(region: np.ndarray, start_map: np.ndarray, fps: float) -> list[np.ndarray]:
+ """Parts of one place that start changing at clearly different times (a stroke drawn after another)."""
+ ts = np.sort(np.unique(start_map[region]))
+ if not len(ts):
+ return []
+ cuts = [ts[0]] + [t for p_, t in zip(ts, ts[1:]) if t - p_ > max(2, GAP_S * 2 * fps)]
+ return [region & (start_map >= c0) & (start_map < c1) for c0, c1 in zip(cuts, cuts[1:] + [ts[-1] + 1])]
+
+
+def _event(cm, fr, act, onset, last, start, fps, gh, gw, texts) -> dict:
+ n = len(fr)
+ area = float(cm.sum()) / (gh * gw)
+ ys, xs = np.nonzero(cm)
+ on, end = onset[cm], last[cm]
+ t0, t1 = int(on.min()), int(np.percentile(end, 90))
+ prof = act[t0:t1 + 1][:, cm].sum(axis=1).astype(float)
+ # what the region looks like before the event starts and after it ends
+ y0, y1, x0, x1 = ys.min() * CELL, (ys.max() + 1) * CELL, xs.min() * CELL, (xs.max() + 1) * CELL
+ before, after = fr[max(0, t0)][y0:y1, x0:x1], fr[min(n - 1, t1 + 2)][y0:y1, x0:x1]
+ diff = np.abs(after.astype(np.int16) - before.astype(np.int16)).max(axis=2) > DIFF
+ sb, sa = float(before.std()), float(after.std())
+ if diff.mean() < 0.05:
+ kind = "change" # comes back to how it was (pulse, pass-through)
+ elif sb < 0.5 * sa and sa > 6:
+ kind = "appear"
+ elif sa < 0.5 * sb and sb > 6:
+ kind = "disappear"
+ else:
+ kind = "change"
+ colour_src = after if kind != "disappear" else before
+ px = colour_src[diff] if diff.any() else colour_src.reshape(-1, 3)
+ # how it enters: only a moving tip changes per frame -> drawn / grown / typed along a direction; the whole element
+ # changes and its centre travels -> slides in; centre fixed while its extent grows -> scales in
+ sl = [a & cm for a in act[t0:t1 + 1]]
+ sl = [a for a in sl if a.any()]
+ tip = float(np.median([a.sum() for a in sl])) / max(1, cm.sum()) if sl else 1.0
+ slide = scale = None
+ sweep = _direction(on.astype(float), ys.astype(float), xs.astype(float)) if tip < 0.35 else None
+ if sl and not sweep and len(sl) >= 3:
+ cy = [float(np.nonzero(a)[0].mean()) / gh for a in sl]
+ cx = [float(np.nonzero(a)[1].mean()) / gw for a in sl]
+ dy, dx = cy[-1] - cy[0], cx[-1] - cx[0]
+ if max(abs(dy), abs(dx)) > 0.02:
+ slide = ("down" if dy > 0 else "up") if abs(dy) > abs(dx) else ("right" if dx > 0 else "left")
+ else:
+ w0 = np.ptp(np.nonzero(sl[0])[1]) + 1
+ w1 = np.ptp(np.nonzero(cm)[1]) + 1
+ if w0 < 0.6 * w1:
+ scale = True
+ box = [round(x0 / (gw * CELL), 3), round(y0 / (gh * CELL), 3), round((x1 - x0) / (gw * CELL), 3), round((y1 - y0) / (gh * CELL), 3)]
+ # change index j is between frames j and j+1: the change shows from frame j+1
+ ev = {"t0": round(start + (t0 + 1) / fps, 2), "t1": round(start + max(t1 + 1, t0 + 2) / fps, 2), "box": box, "area": round(area, 3),
+ "kind": kind, "easing": _easing(prof), "sweep": sweep, "slide": slide, "scale": scale, "colour": _hex(np.median(px, axis=0)) if len(px) else None, "_rank": area * (t1 - t0 + 1)}
+ words = _words(box, texts)
+ if words:
+ ev["text"] = words
+ return ev
+
+
+def _words(box, texts) -> list[str]:
+ words = []
+ for it in texts:
+ bx, by, bw, bh = it["bbox"]
+ if (box[0] - 0.02 <= bx + bw / 2 <= box[0] + box[2] + 0.02 and box[1] - 0.02 <= by + bh / 2 <= box[1] + box[3] + 0.02
+ and it.get("conf", 0) >= 0.8 and len(it["text"].strip()) > 1 and it["text"] not in words):
+ words.append(it["text"])
+ return words[:3]
+
+
+def _union(a: list[float], b: list[float]) -> list[float]:
+ x0, y0 = min(a[0], b[0]), min(a[1], b[1])
+ x1, y1 = max(a[0] + a[2], b[0] + b[2]), max(a[1] + a[3], b[1] + b[3])
+ return [round(x0, 3), round(y0, 3), round(x1 - x0, 3), round(y1 - y0, 3)]
+
+
+def _touch(a: list[float], b: list[float], tol: float = 0.03) -> bool:
+ return not (a[0] + a[2] + tol < b[0] or b[0] + b[2] + tol < a[0] or a[1] + a[3] + tol < b[1] or b[1] + b[3] + tol < a[1])
+
+
+def _chain(evs: list[dict]) -> list[dict]:
+ """One element drawn piece by piece (a growing bar, a stroke, typed text) arrives as touching pieces, each starting
+ as the previous one ends: join them into one event that unfolds along its direction."""
+ evs = sorted(evs, key=lambda e: e["t0"])
+ out: list[dict] = []
+ for e in evs:
+ for o in out:
+ if o["kind"] == e["kind"] and -0.1 <= e["t0"] - o["_last_t1"] <= 0.2 and _touch(o["_last_box"], e["box"], 0.01):
+ (cx0, cy0), (cx1, cy1) = o["_first_c"], (e["box"][0] + e["box"][2] / 2, e["box"][1] + e["box"][3] / 2)
+ o["sweep"] = (("right" if cx1 > cx0 else "left") if abs(cx1 - cx0) >= abs(cy1 - cy0)
+ else ("down" if cy1 > cy0 else "up"))
+ o["box"], o["t1"], o["_last_t1"], o["_last_box"] = _union(o["box"], e["box"]), max(o["t1"], e["t1"]), e["t1"], e["box"]
+ o["area"] = round(o["area"] + e["area"], 3)
+ o["_rank"] += e["_rank"]
+ o["_pieces"] += 1
+ o["slide"] = None
+ o["text"] = list(dict.fromkeys(o.get("text", []) + e.get("text", [])))[:3] or o.get("text")
+ if not o["text"]:
+ o.pop("text")
+ break
+ else:
+ out.append({**e, "_last_t1": e["t1"], "_last_box": e["box"], "_first_c": (e["box"][0] + e["box"][2] / 2, e["box"][1] + e["box"][3] / 2), "_pieces": 1})
+ for o in out:
+ if o.pop("_pieces") >= 3:
+ o["easing"] = "linear" if o["easing"] == "instant" else o["easing"]
+ for key in ("_last_t1", "_last_box", "_first_c"):
+ o.pop(key)
+ return out
+
+
+def _sequences(evs: list[dict]) -> list[dict]:
+ """Same-sized elements entering the same way at a steady interval (list items, icons, bars, lines of text)."""
+ seqs = []
+ used: set[int] = set()
+ for i, e in enumerate(evs):
+ if i in used:
+ continue
+ grp = [i]
+ for j in range(i + 1, len(evs)):
+ f = evs[j]
+ if j in used or f["kind"] != e["kind"]:
+ continue
+ same = (abs(f["box"][2] - e["box"][2]) < 0.4 * max(e["box"][2], f["box"][2])
+ and abs(f["box"][3] - e["box"][3]) < 0.4 * max(e["box"][3], f["box"][3])
+ and abs((f["t1"] - f["t0"]) - (e["t1"] - e["t0"])) < 0.5 * max(0.2, e["t1"] - e["t0"]))
+ if same:
+ grp.append(j)
+ if len(grp) < 3:
+ continue
+ t = [evs[k]["t0"] for k in grp]
+ gaps = np.diff(t)
+ if gaps.min() <= 0 or gaps.std() > 0.4 * gaps.mean():
+ continue
+ used.update(grp)
+ seqs.append({"n": len(grp), "events": grp, "t0": t[0], "interval": round(float(gaps.mean()), 2),
+ "each": round(float(np.median([evs[k]["t1"] - evs[k]["t0"] for k in grp])), 2)})
+ return seqs
+
+
+KIND_WORDS = {"appear": ("出现", "appears"), "disappear": ("消失", "disappears"), "change": ("变化", "changes")}
+EASE_WORDS = {"ease_out": ("先快后慢", "ease-out"), "ease_in": ("先慢后快", "ease-in"), "linear": ("匀速", "linear"),
+ "ease_in_out": ("缓入缓出", "ease-in-out"), "instant": ("瞬间", "instant")}
+DIR_WORDS = {"right": ("向右", "rightward"), "left": ("向左", "leftward"), "down": ("向下", "downward"), "up": ("向上", "upward")}
+
+
+def _where(box: list[float]) -> str:
+ cx, cy = box[0] + box[2] / 2, box[1] + box[3] / 2
+ v = T("上", "top") if cy < 0.33 else T("下", "bottom") if cy > 0.67 else T("中", "middle")
+ hz = T("左", " left") if cx < 0.33 else T("右", " right") if cx > 0.67 else ""
+ return v + hz
+
+
+def event_line(ev: dict) -> str:
+ """One readable line: time, place (box in % of the frame), what happens, how, colour, text."""
+ b = ev["box"]
+ what = T(*KIND_WORDS[ev["kind"]])
+ how = []
+ if ev.get("sweep"):
+ how.append(T("{d}展开(描线/生长/擦除)", "unfolds {d} (draw-on / grow / wipe)", d=T(*DIR_WORDS[ev["sweep"]])))
+ elif ev.get("slide"):
+ how.append(T("{d}移入", "slides {d}", d=T(*DIR_WORDS[ev["slide"]])) if ev["kind"] == "appear"
+ else T("{d}移动", "moves {d}", d=T(*DIR_WORDS[ev["slide"]])))
+ elif ev.get("scale"):
+ how.append(T("由小放大", "scales up"))
+ how.append(T(*EASE_WORDS[ev["easing"]]))
+ bits = [f"{ev['t0']:.2f}–{ev['t1']:.2f}s",
+ T("{w}(x {x:.0%}–{x2:.0%},y {y:.0%}–{y2:.0%})", "{w} (x {x:.0%}–{x2:.0%}, y {y:.0%}–{y2:.0%})",
+ w=_where(b), x=b[0], x2=b[0] + b[2], y=b[1], y2=b[1] + b[3]),
+ what + T(",", ", ") + T(",", ", ").join(how)]
+ if ev.get("colour"):
+ bits.append(ev["colour"])
+ if ev.get("text"):
+ bits.append(T("文字「{t}」", "text “{t}”", t=" / ".join(ev["text"])))
+ if ev.get("crop"):
+ bits.append(f"[{T('截图', 'crop')}]({ev['crop']})")
+ return " · ".join(bits)
+
+
+SHAPE_WORDS = {"hline": ("横线", "horizontal line"), "vline": ("竖线", "vertical line"), "block": ("图形/文字块", "shape / text block")}
+
+
+def static_line(el: dict) -> str:
+ b = el["box"]
+ bits = [T(*SHAPE_WORDS[el["shape"]]), T("x {x:.0%}–{x2:.0%},y {y:.0%}–{y2:.0%}", "x {x:.0%}–{x2:.0%}, y {y:.0%}–{y2:.0%}",
+ x=b[0], x2=b[0] + b[2], y=b[1], y2=b[1] + b[3]), el["colour"]]
+ if el.get("text"):
+ bits.append(T("文字「{t}」", "text “{t}”", t=" / ".join(el["text"])))
+ if el.get("crop"):
+ bits.append(f"[{T('截图', 'crop')}]({el['crop']})")
+ return " · ".join(bits)
+
+
+def layer_line(layer: dict) -> str:
+ b = layer["box"]
+ crops = " ".join(f"[{T('截图', 'crop')} L{k}]({c})" for k, c in enumerate(layer.get("crops") or [], 1))
+ return (crops + " · " if crops else "") + T("持续运动层:{s:.0%} 的画面整镜都在动(x {x:.0%}–{x2:.0%},y {y:.0%}–{y2:.0%}),如漂移的渐变、粒子流、辉光呼吸",
+ "Continuous layer: {s:.0%} of the frame moves through the whole shot (x {x:.0%}–{x2:.0%}, y {y:.0%}–{y2:.0%}), "
+ "e.g. drifting gradients, particle flow, breathing glow",
+ s=layer["share"], x=b[0], x2=b[0] + b[2], y=b[1], y2=b[1] + b[3])
+
+
+def palette(bgr: np.ndarray, k: int = 8, min_share: float = 0.01) -> dict:
+ """Background colour (most common along the border) and the main colours with their share, as hex."""
+ small = cv2.resize(bgr, (96, max(1, int(96 * bgr.shape[0] / bgr.shape[1]))), interpolation=cv2.INTER_AREA)
+ lab = cv2.cvtColor(small, cv2.COLOR_BGR2LAB).reshape(-1, 3).astype(np.float32)
+ k = min(k, len(np.unique(lab, axis=0)))
+ if k < 1:
+ return {"background": None, "colours": []}
+ crit = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 1.0)
+ cv2.setRNGSeed(0) # k-means++ seeding draws from OpenCV's per-thread RNG: fix it so reruns give the same colours
+ _, lbl, centers = cv2.kmeans(lab, k, None, crit, 2, cv2.KMEANS_PP_CENTERS)
+ lbl = lbl.ravel()
+ share = np.bincount(lbl, minlength=k) / len(lbl)
+ hexes = [_hex(cv2.cvtColor(np.uint8([[c]]), cv2.COLOR_LAB2BGR)[0, 0]) for c in centers]
+ grid = lbl.reshape(small.shape[:2])
+ border = np.concatenate([grid[0], grid[-1], grid[:, 0], grid[:, -1]])
+ bg = int(np.bincount(border, minlength=k).argmax())
+ order = [int(i) for i in np.argsort(-share) if share[i] >= min_share]
+ return {"background": hexes[bg], "colours": [{"hex": hexes[i], "share": round(float(share[i]), 2)} for i in order]}
+
+
+def strip_frames(path: str | Path, info: VideoInfo, start: float, dur: float, every: float = 0.5, most: int = 12,
+ width: int = 270) -> tuple[list[np.ndarray], list[float]]:
+ """Frames every `every` seconds (at most `most`, spread evenly) for a time-labelled key-frame strip."""
+ step = max(every, dur / most)
+ frames = list(iter_frames(path, info, width, start=start, duration=dur, fps=1.0 / step))
+ times = [start + i * step for i in range(len(frames))]
+ return frames[:most], times[:most]
+
+
+def element_crops(path: str | Path, info: VideoInfo, start: float, end: float, motion: dict, out_dir: Path, sid: str,
+ width: int, most: int = 16) -> str | None:
+ """Cut every measured element out of the full-size picture once it has settled (a disappearing one just before it
+ goes, a static one at the end of the shot): shots/<sid>_el_NN.jpg, linked from its timeline line, plus a numbered
+ contact sheet shots/<sid>_elements.jpg. One decode of the shot at 10 fps. Returns the sheet's file name."""
+ step = 0.1
+ want: dict[int, list[tuple[str, dict]]] = {}
+ items = ([("el", k + 1, e) for k, e in enumerate(motion.get("events", [])[:most])]
+ + [("st", k + 1, e) for k, e in enumerate(motion.get("static", [])[:most // 2])])
+ if motion.get("layer") and motion["layer"]["share"] >= 0.03:
+ # the continuously moving layer is often the subject itself (particle figure, drifting gradient): mid-shot and end
+ items += [("ly", 1, {**motion["layer"], "_t": (start + end) / 2}), ("ly", 2, {**motion["layer"], "_t": end - 0.05})]
+ last_i = max(0, int((end - start) / step) - 1)
+ for tag, k, e in items:
+ if tag == "ly":
+ t = e["_t"]
+ elif tag == "st":
+ t = end - 0.05
+ elif e["kind"] == "disappear":
+ t = e["t0"] - 0.05
+ else:
+ t = min(end - 0.05, e["t1"] + 0.1)
+ i = min(last_i, max(0, int(round((t - start) / step))))
+ want.setdefault(i, []).append((tag, k, e))
+ if not want:
+ return None
+ out_dir.mkdir(parents=True, exist_ok=True)
+ cells = []
+ for i, fr in enumerate(iter_frames(path, info, width, start=start, duration=end - start, fps=1 / step)):
+ if i > max(want):
+ break
+ for tag, k, e in want.get(i, []):
+ h, w = fr.shape[:2]
+ x, y, bw, bh = e["box"]
+ pad = 0.015
+ x0, y0 = max(0, int((x - pad) * w)), max(0, int((y - pad) * h))
+ x1, y1 = min(w, int((x + bw + pad) * w)), min(h, int((y + bh + pad) * h))
+ if x1 - x0 < 4 or y1 - y0 < 4:
+ continue
+ name = f"{sid}_{tag}_{k:02d}.jpg"
+ crop = fr[y0:y1, x0:x1]
+ cv2.imwrite(str(out_dir / name), crop, [cv2.IMWRITE_JPEG_QUALITY, 94])
+ if tag == "ly":
+ motion["layer"].setdefault("crops", []).append(f"shots/{name}")
+ else:
+ e["crop"] = f"shots/{name}"
+ cells.append((({"ly": 0, "el": 1, "st": 2}[tag], k), {"ly": "L", "el": "", "st": "S"}[tag] + str(k), crop))
+ if not cells:
+ return None
+ cells = [(label, im) for _, label, im in sorted(cells, key=lambda c: c[0])]
+ # numbered contact sheet: element numbers match the timeline (S = static element)
+ ch = 150
+ tiles = []
+ for label, im in cells:
+ sc = ch / im.shape[0]
+ tw = int(min(360, max(40, im.shape[1] * sc)))
+ tile = np.full((ch + 22, tw, 3), 24, np.uint8)
+ tile[22:] = cv2.resize(im, (tw, ch))
+ cv2.putText(tile, label, (4, 16), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1, cv2.LINE_AA)
+ tiles.append(tile)
+ rows, row, row_w = [], [], 0
+ for t in tiles:
+ if row and row_w + t.shape[1] > 1200:
+ rows.append(row)
+ row, row_w = [], 0
+ row.append(t)
+ row_w += t.shape[1] + 4
+ rows.append(row)
+ W_ = max(sum(t.shape[1] + 4 for t in r) for r in rows)
+ sheet = np.full((len(rows) * (ch + 26), W_, 3), 24, np.uint8)
+ for ri, r in enumerate(rows):
+ x = 0
+ for t in r:
+ sheet[ri * (ch + 26): ri * (ch + 26) + ch + 22, x:x + t.shape[1]] = t
+ x += t.shape[1] + 4
+ name = f"{sid}_elements.jpg"
+ cv2.imwrite(str(out_dir / name), sheet, [cv2.IMWRITE_JPEG_QUALITY, 90])
+ return f"shots/{name}"
diff --git a/rea_video/packaging.py b/rea_video/packaging.py
index 4c2dcf5..bd5a570 100644
--- a/rea_video/packaging.py
+++ b/rea_video/packaging.py
@@ -43,8 +43,9 @@ SMALL_W = 160 # sticker search resolution
CELL = 8 # sticker search cell size (px at SMALL_W)
MIN_CONF = 0.6
-KIND_ZH = LangDict({"subtitle": "字幕", "huazi": "花字", "title": "标题", "label": "文字标注", "scene": "画面里的字"},
- en={"subtitle": "subtitle", "huazi": "styled text", "title": "title", "label": "text label", "scene": "text in the scene"})
+KIND_ZH = LangDict({"subtitle": "字幕", "huazi": "花字", "title": "标题", "label": "文字标注", "counter": "数字计数", "scene": "画面里的字"},
+ en={"subtitle": "subtitle", "huazi": "styled text", "title": "title", "label": "text label", "counter": "counter",
+ "scene": "text in the scene"})
ANIM_ZH = LangDict({"cut": "直接出现", "pop": "缩放弹出", "fade": "淡入", "slide": "滑入", "reveal": "逐字出现",
"cut_out": "直接消失", "pop_out": "缩小消失", "fade_out": "淡出", "slide_out": "滑出"},
en={"cut": "hard in", "pop": "scale pop", "fade": "fade in", "slide": "slide in", "reveal": "type-on",
@@ -100,11 +101,15 @@ def _hex(bgr) -> str:
return f"#{r:02x}{g:02x}{b:02x}"
-def text_style(frame: np.ndarray, box: tuple[int, int, int, int]) -> dict | None:
+def text_style(frame: np.ndarray, box: tuple[int, int, int, int], rendered: bool = False) -> dict | None:
"""Colours and decoration of one OCR'd text line. box = (x0, y0, x1, y1) in frame pixels.
Glyph fill = colour blobs inside the box that do not reach the ring around it (letters are closed shapes;
the background between them connects to the outside). Stroke = the colour that surrounds those blobs, when
- it differs from the background. Works on busy backgrounds where the fill colour also occurs in the scene."""
+ it differs from the background. Works on busy backgrounds where the fill colour also occurs in the scene.
+ rendered=True: the text sits on a code-rendered / recorded picture (plain or gradient grounds), where the ground
+ showing through closed glyph counters is read as the fill or a highlight and anti-aliasing as an outline; those
+ readings are corrected. Not used on footage / AI pictures, where white subtitles with dark outlines over bright
+ scenes would be mistaken for dark text."""
H, W = frame.shape[:2]
x0, y0, x1, y1 = box
lh = max(4, y1 - y0)
@@ -128,6 +133,7 @@ def text_style(frame: np.ndarray, box: tuple[int, int, int, int]) -> dict | None
ring_px[rng.choice(len(ring_px), min(len(ring_px), 1000), replace=False)]])
k = 6
crit = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 1.0)
+ cv2.setRNGSeed(0) # k-means++ seeding draws from OpenCV's per-thread RNG: fix it so reruns give the same colours
_, _, centers = cv2.kmeans(pts, k, None, crit, 2, cv2.KMEANS_PP_CENTERS)
lbl = np.argmin(((lab[:, None, :] - centers[None]) ** 2).sum(-1), axis=1).reshape(ch, cw)
# enclosed pixels per colour: connected blobs that stay inside the box
@@ -191,8 +197,19 @@ def text_style(frame: np.ndarray, box: tuple[int, int, int, int]) -> dict | None
if s_c is not None and neigh[s_c] >= 0.4 and neigh[s_c] > 2.0 * ring_share[s_c]:
sm = (lbl == s_c) & cv2.dilate(fm.astype(np.uint8), np.ones((9, 9), np.uint8)).astype(bool) & ~fm
perim = max(1.0, float((d1 & ~fm).sum()))
- out.update(stroke=_hex(bgr_of(s_c)), stroke_name=color_name(bgr_of(s_c)),
- stroke_ratio=round(float(sm.sum()) / perim / lh, 3))
+ ratio = float(sm.sum()) / perim / lh
+ bg_c = int(np.argmax(ring_share))
+ if rendered and ring_share[bg_c] >= 0.6 and contrast(fill, bg_c) < 12 and contrast(s_c, bg_c) > 60:
+ # the "fill" is the background showing through closed glyph counters (口, 日, 回) and the "outline" is
+ # the text itself: dark text on a plain light ground (or the reverse)
+ fill = s_c
+ fm = enc_mask == fill if (enc_mask == s_c).any() else (lbl == s_c)
+ out.update(fill=_hex(bgr_of(fill)), fill_name=color_name(bgr_of(fill)))
+ s_c = None
+ elif rendered and ratio < 0.01: # a one-pixel tint around the glyphs is anti-aliasing against the ground
+ s_c = None
+ else:
+ out.update(stroke=_hex(bgr_of(s_c)), stroke_name=color_name(bgr_of(s_c)), stroke_ratio=round(ratio, 3))
else:
s_c = None
# a second enclosed colour far from the fill, with solid strokes of its own (not an anti-aliased rim):
@@ -206,6 +223,9 @@ def text_style(frame: np.ndarray, box: tuple[int, int, int, int]) -> dict | None
cm = enc_mask == c
if core(cm) / max(1.0, float(cm.sum())) < 0.5 * fill_core:
continue
+ # the ground seen through closed glyph counters (口, 日, o) is a ring colour, not a second text colour
+ if rendered and any(ring_share[x] >= 0.2 and contrast(c, x) < 15 for x in range(k)):
+ continue
# a colour between the fill and the stroke / background in lightness with the same hue is an edge blend
others_l = [float(centers[x][0]) for x in range(k) if x != fill and (x == s_c or ring_share[x] > 0.2)]
between = any(min(float(centers[fill][0]), o_) <= float(centers[c][0]) <= max(float(centers[fill][0]), o_) for o_ in others_l)
@@ -462,12 +482,13 @@ def merge_style(styles: list[dict]) -> dict:
return {}
def vote(key):
vals = [s.get(key) for s in styles if s.get(key)]
- return max(set(vals), key=vals.count) if vals else None
+ return max(dict.fromkeys(vals), key=vals.count) if vals else None # ties: first seen (set order varies per run)
n = len(styles)
out = {"fill_name": vote("fill_name"), "fill": vote("fill")}
stroked = [s for s in styles if s.get("stroke")]
if len(stroked) >= max(1, 0.5 * n):
- out.update(stroke_name=max({s["stroke_name"] for s in stroked}, key=[s["stroke_name"] for s in stroked].count),
+ names = [s["stroke_name"] for s in stroked]
+ out.update(stroke_name=max(dict.fromkeys(names), key=names.count),
stroke=stroked[0]["stroke"], stroke_ratio=round(float(np.median([s["stroke_ratio"] for s in stroked])), 3))
boxed = [s for s in styles if s.get("box")]
if len(boxed) >= max(1, 0.5 * n):
@@ -476,7 +497,8 @@ def merge_style(styles: list[dict]) -> dict:
out["gradient"] = True
multi = [s for s in styles if s.get("multicolor")]
if multi and len(multi) >= 0.25 * n:
- out.update(multicolor=True, highlight_name=max({s["highlight_name"] for s in multi}, key=[s["highlight_name"] for s in multi].count))
+ hl = [s["highlight_name"] for s in multi]
+ out.update(multicolor=True, highlight_name=max(dict.fromkeys(hl), key=hl.count))
w = [s["weight"] for s in styles if s.get("weight")]
if w:
out["weight"] = round(float(np.median(w)), 3)
@@ -519,6 +541,9 @@ def _decor_score(c: dict) -> tuple[int, list[str]]:
return len(why), why
+_NUMERIC = re.compile(r"[+\-−]?[¥$€£]?[\d.,,.::%+\-−万亿千百kKmMwW]*\d[\d.,,.::%+\-−万亿千百kKmMwW]*")
+
+
def classify_cues(cues: list[dict], duration: float) -> None:
"""Assign each cue a kind (subtitle / huazi / title / label / scene)."""
# lanes: cues stacked at the same place one after another
@@ -541,8 +566,11 @@ def classify_cues(cues: list[dict], duration: float) -> None:
h = float(np.median([c["line_h"] for c in lane]))
tilted = float(np.median([abs(c["angle"]) for c in lane])) >= 4
# readable lines (kinetic typography flashing words for a fraction of a second is not a subtitle track)
- is_sub = (changing >= 3 or (changing >= 2 and duration < 15)) and 0.7 <= med <= 7.0 and h < 0.07 and not tilted
+ # a lane of changing numbers is a counter / chart value drawn by the picture, not a subtitle track
+ counter = changing >= 2 and all(_NUMERIC.fullmatch(_norm(c["text"])) for c in lane)
+ is_sub = (changing >= 3 or (changing >= 2 and duration < 15)) and 0.7 <= med <= 7.0 and h < 0.07 and not tilted and not counter
for c in lane:
+ c["_counter"] = counter
c["lane"] = lanes.index(lane)
c["_sub_lane"] = is_sub
c["_lane_texts"] = changing
@@ -566,6 +594,8 @@ def classify_cues(cues: list[dict], duration: float) -> None:
else:
kind = "label"
c["kind"], c["kind_zh"] = kind, KIND_ZH[kind]
+ if c.pop("_counter", False):
+ c["kind"], c["kind_zh"] = "counter", KIND_ZH["counter"]
c["decor"] = why
if moving and kind != "scene":
c["follows"] = True # tracked to an object in the picture (label with a leader / tag)
@@ -1181,7 +1211,7 @@ def analyze(path: str | Path, info: VideoInfo, cuts: list[float], out_dir: Path
for lane in lanes.values():
for key, keys in (("fill_name", ("fill_name", "fill")), ("stroke_name", ("stroke_name", "stroke", "stroke_ratio"))):
vals = [c["style"].get(key) for c in lane]
- top_ = max(set(vals), key=vals.count)
+ top_ = max(dict.fromkeys(vals), key=vals.count)
if vals.count(top_) >= 0.6 * len(vals):
donor = next(c["style"] for c in lane if c["style"].get(key) == top_)
for c in lane:
@@ -1272,6 +1302,39 @@ def to_ass(cues: list[dict], width: int, height: int) -> str:
"Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text"] + events) + "\n"
+def restyle_rendered(pack: dict, shots: list[dict], video: str | Path, frame_h: int | None) -> int:
+ """Text on shots judged code-rendered / screen-recorded: measure its style again with the rendered-picture rules
+ (text_style(rendered=True)); text on other shots gets its original reading back (a review may relabel a shot).
+ Run after classification, so footage / AI subtitles are never touched. Returns how many cues were re-measured."""
+ rendered = {r["index"] for r in shots if r["base"]["label"] in ("code_render", "screen_capture")}
+ todo = []
+ for c in pack.get("text_cues", []):
+ if c.get("shot") in rendered and c.get("style") and "style_overlay" not in c:
+ todo.append(c)
+ elif c.get("shot") not in rendered and "style_overlay" in c:
+ c["style"] = c.pop("style_overlay")
+ c["style_zh"] = style_text(c["style"], c.get("line_h"), frame_h)
+ if not todo or not Path(video).is_file():
+ return 0
+ cap = cv2.VideoCapture(str(video))
+ n = 0
+ for c in todo:
+ cap.set(cv2.CAP_PROP_POS_MSEC, (c["t0"] + c["t1"]) / 2 * 1000)
+ ok, fr = cap.read()
+ if not ok:
+ continue
+ H, W = fr.shape[:2]
+ x, y, w, h = c["bbox"]
+ st = text_style(fr, (int(x * W), int(y * H), int((x + w) * W), int((y + h) * H)), rendered=True)
+ if st:
+ c["style_overlay"] = c["style"]
+ c["style"] = {**{k: v for k, v in c["style"].items() if k in ("highlight_timing",)}, **st}
+ c["style_zh"] = style_text(c["style"], c.get("line_h"), frame_h)
+ n += 1
+ cap.release()
+ return n
+
+
def summary_lines(pack: dict, sfx_align: dict | None = None) -> list[str]:
cues = pack.get("text_cues", [])
L = []
@@ -1290,7 +1353,7 @@ def summary_lines(pack: dict, sfx_align: dict | None = None) -> list[str]:
+ (T(";入场:{a}", "; entrance: {a}", a=join(f'{k}×{v}' for k, v in sorted(anim.items(), key=lambda kv: -kv[1]))) if anim else "")
+ (T(";说到关键词时变色", "; keywords change colour as they are spoken") if any((c.get('style') or {}).get('highlight_timing') == 'spoken' for c in subs) else "")
+ (T(";句中有弹跳/变色动效", "; bounce / colour-change motion inside lines") if sum(1 for c in subs if c.get("mid_motion")) >= max(2, 0.2 * len(subs)) else ""))
- for kind in ("huazi", "title", "label"):
+ for kind in ("huazi", "title", "label", "counter"):
cs = [c for c in cues if c["kind"] == kind]
if cs:
names = join(T("「{t}」", "\"{t}\"", t=c['text'].replace('/', ' ')[:14]) for c in cs[:6]) + (T("等", " …") if len(cs) > 6 else "")
@@ -1470,6 +1533,10 @@ def finalize_pack(breakdown: dict, out: Path) -> dict | None:
c["shot"] = r["index"] if r else None
# on a rendered / recorded picture, words are the picture's content, not a separate overlay
c["part_of_picture"] = bool(r and labels[r["id"]] in ("code_render", "screen_capture") and c["kind"] not in ("subtitle",))
+ src = breakdown.get("source") or {}
+ frame_h = src.get("width") if src.get("rotation") in (90, 270) else src.get("height")
+ if src.get("path"):
+ restyle_rendered(pack, breakdown["shots"], src["path"], frame_h)
stickers = [s for s in pack.get("stickers", []) if not s.get("in_picture")]
cues = [c for c in pack.get("text_cues", []) if c["kind"] != "scene"]
cuts = [r["start"] for r in breakdown["shots"][1:]]
diff --git a/rea_video/pipeline.py b/rea_video/pipeline.py
index 63c9e59..1534deb 100644
--- a/rea_video/pipeline.py
+++ b/rea_video/pipeline.py
@@ -18,6 +18,7 @@ from .media import cut_clip, extract_frame, require_tools, video_info
from .overlay import ocr_frames, persistent_template, static_overlays, summarize_text
from .plan import Planner
from .probe import provenance
+from .motion import element_crops, motion_events, palette, strip_frames
from .shots import build_track, detect_shots
from .util import LOG, fmt_time, round_floats, write_json
from . import aspects
@@ -110,6 +111,18 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
still_w = min(1080, info.display_size[0] or 1080) # never upscale; rotated video: displayed width
extract_frame(video, s.start + min(0.05, s.duration / 4), out / "shots" / f"{sid}_first.jpg", width=still_w)
extract_frame(video, max(s.start, s.end - min(0.08, s.duration / 4)), out / "shots" / f"{sid}_last.jpg", width=still_w)
+ motion = None
+ if top(probs)[0] in ("code_render", "screen_capture") or facts.get("graphic_score", 0.0) >= 0.5:
+ # rendered picture: element-level motion timeline, key-frame strip and hex palette for a code remake
+ motion = motion_events(video, info, s.start, s.duration, text.get("items"))
+ sframes, stimes = strip_frames(video, info, s.start, s.duration)
+ if sframes:
+ 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])
+ 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
rec = {
"id": sid, **s.to_dict(), "features": round_floats(feats), "faces": round(faces, 3),
"aspects": round_floats(asp), "overlay": round_floats(ov), "text": text, "layers": layers, "embedded_assets": round_floats(embedded),
@@ -117,6 +130,10 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,
"assets": {"sheet": f"shots/{sid}.jpg", "first_frame": f"shots/{sid}_first.jpg", "last_frame": f"shots/{sid}_last.jpg"},
"vlm": None,
}
+ if motion is not None:
+ rec["motion"] = round_floats(motion)
+ if (out / "shots" / f"{sid}_strip.jpg").exists():
+ rec["assets"]["strip"] = f"shots/{sid}_strip.jpg"
shot_records.append(rec)
dl, dp = top(probs)
LOG.info("%s %s-%s det=%s(%.0f%%) %s", sid, fmt_time(s.start), fmt_time(s.end), dl, dp * 100, facts.get("temporal_family"))
@@ -298,7 +315,11 @@ def _vlm_gate(rec: dict, vprobs: dict | None, vctx: dict) -> dict | None:
# a lip macro with no face found scores 3D 0.35 / AI 0.27 / live 0.22 (issue #8 #22-#27), which is no call
undecided = dp < 0.4 and vprobs.get(v, 0.0) > 0 and rec["deterministic"]["probs"].get(v, 0.0) >= 0.15 \
and sp - rec["deterministic"]["probs"].get(v, 0.0) <= 0.08
- if v not in (d, ranked[1][0]) and not person and not undecided: # it must back one of the tools' two best guesses
+ # inside the tools' first group (3D vs code render: both "rendered") the reader picks the subtype; the tools
+ # only measured "rendered texture", which is the part the reader cannot see wrong (particle explainer #5 / #21:
+ # tools 3D then AI, reader code render)
+ same_group = group_of(v) == group_of(d) == "rendered"
+ if v not in (d, ranked[1][0]) and not person and not undecided and not same_group: # it must back one of the tools' two best guesses
return None
# the tools' confidence only protects the AI / live axis (frame-rate evidence), not a "rendered" texture call
if (d in AI_LIVE_AXIS or v in AI_LIVE_AXIS) and not (person and d not in AI_LIVE_AXIS):
diff --git a/rea_video/plan.py b/rea_video/plan.py
index 1120460..5f3e781 100644
--- a/rea_video/plan.py
+++ b/rea_video/plan.py
@@ -2,6 +2,7 @@
models are candidates, and how capsule-cinema (or local ffmpeg) would execute it."""
from __future__ import annotations
+import re
from pathlib import Path
import yaml
@@ -76,6 +77,110 @@ def shot_prompts(shot: dict) -> dict:
return out
+def _move_words(f: dict) -> str:
+ """Measured camera / whole-picture motion of a rendered shot in words (what the code camera should do)."""
+ cam = f.get("camera")
+ if cam in (None, "unknown", "static"):
+ return T("固定", "static")
+ if cam == "static_with_subject_motion":
+ return T("固定机位,画面内元素在动", "static frame, elements move inside it")
+ bits = []
+ zoom = f.get("zoom_per_s", 0.0)
+ if abs(zoom) > 0.01:
+ bits.append(T("推近 {z:.0%}/s", "push in {z:.0%}/s", z=zoom) if zoom > 0 else T("拉远 {z:.0%}/s", "pull out {z:.0%}/s", z=-zoom))
+ if f.get("pan_px_per_s", 0.0) > 8:
+ d = f.get("pan_dir_deg", 0.0) % 360
+ where = T("右", "right") if d < 45 or d >= 315 else T("下", "down") if d < 135 else T("左", "left") if d < 225 else T("上", "up")
+ bits.append(T("画面向{w}移", "picture drifts {w}", w=where))
+ if abs(f.get("rot_deg_per_s", 0.0)) > 1:
+ bits.append(T("旋转", "rotates"))
+ return T(",", ", ").join(bits) or T("固定机位,画面内元素在动", "static frame, elements move inside it")
+
+
+def code_scene(shot: dict) -> dict:
+ """What a code-rendered shot draws, for rebuilding it: the picture (image readers' description), whether it is
+ particle / point-cloud graphics on black, the measured camera move and the confident on-screen text."""
+ facts = (shot.get("deterministic") or {}).get("facts") or {}
+ desc = (shot.get("review") or {}).get("description") or (shot.get("vlm") or {}).get("description") or ""
+ text = shot.get("text") or {}
+ sure = {it.get("text") for it in text.get("items", []) if it.get("conf", 0) >= 0.85}
+ words: list[str] = []
+ for tr in text.get("tracks", []):
+ if tr.get("kind") == "subtitle":
+ continue
+ for w in tr.get("texts", []):
+ if w in sure and w not in words:
+ words.append(w)
+ motion = shot.get("motion") or {}
+ 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]],
+ "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"),
+ "flash_s": shot.get("flash_s")}
+
+
+# how a code-rendered picture is built, from the measured look; keys of CODE_STYLES
+def code_style(shot: dict) -> str:
+ facts = (shot.get("deterministic") or {}).get("facts") or {}
+ text = shot.get("text") or {}
+ if facts.get("fine_dark", 0.0) > 0.5:
+ return "particles"
+ if facts.get("fine_light", 0.0) > 0.5:
+ return "lineart"
+ kind = facts.get("vector_kind")
+ if kind in ("procedural", "neon"):
+ return kind
+ sure = {it.get("text") for it in text.get("items", []) if it.get("conf", 0) >= 0.85}
+ numbers = {w for tr in text.get("tracks", []) for w in tr.get("texts", [])
+ if w in sure and re.search(r"[1-9]", w)} # "000" / "0" are usually OCR noise on shapes
+ if len(numbers) >= 3:
+ return "data"
+ if facts.get("ui_text", 0.0) > 0.5 or facts.get("ui_gray", 0.0) > 0.5 or facts.get("text_like", 0.0) > 0.6:
+ return "ui"
+ if kind in ("gradient", "colour_fields"):
+ return "gradient"
+ if text.get("text_coverage", 0.0) > 0.04:
+ return "type"
+ return "shapes"
+
+
+def CODE_STYLES() -> dict[str, tuple[str, str]]:
+ """style -> (short name, how to build it in a Remotion / HTML project)."""
+ return {
+ "particles": (T("粒子/点云", "particles / point cloud"),
+ T("Three.js 粒子系统(点按目标形状采样,形状间插值变形,加辉光后期),用 @remotion/three 逐帧渲染",
+ "Three.js particle system (points sampled on the target shape, morph between shapes, bloom), rendered frame by frame with @remotion/three")),
+ "lineart": (T("线稿/点阵", "line art / dots"),
+ T("SVG 路径用 stroke-dashoffset 逐帧描线,或 Canvas 按噪声场画流线 / 按目标形状排点;线宽、颜色、密度按画面量",
+ "SVG paths drawn on with stroke-dashoffset, or Canvas flow lines from a noise field / dots placed on a target shape; "
+ "match stroke width, colour and density from the frame")),
+ "procedural": (T("程序生成色场", "procedural colour field"),
+ T("GLSL 片元着色器(分形/噪声/plasma),Three.js ShaderMaterial 或 WebGL canvas,时间作 uniform 逐帧驱动",
+ "GLSL fragment shader (fractal / noise / plasma) via Three.js ShaderMaterial or a WebGL canvas, time passed as a uniform each frame")),
+ "neon": (T("暗底辉光", "glow on dark"),
+ T("深色底 + 渐变填充文字/线条,CSS drop-shadow 或 SVG feGaussianBlur 叠两层做辉光,亮度随帧轻微呼吸",
+ "Dark ground + gradient-filled text / lines, glow from two stacked CSS drop-shadows or an SVG feGaussianBlur, brightness breathing per frame")),
+ "data": (T("数据图表", "data chart"),
+ T("SVG/D3 比例尺画坐标和图形,数字用 interpolate() 逐帧计数,柱/线按 spring() 生长",
+ "SVG / D3 scales for axes and marks, numbers counted up with interpolate(), bars / lines grown with spring()")),
+ "ui": (T("界面/文档", "UI / document"),
+ T("HTML/CSS 按截图还原卡片和版式(圆角、阴影、字号),元素用 spring() 进场;真界面可直接录屏",
+ "HTML / CSS cards and layout matched to the frame (radius, shadow, type sizes), elements enter with spring(); a real UI can be screen-recorded")),
+ "gradient": (T("渐变/色块", "gradients / colour fields"),
+ T("CSS 线性/径向渐变,或几个大圆加 filter: blur() 慢速漂移;毛玻璃卡片用 backdrop-filter",
+ "CSS linear / radial gradients, or a few large circles with filter: blur() drifting slowly; glass cards with backdrop-filter")),
+ "type": (T("文字动效", "kinetic type"),
+ T("逐词/逐字 spring() 进场(位移+缩放+透明度),强调词加色块;字体、字号、行距按画面量",
+ "Word-by-word spring() entrances (offset + scale + opacity), highlight boxes on key words; match font, size and leading from the frame")),
+ "shapes": (T("矢量图形", "vector shapes"),
+ T("SVG 图形 + interpolate()/spring() 关键帧,按画面量出位置和节奏",
+ "SVG shapes + interpolate() / spring() keyframes, positions and timing measured from the frame")),
+ }
+
+
def _load(name: str):
with (CAP / name).open(encoding="utf-8") as f:
return yaml.safe_load(f)
@@ -149,5 +254,5 @@ class Planner:
"pan_dir_deg": m.get("pan_dir_deg", 0.0), "analysis_width": 480, "duration": round(dur, 3)}
elif executor == "code_render_spec":
plan["spec"] = {"text_layers": [l for l in shot.get("layers", []) if l["kind"] in ("subtitle", "title", "label")],
- "beats": shot.get("beats", []), "duration": round(dur, 3)}
+ "beats": shot.get("beats", []), "duration": round(dur, 3), "scene": code_scene(shot)}
return plan
diff --git a/rea_video/production.py b/rea_video/production.py
index 8ccce01..7e40d48 100644
--- a/rea_video/production.py
+++ b/rea_video/production.py
@@ -18,7 +18,7 @@ import cv2
from .classify import LABEL_ZH
from .aspects.camera import SUPPORT_ZH
-from .plan import Planner, shot_prompts
+from .plan import CODE_STYLES, Planner, code_scene, shot_prompts
GEN_LABELS = ("ai_video", "cg_3d", "anim_2d")
SHOOT_LABELS = ("live_action", "stop_motion")
@@ -58,6 +58,77 @@ def scene_distance(a: list, b: list) -> float:
return float(min(d)) if d else 1.0
+HUES = ((10, "红", "red"), (22, "橙", "orange"), (35, "黄", "yellow"), (78, "绿", "green"), # OpenCV hue (0-180) bands
+ (100, "青", "cyan"), (130, "蓝", "blue"), (170, "紫", "purple"), (181, "红", "red"))
+
+
+def lit_colours(paths: list[Path], top: int = 3, min_share: float = 0.15) -> list[str]:
+ """Main colours of the lit part of a shot's key frames (what the glowing elements are coloured), most first."""
+ votes: dict[tuple, float] = {}
+ n = 0
+ for p in paths:
+ im = cv2.imread(str(p))
+ if im is None:
+ continue
+ hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV).reshape(-1, 3)
+ lit = hsv[hsv[:, 2] > 60]
+ if not len(lit):
+ continue
+ n += 1
+ grey = lit[:, 1] < 60
+ votes[("白", "white")] = votes.get(("白", "white"), 0.0) + float(grey.mean())
+ hue = lit[~grey][:, 0]
+ lo = 0
+ for hi, zh, en in HUES:
+ votes[(zh, en)] = votes.get((zh, en), 0.0) + float(((hue >= lo) & (hue < hi)).sum()) / len(lit)
+ lo = hi
+ ranked = sorted(votes.items(), key=lambda kv: -kv[1])
+ return [T(*w) for w, v in ranked[:top] if n and v / n >= min_share]
+
+
+def code_motion_md(scenes: list[dict]) -> list[str]:
+ """Per-shot motion timeline of the code shots (measured): what appears where, when, how and in what colour."""
+ from .motion import event_line, layer_line, static_line
+
+ L = ["", T("逐镜动效时间轴(工具测量:位置是占画面宽高的百分比,颜色是元素稳定后的取色;配合关键帧条看)",
+ "Per-shot motion timeline (measured: positions in % of frame width / height, colours sampled once the element settles; "
+ "read together with the key-frame strip)"), ""]
+ for sc in scenes:
+ head = f"#{sc['shot']} {sc['start']:.1f}–{sc['end']:.1f}s"
+ if sc.get("transition_in") == "flash":
+ head += T("(闪亮切入:切进来时整幅画面先变亮,{s:.1f}s 内回落)", " (flash cut: the picture opens bright and settles in {s:.1f}s)",
+ s=sc.get("flash_s") or 0)
+ elif sc.get("transition_in") in ("dissolve", "fade"):
+ head += T("({t}切入)", " ({t} in)", t=T("叠化", "dissolve") if sc["transition_in"] == "dissolve" else T("淡入", "fade"))
+ n_ev = len(sc.get("events") or [])
+ L.append("<details><summary>" + T("动效 {h} · {n} 个", "Motion {h} · {n} events", h=head, n=n_ev) + "</summary>")
+ L.append("")
+ if sc.get("strip"):
+ L += [f"![{head}]({sc['strip']})", ""]
+ 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 "—"))
+ 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, "
+ "S = elements that never move), full-size files in `shots/`:"),
+ "", f"![{head}]({sc['elements_sheet']})", ""]
+ for k, e in enumerate(sc.get("static") or [], 1):
+ L.append(f"- S{k}. " + T("整镜不动:", "never moves: ") + static_line(e))
+ if sc.get("layer"):
+ L.append("- " + layer_line(sc["layer"]))
+ for q in sc.get("sequences") or []:
+ L.append("- " + T("依次出现:{n} 个同样大小的元素,间隔 {i:.2f}s,每个用时约 {e:.2f}s(下面第 {k} 条)",
+ "In sequence: {n} same-size elements, {i:.2f}s apart, about {e:.2f}s each (items {k} below)",
+ n=q["n"], i=q["interval"], e=q["each"], k=T("、", ", ").join(str(x + 1) for x in q["events"])))
+ for i, ev in enumerate(sc.get("events") or [], 1):
+ L.append(f"{i}. " + event_line(ev))
+ if not (sc.get("events") or sc.get("layer") or sc.get("static")):
+ L.append(T("- 没有测到元素运动(静止画面或只有细微变化)", "- No element motion measured (still picture or only slight changes)"))
+ L += ["", "</details>", ""]
+ return L
+
+
# ---------------------------------------------------------------- model choice
def pick_model(planner: Planner, engine: str) -> tuple[dict | None, dict | None]:
"""-> (the user's engine as a capability entry, the model the generation units are planned for).
@@ -105,7 +176,7 @@ def _runs(shots: list[dict], same_scene, labels: tuple) -> list[list[dict]]:
runs.append(cur)
cur, gap = [], False
continue
- joinable = cur and same_scene(cur[-1], r) and (gap or r.get("transition_in") == "cut")
+ joinable = cur and same_scene(cur[-1], r) and (gap or r.get("transition_in") in ("cut", "flash"))
if cur and not joinable:
runs.append(cur)
cur = []
@@ -194,7 +265,7 @@ def _unit(seg: list[dict], k: int, lim: dict, model: dict | None, style: str, ca
+ T(":参考动作、运镜和剪辑节奏(只作参考,不复制画面)",
": reference for action, camera movement and cutting rhythm (reference only, do not copy the picture)"), "user": False})
cont = None
- if prev_unit and same_scene_prev and seg[0].get("transition_in") == "cut" and abs(prev_unit["ranges"][-1][1] - t0) < 1e-3:
+ if prev_unit and same_scene_prev and seg[0].get("transition_in") in ("cut", "flash") and abs(prev_unit["ranges"][-1][1] - t0) < 1e-3:
cont = T("首帧用 {p} 的尾帧,接上动作", "first frame = last frame of {p}, continue the action", p=prev_unit["id"])
elif lim["first_frame"]:
cont = T("首帧:参照原片第 {i} 镜首帧({f})的构图出图", "first frame: generate an image matching the composition of source shot {i}'s first frame ({f})",
@@ -356,7 +427,10 @@ def production_plan(b: dict, out: Path, engine: str = "seedance2.0") -> dict:
code.append({"id": T("段{n}", "Part {n}", n=len(code) + 1), "kind": "code", "shots": [x["index"] for x in cur],
"start": cur[0]["start"], "end": cur[-1]["end"], "duration": round(cur[-1]["end"] - cur[0]["start"], 3),
"screen_capture": [x["index"] for x in cur if x["base"]["label"] == "screen_capture"],
- "text_tracks": sum(len((x.get("text") or {}).get("tracks", [])) for x in cur)})
+ "text_tracks": sum(len((x.get("text") or {}).get("tracks", [])) for x in cur),
+ "scenes": [{"shot": x["index"], "start": x["start"], "end": x["end"], **code_scene(x),
+ "colours": lit_colours([out / x["assets"][k] for k in ("first_frame", "last_frame")
+ if (x.get("assets") or {}).get(k)])} for x in cur]})
cur = []
plan["code"] = code
plan["local"] = [{"shot": r["index"], "label_zh": r["base"]["label_zh"], "duration": r["duration"]}
@@ -485,6 +559,40 @@ def report_md(plan: dict) -> list[str]:
id=c["id"], sh=join("#" + str(i) for i in c["shots"]), a=c["start"], z=c["end"])
+ (semi() + T("其中 {sh} 用真实界面录屏", "{sh} use real screen recordings", sh=join("#" + str(i) for i in c["screen_capture"]))
if c["screen_capture"] else ""))
+ scenes = [sc for c in plan["code"] for sc in c.get("scenes", [])]
+ if any(sc.get("strip") or sc.get("elements_sheet") for sc in scenes):
+ L += ["", T("复刻资产(都在报告目录里,复刻时和下面的数据一起交给写代码的人或 LLM):",
+ "Remake assets (all in the report folder; hand them over together with the data below to whoever writes the code, or to an LLM):"),
+ T("- `shots/shot_XXX_first.jpg` / `_last.jpg`:每镜首尾帧原分辨率,对版式、字号、留白",
+ "- `shots/shot_XXX_first.jpg` / `_last.jpg`: first / last frame of each shot at full size, for layout, type size and margins"),
+ T("- `shots/shot_XXX_strip.jpg`:约每 0.5 秒一张的关键帧条,看动画过程",
+ "- `shots/shot_XXX_strip.jpg`: key frames about every 0.5 s, to follow the animation"),
+ T("- `shots/shot_XXX_elements.jpg` 和 `_el_NN.jpg` / `_st_NN.jpg` / `_ly_NN.jpg`:每个元素停稳后的原分辨率截图,编号对应动效时间轴;"
+ "图形照着重画,图标、Logo、插画这类画不出来的可以直接抠图用",
+ "- `shots/shot_XXX_elements.jpg` and `_el_NN.jpg` / `_st_NN.jpg` / `_ly_NN.jpg`: full-size crop of every element once settled, "
+ "numbered as in the motion timeline; redraw shapes from them, cut out icons, logos and illustrations that cannot be redrawn"),
+ T("- `packaging/overlays.ass`、`packaging/timeline.json`:文字的时间、位置、颜色",
+ "- `packaging/overlays.ass`, `packaging/timeline.json`: timing, position and colour of the text")]
+ if scenes:
+ styles = CODE_STYLES()
+ used = list(dict.fromkeys(sc.get("style", "shapes") for sc in scenes))
+ L += ["", T("画面做法(按工具测得的画面类型):", "How to build the pictures (by the measured picture type):")]
+ L += [f"- {styles[k][0]}{T(':', ': ')}{styles[k][1]}" for k in used]
+ if "particles" in used:
+ L += ["", T("粒子类镜头:每一镜粒子拼成什么形状、怎么动是复刻好坏的关键,章节牌、标注、数字等 HUD 文字用 HTML 层叠在上面,"
+ "按下表逐镜做,不要所有镜头共用一个背景。",
+ "Particle shots: what shape the particles form in each shot and how it moves decides whether the remake works; "
+ "chapter cards, labels and counters go in an HTML layer on top. Build shot by shot from the table below, not one shared background.")]
+ L += ["", T("| 镜头 | 时间 | 做法 | 画面 | 运镜 | 主色 | 画面文字 |", "| Shot | Time | Build | Picture | Camera | Colours | On-screen text |"),
+ "|---|---|---|---|---|---|---|"]
+ 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"])
+ 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 += 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"])
+ T(":一张图 + 测得的缩放/平移参数,ffmpeg 直接出", ": one image + the measured zoom / pan parameters, rendered straight from ffmpeg")]
diff --git a/rea_video/report.py b/rea_video/report.py
index 3f84de1..bf433a7 100644
--- a/rea_video/report.py
+++ b/rea_video/report.py
@@ -147,13 +147,17 @@ def _span(a, z) -> str:
# ------------------------------------------------------------------ sections --------------------------------------
+TRANS_ZH = LangDict({"cut": "硬切", "flash": "闪亮切", "fade": "淡入淡出", "dissolve": "叠化", "mg_transition": "版式切换"},
+ en={"cut": "cut", "flash": "flash cut", "fade": "fade", "dissolve": "dissolve", "mg_transition": "layout change"})
+
+
def _head_md(b: dict) -> list[str]:
s, src = b["summary"], b["source"]
L = [T("# 视频拆解报告:{f}", "# Video breakdown: {f}", f=src["filename"]), "",
T("**结论**:{v}", "**Verdict**: {v}", v=s["verdict"]), "",
T("- 时长 {d}s · {w}×{h} · {fps}fps · {ar};镜头 {n} 个,平均 {avg}s;转场:", "- {d}s · {w}×{h} · {fps}fps · {ar}; {n} shots, {avg}s average; transitions: ",
d=src["duration"], w=src["width"], h=src["height"], fps=src["fps"], ar=src["aspect_ratio"], n=s["shots"], avg=s["avg_shot_s"])
- + join(f"{k}×{v}" for k, v in s["transitions"].items()),
+ + (join(f"{TRANS_ZH[k] if k in TRANS_ZH else k}×{v}" for k, v in s["transitions"].items() if k != "start") or "—"),
T("- 判断置信度(按时长加权){c:.0%};判定方式:{by};{vlm}", "- Confidence (duration-weighted) {c:.0%}; decided by: {by}; {vlm}",
c=s["confidence"], by=_decided_by(b), vlm=s.get("vlm") or vlm_note(b["analysis"]["vlm"], b["analysis"].get("review")))]
if s.get("production"):
diff --git a/rea_video/review.py b/rea_video/review.py
index df0b169..3f3daa5 100644
--- a/rea_video/review.py
+++ b/rea_video/review.py
@@ -39,7 +39,7 @@ INSTRUCTIONS = f"""你是这次的 VLM:逐个镜头看图,判断「底层画
{CONFUSIONS}
每个镜头要填:label_probs({len(LABELS)} 类,和为 1)、image_source({"|".join(IMAGE_SOURCES)})、evidence(看到的具体证据)、
-description(主体、动作、场景、运镜)、embedded_assets(画面里的真实素材:截图、照片、实拍片段、Logo,
+description(主体、动作、场景、运镜;代码渲染画面写清图形元素是什么(粒子/渐变/图表/卡片/文字/矢量图形)、拼成什么形状、颜色、怎么动、文字和数字组件在哪,报告的「代码合成」逐镜表直接用它;代码镜头另有 images.strip 关键帧条(约每 0.5 秒一张),报告「逐镜动效时间轴」已测好每个元素的位置、出现时间、方向、快慢和色值,你按编号补「它是什么」即可,例如"1–12:圆角图标卡片,依次弹入")、embedded_assets(画面里的真实素材:截图、照片、实拍片段、Logo,
kind 取 {"|".join(ASSET_KINDS)},is_real_material 为 true/false)。
某个镜头其实是多刀合并的(暗底图形卡和暗底口播交替时,切点分数低容易被合成一个长镜头)就加 split_suggestion:
{{"cuts": [切点秒数], "labels": [各段类别,比 cuts 多一个], "note": "看到的交替结构"}},报告会在该镜头标注拆分建议;不是合并段就不要填。
@@ -61,7 +61,7 @@ props 道具 / 商品 / Logo(name、note、shots);style 一句整体视觉
剪辑包装(tasks.packaging,有才做):
- stickers:工具找到的贴纸 / 动图 / 画中画,看 image(贴纸截图)和 frame_cmd 抽的帧,在答案 packaging.stickers 里填
is_overlay(true = 后期贴上去的;false = 画面本身的东西,例如 3D 里突然出现的物体)和 what(表情包 / GIF / emoji / 箭头 / 小窗里放的什么)。
-- text:工具分好类的花字 / 标题 / 文字标注,分错了就在 packaging.text 里填 kind(subtitle / huazi / title / label / scene)。
+- text:工具分好类的花字 / 标题 / 文字标注,分错了就在 packaging.text 里填 kind(subtitle / huazi / title / label / counter / scene;counter 是跳动的数字)。
- 工具漏掉的贴纸、动图,写进 packaging.missed:{{"t0": 秒, "t1": 秒, "what": "...", "where": "画面位置"}}。"""
@@ -115,7 +115,8 @@ def build_tasks(breakdown: dict, out_dir: str) -> tuple[dict, dict]:
"evidence": rec["deterministic"]["evidence"][:6]},
"hints": shot_hints(rec["features"], rec["deterministic"]["facts"], dl, dp),
"aspects": {k: v["result"] for k, v in (rec.get("aspects") or {}).items() if v.get("result")},
- "images": {"sheet": rec["assets"]["sheet"], "first": rec["assets"]["first_frame"], "last": rec["assets"]["last_frame"]},
+ "images": {"sheet": rec["assets"]["sheet"], "first": rec["assets"]["first_frame"], "last": rec["assets"]["last_frame"],
+ **({"strip": rec["assets"]["strip"]} if rec["assets"].get("strip") else {})},
"zoom_cmd": _tiles_cmd(video, rec["start"], rec["end"], 0.2, f"{out_dir}/check_{rec['id']}.jpg"),
})
pack = breakdown.get("packaging") or {}
@@ -225,7 +226,7 @@ def apply_answers(breakdown: dict, answers: dict, by: str | None = None) -> dict
changes.append((sid, before))
pk = answers.get("packaging")
if isinstance(pk, dict) and breakdown.get("packaging"):
- kinds = ("subtitle", "huazi", "title", "label", "scene")
+ kinds = ("subtitle", "huazi", "title", "label", "counter", "scene")
clean_pk = {"stickers": {str(a["id"]): {"is_overlay": bool(a["is_overlay"]), "what": str(a.get("what", ""))[:80]}
for a in pk.get("stickers") or [] if isinstance(a, dict) and isinstance(a.get("is_overlay"), bool)},
"text": {str(a["id"]): a["kind"] for a in pk.get("text") or [] if isinstance(a, dict) and a.get("kind") in kinds},
diff --git a/rea_video/shots.py b/rea_video/shots.py
index ca54faa..3da6218 100644
--- a/rea_video/shots.py
+++ b/rea_video/shots.py
@@ -40,6 +40,7 @@ class Shot:
transition_in: str = "cut"
boundary_score: float = 0.0
beats: list[int] = field(default_factory=list) # frame indices of MG/slide beat changes inside the shot
+ flash_s: float = 0.0 # "flash" transitions: how long the white / grey flash takes to decay
times: np.ndarray | None = field(repr=False, default=None) # FrameTrack.times
def t(self, frame: int) -> float:
@@ -68,7 +69,7 @@ class Shot:
return {"index": self.index, "start": round(self.start, 3), "end": round(self.end, 3),
"duration": round(self.duration, 3), "start_frame": self.start_frame, "end_frame": self.end_frame,
"transition_in": self.transition_in, "boundary_score": round(self.boundary_score, 3),
- "beats": [round(self.t(b), 3) for b in self.beats]}
+ "beats": [round(self.t(b), 3) for b in self.beats]} | ({"flash_s": round(self.flash_s, 2)} if self.flash_s else {})
def _hist(bgr: np.ndarray) -> np.ndarray:
@@ -133,7 +134,12 @@ def detect_shots(track: FrameTrack, min_shot_s: float = 0.35, cut_threshold: flo
s = score[i]
strong = s > cut_threshold and s > base[i] * 2.5 + 0.06 and chg[i] > 0.25
relative = chg[i] > 0.45 and chg[i] > chg_base[i] * 3 + 0.2 and s > base[i] * 4 + 0.03
- if strong or relative:
+ # a one-frame swap between two still layouts (slides / MG cards on the same ground): less of the frame
+ # changes, but the colour distribution jumps and the picture before it is digitally frozen (pixel-identical
+ # frames; a filmed screen whose content changes keeps sensor noise, 0.002-0.03, and is not a cut)
+ still_swap = (s > cut_threshold and track.hist_dist[i] > 0.25 and chg[i] > 0.18 and chg_base[i] < 0.01
+ and s > base[i] * 5 + 0.1 and i >= 3 and float(track.pix_diff[i - 3:i].max()) < 1e-3)
+ if strong or relative or still_swap:
boundaries[i] = ("cut", float(max(s, chg[i])))
# 2) fades through black / white: luma dips to an extreme and comes back
@@ -145,7 +151,9 @@ def detect_shots(track: FrameTrack, min_shot_s: float = 0.35, cut_threshold: flo
j = i
while j < n and dark[j]:
j += 1
- if 0 < i and j < n and (j - i) <= fps * 2.5:
+ # a fade passes through an (almost) uniform frame; a white page with a title on it is a shot, not a fade
+ flat = min(float(track.thumbs[k].std()) for k in range(i, j)) < 4.0
+ if 0 < i and j < n and (j - i) <= fps * 2.5 and flat:
# boundary at the last extreme frame (next shot starts after fade-in begins)
mid = j
if not any(abs(mid - b) < radius for b in boundaries):
@@ -174,7 +182,9 @@ def detect_shots(track: FrameTrack, min_shot_s: float = 0.35, cut_threshold: flo
if not 0.2 <= alpha <= 0.8:
continue
resid = float(np.abs(M - (A + alpha * D)).mean() / (np.abs(D).mean() + 1e-6))
- if resid < 0.20 and not _motion_explains(A, B):
+ # a cross-fade is a burst of change; an animated gradient / colour morph is a blend of its
+ # neighbours at every frame, at a steady rate, so require more change than in the windows around it
+ if resid < 0.20 and not _steady_morph(track.thumbs, i, k) and not _motion_explains(A, B):
cand.append((i, resid, far))
cand.sort(key=lambda t: t[1])
for i, resid, far in cand:
@@ -201,9 +211,31 @@ def detect_shots(track: FrameTrack, min_shot_s: float = 0.35, cut_threshold: flo
start = b
for shot in shots:
shot.beats = [b for b in beat_marks if shot.start_frame + min_len <= b <= shot.end_frame - min_len]
+ if shot.transition_in == "cut":
+ shot.flash_s = _flash(track.luma, shot.start_frame, shot.end_frame, fps)
+ if shot.flash_s:
+ shot.transition_in = "flash"
return shots
+def _flash(luma: np.ndarray, start: int, end: int, fps: float) -> float:
+ """A cut that opens on a bright flash decaying into the new shot (a common motion-graphics transition):
+ seconds until the brightness settles, or 0."""
+ if start < 1 or end - start < 3:
+ return 0.0
+ before = float(np.median(luma[max(0, start - 3):start]))
+ settle = float(np.median(luma[start + 1:end][-max(1, min(end - start - 1, int(fps))):])) # level later in the shot
+ jump = float(luma[start]) - max(before, settle)
+ if jump < 40:
+ return 0.0
+ k = start
+ while k + 1 < end and luma[k + 1] - settle > 0.2 * jump:
+ k += 1
+ if k == start or k - start > fps * 1.5: # one bright frame is just a bright shot; a long ramp is a fade
+ return 0.0
+ return (k + 1 - start) / fps
+
+
def _mg_beats(track: FrameTrack, boundaries: dict[int, tuple[str, float]], fps: float) -> list[tuple[int, tuple[str, float]]]:
"""Find 'holds' (runs of frozen frames >= 0.4 s). Consecutive holds whose frames differ
over a large area are different beats of a rendered (MG/slide) video."""
@@ -235,6 +267,21 @@ def _mg_beats(track: FrameTrack, boundaries: dict[int, tuple[str, float]], fps:
return out
+def _steady_morph(thumbs: list[np.ndarray], i: int, k: int) -> bool:
+ """True when the picture changes as fast just before and just after the window [i-k, i+k] as inside it."""
+ n = len(thumbs)
+
+ def rate(a: int, b: int) -> float | None:
+ a, b = max(0, a), min(n - 1, b)
+ if b - a < k:
+ return None
+ return float(np.abs(thumbs[b].astype(np.float32) - thumbs[a].astype(np.float32)).mean()) * (2 * k) / (b - a)
+
+ mid = rate(i - k, i + k)
+ around = [r for r in (rate(i - 3 * k, i - k), rate(i + k, i + 3 * k)) if r is not None]
+ return bool(mid and around and mid < 1.3 * max(around))
+
+
def _motion_explains(a: np.ndarray, b: np.ndarray) -> bool:
"""True when b is (mostly) a warped copy of a (zoom/pan/subject motion), i.e. the change
between them is movement rather than new content fading in."""
diff --git a/rea_video/vlm.py b/rea_video/vlm.py
index de74cb4..9bd6a34 100644
--- a/rea_video/vlm.py
+++ b/rea_video/vlm.py
@@ -200,7 +200,7 @@ SHOT_PROMPT = """你是视频制作逆向工程专家。判断这个镜头的「
- ai_video:AI 生成视频(文生/图生/参考生视频)。常见破绽:物体或手指形变、纹理"沸腾"闪烁、物理不合理、文字乱码、背景人物畸形、过于完美的光线与皮肤、动作缓慢漂浮、镜头结尾定格
- avatar:数字人口播(一张人像被音频驱动说话,嘴型驱动、头部轻微摆动、身体几乎不动)
- cg_3d:传统 3D 渲染(Blender/C4D/UE),几何干净、材质规则、光影一致、运动精确无形变
-- code_render:代码/模板渲染的 2D 画面(MG 动效、文字排版、UI、图表、PPT 式卡片)
+- code_render:代码/模板渲染的画面(MG 动效、文字排版、UI、图表、PPT 式卡片、渐变/毛玻璃/霓虹辉光背景、分形和着色器生成的色场,以及暗底上的粒子/点云/线框数据可视化:Remotion/HTML/Canvas、Three.js、Manim、AE Plexus/Trapcode 这类按参数生成的图形)
- screen_capture:屏幕录制或网页/应用截图(真实界面元素、光标、滚动)
- still_motion:一张静态图片做推拉摇移(Ken Burns),画面内部无独立运动
- static_hold:静帧定格(图片或卡片停留不动)
@@ -215,7 +215,9 @@ SHOT_PROMPT = """你是视频制作逆向工程专家。判断这个镜头的「
注意区分:卡通/3D 风格的 AI 视频(形变、闪烁、不精确)与真正的 3D 渲染(几何稳定、精确);
AI 生成的写实视频与实拍(看手、文字、背景细节、物理);AI 生成的动画风视频(形变、线条游移)与真正的 2D 动画(线条稳定、按帧精确);
-AI 仿定格风格(材质在帧间漂移)与真正的定格动画(同一实物、光照不变、只有逐帧位移)。
+AI 仿定格风格(材质在帧间漂移)与真正的定格动画(同一实物、光照不变、只有逐帧位移);
+暗底发光粒子拼成的器官、人体、地球、分子等科普画面是代码渲染(粒子系统),不是 3D 实体模型,也不是 AI 视频或实拍:亮部由成千上万个点或细线组成、没有连续的明暗表面,常配 HUD 式章节牌和引线标注。
+代码绘制的画面没有材质纹理:大面积平滑渐变、纯色块、辉光、毛玻璃卡片、CSS 3D 翻转卡片都是代码渲染,不是 3D 渲染(3D 渲染有布料/木纹/金属等材质、有投影和物体间的光影关系);分形缩放、plasma 之类彩虹色场是着色器生成,不是实拍或 AI 视频。
实拍(或定格)画面如果被 AI 二次加工过,在 ai_edits 里逐个列出:换脸、对口型/改台词、整段风格化重绘、AI 换装、抠像换背景/绿幕、
加删换物体、美颜瘦脸。依据要写看得到的破绽(脸部边缘、嘴型和下巴不跟、头发与背景交界、光线不一致)。没有就写 []。
@@ -229,7 +231,7 @@ AI 仿定格风格(材质在帧间漂移)与真正的定格动画(同一
"image_source": "ai_image|photo|graphic|screenshot|unknown",
"evidence": ["具体可见证据,尽量指明位置/时间"],
"generator_guess": "可能的生成模型或工具(如 Seedance/Kling/Veo/Hailuo/Blender/Remotion/剪映 模板),无法判断写 unknown",
- "description": "镜头内容:主体、动作、场景、景别、运镜、光线",
+ "description": "镜头内容:主体、动作、场景、景别、运镜、光线;代码渲染画面写清图形元素是什么(粒子/渐变/图表/卡片/文字/矢量图形)、拼成什么形状、颜色、怎么动(进场方式、流向、变形、镜头推/环绕)、文字和数字组件在哪",
"shot_size": "特写|近景|中景|全景|远景",
"camera_move": "固定|推|拉|摇|移|跟|环绕|手持",
"style": "画风/质感关键词",
@@ -300,7 +302,7 @@ WHOLE_PROMPT = WHOLE_PROMPT.replace("<<VIDEO_ASPECTS>>", _aspect_block(video=Tru
def shot_hints(features: dict, facts: dict, det_top: str, det_prob: float) -> str:
keys = ["noise_sigma", "temporal_noise", "flat_ratio", "palette95", "dup_ratio", "camera", "kenburns_score", "local_motion_ratio"]
parts = [f"{k}={features.get(k):.3g}" if isinstance(features.get(k), float) else f"{k}={features.get(k)}" for k in keys]
- parts.append(f"temporal_family={facts.get('temporal_family')}, pulldown={facts.get('pulldown')}, graphic_score={facts.get('graphic_score')}")
+ parts.append(f"temporal_family={facts.get('temporal_family')}, pulldown={facts.get('pulldown')}, graphic_score={facts.get('graphic_score')}, fine_dark={facts.get('fine_dark')}, vector_fill={facts.get('vector_fill')}")
parts.append(f"确定性初判={det_top} ({det_prob:.0%})")
return "; ".join(parts)
diff --git a/skills/rea-video/references/output-template.md b/skills/rea-video/references/output-template.md
index 302c6c7..1b578b6 100644
--- a/skills/rea-video/references/output-template.md
+++ b/skills/rea-video/references/output-template.md
@@ -6,10 +6,10 @@
- 复刻方案按实际制作的组织方式写,不按剪辑镜头逐个写:
- AI 镜头 → **生成单元**:几个连续镜头一次生成、用哪个模型、参考素材(`@图片` 产品/人物、`@视频` 原片片段)、合并后的多镜头提示词、单元之间怎么衔接。默认引擎不支持一次多镜头时,照抄 `engine_note`,说明换模型能省几次调用。
- 实拍镜头 → **拍摄场次**:哪些镜头是同一场景、同一机位,一起拍;每个场景的布光;先大景别后特写。分镜表本身仍然逐镜写细。
- - 代码渲染 → 几段代码合成;静图推拉 → 本地重建。
+ - 代码渲染 → 几段代码合成,每镜写清画面元素和动效(报告「代码合成」一节的逐镜动效时间轴:元素位置、出现时间、方向、快慢、色值,元素截图在 `shots/`);静图推拉 → 本地重建。
- 提示词缺失(未开 VLM)时,你看图补写:`rea-video review` 的答案里每镜填 `replication.image_prompt / video_prompt / video_prompt_en`,`apply-review` 后生成单元会自动带上。
- 然后写剪辑包装(字幕样式和时间轴文件、花字 / 贴纸清单、音效卡点)、声音拆解、真实素材清单,最后写不确定点。
-- 报告文件路径(`report.html`)写给用户。不要把 breakdown.json 整段贴进对话。
+- 报告文件路径(`report.html`)写给用户。有代码渲染镜头、用户要复刻时,告诉用户复刻要用整个报告目录(`shots/` 里的元素截图和关键帧条、`packaging/` 里的字幕文件),只给 HTML 或 PDF 会缺单张截图。不要把 breakdown.json 整段贴进对话。
## 语言
@@ -35,7 +35,7 @@
**需要你提供的真实素材**:镜头 #4 中部的 GitHub 页面截图……
-**复刻方案**:按 `production_plan` 写。AI 镜头写生成单元(镜头范围、模型、参考素材、多镜头提示词、衔接);实拍镜头写拍摄场次(场景 → 机位 → 镜头,布光);代码渲染和静图推拉各一句。涉及付费的操作先确认。
+**复刻方案**:按 `production_plan` 写。AI 镜头写生成单元(镜头范围、模型、参考素材、多镜头提示词、衔接);实拍镜头写拍摄场次(场景 → 机位 → 镜头,布光);代码渲染写几段代码合成、每段用什么做法,并指向逐镜动效时间轴和元素截图;静图推拉一句。涉及付费的操作先确认。
> 例:AI 画面 8 镜 → 3 个生成单元、3 次 Seedance 2.5 调用(默认的 Seedance 2.0 不支持一次多镜头,逐镜要 8 次)。G1 #1–#5(9.0s):@图片1 产品图 + @视频1 原片 0–9s,一次出 5 个镜头……
diff --git a/skills/rea-video/references/remake.md b/skills/rea-video/references/remake.md
index 5a2ad38..a6bb952 100644
--- a/skills/rea-video/references/remake.md
+++ b/skills/rea-video/references/remake.md
@@ -4,7 +4,7 @@
- **AI 类镜头**:用原镜头首尾帧加 VLM 提示词,通过 capsule-cinema 生成(会计费,先 `--dry-run`,并征得用户同意)。
- **静态图推拉、静帧**:本地按测得的运动参数重建。
-- **代码渲染**:给出文字轨和版式,用 Remotion 重建。
+- **代码渲染**:用 Remotion 重建。把报告「代码合成」一节(每镜做法、逐镜动效时间轴、色值)连同 `shots/` 里的元素截图、关键帧条和 `packaging/overlays.ass` 一起交给写代码的人或 LLM;按时间轴的时间和位置写动画,按截图重画图形,图标 / Logo / 插画这类画不出来的直接抠图用。
- **真实素材**:列清单让用户提供。
- **声音**:TTS、BGM(按 BPM / 调性 / 情绪)、音效(按时间点)三条轨分别准备。
diff --git a/skills/rea-video/references/taxonomy.md b/skills/rea-video/references/taxonomy.md
index 5054c68..19db525 100644
--- a/skills/rea-video/references/taxonomy.md
+++ b/skills/rea-video/references/taxonomy.md
@@ -8,7 +8,7 @@
| ai_video | AI 生成视频 | 无传感器噪声的照片纹理、24→30 重复帧或插帧周期、平滑漂浮的运镜;VLM 看到手指、文字、物体形变或纹理闪烁 | capsule-cinema 首尾帧生成 |
| avatar | 数字人口播 | 固定机位正脸,只有嘴和头在动,音频驱动 | TTS/克隆 + 数字人 |
| cg_3d | 3D 渲染 | 平涂/干净材质但背景不是逐像素冻结,几何稳定、无形变 | Blender/C4D,或 AI 首尾帧近似 |
-| code_render | 代码/模板渲染 | 平坦块 >20%、用色 <70、横竖直边多;背景逐像素冻结、只有局部元素在动 | Remotion/HTML 重建 |
+| code_render | 代码/模板渲染 | 平坦块 >20%、用色 <70、横竖直边多;背景逐像素冻结、只有局部元素在动;没有材质纹理(平滑彩色渐变、大块饱和纯色、暗底辉光、分形/着色器色场);暗底上亮部全是细碎亮点/细线(粒子、点云、线框) | Remotion/HTML 重建;报告按画面类型给做法(粒子 → Three.js,色场 → GLSL,渐变 → CSS blur,图表 → SVG/D3) |
| screen_capture | 录屏/截图 | 大面积浅色界面、密集小字号文字、低饱和、整页滚动 | 真实界面录制(用户提供) |
| still_motion | 静态图推拉 | 刚体变换内点率 >95%、残差 <0.3px、补偿后无残余、无 24fps 帧率痕迹 | 一张图 + 本地 ffmpeg 按测得参数重建 |
| static_hold | 静帧 | 85% 以上帧逐像素重复 | 一张图 |
@@ -43,6 +43,8 @@
| 传感器噪声和时域噪声明显、手持抖动 | 实拍 |
| 平台转码文件:整片原生 30fps、实拍类镜头没有重复帧 | 倾向手机实拍(转码后噪声证据失效,以帧率为准) |
| 几乎无彩色、只用个位数颜色的平面画面 | 界面/文档动效(代码渲染),不是 3D |
+| 近黑底上的亮部几乎全是细碎亮点或细线、没有连续的明暗表面 | 粒子/点云/线框图形(代码渲染),不是 3D 实体、AI 或夜景实拍 |
+| 整幅画面几乎没有细纹理:平滑彩色渐变、大块饱和纯色、暗底辉光,或彩虹色场 | 代码绘制的渐变/矢量/着色器画面,不是 3D 渲染(3D 有布料、木纹等材质纹理);整帧都在动也一样 |
| 整片铺满音乐、人声在唱(持续音高多) | 音乐 MV → 歌大概率 AI 生成 |
| 旁白说话 + 垫底 BGM | 普通配乐 → 倾向现成曲库(待确认,AI 工作流常用 Suno) |
| 切镜处底噪跳变 | 声音跟着片段走:AI 视频原生出声或实拍同期声 |
@@ -65,11 +67,27 @@
- AI:同一物体在镜头内轻微变形,纹理闪烁,噪声更像照片(用色 >100)。
- 抖音上大量"3D 卡通"账号是 AI 生成的,但没有标识时只能写倾向。
+**暗底粒子图形 vs 3D 渲染 vs AI 视频 / 夜景实拍**
+- 粒子图形(代码渲染):器官、人体、地球、分子等由成千上万个发光点或细线拼成,没有连续的明暗表面;常配左上角章节牌、引线标注、跳动的数字。Three.js、AE Plexus / Trapcode 都能做,复刻按代码工程走。
+- 3D 渲染:有连续的表面明暗、材质和阴影。
+- 夜景实拍 / AI:亮部是有明暗过渡的物体和光斑,带颗粒或形变。
+- 复核时 `description` 要写清每镜粒子拼成什么形状、颜色、怎么动(粒子流向、变形、推镜/环绕)、标注和数字在哪;报告「代码合成」一节的逐镜表就用它。只写"粒子背景"复刻出来就是一团光斑。
+
+**代码绘制的渐变 / 辉光 / 色场 vs 3D 渲染**
+- 代码画面:整幅几乎没有细纹理,只有平滑渐变、纯色块、辉光和文字;常见渐变光斑背景、毛玻璃卡片、霓虹字、CSS 3D 翻转卡片、分形缩放和 plasma 着色器。即使整帧都在动(背景漂移、辉光呼吸),也是代码渲染。
+- 3D 渲染:物体有材质纹理(布料、木纹、金属、塑料颗粒)、有投影和物体间的光影关系。
+- 加了胶片颗粒的扁平海报:颗粒去掉后是纯色块,算代码渲染;颗粒很重(工具测到噪声 σ≥3)时工具可能看不穿,要看图判断。
+- 平滑渐变缓慢变色容易被误认成交叉溶解;工具按"变化速度是否平稳"排除,复核时如果一个连续的背景动效仍被切成多镜,按一镜处理。
+
**代码渲染 vs 录屏截图**
- 代码渲染:字号大、品牌配色、矢量清晰、元素有动画入场。
- 截图:浅色底、密集小字、界面控件(按钮、图标、导航),往往被整体缩放或滚动。
- 模板里嵌入了截图:底层算代码渲染,截图在"真实素材"里单独列出。
+**代码渲染镜头怎么写 description**
+- 报告「代码合成」一节的「逐镜动效时间轴」是工具测的:每个元素的位置、出现时间、方向、快慢曲线、色值,依次出现的元素合并成一条"间隔 X 秒";关键帧条是 `shots/shot_XXX_strip.jpg`,元素截图和编号拼图是 `shots/shot_XXX_elements.jpg`。
+- 对照它们在 `description` 里按编号写清每个元素是什么("1–12:圆角图标卡片,依次弹入"),不用重复测量值。
+
**静态图推拉 vs AI 视频的缓慢推镜**
- 推拉:剪辑软件按时间线帧率渲染,每帧都不同,没有 24→30 的重复规律。
- AI 推镜:带 24fps 源的重复帧规律,主体常有细微动作(呼吸、眨眼)。
diff --git a/tests/test_code_render.py b/tests/test_code_render.py
new file mode 100644
index 0000000..c90d6d7
--- /dev/null
+++ b/tests/test_code_render.py
@@ -0,0 +1,118 @@
+"""Code-drawn pictures beyond particles: gradients, glass cards, neon, procedural colour fields, grain over flat design.
+They have no material texture, which separates them from footage, AI video and 3D renders."""
+import cv2
+import numpy as np
+
+from rea_video.classify import deterministic
+from rea_video.features import spatial_features
+from rea_video.plan import code_style
+from rea_video.shots import _steady_morph
+
+
+def _feat(img):
+ f = spatial_features(img)
+ # whole-frame motion, no frozen background: the case where a rendered picture is easily taken for a 3D render
+ f.update({"dup_ratio": 0.0, "moving_pair_ratio": 1.0, "camera": "static", "temporal_noise": 0.5, "zero_pixel_ratio": 0.6})
+ return f
+
+
+def _gradient_blobs(shift=0.0):
+ yy, xx = np.mgrid[0:480, 0:270].astype(np.float32)
+ img = np.zeros((480, 270, 3), np.float32) + (255, 230, 240)
+ for colour, x, y in (((107, 107, 255), 60, 120), ((255, 150, 77), 200, 250), ((61, 217, 255), 90, 400)):
+ a = 0.85 * np.exp(-((xx - x - shift) ** 2 + (yy - y) ** 2) / (2 * 70.0 ** 2))[..., None]
+ img = img * (1 - a) + np.array(colour, np.float32) * a
+ return img.astype(np.uint8)
+
+
+def _neon():
+ img = np.full((480, 270, 3), (12, 2, 8), np.uint8)
+ glow = np.zeros_like(img)
+ cv2.putText(glow, "AI", (50, 270), cv2.FONT_HERSHEY_DUPLEX, 4, (214, 43, 255), 8, cv2.LINE_AA)
+ img = cv2.add(img, cv2.GaussianBlur(glow, (0, 0), 8))
+ return cv2.add(img, glow)
+
+
+def _grain_poster(seed=0):
+ img = np.full((480, 270, 3), (196, 220, 232), np.uint8)
+ cv2.circle(img, (135, 170), 100, (61, 85, 200), -1, cv2.LINE_AA)
+ img[330:] = (71, 48, 45)
+ noise = np.random.default_rng(seed).normal(0, 2, img.shape[:2])[..., None] # rendered posters measure sigma ~0.6; sigma >= 3 is not seen through
+ return np.clip(img + noise, 0, 255).astype(np.uint8)
+
+
+def _textured_photo(seed=0):
+ rng = np.random.default_rng(seed)
+ yy, xx = np.mgrid[0:480, 0:270]
+ shade = 90 + 80 * np.cos(xx / 60.0) * np.sin(yy / 90.0) # lit surfaces
+ fabric = cv2.GaussianBlur(rng.normal(0, 14, (480, 270)), (0, 0), 0.8) # material texture
+ base = np.clip(shade + fabric, 0, 255)
+ return np.dstack([base * 0.8, base * 0.9, base]).astype(np.uint8)
+
+
+def test_vector_fills_are_code_render():
+ for name, img in (("gradient", _gradient_blobs()), ("neon", _neon()), ("grain", _grain_poster())):
+ f = _feat(img)
+ probs, ev, facts = deterministic(f)
+ assert facts["vector_fill"] > 0.5, (name, f["tex_fine"], facts)
+ assert max(probs, key=probs.get) == "code_render", (name, probs)
+ assert any("纹理" in e for e in ev)
+
+
+def _ink_lines(seed=0):
+ rng = np.random.default_rng(seed)
+ img = np.full((480, 270, 3), (240, 247, 250), np.uint8)
+ for _ in range(150): # generative flow strokes on paper
+ x, y = rng.uniform(0, 270), rng.uniform(0, 480)
+ pts = []
+ for _ in range(30):
+ a = np.sin(x / 40.0) * 2 + np.cos(y / 55.0)
+ x, y = x + 2 * np.cos(a), y + 2 * np.sin(a)
+ pts.append((int(x), int(y)))
+ cv2.polylines(img, [np.array(pts, np.int32)], False, (90, 60, 40), 1, cv2.LINE_AA)
+ return img
+
+
+def test_line_art_on_light_ground_is_code_render():
+ f = _feat(_ink_lines())
+ probs, ev, facts = deterministic(f)
+ assert facts["fine_light"] > 0.5, {k: f[k] for k in ("light_ratio", "ink_ratio", "ink_smooth", "ink_peaks")}
+ assert max(probs, key=probs.get) == "code_render"
+
+
+def test_grainy_dark_ground_is_not_neon():
+ img = _neon().astype(np.float32)
+ img += np.random.default_rng(1).normal(0, 4, img.shape[:2])[..., None] * (img.mean(2, keepdims=True) < 40)
+ f = _feat(np.clip(img, 0, 255).astype(np.uint8))
+ assert f["dark_flat"] < 0.5
+ _, _, facts = deterministic(f)
+ assert facts["vector_fill"] < 0.3
+
+
+def test_textured_picture_is_not_vector():
+ f = _feat(_textured_photo())
+ assert f["tex_fine"] > 0.15
+ probs, _, facts = deterministic(f)
+ assert facts["vector_fill"] < 0.2
+ assert probs["code_render"] < 0.3
+
+
+def test_code_style_names_the_build():
+ def shot(facts, texts=()):
+ return {"deterministic": {"facts": facts}, "text": {"tracks": [{"kind": "title", "texts": list(texts)}], "text_coverage": 0.01,
+ "items": [{"text": t, "conf": 0.95} for t in texts]}}
+ assert code_style(shot({"fine_dark": 0.9})) == "particles"
+ assert code_style(shot({"fine_light": 0.9})) == "lineart"
+ assert code_style(shot({"vector_kind": "neon"})) == "neon"
+ assert code_style(shot({"vector_kind": "gradient"})) == "gradient"
+ assert code_style(shot({}, ["82", "610", "470", "抖音"])) == "data"
+ assert code_style(shot({})) == "shapes"
+ assert code_style(shot({}, ["000", "0", "00"])) == "shapes" # zeros read off shapes are OCR noise
+
+
+def test_colour_morph_is_not_a_dissolve():
+ morph = [cv2.cvtColor(_gradient_blobs(3.0 * t), cv2.COLOR_BGR2GRAY) for t in range(40)]
+ assert _steady_morph(morph, 20, 4)
+ a, b = morph[0], cv2.cvtColor(_neon(), cv2.COLOR_BGR2GRAY)
+ fade = [a] * 16 + [(a * (1 - w) + b * w).astype(np.uint8) for w in np.linspace(0, 1, 9)] + [b] * 16
+ assert not _steady_morph(fade, 20, 4)
diff --git a/tests/test_memory.py b/tests/test_memory.py
index 6ff7c60..20d993d 100644
--- a/tests/test_memory.py
+++ b/tests/test_memory.py
@@ -113,6 +113,8 @@ def test_single_image_reader_cannot_flip_ai_vs_live_axis():
assert _vlm_gate(rec(p(ai_video=0.9, avatar=0.03)), vlm_avatar, {}) is None # tools sure + not in top-2
assert _vlm_gate(rec(p(ai_video=0.74, cg_3d=0.1)), p(cg_3d=0.95), {}) is None # tools sure on AI axis
assert _vlm_gate(rec(p(cg_3d=0.56, code_render=0.36)), p(code_render=0.8), {}) # 3D vs code: VLM helps
+ assert _vlm_gate(rec(p(cg_3d=0.51, ai_video=0.18, code_render=0.12)), p(code_render=0.8), {}) # rendered subtype: reader picks
+ assert _vlm_gate(rec(p(ai_video=0.3, live_action=0.25, cg_3d=0.2)), p(avatar=0.9), {}) is None # not for generated subtypes
assert _vlm_gate(rec(p(ai_video=0.46, live_action=0.38), {"transcode_degraded": True, "pulldown": "24→30"}),
p(live_action=0.85), {"native30": False}) is None # 24fps transcode never -> live
assert _vlm_gate(rec(p(ai_video=0.46, live_action=0.38), {"transcode_degraded": True, "native_cadence": True}),
diff --git a/tests/test_motion.py b/tests/test_motion.py
new file mode 100644
index 0000000..cbd4f9a
--- /dev/null
+++ b/tests/test_motion.py
@@ -0,0 +1,142 @@
+"""Element motion timeline of code-rendered shots, flash cuts, counters and dark text on light grounds."""
+import cv2
+import numpy as np
+
+from rea_video.media import video_info
+from rea_video.motion import event_line, motion_events, palette
+from rea_video.packaging import _NUMERIC, _norm, text_style
+from rea_video.shots import build_track, detect_shots
+
+
+def _close(a, b, tol=6):
+ return all(abs(int(a[i:i + 2], 16) - int(b[i:i + 2], 16)) <= tol for i in (1, 3, 5))
+
+
+def _write(path, frames, fps=30):
+ h, w = frames[0].shape[:2]
+ vw = cv2.VideoWriter(str(path), cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
+ for f in frames:
+ vw.write(f)
+ vw.release()
+ return str(path)
+
+
+def _staggered(n=90):
+ """Three cards pop in 0.5 s apart from 0.2 s, then a bar grows left to right from 1.5 s to 2.5 s."""
+ frames = []
+ for i in range(n):
+ f = np.full((640, 360, 3), (240, 240, 240), np.uint8)
+ for k, colour in enumerate([(60, 60, 230), (60, 200, 60), (230, 120, 40)]):
+ if i >= 6 + 15 * k:
+ cv2.rectangle(f, (40 + 110 * k, 120), (120 + 110 * k, 220), colour, -1)
+ if i >= 45:
+ w = int(280 * min(1.0, (i - 45) / 30))
+ cv2.rectangle(f, (40, 400), (40 + max(1, w), 430), (30, 30, 30), -1)
+ frames.append(f)
+ return frames
+
+
+def test_events_time_place_colour(tmp_path):
+ p = _write(tmp_path / "s.mp4", _staggered())
+ r = motion_events(p, video_info(p), 0.0, 3.0)
+ ev = r["events"]
+ cards = [e for e in ev if e["box"][1] < 0.4]
+ assert len(cards) == 3
+ assert [round(e["t0"], 1) for e in cards] == [0.2, 0.7, 1.2]
+ assert _close(cards[0]["colour"], "#e63c3c")
+ bar = [e for e in ev if e["box"][1] > 0.55]
+ assert len(bar) == 1 and bar[0]["sweep"] == "right" and abs(bar[0]["t0"] - 1.5) < 0.15
+ assert "向右展开" in event_line(bar[0])
+ assert r["sequences"] and r["sequences"][0]["n"] == 3 and abs(r["sequences"][0]["interval"] - 0.5) < 0.1
+
+
+def test_palette_background():
+ f = np.full((200, 100, 3), (231, 241, 246), np.uint8)
+ f[80:120, 20:80] = (54, 89, 254)
+ pal = palette(f)
+ assert _close(pal["background"], "#f6f1e7")
+ assert any(_close(c["hex"], "#fe5936") for c in pal["colours"])
+
+
+def test_flash_cut_and_light_shot_not_a_fade(tmp_path):
+ frames = [np.full((360, 200, 3), 20, np.uint8) for _ in range(30)]
+ for i in range(30): # cut into a shot that opens on a grey flash decaying over 0.2 s
+ f = np.full((360, 200, 3), 20, np.uint8)
+ cv2.circle(f, (100, 180), 40, (200, 200, 60), -1)
+ f = cv2.addWeighted(f, 1.0, np.full_like(f, 160), max(0.0, 1 - i / 6), 0)
+ frames.append(f)
+ for i in range(30): # hard cut to a white page with a title: a shot, not a fade through white
+ f = np.full((360, 200, 3), 255, np.uint8)
+ cv2.putText(f, "TITLE", (40, 60), cv2.FONT_HERSHEY_SIMPLEX, 1, (40, 40, 40), 2)
+ frames.append(f)
+ p = _write(tmp_path / "c.mp4", frames)
+ shots = detect_shots(build_track(p, video_info(p)))
+ assert [round(s.start, 1) for s in shots] == [0.0, 1.0, 2.0]
+ assert shots[1].transition_in == "flash" and 0.1 <= shots[1].flash_s <= 0.4
+ assert shots[2].transition_in == "cut"
+
+
+def test_numbers_are_counters_and_dark_text_is_not_outlined():
+ assert all(_NUMERIC.fullmatch(_norm(t)) for t in ["820", "4.7%", "12,840", "3.6万", "+4"])
+ assert not _NUMERIC.fullmatch(_norm("抖音"))
+ f = np.full((120, 400, 3), 255, np.uint8)
+ cv2.putText(f, "ABOOD", (20, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, (40, 40, 40), 5)
+ st = text_style(f, (20, 30, 300, 90), rendered=True)
+ assert st and st["fill_name"] in ("黑", "灰") and "stroke" not in st
+
+
+def test_outlined_subtitle_on_bright_footage_keeps_its_outline():
+ """The rendered-picture corrections stay off for footage: white text with a dark outline over a bright scene."""
+ f = np.full((120, 400, 3), 235, np.uint8)
+ cv2.putText(f, "ABOOD", (20, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, (20, 20, 20), 12)
+ cv2.putText(f, "ABOOD", (20, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 4)
+ st = text_style(f, (14, 26, 310, 94))
+ assert st and st["fill_name"] == "白" # not swapped to dark text, as the rendered rules would on a light ground
+
+
+def test_element_crops_numbered_like_the_timeline(tmp_path):
+ from pathlib import Path
+
+ from rea_video.motion import element_crops
+
+ p = _write(tmp_path / "s.mp4", _staggered())
+ info = video_info(p)
+ m = motion_events(p, info, 0.0, 3.0)
+ sheet = element_crops(p, info, 0.0, 3.0, m, tmp_path / "shots", "shot_001", 360)
+ assert sheet == "shots/shot_001_elements.jpg" and (tmp_path / sheet).is_file()
+ for k, e in enumerate(m["events"], 1):
+ assert e["crop"] == f"shots/shot_001_el_{k:02d}.jpg"
+ im = cv2.imread(str(tmp_path / e["crop"]))
+ assert im is not None and im.shape[0] > 10
+ assert "[截图](shots/shot_001_el_01.jpg)" in event_line(m["events"][0])
+ assert Path(tmp_path / "shots").is_dir()
+
+
+def test_text_style_is_repeatable():
+ """Colour clustering must not depend on OpenCV's RNG state (other calls, other threads)."""
+ from concurrent.futures import ThreadPoolExecutor
+
+ rng = np.random.default_rng(5)
+ f = np.clip(rng.normal(120, 40, (120, 400, 3)), 0, 255).astype(np.uint8)
+ cv2.putText(f, "ABOOD", (20, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, (30, 30, 200), 9)
+ cv2.putText(f, "ABOOD", (20, 80), cv2.FONT_HERSHEY_SIMPLEX, 2, (250, 250, 250), 3)
+
+ def run(_):
+ cv2.randu(np.zeros((50, 50), np.uint8), 0, 255) # disturb the RNG
+ return text_style(f, (14, 26, 310, 94)), palette(f)
+
+ first = run(0)
+ with ThreadPoolExecutor(4) as pool:
+ assert all(r == first for r in pool.map(run, range(12)))
+
+
+def test_style_vote_ties_do_not_depend_on_hash_seed():
+ """Python randomises str hashing per process; a tie broken by set order would give different colours per run."""
+ import subprocess
+ import sys
+
+ code = ("from rea_video.packaging import merge_style;"
+ "print(merge_style([{'fill_name':'棕','fill':'#a0522d'},{'fill_name':'橙','fill':'#ff8800'}]))")
+ outs = {subprocess.run([sys.executable, "-c", code], capture_output=True, text=True,
+ env={**__import__("os").environ, "PYTHONHASHSEED": str(seed)}).stdout for seed in range(6)}
+ assert len(outs) == 1 and "棕" in outs.pop()
diff --git a/tests/test_particles.py b/tests/test_particles.py
new file mode 100644
index 0000000..1f065c1
--- /dev/null
+++ b/tests/test_particles.py
@@ -0,0 +1,65 @@
+"""Particle / point-cloud graphics on black: rendered by code, not 3D, AI or night footage."""
+import cv2
+import numpy as np
+
+from rea_video.classify import deterministic
+from rea_video.features import spatial_features
+from rea_video.plan import code_scene
+from rea_video.production import lit_colours, report_md
+
+
+def _particles(seed=0):
+ rng = np.random.default_rng(seed)
+ img = np.zeros((270, 480, 3), np.uint8)
+ for _ in range(1500): # glowing dots sampled on an ellipse, like a particle organ
+ a = rng.uniform(0, 2 * np.pi)
+ r = rng.uniform(0, 1) ** 0.5
+ x, y = int(240 + 90 * r * np.cos(a)), int(135 + 60 * r * np.sin(a))
+ cv2.circle(img, (x, y), 1, (230, 220, 60), -1)
+ return img
+
+
+def _shaded():
+ img = np.zeros((270, 480, 3), np.uint8)
+ yy, xx = np.mgrid[0:270, 0:480]
+ d = np.sqrt((xx - 240) ** 2 + (yy - 135) ** 2)
+ ball = np.clip(255 * (1 - d / 90), 0, 255).astype(np.uint8) # a smoothly shaded sphere on black
+ img[..., 1] = ball
+ img[..., 2] = ball
+ return img
+
+
+def _feat(img):
+ f = spatial_features(img)
+ f.update({"dup_ratio": 0.0, "moving_pair_ratio": 1.0, "camera": "smooth_move", "temporal_noise": 0.5, "zero_pixel_ratio": 0.6})
+ return f
+
+
+def test_fine_dark_separates_particles_from_shaded_surfaces():
+ fp, fs = _feat(_particles()), _feat(_shaded())
+ assert fp["lit_smooth"] < 0.3 and fp["lit_peaks"] > 4
+ assert fs["lit_smooth"] > 0.5
+ probs, ev, facts = deterministic(fp)
+ assert facts["fine_dark"] > 0.5
+ assert max(probs, key=probs.get) == "code_render"
+ assert any("粒子" in e for e in ev)
+ _, _, facts_s = deterministic(fs)
+ assert facts_s["fine_dark"] < 0.1
+
+
+def test_code_scene_and_report_table(tmp_path):
+ cv2.imwrite(str(tmp_path / "a.jpg"), _particles())
+ assert lit_colours([tmp_path / "a.jpg"])[0] in ("青", "白")
+ shot = {"deterministic": {"facts": {"fine_dark": 0.9}}, "features": {"camera": "smooth_move", "zoom_per_s": 0.05},
+ "review": {"description": "青色粒子拼成的胶囊"},
+ "text": {"tracks": [{"kind": "subtitle", "texts": ["字幕"]}, {"kind": "title", "texts": ["第一站·胃", "ECOPSWOE"]}],
+ "items": [{"text": "第一站·胃", "conf": 0.99}, {"text": "ECOPSWOE", "conf": 0.55}, {"text": "字幕", "conf": 0.99}]}}
+ sc = code_scene(shot)
+ assert sc["particles"] and sc["picture"] == "青色粒子拼成的胶囊"
+ assert sc["on_screen_text"] == ["第一站·胃"] # subtitles and low-confidence OCR are left out
+ assert "推近" in sc["move"]
+ plan = {"summary": "x", "units": [], "shoot": [], "local": [], "avatar": [],
+ "code": [{"id": "段1", "shots": [1], "start": 0, "end": 3, "screen_capture": [],
+ "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