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
Improve OCR install, subtitle and audio detection, and English output
june3da6a9dab02c
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.ymlindex 46a8ad8..4ab303f 100644--- a/.github/ISSUE_TEMPLATE/config.yml+++ b/.github/ISSUE_TEMPLATE/config.yml@@ -1,5 +1,5 @@blank_issues_enabled: truecontact_links:- - name: 交流讨论+ - name: 交流讨论 / Discussionurl: https://linux.do/- about: 使用体验、拆解案例和复刻思路,欢迎到 linux.do 聊。+ about: 使用体验、拆解案例和复刻思路,欢迎到 linux.do 聊。/ Experiences, breakdown cases and remake ideas — come chat on linux.do.diff --git a/.github/ISSUE_TEMPLATE/request_breakdown.yml b/.github/ISSUE_TEMPLATE/request_breakdown.ymlindex 0f17838..74bcf98 100644--- a/.github/ISSUE_TEMPLATE/request_breakdown.yml+++ b/.github/ISSUE_TEMPLATE/request_breakdown.yml@@ -1,5 +1,5 @@-name: 求拆解-description: 有条视频想知道是怎么做的?贴链接,我们拆完发成案例。+name: 求拆解 / Request a breakdown+description: 有条视频想知道是怎么做的?贴链接,我们拆完发成案例。/ Want to know how a video was made? Paste the link and we'll publish the breakdown as a case.title: "[求拆解] "labels: ["求拆解"]body:@@ -7,37 +7,39 @@ body:attributes:value: |拆完的结果会发到 [docs/cases.md](https://github.com/JuneYaooo/rea-video/blob/main/docs/cases.md),附逐镜头拼帧和报告。请只提交你有权分享的公开视频。++ The result goes to [docs/cases.md](https://github.com/JuneYaooo/rea-video/blob/main/docs/cases.md) with per-shot contact sheets and a report. Please only submit public videos you are allowed to share.- type: inputid: linkattributes:- label: 视频链接- description: 抖音、B 站、小红书、YouTube、TikTok 都行。没有链接就说明怎么找到它。+ label: 视频链接 / Video link+ description: 抖音、B 站、小红书、YouTube、TikTok 都行。没有链接就说明怎么找到它。/ Douyin, Bilibili, Xiaohongshu, YouTube, TikTok all work. No link? Tell us how to find it.placeholder: https://validations:required: true- type: dropdownid: wantattributes:- label: 最想知道什么+ label: 最想知道什么 / What do you most want to knowmultiple: trueoptions:- - 是实拍、AI 还是代码做的- - 实拍怎么拍(机位、布光、调色)- - AI 镜头的提示词和用哪个模型- - 字幕、花字、剪辑节奏- - 配乐和音效是怎么来的- - 整条怎么复刻、要花多少钱+ - 是实拍、AI 还是代码做的 / Live action, AI or code-rendered+ - 实拍怎么拍(机位、布光、调色)/ How the live footage was shot (camera, lighting, grading)+ - AI 镜头的提示词和用哪个模型 / Prompts and models for the AI shots+ - 字幕、花字、剪辑节奏 / Captions, text effects and editing rhythm+ - 配乐和音效是怎么来的 / Where the music and sound effects came from+ - 整条怎么复刻、要花多少钱 / How to remake it and what it costsvalidations:required: true- type: textareaid: guessattributes:- label: 你自己的判断- description: 可不填。你觉得它是怎么做的、哪里看不出来,写下来方便对照。+ label: 你自己的判断 / Your own take+ description: 可不填。你觉得它是怎么做的、哪里看不出来,写下来方便对照。/ Optional. How you think it was made and what you can't tell, so we can compare.- type: checkboxesid: publishattributes:- label: 发布+ label: 发布 / Publicationoptions:- - label: 同意把拆解结果作为公开案例发在仓库里+ - label: 同意把拆解结果作为公开案例发在仓库里 / I agree to publish the breakdown as a public case in this repositoryrequired: truediff --git a/docs/cases/qing_mv/report_en.md b/docs/cases/qing_mv/report_en.mdindex f66d945..0cc4f82 100644--- a/docs/cases/qing_mv/report_en.md+++ b/docs/cases/qing_mv/report_en.md@@ -9,7 +9,7 @@- Confidence (duration-weighted): 71%; method: deterministic forensics fused with a vision model (VLM)- VLM partly active (gemini-3.1-pro-preview, gemini-3.1-pro-preview-pc, gcp-gemini-3-pro-preview: results for 60/60 shots, whole-video analysis failed); the agent (claude) visually reviewed 9 of 86 shots, merged into the verdict-+## Production method share@@ -723,7 +723,7 @@ Gear:## Audio breakdown-+- Overall loudness −17.4 dBFS, peak −1.9 dBFS- **Voice**: present, 26% of duration, fundamental about 142.8 Hz (reads male)diff --git a/docs/cases/salted_egg/report_en.md b/docs/cases/salted_egg/report_en.mdindex 6740cf4..5265056 100644--- a/docs/cases/salted_egg/report_en.md+++ b/docs/cases/salted_egg/report_en.md@@ -9,7 +9,7 @@- Confidence (duration-weighted): 98%; method: deterministic forensics fused with a vision model (VLM)- VLM active (gemini-3.1-pro-preview, gemini-3.1-pro-preview-pc, gcp-gemini-3-pro-preview)-+## Production method share@@ -291,7 +291,7 @@ Shot 3 (5.8-9.3s): Static camera, three fluffy cartoon animal characters standin## Audio breakdown-+- Overall loudness −17.3 dBFS, peak −1.6 dBFS- **Voice**: present, 76% of duration, fundamental about 319.6 Hz (reads female)diff --git a/docs/cases/unboxing/report_en.md b/docs/cases/unboxing/report_en.mdindex 557dfc3..4d70fb6 100644--- a/docs/cases/unboxing/report_en.md+++ b/docs/cases/unboxing/report_en.md@@ -9,7 +9,7 @@- Confidence (duration-weighted): 82%; method: deterministic forensics fused with a vision model (VLM)- VLM active (gemini-3.1-pro-preview, gemini-3.1-pro-preview-pc, gcp-gemini-3-pro-preview @ daydream88.fun); the agent (claude) visually reviewed 29 of 29 shots, merged into the verdict-+## Production method share@@ -136,7 +136,7 @@ Gear:## Audio breakdown-+- Overall loudness -28.3 dBFS, peak -0.0 dBFS- **Voice**: present, 33% of duration, fundamental about 157.5 Hz (gender unclear)diff --git a/docs/cases/v10/report_en.md b/docs/cases/v10/report_en.mdindex 1698ecb..8e7efd2 100644--- a/docs/cases/v10/report_en.md+++ b/docs/cases/v10/report_en.md@@ -9,7 +9,7 @@- Confidence (duration-weighted): 96%; method: deterministic forensics fused with a vision model (VLM)- VLM active (gemini-3.1-pro-preview, gemini-3.1-pro-preview-pc, gcp-gemini-3-pro-preview)-+## Production method share@@ -48,7 +48,7 @@ One Remotion / HTML project rebuilt from the text tracks and layout (text and UI## Audio breakdown-+- Overall loudness −17.4 dBFS, peak −1.4 dBFS- **Voice**: none / very little, 5% of duration, fundamental about 247.8 Hz (reads female)diff --git a/pyproject.toml b/pyproject.tomlindex ec913d0..56afb64 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -18,9 +18,13 @@ dependencies = [][project.optional-dependencies]-# rapidocr 会顺带装 opencv-python(带 GUI 的那套),和上面的 headless 抢同一个 cv2 目录;-# scripts/install_skill.sh 装完会删掉它、重装 headless。手动安装见 setup.md。-ocr = ["rapidocr-onnxruntime>=1.3,<2"]+# Python ≤ 3.12 用 rapidocr-onnxruntime;它没有 3.13 及以上的版本,那里改用 rapidocr 3(同一个作者的新包)。+# rapidocr-onnxruntime 会顺带装 opencv-python(带 GUI 的那套),和上面的 headless 抢同一个 cv2 目录;+# scripts/install_skill.sh 装完会删掉它、重装 headless。手动安装见 setup.md。rapidocr 3 本身就用 headless。+ocr = [+ "rapidocr-onnxruntime>=1.3,<2; python_version < '3.13'",+ "rapidocr>=3.4,<4; python_version >= '3.13'",+]dev = ["pytest>=7", "jsonschema>=4"][project.scripts]diff --git a/rea_video/audio.py b/rea_video/audio.pyindex 5ad5096..d1e44d5 100644--- a/rea_video/audio.py+++ b/rea_video/audio.py@@ -526,7 +526,7 @@ def refine_with_stems(audio: dict, vocals_wav: str) -> dict:if st:rep = vocal_repetition(x, freqs)st["chorus_repeat_share"] = rep- if rep > 0.1 and st["style"] == "speech": # repeated melodic lines = a song (rap included), narration never repeats+ if rep > 0.1 and st["style"] == "speech": # repeated melodic lines = a song (rap included); narration does not repeatst["style"], st["sung"] = "rap_or_rhythmic", Truevoice.update(st)voice["style_measured_on"] = "vocals_stem"@@ -535,9 +535,11 @@ def refine_with_stems(audio: dict, vocals_wav: str) -> dict:def vocal_repetition(x: np.ndarray, freqs: np.ndarray, win_s: float = 4.0, min_lag_s: float = 6.0) -> float:"""Share of 4 s vocal windows whose pitch-class pattern recurs >= 6 s later (choruses / hooks).- Measured on the dry vocal stem: AI rap MV 0.26, TTS narration 0.00."""- S = _stft(x)- C = _chroma(S, freqs)+ The clip's average pitch-class profile is removed first: one voice speaking keeps roughly the same+ profile the whole time, so without this every window of plain narration "matches" every other one.+ What is left is the melodic movement, which only repeats when a line is sung (or rapped) again."""+ S = _stft(x).astype(np.float64)+ C = _chroma(S, freqs).astype(np.float64)e = (S ** 2).sum(axis=1)blk = max(1, int(0.25 / T_HOP))n = len(C) // blk@@ -546,6 +548,9 @@ def vocal_repetition(x: np.ndarray, freqs: np.ndarray, win_s: float = 4.0, min_lC = C[:n * blk].reshape(n, blk, 12).mean(axis=1)E = 10 * np.log10(e[:n * blk].reshape(n, blk).mean(axis=1) + 1e-12)act = E > np.percentile(E, 95) - 30+ if not act.any():+ return 0.0+ C = C - C[act].mean(axis=0)W = int(win_s / 0.25)feats, idx = [], []for i in range(0, n - W, 2):@@ -557,6 +562,7 @@ def vocal_repetition(x: np.ndarray, freqs: np.ndarray, win_s: float = 4.0, min_lif len(feats) < 4:return 0.0F, idx = np.array(feats), np.array(idx)- sim = F @ F.T / F.shape[1]+ with np.errstate(all="ignore"): # some BLAS builds raise spurious floating-point flags on large products+ sim = F @ F.T / F.shape[1]sim[np.abs(idx[:, None] - idx[None, :]) * 0.25 < min_lag_s] = -1return round(float((sim.max(axis=1) > 0.6).mean()), 3)diff --git a/rea_video/cli.py b/rea_video/cli.pyindex 849970b..4e9d5f4 100644--- a/rea_video/cli.py+++ b/rea_video/cli.py@@ -114,9 +114,11 @@ def cmd_apply_review(args) -> int:(":" + ", ".join(f"{i} {a}→{c}" for i, a, c in changed) if changed else ""))print(f"结论: {b['summary']['verdict']}")print(f"VLM: {b['summary']['vlm']}")- if not log["applied"] and not log["problems"]:+ if log.get("packaging"):+ print("已并入包装复核:" + ", ".join(f"{k} {n}" for k, n in log["packaging"].items()))+ if not log["applied"] and not log.get("packaging") and not log["problems"]:print("答案文件里没有可并入的镜头(先按 review_tasks.md 填 review_answers.json)")- return 0 if log["applied"] else 1+ return 0 if log["applied"] or log.get("packaging") else 1def cmd_stems(args) -> int:@@ -321,8 +323,8 @@ 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"{(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')}"]+ f"{(T('无明显节拍', 'no beat') if mu.get('no_beat') else (str(mu['tempo_bpm']) + 'BPM' if mu.get('tempo_bpm') is not None else ''))} {(mu.get('key') or {}).get('tonic', '')}{(mu.get('key') or {}).get('mode', '')} | "+ f"{T('音效', 'SFX')}: {_sfx_count(b)} | {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"])if (b.get("stems") or {}).get("ok"):@@ -342,6 +344,13 @@ def cmd_summary(args) -> int:return 0+def _sfx_count(b: dict) -> str:+ sfx = (b.get("audio_plan") or {}).get("sfx_merged", [])+ maybe = sum(1 for e in sfx if e.get("confidence") == "low")+ sure = len(sfx) - maybe+ return f"{sure}" + (T(" + 可能 {m}(待确认)", " + {m} possible (unconfirmed)", m=maybe) if maybe else "")++def cmd_correct(args) -> int:"""The user says a shot is wrong: fix this breakdown and remember the correction."""from .memory import correctdiff --git a/rea_video/overlay.py b/rea_video/overlay.pyindex 3741381..c36fe04 100644--- a/rea_video/overlay.py+++ b/rea_video/overlay.py@@ -70,16 +70,42 @@ def rec_model(lang: str) -> Path:return p+class _RapidOCR3:+ """rapidocr 3.x (used on Python >= 3.13, where rapidocr-onnxruntime has no release) behind the+ rapidocr-onnxruntime call shape: ocr(img) -> ([[box, text, score], ...] or None, elapse)."""++ def __init__(self, rec_model_path: str | None = None):+ from rapidocr import RapidOCR # type: ignore++ params = {"Global.log_level": "warning"}+ if rec_model_path: # its character list is read from the ONNX metadata, as with rapidocr-onnxruntime+ params["Rec.model_path"] = rec_model_path+ self._ocr = RapidOCR(params=params)++ def __call__(self, img):+ out = self._ocr(img)+ boxes, txts, scores = getattr(out, "boxes", None), getattr(out, "txts", None), getattr(out, "scores", None)+ if boxes is None or txts is None or scores is None:+ return None, getattr(out, "elapse", 0.0)+ return [[np.asarray(b).tolist(), t, float(s)] for b, t, s in zip(boxes, txts, scores)], out.elapse+++def _ocr_engine(**kwargs):+ try:+ from rapidocr_onnxruntime import RapidOCR # type: ignore+ except ImportError:+ return _RapidOCR3(**kwargs)+ return RapidOCR(**kwargs)++def get_ocr():lang = ocr_lang()if lang not in _OCR:try:- from rapidocr_onnxruntime import RapidOCR # type: ignore-kwargs = {"rec_model_path": str(rec_model(lang))} if lang in _REC_MODELS else {}- _OCR[lang] = RapidOCR(**kwargs)+ _OCR[lang] = _ocr_engine(**kwargs)except Exception as exc: # pragma: no cover - optional dependency / offline- LOG.warning("OCR disabled (pip install rapidocr-onnxruntime to enable; lang=%s): %s", lang, exc)+ LOG.warning("OCR disabled (pip install 'rea-video[ocr]' to enable; lang=%s): %s", lang, exc)_OCR[lang] = Nonereturn _OCR[lang]diff --git a/rea_video/packaging.py b/rea_video/packaging.pyindex 0c4fd89..b13cb06 100644--- a/rea_video/packaging.py+++ b/rea_video/packaging.py@@ -584,6 +584,31 @@ def _decor_score(c: dict) -> tuple[int, list[str]]:_NUMERIC = re.compile(r"[+\-−]?[¥$€£]?[\d.,,.::%+\-−万亿千百kKmMwW]*\d[\d.,,.::%+\-−万亿千百kKmMwW]*")+def _block_lines(c: dict, cues: list[dict]) -> int:+ """Other lines on screen at the same time, of about the same size, stacked within a few lines of this one:+ the rest of a paragraph / list / page it belongs to."""+ cy = c["bbox"][1] + c["bbox"][3] / 2+ n = 0+ for o in cues:+ if o is c or o["t0"] >= c["t1"] - 0.05 or o["t1"] <= c["t0"] + 0.05:+ continue+ if not 0.7 <= o["line_h"] / max(c["line_h"], 1e-6) <= 1.4:+ continue+ if abs(o["bbox"][1] + o["bbox"][3] / 2 - cy) <= 4 * c["line_h"]:+ n += 1+ return n+++def _aligned(lane: list[dict]) -> bool:+ """Lines of one subtitle track share a horizontal anchor: centred, left- or right-aligned. Words of a page+ (a menu, a file list, a button) that happen to sit at the same height are scattered across it."""+ if len(lane) < 2:+ return True+ anchors = ([c["bbox"][0] for c in lane], [c["bbox"][0] + c["bbox"][2] / 2 for c in lane],+ [c["bbox"][0] + c["bbox"][2] for c in lane])+ return min(float(np.median(np.abs(np.array(a) - np.median(a)))) for a in anchors) <= 0.05++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@@ -612,10 +637,22 @@ def classify_cues(cues: list[dict], duration: float) -> None: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 tiltedand not counter and not numbered)+ # words of a page / document in the picture (a screenshot, a recorded screen) can line up at one height and+ # change like a subtitle track. Each of them is one line among others of the same size on screen with it:+ # a lane made only of such lines is page text, and in a lane whose lines do not share a horizontal anchor+ # the lines sitting in such a block are page text while the lone ones may still be captions+ page = set()+ if is_sub:+ block = {id(c): _block_lines(c, cues) for c in lane}+ if len(lane) >= 3 and all(n >= 3 for n in block.values()):+ page = {id(c) for c in lane}+ elif not _aligned(lane):+ page = {id(c) for c in lane if block[id(c)] >= 2}for c in lane:c["_counter"] = counterc["lane"] = lanes.index(lane)- c["_sub_lane"] = is_sub+ c["_page"] = id(c) in page+ c["_sub_lane"] = is_sub and not c["_page"]c["_lane_texts"] = changingfor c in cues:st = c.get("style") or {}@@ -626,6 +663,10 @@ def classify_cues(cues: list[dict], duration: float) -> None:if moving and not (st.get("stroke") or st.get("box")):kind = "scene"why = [T("跟着画面移动、没有描边或底框", "moves with the picture, no outline or box")]+ elif c.get("_page"):+ kind = "scene"+ why = [T("画面里页面/文档的字:和同字号的几行字同时出现、挨在一起",+ "text of a page / document in the picture: one line in a block of same-size lines on screen together")]elif c.get("_sub_lane") and not (score >= 3 and c["line_h"] >= 0.05):kind = "subtitle"elif cy < 0.3 and (dur >= 0.5 * duration or dur >= 8) and not moving and c.get("_lane_texts", 1) == 1:@@ -644,6 +685,7 @@ def classify_cues(cues: list[dict], duration: float) -> None:c["follows"] = True # tracked to an object in the picture (label with a leader / tag)c["band"] = _band(cy)c.pop("_sub_lane", None)+ c.pop("_page", None)c.pop("_lane_texts", None)@@ -1157,6 +1199,7 @@ def align_sfx(sfx: list[dict], events: list[dict]) -> dict:"""Which on-screen event each sound effect lands on, and which pops / stickers carry a sound."""times = np.array([e["t"] for e in events]) if events else np.zeros(0)counts: dict[str, int] = {}+ possible: dict[str, int] = {} # low-confidence signal candidates, kept apart from heard / reviewed effectsfor s in sfx:t = float(s.get("t", -9))if not len(times):@@ -1167,7 +1210,8 @@ def align_sfx(sfx: list[dict], events: list[dict]) -> dict:i = order[0]if d[i] <= SFX_TOL:s["on"] = {"type": events[i]["type"], "what": events[i]["what"], "dt": round(float(events[i]["t"] - t), 3), "ref": events[i]["ref"]}- counts[events[i]["type"]] = counts.get(events[i]["type"], 0) + 1+ tally = possible if s.get("confidence") == "low" else counts+ tally[events[i]["type"]] = tally.get(events[i]["type"], 0) + 1st = np.array([float(s.get("t", -9)) for s in sfx]) if sfx else np.zeros(0)voiced = {}for e in events:@@ -1177,7 +1221,7 @@ def align_sfx(sfx: list[dict], events: list[dict]) -> dict:k = e["type"]a, b = voiced.get(k, (0, 0))voiced[k] = (a + has, b + 1)- return {"sfx_on": counts, "events_with_sfx": {k: {"with_sfx": a, "total": b} for k, (a, b) in voiced.items()}}+ return {"sfx_on": counts, "sfx_on_possible": possible, "events_with_sfx": {k: {"with_sfx": a, "total": b} for k, (a, b) in voiced.items()}}def anchored_sfx(path: str | Path, events: list[dict], known: list[dict]) -> list[dict]:@@ -1570,6 +1614,10 @@ def summary_lines(pack: dict, sfx_align: dict | None = None) -> list[str]:on = sfx_align.get("sfx_on", {})if on:L.append(T("音效卡点:", "SFX hits on: ") + join(T("{k} {v} 处", "{k} ×{v}", k=EVENT_ZH.get(k, k), v=v) for k, v in sorted(on.items(), key=lambda kv: -kv[1])))+ maybe_on = sfx_align.get("sfx_on_possible", {})+ if maybe_on:+ L.append(T("可能的音效卡点(信号候选,待确认):", "Possible SFX hits (unconfirmed signal candidates) on: ")+ + join(T("{k} {v} 处", "{k} ×{v}", k=EVENT_ZH.get(k, k), v=v) for k, v in sorted(maybe_on.items(), key=lambda kv: -kv[1])))elems = [c for c in cues if c["kind"] in ANCHOR_KINDS and not c.get("part_of_picture")] + stanchored = sorted((e for e in elems if e.get("anchor")), key=lambda e: (not e["anchor"].get("word"), e["t0"]))if anchored:diff --git a/rea_video/pipeline.py b/rea_video/pipeline.pyindex 275a39d..8b9243e 100644--- a/rea_video/pipeline.py+++ b/rea_video/pipeline.py@@ -760,9 +760,12 @@ def finalize(breakdown: dict, out: Path, engine: str | None = None) -> dict: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:- a_parts.append(T("音效 {n} 处", "{n} sound effects", n=n_sfx))+ sfx_all = breakdown["audio_plan"].get("sfx_merged", [])+ n_maybe = sum(1 for e in sfx_all if e.get("confidence") == "low")+ if len(sfx_all) - n_maybe:+ a_parts.append(T("音效 {n} 处", "{n} sound effects", n=len(sfx_all) - n_maybe))+ if n_maybe:+ a_parts.append(T("可能的音效 {n} 处(信号候选,待确认)", "{n} possible sound effects (unconfirmed signal candidates)", n=n_maybe))if a_parts:summary["verdict"] += semi() + T("声音:", "audio: ") + " + ".join(a_parts)if pack:@@ -778,10 +781,13 @@ def finalize(breakdown: dict, out: Path, engine: str | None = None) -> dict:n_st = sum(1 for st in pack.get("stickers", []) if not st.get("in_picture") and st.get("confidence") != "low")if n_st:p_parts.append(T("贴纸/动图 {n} 处", "stickers / GIFs ×{n}", n=n_st))- on = (pack.get("sfx_alignment") or {}).get("sfx_on", {})- n_on = sum(v for k, v in on.items() if k != "cut")+ al = pack.get("sfx_alignment") or {}+ n_on = sum(v for k, v in al.get("sfx_on", {}).items() if k != "cut")if n_on:p_parts.append(T("{n} 个音效卡在文字/贴纸出现上", "{n} sound effects land on text / sticker pops", n=n_on))+ n_maybe_on = sum(v for k, v in al.get("sfx_on_possible", {}).items() if k != "cut")+ if n_maybe_on:+ p_parts.append(T("可能有 {n} 个音效卡在文字/贴纸出现上(待确认)", "{n} possible sound effects at text / sticker pops (unconfirmed)", n=n_maybe_on))if p_parts:summary["verdict"] += semi() + T("剪辑包装:", "packaging: ") + join(p_parts)summary["packaging"] = pack.get("summary_zh", [])diff --git a/rea_video/report.py b/rea_video/report.pyindex 843b996..2487968 100644--- a/rea_video/report.py+++ b/rea_video/report.py@@ -42,8 +42,10 @@ ROUTE_ZH = LangDict({"ai_video": "AI 生成(首尾帧)", "live_action": "实en={"ai_video": "AI generation (first / last frame)", "live_action": "reshoot", "avatar": "TTS + avatar", "cg_3d": "AI generation / 3D render","code_render": "code render", "screen_capture": "screen recording", "still_motion": "local ffmpeg move", "static_hold": "static frame","anim_2d": "AI generation (2D animation)", "stop_motion": "stop motion shoot", "film_footage": "cut from the source film"})-SFX_SRC_ZH = LangDict({"vlm": "听到", "deterministic": "信号候选(低置信)", "review": "看图复核", "merged": "听到 + 信号"},- en={"vlm": "heard", "deterministic": "signal candidate (low confidence)", "review": "agent review", "merged": "heard + signal"})+SFX_SRC_ZH = LangDict({"vlm": "听到", "deterministic": "信号候选(低置信)", "deterministic_anchored": "信号候选,对上文字/贴纸出现(低置信)",+ "review": "看图复核", "merged": "听到 + 信号"},+ en={"vlm": "heard", "deterministic": "signal candidate (low confidence)", "deterministic_anchored": "signal candidate at a text / sticker pop (low confidence)",+ "review": "agent review", "merged": "heard + signal"})ENDING_ZH = LangDict({"natural_end": "自然结束", "fade_out": "淡出", "hard_cut": "硬切断"}, en={"natural_end": "ends naturally", "fade_out": "fades out", "hard_cut": "cut off hard"})NARR_ZH = LangDict({"tts": "TTS 合成", "human": "真人", "none": "无", "mixed": "真人 + TTS"}, en={"tts": "TTS", "human": "human", "none": "none", "mixed": "human + TTS"})@@ -335,7 +337,10 @@ def _audio_md(b: dict) -> list[str]:# sfxsfx = (b.get("audio_plan") or {}).get("sfx_merged", [])- L += ["", T("**音效**", "**Sound effects**") + (f"({len(sfx)})" if sfx and lang() == "zh" else (f" ({len(sfx)})" if sfx else "")), ""]+ n_maybe = sum(1 for e in sfx if e.get("confidence") == "low")+ count = (T("{n},其中 {m} 处是待确认的信号候选", "{n}, of which {m} are unconfirmed signal candidates", n=len(sfx), m=n_maybe)+ if n_maybe and n_maybe < len(sfx) else T("{n},都是待确认的信号候选", "{n}, all unconfirmed signal candidates", n=len(sfx)) if n_maybe else str(len(sfx)))+ L += ["", T("**音效**", "**Sound effects**") + (f"({count})" if sfx and lang() == "zh" else (f" ({count})" if sfx else "")), ""]if sfx:rows = []for e in sfx[:60]:diff --git a/rea_video/review.py b/rea_video/review.pyindex b48da19..67004c2 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(复刻首帧的<PROMPT_LANG>图像提示词:景别、机位高度和俯仰角、主体在画面里的位置和朝向、主体、光线、风格,具体可执行)、+video_prompt(复刻该镜头的<PROMPT_LANG>视频提示词:先写景别、机位角度、主体在画面里的位置,再写动作过程和结束状态、运镜;只写想要的内容,不写否定句)、video_prompt_en(英文版)。这些提示词会被合并进「生成单元」的多镜头提示词,所以每镜只写这一镜的内容,统一的风格和场景描述写在 description 里即可。实拍/写实镜头再填 aspects(怎么拍、怎么打光;纯图形/界面画面不填),像素测不出的部分靠你看:@@ -158,7 +158,10 @@ def build_tasks(breakdown: dict, out_dir: str) -> tuple[dict, dict]:s["tool"]["evidence"] = [e for e in s["tool"]["evidence"] if e not in common]if "aspects" in s:s["aspects"] = _strip_glosses(s["aspects"])- tasks = {"instructions": INSTRUCTIONS, "video": video, "storyboard": "storyboard.jpg",+ instructions = INSTRUCTIONS.replace("<PROMPT_LANG>", "英文" if breakdown.get("lang") == "en" else "中文")+ if breakdown.get("lang") == "en":+ instructions += "\n\n报告语言是英文:evidence、description、image_prompt、video_prompt 和其他自由文本都用英文写(video_prompt_en 可以和 video_prompt 相同)。"+ tasks = {"instructions": instructions, "video": video, "storyboard": "storyboard.jpg","zoom_cmd": _tiles_cmd(video, 0, 0, 0.2, f"{out_dir}/check_ID.jpg").replace("--start 0.00 --end 0.00", "--start {start} --end {end}").replace("check_ID.jpg", "check_{id}.jpg"),"shot_aspects_template": aspects.review_template(),@@ -257,6 +260,7 @@ def apply_answers(breakdown: dict, answers: dict, by: str | None = None) -> dictrec["review"] = cleanapplied.append(sid)changes.append((sid, before))+ pk_applied: dict = {}pk = answers.get("packaging")if isinstance(pk, dict) and breakdown.get("packaging"):kinds = ("subtitle", "huazi", "title", "label", "counter", "scene")@@ -266,6 +270,7 @@ def apply_answers(breakdown: dict, answers: dict, by: str | None = None) -> dict"missed": [m for m in pk.get("missed") or [] if isinstance(m, dict) and "t0" in m], "by": by}if clean_pk["stickers"] or clean_pk["text"] or clean_pk["missed"]:breakdown["packaging"]["review"] = clean_pk+ pk_applied = {k: len(clean_pk[k]) for k in ("stickers", "text", "missed") if clean_pk[k]}whole = aspects.clean_answers(answers.get("aspects"), video=True)if whole:breakdown["review_aspects"] = whole@@ -277,4 +282,4 @@ def apply_answers(breakdown: dict, answers: dict, by: str | None = None) -> dictbreakdown["review_cast"] = castbreakdown.setdefault("analysis", {})["review"] = {"by": by, "shots": len(applied), "of": len(breakdown["shots"]),"time": time.strftime("%Y-%m-%d %H:%M"), "problems": problems}- return {"applied": applied, "problems": problems, "unanswered": unanswered, "before": dict(changes)}+ return {"applied": applied, "problems": problems, "unanswered": unanswered, "before": dict(changes), "packaging": pk_applied}diff --git a/scripts/install_skill.sh b/scripts/install_skill.shindex 49ea187..691df82 100755--- a/scripts/install_skill.sh+++ b/scripts/install_skill.sh@@ -46,7 +46,8 @@ install_failed() {exit 1}-# rapidocr 依赖 opencv-python,和 rea-video 的 opencv-python-headless 共用 cv2 目录,后装的覆盖先装的。+# Python ≤ 3.12 上的 OCR 依赖 rapidocr-onnxruntime 会带上 opencv-python,和 rea-video 的 opencv-python-headless+# 共用 cv2 目录,后装的覆盖先装的(3.13 及以上用的 rapidocr 3 不带,下面自然跳过)。# 只留 headless 一套:删掉 opencv-python 后强制重装 headless(删除会带走共用文件)。dedupe_cv() { # 参数:能跑 pip 的命令,如 python -m pip / pipx runpip rea-videoif "$@" show opencv-python >/dev/null 2>&1; thendiff --git a/skills/rea-video/references/memory.md b/skills/rea-video/references/memory.mdindex fa9246a..6c8c95c 100644--- a/skills/rea-video/references/memory.md+++ b/skills/rea-video/references/memory.md@@ -1,7 +1,7 @@# 记住用户的纠正和偏好- 用户指出某个镜头判错("这是定格动画不是 AI"、"这段是我自己拍的素材"):运行- `rea-video correct out/ref --shots 3,5 --label still_motion --note "<用户原话>"`(也可用 `--start/--end` 指定时间段,`--shots all` 表示整条;真实素材用 `--real yes|no`)。+ `rea-video correct out/ref --shots 3,5 --label stop_motion --note "<用户原话>"`(`--label` 填用户说的那一类,类别名见 `taxonomy.md`:定格动画是 `stop_motion`,静态图 + 推拉是 `still_motion`;也可用 `--start/--end` 指定时间段,`--shots all` 表示整条;真实素材用 `--real yes|no`)。这会立刻改结论和报告,并记入 `~/.rea-video/corrections.jsonl`;以后拆同一个文件会自动套用,同类镜头会在复核任务里提示。- 用户说出长期偏好:能对应参数的用 `rea-video prefs engine kling2.1`、`prefs vlm on`、`prefs env_file <路径>`、`prefs reviewer <名字>`、`prefs capsule_root <capsule-cinema 路径>`;其余的用 `rea-video prefs --note "报告尽量短,重点写复刻方案"` 记下,下次 `rea-video memory` 会显示,按它调整回复。- 只记用户明确说的,不要把你自己的猜测写成纠正。纠正不会自动改分类权重;积累到几条以后,用 `rea-video memory --export-labels eval/user_labels.yaml` 导出成评测样本,再按开发约定评测、改规则(仓库 `docs/dev/evaluation.md`)。diff --git a/skills/rea-video/references/setup.md b/skills/rea-video/references/setup.mdindex ccd278a..144d264 100644--- a/skills/rea-video/references/setup.md+++ b/skills/rea-video/references/setup.md@@ -11,9 +11,9 @@ rea-video --helppip 报 `externally-managed-environment`(Homebrew / 新版 Ubuntu 的系统 Python)时,不要加 `--break-system-packages`,改用`pipx install "rea-video[ocr] @ git+https://github.com/JuneYaooo/rea-video"`,或直接跑 `install_skill.sh`(会自动改用 pipx 或仓库内 `.venv`)。-报 `onnxruntime` 找不到匹配的安装包(如 `no wheels with a matching Python ABI tag`)时,是默认 Python 太新、依赖还没出对应版本:换一个 3.10–3.14 的解释器,`pipx install --python python3.12 "rea-video[ocr] @ git+https://github.com/JuneYaooo/rea-video"` 或 `PYTHON_BIN=python3.12 bash scripts/install_skill.sh`。`install_skill.sh` 自动选解释器时已经优先 3.10–3.14。+报 `onnxruntime` 找不到匹配的安装包(如 `no wheels with a matching Python ABI tag`)时,是默认 Python 太新、依赖还没出对应版本:换一个 3.10–3.14 的解释器,`pipx install --python python3.12 "rea-video[ocr] @ git+https://github.com/JuneYaooo/rea-video"` 或 `PYTHON_BIN=python3.12 bash scripts/install_skill.sh`。`install_skill.sh` 自动选解释器时已经优先 3.10–3.14。3.10–3.14 都能装全 `[ocr]`:3.12 及以下用 `rapidocr-onnxruntime`,3.13 起自动换成 `rapidocr` 3。-手动装了 `[ocr]` 时,OCR 依赖会再装一套 `opencv-python`,和 rea-video 用的 `opencv-python-headless` 抢同一个 `cv2` 目录。装完跑一次:+在 Python 3.12 及以下手动装了 `[ocr]` 时,OCR 依赖会再装一套 `opencv-python`,和 rea-video 用的 `opencv-python-headless` 抢同一个 `cv2` 目录。装完跑一次:`pip uninstall -y opencv-python && pip install --force-reinstall --no-deps "opencv-python-headless>=4.8,<5"`(`install_skill.sh` 会自动做)。## VLM 配置(建议,不强制)diff --git a/tests/test_audio.py b/tests/test_audio.pyindex 303c147..bf2c450 100644--- a/tests/test_audio.py+++ b/tests/test_audio.py@@ -88,3 +88,29 @@ def test_held_chord_is_still_music(tmp_path):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")+++def _syllables(pitches_hz, syl=0.25, gap=0.05, seed=0):+ """One voice: the same harmonic timbre throughout, a gliding pitch per syllable, short gaps between."""+ rng = np.random.default_rng(seed)+ out = []+ for f in pitches_hz:+ t = np.arange(int(syl * SR)) / SR+ glide = f * (1 + rng.uniform(-0.15, 0.15) * t / syl)+ ph = 2 * np.pi * np.cumsum(glide) / SR+ y = sum((0.7 ** k) * np.sin((k + 1) * ph) for k in range(8))+ out += [y * np.hanning(len(t)), np.zeros(int(gap * SR))]+ y = np.concatenate(out)+ return 0.3 * y / np.abs(y).max()+++def test_vocal_repetition_separates_narration_from_repeated_lines():+ from rea_video.audio import N_FFT, vocal_repetition++ freqs = np.fft.rfftfreq(N_FFT, 1 / SR)+ rng = np.random.default_rng(1)+ speech = _syllables(rng.uniform(110, 190, 100)) # 30 s, the pitch never retraces a line+ line = rng.choice([220.0, 246.9, 261.6, 293.7, 329.6, 349.2, 392.0], 26)+ song = _syllables(np.tile(line, 4), syl=0.25, gap=0.05) # an ~8 s line sung four times+ assert vocal_repetition(speech, freqs) <= 0.1+ assert vocal_repetition(song, freqs) > 0.3diff --git a/tests/test_i18n.py b/tests/test_i18n.pyindex 8253879..2c9ad4e 100644--- a/tests/test_i18n.py+++ b/tests/test_i18n.py@@ -41,3 +41,20 @@ def test_image_labels_follow_language():assert LABEL_SHORT["code_render"] == "代码渲染"finally:set_lang("zh")+++def test_summary_without_tempo_prints_no_bpm(tmp_path, capsys):+ import json++ from rea_video.cli import main++ b = {"lang": "en", "source": {"filename": "x.mp4", "duration": 1.0, "width": 16, "height": 16, "fps": 1.0},+ "summary": {"verdict": "x", "confidence": 1.0, "vlm": "none"}, "shots": [],+ "audio": {"has_audio": True, "voice": {"present": True, "ratio": 0.8}, "music": {"present": False, "ratio": 0.0, "segments": []}}}+ p = tmp_path / "breakdown.json"+ p.write_text(json.dumps(b), encoding="utf-8")+ try:+ assert main(["summary", str(p)]) == 0+ finally:+ set_lang("zh")+ assert "NoneBPM" not in capsys.readouterr().outdiff --git a/tests/test_ocr_lang.py b/tests/test_ocr_lang.pyindex bfe2bb0..c9b40e5 100644--- a/tests/test_ocr_lang.py+++ b/tests/test_ocr_lang.py@@ -63,3 +63,37 @@ def test_ocr_lang_pref_is_validated(monkeypatch, tmp_path):monkeypatch.setenv("REA_VIDEO_HOME", str(tmp_path))with pytest.raises(ValueError):memory.set_pref("ocr_lang", "fr")+++def test_rapidocr3_is_used_when_rapidocr_onnxruntime_is_missing(monkeypatch, tmp_path):+ import numpy as np++ made = []++ class Output:+ boxes = np.array([[[0, 0], [10, 0], [10, 5], [0, 5]]], dtype=np.float32)+ txts = ("字幕",)+ scores = (0.9,)+ elapse = 0.1++ class RapidOCR:+ def __init__(self, params=None):+ made.append(params)++ def __call__(self, img):+ return Output() if img is not None else types.SimpleNamespace(boxes=None, txts=None, scores=None, elapse=0.0)++ monkeypatch.setitem(sys.modules, "rapidocr_onnxruntime", None) # import raises ImportError+ monkeypatch.setitem(sys.modules, "rapidocr", types.SimpleNamespace(RapidOCR=RapidOCR))+ monkeypatch.setattr(overlay, "_OCR", {})+ model = tmp_path / "japan.onnx"+ model.write_bytes(b"x")+ monkeypatch.setenv("REA_OCR_REC_MODEL", str(model))+ monkeypatch.setenv("REA_OCR_LANG", "ja")+ ocr = overlay.get_ocr()+ assert made[0]["Rec.model_path"] == str(model)+ res, _ = ocr(np.zeros((5, 10, 3), np.uint8))+ assert res == [[[[0.0, 0.0], [10.0, 0.0], [10.0, 5.0], [0.0, 5.0]], "字幕", 0.9]]+ assert ocr(None)[0] is None # nothing found: same as rapidocr-onnxruntime+ for box, text, conf in res: # the shape overlay / packaging iterate over+ assert len(box) == 4 and text == "字幕" and conf == 0.9diff --git a/tests/test_packaging.py b/tests/test_packaging.pyindex 01064f9..0643714 100644--- a/tests/test_packaging.py+++ b/tests/test_packaging.py@@ -247,9 +247,42 @@ def test_numbered_labels_split_per_shot():assert all(c["kind"] == "label" for c in cues)+def test_page_text_in_a_screenshot_is_not_a_subtitle():+ """Words of a page at one height (tabs, a file list) change like a subtitle track but sit among other lines of+ the same size and are scattered left to right; the caption band under the screenshot stays a subtitle."""+ from rea_video.packaging import classify_cues++ def cue(i, t0, t1, x, y, w, text, h=0.025):+ return {"id": f"t{i}", "t0": t0, "t1": t1, "bbox": [x, y, w, h], "line_h": h, "angle": 0.0, "drift": 0.0,+ "samples": 3, "text": text, "style": {}}++ cues, i = [], 0+ captions = ["这条才发二十一分钟", "就被判九成扑街", "封面顺序反了", "带钩子那张埋在第三张", "先别删拿它查查"]+ words = ["docs", "Code", "main", "Pull requests", "README"]+ for k in range(5):+ t0, t1 = 2.0 * k, 2.0 * k + 1.6+ cues.append(cue(i := i + 1, t0, t1, 0.5 - 0.04 * len(captions[k]) / 2, 0.875, 0.04 * len(captions[k]), captions[k], 0.033))+ # one page word on the lane at y≈0.40, at a different place each time, with the page's other lines around it+ cues.append(cue(i := i + 1, t0, t1, [0.1, 0.9, 0.1, 0.6, 0.3][k], 0.39, 0.08, words[k]))+ for j, dy in enumerate((-0.06, -0.03, 0.03, 0.06)):+ cues.append(cue(i := i + 1, t0, t1, 0.05, 0.39 + dy, 0.5, f"2 weeks ago {k}{j}"))+ classify_cues(cues, 10.0)+ kinds = {c["text"]: c["kind"] for c in cues}+ assert all(kinds[t] == "subtitle" for t in captions)+ assert all(kinds[t] == "scene" for t in words)++def test_counter_ticking_every_frame_stays_one_cue():from rea_video.packaging import build_cuesitems = [{"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+++def test_low_confidence_sfx_are_counted_as_possible():+ from rea_video.packaging import align_sfx++ events = [{"t": 1.0, "type": "text_in", "what": "A", "ref": "text_001"}, {"t": 2.0, "type": "text_in", "what": "B", "ref": "text_002"}]+ al = align_sfx([{"t": 1.02, "source": "vlm"}, {"t": 2.01, "source": "deterministic_anchored", "confidence": "low"}], events)+ assert al["sfx_on"] == {"text_in": 1} and al["sfx_on_possible"] == {"text_in": 1}diff --git a/tests/test_review.py b/tests/test_review.pyindex fa00dd1..6718459 100644--- a/tests/test_review.py+++ b/tests/test_review.py@@ -105,3 +105,34 @@ def test_split_suggestion_rejects_malformed_input_instead_of_raising():# cuts come back sorted, labels stay as givenok, err = _clean({**base, "split_suggestion": {"cuts": [40, 12.5], "labels": ["code_render", "live_action", "code_render"]}})assert err is None and ok["split_suggestion"]["cuts"] == [12.5, 40.0]+++def test_packaging_only_answers_count_as_applied(media, tmp_path, capsys):+ out = tmp_path / "p"+ b = decompose(media["code"], out, use_vlm=False, ocr=False, workers=1, stems=False)+ if not b.get("packaging"):+ b["packaging"] = {"text_cues": [], "stickers": []}+ (out / "breakdown.json").write_text(json.dumps(b, ensure_ascii=False), encoding="utf-8")+ ans = tmp_path / "a.json"+ ans.write_text(json.dumps({"shots": [], "packaging": {"text": [{"id": "text_001", "kind": "scene"}]}}), encoding="utf-8")+ assert main(["apply-review", str(out), str(ans), "--by", "tester"]) == 0+ assert json.loads((out / "breakdown.json").read_text(encoding="utf-8"))["packaging"]["review"]["text"] == {"text_001": "scene"}+ empty = tmp_path / "e.json"+ empty.write_text(json.dumps({"shots": []}), encoding="utf-8")+ assert main(["apply-review", str(out), str(empty), "--by", "tester"]) == 1+++def test_english_review_asks_for_english_prompts(media, tmp_path):+ from rea_video.review import build_tasks++ from rea_video.i18n import set_lang++ try:+ b = decompose(media["code"], tmp_path / "en", use_vlm=False, ocr=False, workers=1, stems=False, lang="en")+ finally:+ set_lang("zh")+ tasks, _ = build_tasks(b, str(tmp_path / "en"))+ assert "中文图像提示词" not in tasks["instructions"] and "英文图像提示词" in tasks["instructions"]+ b["lang"] = "zh"+ tasks, _ = build_tasks(b, str(tmp_path / "en"))+ assert "中文图像提示词" in tasks["instructions"] and "<PROMPT_LANG>" not in tasks["instructions"]