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

只有画面干净一条证据判 AI 时标「待确认」,识别 YouTube 下载的转码;没有关于音乐本身的证据时来源只给倾向;整段持续单音不算音乐;复刻提示词前补上测得的景别、机位、主体位置和运镜;镜头检测识别划像类转场

june1f5b361abbce
diff --git a/rea_video/audio.py b/rea_video/audio.py
index a53aecf..5ad5096 100644
--- a/rea_video/audio.py
+++ b/rea_video/audio.py
@@ -225,6 +225,22 @@ def sfx_type(S: np.ndarray, freqs: np.ndarray, frame_db: np.ndarray, c: int, hop
return kind, {"dur": round(d, 3), "centroid_hz": int(centroid), "hf_ratio": round(hf_ratio, 3)}
+def steady_tone(Sh: np.ndarray, freqs: np.ndarray, frames: np.ndarray) -> float | None:
+ """Frequency of a single held pitch, or None. Every frame's harmonic energy sits in one narrow spectral
+ peak (a sine wave: one bin and its window leakage) and the peak stays on the same bin; a chord, a melody
+ or a pad spreads over several peaks or moves."""
+ M = Sh[frames] ** 2
+ if len(M) < int(1.0 / T_HOP):
+ return None
+ pk = M.argmax(axis=1)
+ near = np.abs(np.arange(M.shape[1])[None, :] - pk[:, None]) <= 2
+ conc = (M * near).sum(axis=1) / (M.sum(axis=1) + 1e-12)
+ mode = int(np.bincount(pk).argmax())
+ if float((np.abs(pk - mode) <= 1).mean()) > 0.9 and float(np.median(conc)) > 0.8:
+ return float(freqs[mode])
+ return None
+
+
def perc_share(S: np.ndarray, Sp: np.ndarray) -> np.ndarray:
return (Sp ** 2).sum(axis=1) / ((S ** 2).sum(axis=1) + 1e-12)
@@ -309,6 +325,15 @@ def analyze_audio(path: str, cut_times: list[float] | None = None, visual_marks:
beats = np.array([])
if music["present"] and float(np.percentile(share, 90)) < PERC_FLOOR:
music["no_beat"] = True # a held tone / drone: nothing percussive to count a tempo from
+ mframes = np.zeros(len(Sh), bool)
+ for a_, b_ in music_segs:
+ mframes[int(a_ / T_HOP):int(b_ / T_HOP)] = True
+ hz = steady_tone(Sh, freqs, mframes & ~silent)
+ if hz:
+ # one pitch held the whole time (test tone, beep, mains hum): it passes the "loud and harmonic" bed test,
+ # but there is no melody, no harmony and no beat, so it is not music
+ music = {"present": False, "ratio": music["ratio"], "segments": music_segs[:40],
+ "steady_tone": {"hz": round(hz, 1), "segments": music_segs[:40]}}
if music["present"]:
env = perc - perc.mean()
ac = np.correlate(env, env, "full")[len(env) - 1:]
diff --git a/rea_video/classify.py b/rea_video/classify.py
index 9c9bfd4..d20f40c 100644
--- a/rea_video/classify.py
+++ b/rea_video/classify.py
@@ -148,7 +148,7 @@ def lowlight_photo(f: dict, faces: float = 0.0) -> bool:
and f.get("dark_flat", 1.0) < r["dark_flat_max"] and f.get("flat_lit", 1.0) < r["flat_lit_max"] and faces >= r["faces"])
-PLATFORM_TRANSCODES = ("WeChat transcode", "WeChat Channels", "Douyin/TikTok", "Douyin", "Kuaishou", "Xiaohongshu")
+PLATFORM_TRANSCODES = ("WeChat transcode", "WeChat Channels", "Douyin/TikTok", "Douyin", "Kuaishou", "Xiaohongshu", "YouTube")
def video_context(shots: list[dict], provenance: dict | None, fps: float | None) -> dict:
@@ -173,7 +173,7 @@ def video_context(shots: list[dict], provenance: dict | None, fps: float | None)
film_dur = sum(float(r.get("duration", 0)) for r in shots
if (r.get("features") or {}).get("palette95", 0) >= 100 and film_hints(r.get("features") or {}, fps, None))
total = sum(float(r.get("duration", 0)) for r in shots) or 1.0
- return {"transcoded": bool(plat), "platform": plat, "native30": native30,
+ return {"transcoded": bool(plat), "platform": plat, "native30": native30, "fps": fps,
"native30_share": round(native_dur / photo_dur, 3) if photo_dur else None,
"film_hint_share": round(film_dur / total, 3)}
diff --git a/rea_video/pipeline.py b/rea_video/pipeline.py
index 6d90f1c..275a39d 100644
--- a/rea_video/pipeline.py
+++ b/rea_video/pipeline.py
@@ -328,6 +328,16 @@ def _ai_or_live_doubt(label: str, facts: dict, prov: dict, vctx: dict, seen_live
"AI or live action, to confirm: only a sharpness rhythm and no duplicate frames (re-encodes leave it too), the image reader calls it live action, and there is no AIGC label")
return T("AI 还是实拍待确认:只有清晰度节奏、没有重复帧(重新压缩也会留下)、没有 AIGC 标识,需要看图确认",
"AI or live action, to confirm: only a sharpness rhythm, no duplicate frames (re-encodes leave it too) and no AIGC label, needs an image reader")
+ fps = vctx.get("fps") or 0
+ if (label == "ai_video" and not seen and not facts.get("pulldown") and not facts.get("transcode_degraded")
+ and not (prov.get("hints") or {}).get("generator") and not 23.5 <= fps <= 25.5):
+ # a 30/60 fps file with no frame-rate marks and no label (a native 24/25 fps file is itself a generator's rate):
+ # the AI call rests on the picture being clean (little sensor noise). Platform
+ # re-encodes (X, YouTube, Bilibili ... downloads, and any file whose platform tags were stripped) wipe the noise too
+ return T("AI 还是实拍待确认:没有 24fps 源的重复帧、没有 AIGC 或生成工具标识,判 AI 主要靠画面干净、传感器噪声少;"
+ "从平台下载、重新压缩过的实拍也会这样,需要看图确认",
+ "AI or live action, to confirm: no 24fps-source duplicate frames and no AIGC / generator label, so the AI call rests on a clean "
+ "picture with little sensor noise; live footage downloaded from a platform or re-compressed looks the same, needs an image reader")
if not facts.get("transcode_degraded"):
return None
if label == "live_action" and not facts.get("pulldown"):
diff --git a/rea_video/plan.py b/rea_video/plan.py
index 1e3f929..0b361e0 100644
--- a/rea_video/plan.py
+++ b/rea_video/plan.py
@@ -80,6 +80,66 @@ def shot_prompts(shot: dict) -> dict:
return out
+def _where(cx: float | None, cy: float | None) -> tuple[str, str] | None:
+ """Where the measured subject sits in the frame, (zh, en)."""
+ if cx is None or cy is None:
+ return None
+ h = ("左侧", "left") if cx < 0.38 else ("右侧", "right") if cx > 0.62 else ("中间", "centre")
+ v = ("上部", "upper") if cy < 0.38 else ("下部", "lower") if cy > 0.62 else ("", "")
+ if h[1] == "centre" and not v[1]:
+ return "主体在画面正中", "subject centred in frame"
+ return f"主体在画面{v[0]}{h[0]}".replace("上部中间", "上部正中").replace("下部中间", "下部正中"), \
+ f"subject in the {(v[1] + ' ') if v[1] else ''}{h[1]} of the frame".replace("upper centre", "upper middle").replace("lower centre", "lower middle")
+
+
+def framing_words(shot: dict) -> tuple[str, str]:
+ """Shot size, camera angle, subject position and camera move as a prompt prefix, (report language, English).
+ The readers' free-text prompts tend to keep the style words and drop these, which flattens the camera in a remake."""
+ from .aspects.base import seen
+ from .i18n import lang
+
+ asp = shot.get("aspects") or {}
+ fr = (asp.get("framing") or {}).get("result") or {}
+ fm = (asp.get("framing") or {}).get("measured") or {}
+ cm = (asp.get("camera") or {}).get("measured") or {}
+ v = shot.get("review") or shot.get("vlm") or {}
+ size = fr.get("shot_size") or v.get("shot_size")
+ angle = fr.get("camera_angle")
+ comp = seen(shot, "framing", "composition")
+ comp = comp.get("agent") or comp.get("vlm")
+ where = _where(fm.get("center_x"), fm.get("center_y")) if fm.get("subject") in ("face", "focus") else None
+ move = cm.get("move") or (v.get("camera_move") if v.get("camera_move") not in (None, "", "固定", "static") else None)
+ loc = [x for x in (size, angle, comp or (where and (where[1] if lang() == "en" else where[0])),
+ move and T("镜头{m}", "camera {m}", m=move)) if x]
+ en_size = {"大特写": "extreme close-up", "特写": "close-up", "近景": "medium close-up", "中景": "medium shot",
+ "全景": "full shot", "远景": "wide shot"}
+ en_move = {"推": "push-in", "拉": "pull-out", "摇/移": "pan / track", "摇": "pan", "移": "track", "跟": "follow",
+ "环绕": "orbit", "手持": "handheld"}
+ en_angle = {"平视": "eye level", "略俯拍": "slightly high angle", "俯拍": "high angle", "顶拍": "top-down overhead",
+ "略仰拍": "slightly low angle", "仰拍": "low angle"}
+
+ def head(x): # "顶拍(正上方俯拍桌面)" -> "顶拍"
+ return re.split(r"[((,,]", x)[0].strip() if x else x
+
+ en = [en_size.get(head(size), size if size and size.isascii() else None),
+ en_angle.get(head(angle), angle if angle and angle.isascii() else None),
+ comp if comp and comp.isascii() else (where[1] if where and not comp else None),
+ move and ("camera " + en_move.get(move, move if move.isascii() else "moves"))]
+ return T(",", ", ").join(loc), ", ".join(x for x in en if x)
+
+
+def _with_framing(prompt: str, words: str) -> str:
+ """Prefix the framing words unless the prompt already states each of them."""
+ if not prompt or not words:
+ return prompt
+ sep = "," if "," in words else ", "
+ missing = [w for w in words.split(sep) if w and w not in prompt]
+ if not missing:
+ return prompt
+ end = "。" if not words.isascii() else ". "
+ return sep.join(missing) + end + prompt
+
+
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")
@@ -242,10 +302,14 @@ class Planner:
gen_dur = int(min(hi, max(lo, round(dur + 0.49))))
rep = shot_prompts(shot)
prompt = rep.get("video_prompt") or (shot.get("vlm") or shot.get("review") or {}).get("description") or ""
+ # the measured / seen framing goes in front, so a remake keeps the camera height, angle and subject position
+ fw, fw_en = framing_words(shot)
+ still = T(",", ", ").join(w for w in fw.split(T(",", ", ")) if not w.startswith(T("镜头", "camera ")))
plan["capsule"] = {
"engine": engine, "generation_type": gen_type, "duration": gen_dur,
"trim_to": round(dur, 3), "aspect_ratio": video.get("aspect_ratio", "9:16"),
- "prompt": prompt, "prompt_en": rep.get("video_prompt_en", ""), "image_prompt": rep.get("image_prompt", ""),
+ "prompt": _with_framing(prompt, fw), "prompt_en": _with_framing(rep.get("video_prompt_en", ""), fw_en),
+ "image_prompt": _with_framing(rep.get("image_prompt", ""), still), "framing": fw,
"needs_split": dur > hi,
}
if not prompt:
diff --git a/rea_video/probe.py b/rea_video/probe.py
index e49d483..1f90cbc 100644
--- a/rea_video/probe.py
+++ b/rea_video/probe.py
@@ -44,6 +44,7 @@ SIGNATURES: list[tuple[str, str, str]] = [
(r"\bvid:v[0-9a-z]{8,}", "platform", "Douyin/TikTok"),
(r"kuaishou|快手", "platform", "Kuaishou"),
(r"xiaohongshu|小红书", "platform", "Xiaohongshu"),
+ (r"ISO Media file produced by Google", "platform", "YouTube"),
]
CAMERA_KEYS = ("com.apple.quicktime.make", "com.apple.quicktime.model", "make", "model", "com.android.manufacturer",
diff --git a/rea_video/report.py b/rea_video/report.py
index 5e26441..7ba785b 100644
--- a/rea_video/report.py
+++ b/rea_video/report.py
@@ -148,8 +148,8 @@ def _span(a, z) -> str:
# ------------------------------------------------------------------ sections --------------------------------------
-TRANS_ZH = LangDict({"cut": "硬切", "jump": "跳剪", "flash": "闪亮切", "fade": "淡入淡出", "dissolve": "叠化", "mg_transition": "版式切换"},
- en={"cut": "cut", "jump": "jump cut", "flash": "flash cut", "fade": "fade", "dissolve": "dissolve", "mg_transition": "layout change"})
+TRANS_ZH = LangDict({"cut": "硬切", "jump": "跳剪", "flash": "闪亮切", "fade": "淡入淡出", "dissolve": "叠化", "wipe": "划像/转场特效", "mg_transition": "版式切换"},
+ en={"cut": "cut", "jump": "jump cut", "flash": "flash cut", "fade": "fade", "dissolve": "dissolve", "wipe": "wipe / transition effect", "mg_transition": "layout change"})
def _head_md(b: dict) -> list[str]:
@@ -326,6 +326,10 @@ def _audio_md(b: dict) -> list[str]:
L += _source_lines("music")
if tracks.get("music"):
L.append(T("- 复刻:{h}", "- Remake: {h}", h=tracks["music"]["how"]))
+ elif mu.get("steady_tone"):
+ L.append(T("- 不是音乐:整段是一个持续单音(约 {hz:.0f} Hz),没有旋律、和声和节拍,像测试音、提示音或电流声",
+ "- Not music: one held pitch (about {hz:.0f} Hz) with no melody, harmony or beat, like a test tone, a beep or mains hum",
+ hz=mu["steady_tone"]["hz"]))
else:
L.append(T("- 未检测到持续的音乐床", "- No sustained music bed detected"))
diff --git a/rea_video/review.py b/rea_video/review.py
index 79f1340..b48da19 100644
--- a/rea_video/review.py
+++ b/rea_video/review.py
@@ -46,8 +46,8 @@ kind 取 {"|".join(ASSET_KINDS)},is_real_material 为 true/false)。
某个镜头其实是多刀合并的(暗底图形卡和暗底口播交替时,切点分数低容易被合成一个长镜头)就加 split_suggestion:
{{"cuts": [切点秒数], "labels": [各段类别,比 cuts 多一个], "note": "看到的交替结构"}},报告会在该镜头标注拆分建议;不是合并段就不要填。
实拍或定格镜头被 AI 二次加工过时填 ai_edits:[{{"kind": "{"|".join(EDIT_KINDS)}", "evidence": "看到的破绽"}}](换脸、对口型、风格化、换装、换背景、加删物体、美颜);没有就留空。
-AI 生成 / 3D / 实拍镜头再填 replication:image_prompt(复刻首帧的中文图像提示词:主体、构图、光线、风格,具体可执行)、
-video_prompt(复刻该镜头的中文视频提示词:写清动作过程和结束状态、运镜;只写想要的内容,不写否定句)、video_prompt_en(英文版)。
+AI 生成 / 3D / 实拍镜头再填 replication:image_prompt(复刻首帧的中文图像提示词:景别、机位高度和俯仰角、主体在画面里的位置和朝向、主体、光线、风格,具体可执行)、
+video_prompt(复刻该镜头的中文视频提示词:先写景别、机位角度、主体在画面里的位置,再写动作过程和结束状态、运镜;只写想要的内容,不写否定句)、video_prompt_en(英文版)。
这些提示词会被合并进「生成单元」的多镜头提示词,所以每镜只写这一镜的内容,统一的风格和场景描述写在 description 里即可。
实拍/写实镜头再填 aspects(怎么拍、怎么打光;纯图形/界面画面不填),像素测不出的部分靠你看:
diff --git a/rea_video/shots.py b/rea_video/shots.py
index d83fa99..29abd1b 100644
--- a/rea_video/shots.py
+++ b/rea_video/shots.py
@@ -1,4 +1,4 @@
-"""Shot boundary detection: hard cuts, fades through black/white, dissolves.
+"""Shot boundary detection: hard cuts, fades through black/white, dissolves, wipes.
Works on tiny thumbnails of every frame (cheap) and combines a colour-histogram
distance with a pixel difference so lighting flicker and fast motion do not fire
@@ -203,6 +203,12 @@ def detect_shots(track: FrameTrack, min_shot_s: float = 0.35, cut_threshold: flo
if all(abs(i - bnd) > 2 * k for bnd in boundaries):
boundaries[i] = ("dissolve", round(1 - resid, 3))
+ # 4) wipes and other editor transitions (wipe / radial / clock / pixelate ...): the new shot replaces the old one
+ # region by region, so every in-between frame is old picture in some places and new picture in the others
+ if dissolve and n > 2 * fps:
+ for i, strength in _wipes(track, score, cut_threshold, boundaries):
+ boundaries[i] = ("wipe", strength)
+
beat_marks = [b for b, _ in _mg_beats(track, boundaries, fps)]
# assemble shots, enforce minimum length. Boundaries closer than that are one transition (a flash, a
@@ -216,7 +222,7 @@ def detect_shots(track: FrameTrack, min_shot_s: float = 0.35, cut_threshold: flo
prev = kept[-1] if kept else 0
gap = b - prev
if gap >= min_len or (gap >= short_len and _clean_cut(boundaries, b) and (not kept or _clean_cut(boundaries, prev))
- and float(track.changed[prev + 1:b].max()) < 0.3): # a held insert, not transition frames
+ and float(track.changed[prev + 1:b].max(initial=0.0)) < 0.3): # a held insert, not transition frames
kept.append(b)
elif kept and boundaries[b][1] > boundaries[prev][1] and b - (kept[-2] if len(kept) > 1 else 0) >= short_len:
kept[-1] = b
@@ -355,6 +361,93 @@ def _mg_beats(track: FrameTrack, boundaries: dict[int, tuple[str, float]], fps:
return out
+WIPE_GRID = (6, 8) # blocks across, down (thumbs are portrait or landscape; the grid only needs to be coarse)
+WIPE_SECONDS = (0.3, 0.6, 1.0, 1.6)
+
+
+WIPE_MIN_TEXTURE = 4.0
+
+
+def _texture(g: np.ndarray) -> float:
+ """Mean absolute Laplacian of a gray thumb: photographic frames have detail everywhere, gradients do not."""
+ return float(np.abs(cv2.Laplacian(g.astype(np.float32), cv2.CV_32F)).mean())
+
+
+def _block_diff(a: np.ndarray, b: np.ndarray, shift: int = 2) -> np.ndarray:
+ """Per-block mean |a - b|, taking the best of a few small shifts so that ordinary motion in the
+ shot does not count as a different picture."""
+ a = a.astype(np.float32)
+ b = b.astype(np.float32)
+ h, w = a.shape
+ best = None
+ for dx, dy in ((0, 0), (shift, 0), (-shift, 0), (0, shift), (0, -shift)):
+ bs = np.roll(b, (dy, dx), axis=(0, 1))
+ d = cv2.resize(np.abs(a - bs)[shift:h - shift, shift:w - shift], WIPE_GRID, interpolation=cv2.INTER_AREA)
+ best = d if best is None else np.minimum(best, d)
+ return best
+
+
+def _wipes(track: FrameTrack, score: np.ndarray, cut_threshold: float,
+ boundaries: dict[int, tuple[str, float]]) -> list[tuple[int, float]]:
+ """Gradual transitions where the new shot takes over the frame region by region. For a window [s, e]
+ whose two ends are different pictures, each block of the frames inside matches one end or the other
+ or sits between them (camera / subject motion inside one shot gives blocks that match neither), and the share of blocks
+ already showing the new picture grows from ~0 to ~1 across the window."""
+ n, fps, thumbs = track.n, track.fps, track.thumbs
+ tiny = [cv2.resize(t, WIPE_GRID, interpolation=cv2.INTER_AREA).astype(np.float32) for t in thumbs]
+ taken = sorted(boundaries)
+ found: list[tuple[int, float]] = []
+ for sec in WIPE_SECONDS:
+ L = max(6, int(round(sec * fps)))
+ for s in range(0, n - L, max(1, L // 6)):
+ e = s + L
+ if any(s - L // 2 <= b <= e + L // 2 for b in taken) or any(abs(s + L // 2 - i) <= L for i, _ in found):
+ continue
+ if float(np.abs(tiny[s] - tiny[e]).mean()) < 14 or float(score[s + 1:e + 1].max()) >= cut_threshold:
+ continue # the two ends look alike at a glance, or a hard cut sits inside (handled above)
+ dab = _block_diff(thumbs[s], thumbs[e])
+ sig = dab > max(12.0, 0.5 * float(np.median(dab)))
+ if sig.mean() < 0.75:
+ continue # most of the frame must change: someone walking into the foreground changes only part of it
+ if min(_texture(thumbs[s]), _texture(thumbs[e])) < WIPE_MIN_TEXTURE:
+ continue # smooth gradients / flat cards: an animated sweep looks the same, leave those to the MG rules
+ us, fits, new = [], [], []
+ for q in (0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875):
+ m = thumbs[s + int(round(q * L))]
+ da, db = _block_diff(m, thumbs[s])[sig], _block_diff(m, thumbs[e])[sig]
+ # a block is the old picture, the new one, or (on the moving edge / in a blend) part of each
+ fits.append(float(((np.minimum(da, db) < 0.4 * dab[sig]) | (da + db < 1.2 * dab[sig])).mean()))
+ new.append(db < da)
+ us.append(float(new[-1].mean()))
+ # every in-between frame is old-or-new block by block, the new part grows, and it is not the same
+ # mixture throughout (a static split screen / picture-in-picture is that, not a transition)
+ if min(fits[1:-1]) < 0.75 or not (us[1] < us[3] < us[5]) or us[1] > 0.45 or us[5] < 0.55 or us[5] - us[1] < 0.35:
+ continue
+ # a block turns into the new picture once and stays (a moving head flips blocks back and forth)
+ flips = np.diff(np.array(new, np.int8), axis=0)
+ if float((flips < 0).any(axis=0).mean()) > 0.15:
+ continue
+ # the two ends differ much more than the picture changes in as long a stretch just before / after
+ # (one shot with large motion changes as much outside the window as across it)
+ prev_b = max([b for b in taken if b <= s] + [0])
+ next_b = min([b for b in taken if b >= e] + [n - 1])
+ around = [float(_block_diff(thumbs[a], thumbs[b])[sig].mean()) * L / (b - a)
+ for a, b in ((max(prev_b, s - L), s), (e, min(next_b, e + L))) if b - a >= max(3, L // 3)]
+ if around and float(dab[sig].mean()) < 2.0 * max(around):
+ continue
+ if _motion_explains(thumbs[s].astype(np.float32), thumbs[e].astype(np.float32)):
+ continue
+ # boundary: the frame where most of the picture has become the new shot
+ mid = s + L // 2
+ for j in range(s + 1, e):
+ db_, da_ = _block_diff(thumbs[j], thumbs[e])[sig], _block_diff(thumbs[j], thumbs[s])[sig]
+ if float((db_ < da_).mean()) >= 0.5:
+ mid = j
+ break
+ found.append((mid, round(min(fits), 3)))
+ return found
+
+
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)
diff --git a/rea_video/sound_source.py b/rea_video/sound_source.py
index 1ed656a..4b6e38c 100644
--- a/rea_video/sound_source.py
+++ b/rea_video/sound_source.py
@@ -71,6 +71,12 @@ def per_clip_audio(path: str, cuts: list[float], duration: float) -> dict:
"resets_at_cuts": r > 1.6}
+def mt_title(meta: dict) -> str:
+ """Title of the platform music tag (Douyin / Xiaohongshu post metadata), or ''."""
+ mt = meta.get("music") if isinstance(meta.get("music"), dict) else {}
+ return str(mt.get("title") or "")
+
+
def music_ending(audio: dict, duration: float) -> str:
m = audio.get("music") or {}
ec = audio.get("energy_curve") or []
@@ -139,6 +145,10 @@ def classify_sound_sources(b: dict, meta: dict | None = None) -> dict:
ev.append(T("人声是说话/旁白而不是唱歌(持续音高占比 {r:.2f}):属于「旁白 + BGM」的普通视频形式",
"The voice is speech / narration, not singing (sustained-pitch ratio {r:.2f}): a regular \"voice-over + music bed\" video",
r=voice.get('sustained_note_ratio', 0)))
+ # something about this very track: a sung music video, what the VLM heard, or the platform's music tag.
+ # The bed-under-a-video prior, the ending shape and a whole-file AIGC marker are not enough on their own
+ heard = bool(is_mv or ctx["music_mv_maybe"] or wm.get("lyrics_match_content") is True or wm.get("song_guess")
+ or wm.get("source_guess") in ("ai_generated", "popular_song", "stock_library") or mt_title(meta))
if wm.get("lyrics_match_content") is True:
p["ai_generated"] += 1.2
ev.append(T("歌词唱的正是这条视频的具体内容/角色/商品:为本片定制的歌,几乎只能是 AI 生成或专门创作",
@@ -149,11 +159,11 @@ def classify_sound_sources(b: dict, meta: dict | None = None) -> dict:
sg = wm.get("source_guess")
if sg in ("ai_generated", "popular_song", "stock_library"):
key = {"stock_library": "existing_library"}.get(sg, sg)
- p[key] += 0.5
+ p[key] += 0.8 # what was heard outweighs the format prior plus the ending shape
ev.append(T("VLM 听感判断:{s}", "VLM listening judgement: {s}",
s={'ai_generated': T('AI 生成', 'AI-generated'), 'popular_song': T('知名歌曲', 'well-known song'), 'stock_library': T('曲库配乐', 'stock library music')}[sg]))
mt = (meta.get("music") or {}) if isinstance(meta.get("music"), dict) else {}
- if mt.get("title"):
+ if mt_title(meta):
original = bool(mt.get("is_original")) or any(k in str(mt.get("title")) for k in ("原声", "original sound"))
if original:
p["ai_generated"] += 0.3 if (is_mv or ctx["music_mv_maybe"]) else 0.0
@@ -185,8 +195,12 @@ def classify_sound_sources(b: dict, meta: dict | None = None) -> dict:
probs = _norm(p)
lab = max(probs, key=probs.get)
conf = probs[lab]
+ decided = conf >= 0.45 and heard
+ if not heard:
+ ev.append(T("除了视频形式的先验和片尾形状这类弱证据,没有关于这段音乐本身的证据(没听出来源、没有平台音乐信息):来源待确认,AI 生成的配乐在这里和曲库配乐分不开",
+ "Nothing about this track beyond the format prior and weak cues like the ending (no source heard, no platform music tag): source to confirm; an AI-generated bed cannot be told from a library bed here"))
out["music"] = {
- "source": lab if conf >= 0.45 else "unknown", "source_zh": MUSIC_ZH[lab if conf >= 0.45 else "unknown"],
+ "source": lab if decided else "unknown", "source_zh": MUSIC_ZH[lab if decided else "unknown"],
"leaning": lab, "probs": probs, "ending": ending, "evidence": ev,
"how_to_confirm": [
T("在抖音/小红书原视频页面看音乐标签:显示歌名 → 现成曲目;显示「@作者创作的原声」→ 作者自己上传(MV 类多为 AI 歌)",
diff --git a/tests/test_audio.py b/tests/test_audio.py
index 7d5c5a1..303c147 100644
--- a/tests/test_audio.py
+++ b/tests/test_audio.py
@@ -72,10 +72,19 @@ def test_held_tone_has_no_beat_or_sfx(tmp_path):
"""A pure 440 Hz tone is a music-like bed with nothing percussive: no tempo, no sound effects."""
t = np.arange(int(12 * SR)) / SR
r = analyze_audio(str(_write_av(tmp_path, 0.3 * np.sin(2 * np.pi * 440 * t), "tone")))
- assert r["music"].get("tempo_bpm") is None and r["music"].get("no_beat")
+ assert r["music"].get("tempo_bpm") is None and not r["music"]["present"]
+ assert abs(r["music"]["steady_tone"]["hz"] - 440) < 25
assert r["sfx"]["count"] == 0
+def test_held_chord_is_still_music(tmp_path):
+ """A sustained pad (several notes, no drums) is music, not a test tone."""
+ t = np.arange(int(12 * SR)) / SR
+ y = 0.08 * sum(np.sin(2 * np.pi * f * t) for f in (261.63, 329.63, 392.0, 523.25))
+ r = analyze_audio(str(_write_av(tmp_path, y, "pad")))
+ assert r["music"]["present"] and not r["music"].get("steady_tone")
+
+
def test_beat_survives_percussive_floor(music_mp4):
r = analyze_audio(str(music_mp4))
assert not r["music"].get("no_beat") and r["music"].get("tempo_bpm")
diff --git a/tests/test_production.py b/tests/test_production.py
index 5c1cc3d..b7eaa8f 100644
--- a/tests/test_production.py
+++ b/tests/test_production.py
@@ -105,3 +105,18 @@ def test_inserts_do_not_split_a_generation(tmp_path):
assert u["shots"] == [2, 4, 6] and u["duration"] == 6.0 and len(u["ranges"]) == 3
assert "镜头2(2.0–3.5s)" in u["prompt"] # generation-relative times
assert "1 个代码工程(3 段)" in plan["summary"]
+
+
+def test_framing_goes_into_capsule_prompt():
+ from rea_video.plan import _with_framing, framing_words
+
+ shot = {"aspects": {"framing": {"result": {"shot_size": "近景", "camera_angle": "略俯拍"},
+ "measured": {"subject": "face", "center_x": 0.3, "center_y": 0.7}},
+ "camera": {"measured": {"move": "推"}}},
+ "vlm": {"replication": {"video_prompt": "女生在厨房切菜"}}}
+ zh, en = framing_words(shot)
+ assert zh == "近景,略俯拍,主体在画面下部左侧,镜头推"
+ assert en == "medium close-up, slightly high angle, subject in the lower left of the frame, camera push-in"
+ assert _with_framing("女生在厨房切菜", zh) == zh + "。女生在厨房切菜"
+ assert _with_framing("近景,略俯拍,主体在画面下部左侧,镜头推,切菜", zh).startswith("近景,略俯拍,主体") # nothing added twice
+ assert _with_framing("", zh) == ""
diff --git a/tests/test_shots.py b/tests/test_shots.py
index 8526bc1..a9e945c 100644
--- a/tests/test_shots.py
+++ b/tests/test_shots.py
@@ -48,3 +48,35 @@ def test_generated_clip_is_retimed_to_the_shot():
assert abs(fit_speed(5.0, 2.5) - 2.0) < 1e-9
assert abs(fit_speed(2.0, 4.0) - 0.8) < 1e-9 # too short: slowed a little, the rest held
assert fit_speed(0.0, 2.0) == 1.0
+
+
+def _drift(img: np.ndarray, t: int) -> np.ndarray:
+ return np.roll(img, t // 3, axis=1) # slow camera drift
+
+
+def test_wipe_transition_is_a_boundary(tmp_path):
+ a = _photo_like(W, H, 21)
+ b = np.clip(_photo_like(W, H, 22).astype(np.int16) + 50, 0, 255).astype(np.uint8) # another shot, another tone
+ frames = [_drift(a, t) for t in range(60)]
+ for k in range(1, 13): # 0.4 s wipe from the left
+ f = _drift(a, 60 + k).copy()
+ x = int(W * k / 12)
+ f[:, :x] = _drift(b, k)[:, :x]
+ frames.append(f)
+ frames += [_drift(b, t) for t in range(13, 73)]
+ p = str(_write(frames, tmp_path / "wipe.mp4"))
+ shots = detect_shots(build_track(p, video_info(p)))
+ assert len(shots) == 2 and shots[1].transition_in == "wipe" and 62 <= shots[1].start_frame <= 70
+
+
+def test_pan_across_one_picture_is_not_a_wipe(tmp_path):
+ a = _photo_like(W * 3, H, 23)
+ frames = [a[:, 6 * t:6 * t + W] for t in range(110)] # one long pan: the view keeps changing, no new shot
+ p = str(_write(frames, tmp_path / "pan.mp4"))
+ assert len(detect_shots(build_track(p, video_info(p)))) == 1
+
+
+def test_low_frame_rate_cuts_one_frame_apart(tmp_path):
+ a, b, c = (_photo_like(W, H, s) for s in (31, 32, 33))
+ p = str(_write([a] * 20 + [b] + [c] * 20, tmp_path / "lowfps.mp4", fps=10))
+ assert detect_shots(build_track(p, video_info(p))) # 10 fps: a one-frame shot between two cuts does not crash
diff --git a/tests/test_sound_source.py b/tests/test_sound_source.py
index f152561..dd42ef9 100644
--- a/tests/test_sound_source.py
+++ b/tests/test_sound_source.py
@@ -54,3 +54,13 @@ def test_sung_vocals_without_vlm_lean_ai_but_tts_narration_does_not():
b["audio"]["voice"].update({"style": "speech", "sung": False, "sustained_note_ratio": 0.15})
r = classify_sound_sources(b)
assert not r["format_context"]["music_mv_maybe"] and r["music"]["leaning"] == "existing_library"
+
+
+def test_prior_alone_is_only_a_leaning():
+ # no VLM, no platform tag: an instrumental bed under narration leans library but is not called library
+ r = classify_sound_sources(_b(ending_curve=[0.0] * 40))
+ assert r["music"]["leaning"] == "existing_library" and r["music"]["source"] == "unknown"
+ assert "待确认" in r["summary_zh"] or "to confirm" in r["summary_zh"]
+ w = {"music": {"present": True, "has_vocals": False, "source_guess": "ai_generated"}, "narration": {"type": "tts"}}
+ r = classify_sound_sources(_b(whole=w))
+ assert r["music"]["leaning"] == "ai_generated" # heard as AI: beats the library prior and the hard-cut ending
diff --git a/tests/test_transcode.py b/tests/test_transcode.py
index 63afad8..fd6f901 100644
--- a/tests/test_transcode.py
+++ b/tests/test_transcode.py
@@ -123,3 +123,14 @@ def test_transcoded_native30_shot_counts_as_phone_footage():
probs, _, facts = deterministic(f, provenance=PROV_DOUYIN, fps=30.0, ctx=ctx)
assert facts["transcode_degraded"] and facts["native_cadence"]
assert probs["live_action"] > probs["ai_video"]
+
+
+def test_clean_picture_alone_is_not_enough_for_ai_without_an_image_reader():
+ from rea_video.pipeline import _ai_or_live_doubt
+
+ clean = {"pulldown": None, "transcode_degraded": False}
+ # 30 fps download whose platform tags are gone: only "little noise" says AI
+ assert _ai_or_live_doubt("ai_video", clean, {}, {"fps": 30.0}, seen=False)
+ assert _ai_or_live_doubt("ai_video", clean, {}, {"fps": 30.0}, seen=True) is None # an image reader looked
+ assert _ai_or_live_doubt("ai_video", clean, {}, {"fps": 24.0}, seen=False) is None # native 24 fps: generator rate
+ assert _ai_or_live_doubt("ai_video", clean, {"hints": {"generator": ["Kling"]}}, {"fps": 30.0}, seen=False) is None