Reverse-engineer any video, shot by shot: filmed, AI-generated or coded, and how to remake it. Breakdowns in the open VIDEO.md format. 逆向一切视频,逐个镜头看是拍的、AI 生成的还是代码做的,再告诉你怎么复刻;拆解结果按 VIDEO.md 格式输出。
Python agent-skillsai-videoaigc-detectionclaude-codecodexffmpegprompt-engineeringremotionreverse-engineeringshort-videoshot-detectionsubtitlesvideo-analysisvideo-breakdownvideo-editingvideo-generationvideomdvlm
同位置只换编号的文字(SHOT 01 → SHOT 02)按镜头分成多条标注,不再并成一条横跨全片,也不算字幕;持续音、长音铺底报「无明显节拍」,不给 BPM,瞬态处没有打击能量的不算音效,音轨末尾截断声不算音效;没有人声时不标「说到关键词时变色」,标题、标注也不标
junee7b8793056d6
diff --git a/rea_video/audio.py b/rea_video/audio.pyindex c63f34d..a53aecf 100644--- a/rea_video/audio.py+++ b/rea_video/audio.py@@ -18,6 +18,9 @@ import numpy as npfrom .media import extract_audioSR = 22050+# share of a frame's energy in the percussive part. A sustained tone / drone sits near 1e-5; the quietest real hit+# or drum in the eval set is ~5e-3. Below this there is no beat to count and no transient to call a sound effect+PERC_FLOOR = 1e-3N_FFT = 1024HOP = 256T_HOP = HOP / SR@@ -222,8 +225,17 @@ def sfx_type(S: np.ndarray, freqs: np.ndarray, frame_db: np.ndarray, c: int, hopreturn kind, {"dur": round(d, 3), "centroid_hz": int(centroid), "hf_ratio": round(hf_ratio, 3)}+def perc_share(S: np.ndarray, Sp: np.ndarray) -> np.ndarray:+ return (Sp ** 2).sum(axis=1) / ((S ** 2).sum(axis=1) + 1e-12)+++def has_transient(share: np.ndarray, c: int) -> bool:+ return bool(share[max(0, c - 3):c + 4].max() >= PERC_FLOOR)++def onset_envelope(path: str):- """(percussive onset curve, frame dB, magnitude STFT, freqs, seconds per frame) of a file's soundtrack."""+ """(percussive onset curve, frame dB, magnitude STFT, freqs, seconds per frame, percussive share) of a file's+ soundtrack."""x = extract_audio(path, SR)if x is None or len(x) < SR * 0.3:return None@@ -232,7 +244,7 @@ def onset_envelope(path: str):_, Sp = hpss(S)frame_db = 10 * np.log10((S ** 2).mean(axis=1) + 1e-12)perc = np.maximum(0, np.diff(np.log1p(Sp.sum(axis=1)), prepend=0))- return perc, frame_db, S, freqs, T_HOP+ return perc, frame_db, S, freqs, T_HOP, perc_share(S, Sp)def analyze_audio(path: str, cut_times: list[float] | None = None, visual_marks: list[float] | None = None) -> dict:@@ -255,6 +267,7 @@ def analyze_audio(path: str, cut_times: list[float] | None = None, visual_marks:local_max = np.array([sb_db[max(0, i - w1):i + w1].max() for i in range(len(sb_db))])dip = sb_db < local_max - 12 # gaps between syllables / phrasesharm_ratio = (Sh ** 2).sum(axis=1) / ((S ** 2).sum(axis=1) + 1e-12)+ share = perc_share(S, Sp)win = int(round(1.0 / T_HOP))step = int(round(0.5 / T_HOP))speech_w, music_w = [], []@@ -294,13 +307,15 @@ def analyze_audio(path: str, cut_times: list[float] | None = None, visual_marks:# ---------------- music: tempo, beats, key, sections ------------------------------------music: dict = {"present": music_ratio > 0.25, "ratio": round(music_ratio, 3), "segments": music_segs[:40]}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 fromif music["present"]:env = perc - perc.mean()ac = np.correlate(env, env, "full")[len(env) - 1:]ac /= ac[0] + 1e-9lo, hi = int(60 / 190 / T_HOP), int(60 / 60 / T_HOP)lag = lo + int(np.argmax(ac[lo:hi])) if hi < len(ac) else 0- if lag:+ if lag and not music.get("no_beat"):tempo = 60 / (lag * T_HOP)if tempo < 75: # prefer the common 75-180 BPM octavetempo *= 2@@ -370,6 +385,8 @@ def analyze_audio(path: str, cut_times: list[float] | None = None, visual_marks:continue # under a music bed only very prominent transients are trustedif len(beat_frames) and np.min(np.abs(beat_frames - c)) * T_HOP < 0.05:continue+ if not has_transient(share, c) or c * T_HOP > dur - 0.1:+ continue # the onset curve is relative: a held tone's codec noise wobbles it; the last 0.1 s is the track stoppingkind, info = sfx_type(S, freqs, frame_db, c, T_HOP)events.append({"t": round(c * T_HOP, 3), "type": kind, **info, "strength": round(strength, 1),"source": "deterministic", "confidence": "low"})@@ -449,7 +466,8 @@ def merge_audio_with_vlm(audio: dict, whole: dict | None) -> dict:src = m.get("source_guess") or "unknown"plan.append({"track": "music", "rule": "A03-music","what": semi().join(x for x in [m.get("style") or m.get("genre") or "", m.get("mood") or "",- f"{music.get('tempo_bpm') or m.get('bpm_estimate') or '?'} BPM",+ (T("无明显节拍", "no clear beat") if music.get("no_beat") and not m.get("bpm_estimate")+ else f"{music.get('tempo_bpm') or m.get('bpm_estimate') or '?'} BPM"),(f"{music['key']['tonic']} {music['key']['mode']}" if music.get("key") else "")] if x),"how": (T("疑似知名歌曲,需要授权或换成风格相近的授权曲/生成曲", "Possibly a well-known song: needs a licence, or swap in a licensed / generated track in a similar style") if src == "popular_song" elseT("capsule-cinema UniversalMusicGenerationTool(Suno)或曲库:按 BPM/调性/情绪选曲,在段落变化点对齐镜头",diff --git a/rea_video/cli.py b/rea_video/cli.pyindex da0a16f..849970b 100644--- a/rea_video/cli.py+++ b/rea_video/cli.py@@ -321,7 +321,7 @@ def cmd_summary(args) -> int:if a.get("has_audio"):mu = a.get("music", {})lines += ["", f"{T('人声', 'Voice')}: {a.get('voice', {}).get('present')} ({a.get('voice', {}).get('ratio')}) | {T('音乐', 'Music')}: {mu.get('present')} "- f"{mu.get('tempo_bpm')}BPM {(mu.get('key') or {}).get('tonic', '')}{(mu.get('key') or {}).get('mode', '')} | "+ f"{(T('无明显节拍', 'no beat') if mu.get('no_beat') else str(mu.get('tempo_bpm')) + 'BPM')} {(mu.get('key') or {}).get('tonic', '')}{(mu.get('key') or {}).get('mode', '')} | "f"{T('音效', 'SFX')}: {len((b.get('audio_plan') or {}).get('sfx_merged', []))} | {T('卡点', 'beat-synced')}: {a.get('beat_synced_edit')}"]if (b.get("sound_sources") or {}).get("summary_zh"):lines.append(f"{T('声音来源', 'Sound sources')}: " + b["sound_sources"]["summary_zh"])diff --git a/rea_video/integrations/capsule_cinema.py b/rea_video/integrations/capsule_cinema.pyindex 06bb453..cf7a3b6 100644--- a/rea_video/integrations/capsule_cinema.py+++ b/rea_video/integrations/capsule_cinema.py@@ -145,7 +145,7 @@ def export_capsule_analysis(b: dict, out_path: Path) -> Path:if (whole.get("music") or {}).get("style"):audio_rules.append(f"BGM:{whole['music']['style']}")elif a.get("music_likely"):- audio_rules.append(f"有背景音乐,约 {a.get('tempo_bpm')} BPM")+ audio_rules.append(f"有背景音乐,约 {a.get('tempo_bpm')} BPM" if a.get("tempo_bpm") else "有背景音乐(无明显节拍)")if a.get("beat_synced_edit"):audio_rules.append("切镜卡在音乐节拍上")mu = a.get("music") or {}diff --git a/rea_video/packaging.py b/rea_video/packaging.pyindex 475f96c..0c4fd89 100644--- a/rea_video/packaging.py+++ b/rea_video/packaging.py@@ -381,6 +381,46 @@ def _blocks(items: list[dict]) -> list[dict]:return out+def _numbers(s: str) -> tuple[str, tuple[str, ...]]:+ n = _norm(s)+ return re.sub(r"\d+", "#", n), tuple(re.findall(r"\d+", n))+++def _split_numbered(c: dict) -> list[dict]:+ """Same words, different number (SHOT 01 → SHOT 02, 第 1 步 → 第 2 步) read for two samples or more in a row:+ one label per shot, not one cue. A number misread in a single frame stays part of its run."""+ runs: list[list] = []+ for o in c["obs"]:+ skel, nums = _numbers(o["text"])+ key = (skel, nums) if nums else None+ if runs and (key is None or runs[-1][0] == key):+ runs[-1][1].append(o)+ else:+ runs.append([key, [o]])+ stable = [i for i, (key, obs) in enumerate(runs) if key is not None and len(obs) >= 2]+ if len(stable) < 2: # a number ticking every frame is a counter, one cue+ return [c]+ merged: list[list] = []+ for i, (key, obs) in enumerate(runs): # one-sample readings join the stable run before (the first one: after)+ if i in stable and not (merged and merged[-1][0] == key):+ merged.append([key, list(obs)])+ elif merged:+ merged[-1][1] += obs+ else:+ runs[stable[0]][1][:0] = obs+ if len(merged) < 2 or len({k[0] for k, _ in merged if k}) != 1:+ return [c]+ out = []+ for _, obs in merged:+ votes: dict[str, int] = {}+ for o in obs:+ votes[o["text"]] = votes.get(o["text"], 0) + 1+ text = max(votes, key=votes.get)+ out.append({**c, "obs": obs, "first": obs[0]["t"], "last": obs[-1]["t"], "text": text,+ "conf": max(o["conf"] for o in obs if o["text"] == text), "reveal": False})+ return out++def build_cues(items: list[dict], step: float) -> list[dict]:"""Track text blocks over time: same place + same words = one cue; same place, new words = the next cue."""by_t: dict[float, list[dict]] = {}@@ -447,7 +487,7 @@ def build_cues(items: list[dict], step: float) -> list[dict]:prev["last"] = c["last"]continuekeep.append(c)- cues = keep+ cues = [p for c in keep for p in _split_numbered(c)]out = []for c in cues:obs = c["obs"]@@ -568,7 +608,10 @@ def classify_cues(cues: list[dict], duration: float) -> None:# readable lines (kinetic typography flashing words for a fraction of a second is not a subtitle track)# a lane of changing numbers is a counter / chart value drawn by the picture, not a subtitle trackcounter = 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+ # SHOT 01 → SHOT 02 → …, 第 1 步 → 第 2 步: the same words with a running number are a label, not lines read out+ numbered = changing >= 2 and len({_numbers(c["text"])[0] for c in lane}) == 1 and all(_numbers(c["text"])[1] 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 and not numbered)for c in lane:c["_counter"] = counterc["lane"] = lanes.index(lane)@@ -1140,12 +1183,12 @@ def align_sfx(sfx: list[dict], events: list[dict]) -> dict:def anchored_sfx(path: str | Path, events: list[dict], known: list[dict]) -> list[dict]:"""Extra SFX candidates: a sharp transient right on a text pop / sticker entrance (not cuts: music hitsland there too). Editors put a pop / ding on these moments far more often than chance."""- from .audio import onset_envelope, sfx_type+ from .audio import has_transient, onset_envelope, sfx_typeenv = onset_envelope(str(path))if env is None:return []- perc, frame_db, S, freqs, hop_t = env+ perc, frame_db, S, freqs, hop_t, share = envif not len(perc):return []peak_db = float(np.percentile(frame_db, 99))@@ -1159,6 +1202,8 @@ def anchored_sfx(path: str | Path, events: list[dict], known: list[dict]) -> lisif a < 1 or b >= len(perc):continuec = a + int(np.argmax(perc[a:b]))+ if not has_transient(share, c):+ continueloc = float(np.percentile(perc[max(0, c - w2):c + w2], 90)) + 1e-6strength = float(perc[c]) / locif strength < 1.6 or frame_db[c] < peak_db - 30:@@ -1305,8 +1350,10 @@ def layer_name(e: dict) -> str:# ----------------------------------------------------------------------------- top level-def analyze(path: str | Path, info: VideoInfo, cuts: list[float], out_dir: Path | None = None, ocr: bool = True) -> dict:- """Whole-video packaging pass: text cues (subtitles / 花字 / titles / labels) and stickers."""+def analyze(path: str | Path, info: VideoInfo, cuts: list[float], out_dir: Path | None = None, ocr: bool = True,+ speech: bool | None = None) -> dict:+ """Whole-video packaging pass: text cues (subtitles / 花字 / titles / labels) and stickers. speech=False (no voice+ in the audio) rules out keywords lighting up as they are said."""items, step = ocr_pass(path, info) if ocr else ([], 0.0)cues = build_cues(items, step) if items else []for k, c in enumerate(sorted(cues, key=lambda c: (c["t0"], c["bbox"][1])), 1):@@ -1327,10 +1374,13 @@ def analyze(path: str | Path, info: VideoInfo, cuts: list[float], out_dir: Pathc.pop("_last", None)c.pop("_first", None)c["style"] = merge_style(c.pop("style_obs"))- if c["style"].get("multicolor") and not c.pop("first_style_multicolor", False) and c["samples"] >= 2:+ if c["style"].get("multicolor") and not c.pop("first_style_multicolor", False) and c["samples"] >= 2 and speech is not False:c["style"]["highlight_timing"] = "spoken" # colour arrives later: keyword lights up when it is saidc.pop("first_style_multicolor", None)classify_cues(cues, info.duration)+ for c in cues: # a label / title changing colour is the picture behind it (colour bars, a cut), not a spoken keyword+ if c["kind"] not in ("subtitle", "huazi"):+ c["style"].pop("highlight_timing", None)# subtitles in one lane share a template: per-line fill / stroke readings that disagree with the lane are noise# (a keyword bouncing in its highlight colour, a dark frame); keyword highlight stays per linelanes: dict[int, list[dict]] = {}diff --git a/rea_video/pipeline.py b/rea_video/pipeline.pyindex 3fa7735..6d90f1c 100644--- a/rea_video/pipeline.py+++ b/rea_video/pipeline.py@@ -96,7 +96,8 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,from .packaging import analyze as analyze_packaging, anchored_sfx, visual_eventsLOG.info("packaging layer: subtitle timeline, 花字, stickers%s", "" if ocr else " (no OCR: stickers only)")- pack = analyze_packaging(video, info, [s.start for s in shots[1:]], out, ocr=ocr)+ pack = analyze_packaging(video, info, [s.start for s in shots[1:]], out, ocr=ocr,+ speech=bool((audio.get("voice") or {}).get("present")) if audio.get("has_audio") else False)if info.has_audio:ev = [e for e in visual_events(pack["text_cues"], pack["stickers"], []) if e["type"] != "subtitle_in"]pack["sfx_anchored"] = anchored_sfx(video, ev, (audio.get("sfx") or {}).get("events", []))@@ -746,7 +747,8 @@ def finalize(breakdown: dict, out: Path, engine: str | None = None) -> dict:a_parts.append(T("人声", "voice"))if audio.get("music", {}).get("present"):ms = srcs.get("music") or {}- a_parts.append(T("BGM {bpm}BPM({src}", "music {bpm}BPM ({src}", bpm=audio['music'].get('tempo_bpm', '?'), src=ms.get('source_zh', T('来源待确认', 'source to confirm')))+ a_parts.append(T("BGM {bpm}({src}", "music {bpm} ({src}", bpm=T("无明显节拍", "no clear beat") if audio['music'].get('no_beat') else f"{audio['music'].get('tempo_bpm', '?')}BPM",+ src=ms.get('source_zh', T('来源待确认', 'source to confirm')))+ (T(",倾向{m}", ", leaning {m}", m=MUSIC_ZH[ms['leaning']]) if ms.get("source") == "unknown" else "") + T(")", ")"))n_sfx = len(breakdown["audio_plan"].get("sfx_merged", []))if n_sfx:diff --git a/rea_video/report.py b/rea_video/report.pyindex fff0d12..5e26441 100644--- a/rea_video/report.py+++ b/rea_video/report.py@@ -303,6 +303,8 @@ def _audio_md(b: dict) -> list[str]:L.append(T("- 歌词:{l}", "- Lyrics: {l}", l=str(vm["lyrics_excerpt"])[:120])+ (T("(唱的就是画面内容)", " (the lyrics describe the video itself)") if vm.get("lyrics_match_content") else ""))tempo = []+ if mu.get("no_beat"):+ tempo.append(T("无明显节拍(持续音,没有打击成分)", "no clear beat (a held tone, nothing percussive)"))if mu.get("tempo_bpm"):tempo.append(T("{bpm} BPM(也可能是 {alt})", "{bpm} BPM (or {alt})", bpm=mu["tempo_bpm"], alt="/".join(str(t) for t in mu.get("tempo_alternatives", []))) if mu.get("tempo_alternatives")else f"{mu['tempo_bpm']} BPM")diff --git a/skills/rea-video/references/audio.md b/skills/rea-video/references/audio.mdindex 3957a50..5b2ab74 100644--- a/skills/rea-video/references/audio.md+++ b/skills/rea-video/references/audio.md@@ -8,10 +8,10 @@|---|---|---|| 有无人声 | 人声频段的音节调制(3–8Hz),加上句间停顿 | 高 || 有无 BGM | 人声间隙里仍有响亮、有音调的声音(谐波占比 >0.62);没有人声时看谐波持续性;或者有明显节拍周期 | 高 |-| BPM | 打击成分起音包络的自相关,同时给出半速/倍速候选 | 高(咸鸭蛋 110.0 vs 真值 110.15) |+| BPM | 打击成分起音包络的自相关,同时给出半速/倍速候选;持续音、长音铺底这类几乎没有打击成分的声音报「无明显节拍」,不给 BPM | 高(咸鸭蛋 110.0 vs 真值 110.15) || 调性 | 色度 + Krumhansl 调性轮廓 | 中高(两条真值都对:D major) || 段落变化 | 色度和响度的新颖度峰值 | 中 |-| 音效 | 人声段落之外非常突出的瞬态,且不在节拍上;有 BGM 时要求更突出 | **低**:在人声 + BGM 的混音里,信号层面实测精度只有约 0.2,轻音效基本测不出。音效清单以 VLM 为准 |+| 音效 | 人声段落之外非常突出的瞬态,且不在节拍上;有 BGM 时要求更突出;瞬态处要有真实的打击能量(持续音的压缩噪声不算),音轨最后 0.1 秒的截断声不算 | **低**:在人声 + BGM 的混音里,信号层面实测精度只有约 0.2,轻音效基本测不出。音效清单以 VLM 为准 || TTS 还是真人 | 交给 VLM | — || 男声 / 女声 | 基频中位数(<150Hz 偏男声,>200Hz 偏女声) | 中,只作参考 || 卡点剪辑 | 切点落在节拍上的比例 vs 随机概率 | 中高 |diff --git a/tests/test_audio.py b/tests/test_audio.pyindex ddb0757..7d5c5a1 100644--- a/tests/test_audio.py+++ b/tests/test_audio.py@@ -66,3 +66,16 @@ def test_isolated_sfx_in_silence(tmp_path):ts = [e["t"] for e in a["sfx"]["events"]]assert all(any(abs(t - t0) < 0.08 for t in ts) for t0 in (1.0, 2.5, 4.0)), tsassert not a["music"]["present"]+++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["sfx"]["count"] == 0+++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_packaging.py b/tests/test_packaging.pyindex fc0abc0..01064f9 100644--- a/tests/test_packaging.py+++ b/tests/test_packaging.py@@ -226,3 +226,30 @@ def test_pipeline_writes_packaging(tmp_path, media):assert not [s for s in pk["stickers"] if not s.get("in_picture")]md = (tmp_path / "edit" / "report.md").read_text(encoding="utf-8")assert "剪辑包装层" in md+++def test_numbered_labels_split_per_shot():+ """SHOT 01 … SHOT 03 at one place: three labels (not one cue spanning the video), and not a subtitle lane."""+ from rea_video.packaging import build_cues, classify_cues++ items = []+ for k in range(30):+ t = k * 0.5+ n = 1 + int(t // 5)+ text = f"SHOT 0{n}" if k != 4 else "SHOT 07" # one frame misread stays inside its run+ items.append({"t": t, "text": text, "conf": 0.95, "bbox": [0.4, 0.48, 0.2, 0.03], "angle": 0.0, "style": None})+ cues = build_cues(items, 0.5)+ assert [c["text"] for c in cues] == ["SHOT 01", "SHOT 02", "SHOT 03"]+ assert cues[1]["t0"] == 5.0+ for c in cues:+ c.update(style={}, t1=c["t1"])+ classify_cues(cues, 15.0)+ assert all(c["kind"] == "label" for c in cues)+++def test_counter_ticking_every_frame_stays_one_cue():+ from rea_video.packaging import build_cues++ items = [{"t": k * 0.5, "text": f"第{k}名", "conf": 0.9, "bbox": [0.4, 0.1, 0.2, 0.03], "angle": 0.0, "style": None}+ for k in range(10)]+ assert len(build_cues(items, 0.5)) == 1