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
Describe transitions and tell speakers apart
juneca8e86bd6cad
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6f219df..a6fbc89 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,19 @@# 更新记录+## 转场类型和区间,多人对话分说话人++**转场**+- 每处镜头边界量出转场的起止时间,并分出类型:淡入淡出(经黑场 / 白场)、闪白和漏光、叠化、划像、推移、甩镜、缩放、旋转、模糊、故障、抖动。划像和推移带方向,推移还分新旧一起动、新画面滑入、旧画面滑走。+- 没有硬切的转场也能找到:前后画面稳定、中间一段过渡、两端是不同画面。黑边里的画面先裁掉黑边再量。+- 一个转场被看成几处硬切时合并成一处(快速推移、故障闪烁、经黑场的两侧)。+- 报告「剪辑」里多一张转场表(时间、进入哪一镜、类型和方向、时长);VIDEO.md 的 `transition_in` 带 `duration` 和 `direction`。+- `scripts/bench_transitions.py`:从真实镜头两两拼接 47 种已知转场做基准。++**说话人**+- 装了 `rea-video[asr]` 时,在人声干声上分出谁在什么时候说话。两个以上的人说话时,每人输出一条 `stems/voice_S1.wav`…,报告「声音」列出每个声音的时长、占比、基频和音轨,并标出两人同时说话的地方。+- 台词每句带说话人,一口气里换了人会在换人处断句;开了 VLM 时角色名按时间对到声音上。+- `--no-speakers` 跳过。`scripts/bench_speakers.py`:用单人视频拼出已知答案的对话做基准。+## 视频拆解标准包 VIDEO.md,报告重写,音效单独分离这一版定下了视频拆解的标准包格式:拆片包(VIDEO.md)。拆一条视频现在得到两样东西:给人看的报告(HTML / PDF),和给模型、下游项目读的拆片包。VIDEO.md 是开放格式,规范在 [videomd/videomd](https://github.com/videomd/videomd);rea-video 生成的内容见 [docs/videomd.md](docs/videomd.md)。diff --git a/docs/cli.md b/docs/cli.mdindex 09861a9..9858064 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -59,6 +59,7 @@ rea-video stems ref.mp4 -o out/ref分轨用两个模型,都在本机 CPU 上跑,第一次用时自动下载到 `$REA_VIDEO_MODELS`(默认 `~/.cache/rea-video/models`):- 人声和配乐:UVR MDX-Net Inst HQ 3(约 67 MB)。+- 说话人(装了 `rea-video[asr]` 才做):pyannote segmentation 3.0 + 3D-Speaker CAM++(共约 35 MB)。两个以上的人说话时,每人一条 `stems/voice_S1.wav`…,台词带上是谁说的。- 音效:BandIt v2 多语种版(约 149 MB;Watcharasupat、Wu、Orife,[arXiv 2407.07275](https://arxiv.org/abs/2407.07275),权重为 CC BY-SA 4.0),把声音拆成对白、音乐、音效三轨,取音效轨。报告里的音效从这一轨找,试听片段也从这一轨剪,听不到人声和配乐。速度约为音频时长的 1.5 倍;模型下载不了时,退回到在混音上找音效。输出示例(混合片):@@ -91,7 +92,7 @@ rea-video capsule-draft out/ref/breakdown.json --capsule-root $CC --capsule-name| 命令 | 作用 ||---|---|-| `decompose VIDEO [--vlm] [--no-ocr] [--ocr-lang zh\|ja] [--lang zh\|en] [--no-packaging] [--max-vlm-shots N] [--no-asr]` | 拆解,输出 breakdown.json、report.html/md、拆片包(`VIDEO.md` + `video/`)、storyboard.jpg、每镜首尾帧,`packaging/`(字幕 SRT、带样式的 ASS、包装时间轴、贴纸截图),以及 `sfx/`(每处音效从原片剪出的一小段,报告音效表里可直接试听);`--lang en` 让结论、报告、`summary` 输出和 VLM 描述都用英文(默认中文;agent 按用户提问的语言选,`rea-video prefs lang en` 可设成默认;breakdown.json 里的 `*_zh` 字段名保留,内容跟报告语言走);`--no-packaging` 跳过包装层(省约每分钟 30–50 秒);`--ocr-lang ja` 用日文识别模型读字幕和花字(首次使用自动下载约 10 MB 到 `$REA_VIDEO_MODELS`,离线时可用 `$REA_OCR_REC_MODEL` 指向本地模型),`rea-video prefs ocr_lang ja` 可设成默认;`--max-vlm-shots N` 是最多发给 VLM 的调用数(默认 60),镜头更多时先看最拿不准的,其余只靠确定性取证,`VLM:` 一行会写明送了多少个;装了可选的 `rea-video[asr]` 时会在人声干声上做本地语音识别,带时间的台词写进 `speech.lines` 和报告的脚本表(机器听写,未校对),`--no-asr` 跳过 |+| `decompose VIDEO [--vlm] [--no-ocr] [--ocr-lang zh\|ja] [--lang zh\|en] [--no-packaging] [--max-vlm-shots N] [--no-asr] [--no-speakers]` | 拆解,输出 breakdown.json、report.html/md、拆片包(`VIDEO.md` + `video/`)、storyboard.jpg、每镜首尾帧,`packaging/`(字幕 SRT、带样式的 ASS、包装时间轴、贴纸截图),以及 `sfx/`(每处音效从原片剪出的一小段,报告音效表里可直接试听);`--lang en` 让结论、报告、`summary` 输出和 VLM 描述都用英文(默认中文;agent 按用户提问的语言选,`rea-video prefs lang en` 可设成默认;breakdown.json 里的 `*_zh` 字段名保留,内容跟报告语言走);`--no-packaging` 跳过包装层(省约每分钟 30–50 秒);`--ocr-lang ja` 用日文识别模型读字幕和花字(首次使用自动下载约 10 MB 到 `$REA_VIDEO_MODELS`,离线时可用 `$REA_OCR_REC_MODEL` 指向本地模型),`rea-video prefs ocr_lang ja` 可设成默认;`--max-vlm-shots N` 是最多发给 VLM 的调用数(默认 60),镜头更多时先看最拿不准的,其余只靠确定性取证,`VLM:` 一行会写明送了多少个;装了可选的 `rea-video[asr]` 时会在人声干声上做本地语音识别,带时间的台词写进 `speech.lines` 和报告的脚本表(机器听写,未校对),`--no-asr` 跳过 || `review OUT_DIR` | 给能看图的 agent 生成逐镜看图任务(review_tasks.json)和答案模板(review_answers.json) || `apply-review OUT_DIR [ANSWERS] [--by NAME] [--lang zh\|en]` | 把 agent 看图的答案和确定性结果融合,重写 breakdown.json 和报告;`--lang` 可以在这一步换报告语言(结论、证据和报告文字重新生成,VLM 已写好的描述和提示词保持原语言) || `correct OUT_DIR --shots N --label L [--real yes/no] [--note]` | 用户指出判错:改正结论和报告,并记入记忆(以后同一文件自动套用,同类镜头复核时提示) |diff --git a/docs/decompose.md b/docs/decompose.mdindex 48ccc04..6c1aa9e 100644--- a/docs/decompose.md+++ b/docs/decompose.md@@ -23,7 +23,7 @@| 问题 | 方法 | 可靠度 ||---|---|---|-| 哪里切镜 | HSV 直方图距离与像素差分,加局部自适应阈值;变化面积要足够大,元素弹出不算切镜。跳剪 / 推近切:同机位一帧内的跳变,比前后几帧的变化高出很多且前后平稳;一两帧内亮了又恢复的闪光、火光不算切镜。交叉溶解:中间帧是否为两端帧的线性混合,并用光流排除推拉运动 | 高(两条真值片 F1=1.0,其中一条含 14 处 0.25s 溶解) |+| 哪里切镜 | HSV 直方图距离与像素差分,加局部自适应阈值;变化面积要足够大,元素弹出不算切镜。跳剪 / 推近切:同机位一帧内的跳变,比前后几帧的变化高出很多且前后平稳;一两帧内亮了又恢复的闪光、火光不算切镜。交叉溶解:中间帧是否为两端帧的线性混合,并用光流排除推拉运动。转场:每处边界量出起止区间,再分淡入淡出 / 闪白 / 叠化 / 划像 / 推移 / 甩镜 / 缩放 / 旋转 / 模糊 / 故障 / 抖动,划像和推移带方向 | 高(两条真值片 F1=1.0,其中一条含 14 处 0.25s 溶解) || 画面动没动 | 逐像素完全重复帧的比例、首尾帧差 | 高 || 是不是一张图在推拉 | LK 光流拟合相似变换(RANSAC):内点率高、残差小、无局部运动,且运动补偿后几乎没有残余 | 高 || 渲染还是拍摄的纹理 | 平坦 8×8 块比例、覆盖 95% 像素所需颜色数、横竖直边比例、Immerkær 噪声 | 高(区分渲染与照片) |@@ -51,7 +51,7 @@在 STFT 上做 HPSS(中值滤波分离谐波和打击成分):-- **人声**:人声频段 3–8Hz 的音节调制,加上句间停顿;用基频给出男/女声提示。+- **人声**:人声频段 3–8Hz 的音节调制,加上句间停顿;用基频给出男/女声提示。多人说话时在人声干声上按音色分出说话人,每人一条音轨。- **音乐**:人声间隙里仍然响亮且有音调的音乐床,或明显的节拍周期;用起音自相关估 BPM,用 Krumhansl 轮廓估调性,用色度新颖度找段落变化。- **剪辑**:切点落在节拍或起音上的比例。- **音效**:确定性层只给人声之外的显著瞬态作为低置信候选,完整清单由 VLM 听出(见 eval/RESULTS.md 的实测)。diff --git a/docs/dev/evaluation.md b/docs/dev/evaluation.mdindex c937af4..af4d494 100644--- a/docs/dev/evaluation.md+++ b/docs/dev/evaluation.md@@ -11,3 +11,20 @@2. 真值要有出处,写在 `source` 字段:生产记录(timeline.json、manifest、cues.py)> 平台 AIGC 标识 > 人工目测(目测的要写"存疑")。3. 跑 `rea-video eval eval/xxx.yaml -o out/eval_xxx`。只改分类规则时不用重新解码:评测会用缓存特征重新分类;改了测量视频的代码(解码、切镜、特征、声音、包装)会自动重新解码,不会拿旧特征给新代码打分(`--fresh` 全部重来,`--only id` 只重解指定视频)。清单里的路径找不到时会用 `eval/media/<id>.<扩展名>` 里的备份,仍然缺的会在摘要的 `missing` 里列出。摘要里的 `by_resolution` / `by_camera` 按分辨率档和运镜拆开准确率和误判方向,改规则前后对比看错误是不是集中在某类画面上。4. 调规则要防止过拟合:至少保留一组**改规则之后才第一次跑**的留出集,结果写进 `eval/RESULTS.md`。++## 转场和说话人的基准++这两项没有现成的带标注视频,用已知答案的合成样本测:++```bash+# 转场:从给定视频里取画面平稳的镜头,两两拼上 47 种转场(ffmpeg xfade 加自己合成的甩镜 / 旋转 / 缩放 / 故障 / 抖动 / 模糊),+# 每种 0.3 / 0.6 / 1.0 秒。找到 = 只报一处边界且落在转场内;类型对 = 报的类型属于该转场所在的族+python3 scripts/bench_transitions.py a.mp4 b.mp4 c.mp4 --out out/bench_transitions --pairs 5++# 说话人:每条输入是一个人在说话的视频,干声切成 2–7 秒的片段轮流拼成对话,可叠配乐(--music)和抢话(--overlap)+python3 scripts/bench_speakers.py a.mp4 b.mp4 c.mp4 --out out/bench_speakers --music bgm.mp4+```++改了 `shots.py` / `transitions.py` 后两头都要看:合成基准看类型,`eval/film.yaml`、`koubo.yaml`、`daihuo.yaml` 的切点真值看真实视频上有没有多报少报。+评测算切点时,标注的切点落在某个转场的起止区间内就算找到(标注的人和检测器可能各取了半秒划像里的不同一帧)。+diff --git a/pyproject.toml b/pyproject.tomlindex eba9ee6..63a6712 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -27,6 +27,7 @@ ocr = ["rapidocr>=3.4,<4; python_version >= '3.13'",]# 本地语音识别(SenseVoice,中英日韩粤):没有字幕、没开 VLM 时也能拿到带时间的台词;首次使用下载约 160 MB 模型+# 同一个包也用来分说话人(pyannote 分段 + 3D-Speaker 音色向量,另下约 35 MB)asr = ["sherpa-onnx>=1.12"]dev = ["pytest>=7", "jsonschema>=4"]diff --git a/rea_video/cli.py b/rea_video/cli.pyindex 817d38d..8208a94 100644--- a/rea_video/cli.py+++ b/rea_video/cli.py@@ -61,7 +61,8 @@ def cmd_decompose(args) -> int:raise SystemExit(f"错误:不支持的报告语言 {lang}(可选:{', '.join(LANGS)})")b = decompose(args.video, out, use_vlm=use_vlm, whole_vlm=not args.no_whole, ocr=not args.no_ocr,workers=args.workers, engine=args.engine or pref("engine", "seedance2.0"), platform_meta=meta, stems=stems,- packaging=not args.no_packaging, lang=lang, asr=not args.no_asr, max_shots_vlm=max(1, args.max_vlm_shots))+ packaging=not args.no_packaging, lang=lang, asr=not args.no_asr, max_shots_vlm=max(1, args.max_vlm_shots),+ speakers=not args.no_speakers)print(json.dumps({"out": str(out), "verdict": b["summary"]["verdict"], "shots": b["summary"]["shots"],"confidence": b["summary"]["confidence"], "vlm": b["summary"]["vlm"],"report": str(out / "report.html")}, ensure_ascii=False, indent=2))@@ -471,6 +472,7 @@ def main(argv: list[str] | None = None) -> int:d.add_argument("--engine", help="复刻计划使用的 capsule-cinema 视频引擎(默认 prefs 里的 engine,否则 seedance2.0)")d.add_argument("--meta", help='平台元数据 JSON,例如 {"music": {"title": "xx", "author": "yy", "is_original": false, "popular": true}}')d.add_argument("--no-asr", action="store_true", help="不做本地语音识别(装了 rea-video[asr] 才会做:在人声干声上识别台词和时间,首次使用下载约 160 MB 模型)")+ d.add_argument("--no-speakers", action="store_true", help="不区分说话人(装了 rea-video[asr] 才会做:在人声干声上分出谁在什么时候说话,多人时每人输出一条 stems/voice_S1.wav;首次使用下载约 35 MB 模型)")d.add_argument("--no-stems", action="store_true", help="不做人声/配乐分离(默认会输出 stems/original.wav、vocals.wav、music.wav)")d.set_defaults(func=cmd_decompose)diff --git a/rea_video/entities.py b/rea_video/entities.pyindex 0097b10..1cacbe0 100644--- a/rea_video/entities.py+++ b/rea_video/entities.py@@ -91,18 +91,37 @@ def cast(b: dict) -> dict:return out+def speaker_label(b: dict, sid: str) -> str:+ """How a separated voice (S1, S2 ...) is called in the report: the name a viewer gave it, else "说话人 N"."""+ for sp in (b.get("speakers") or {}).get("speakers") or []:+ if sp.get("id") == sid:+ return sp.get("name") or T("说话人 {n}", "Speaker {n}", n=sid[1:])+ return ""++def script(b: dict) -> list[dict]:- """Lines of dialogue / narration with time and speaker, from the whole-video VLM; falls back to segment copy."""+ """Lines of dialogue / narration with time and speaker, from the whole-video VLM; falls back to segment copy.+ With more than one separated voice, each line also says which voice it is ("voice": S1 ...)."""w = b.get("whole_video_vlm") or {}+ who = b.get("speakers") or {}+ turns = who.get("turns") or [] if who.get("count", 0) >= 2 else []rows = []for ln in ((w.get("narration") or {}).get("lines") or []):if isinstance(ln, dict) and _s(ln, "text"):rows.append({"start": ln.get("start"), "end": ln.get("end"), "speaker": _s(ln, "speaker", 20), "text": _s(ln, "text", 200)})+ if turns and isinstance(ln.get("start"), (int, float)) and isinstance(ln.get("end"), (int, float)):+ from .speakers import speaker_at++ voice = speaker_at(turns, float(ln["start"]), float(ln["end"]))+ if voice:+ rows[-1]["voice"] = voiceif rows:return rowsfor ln in ((b.get("speech") or {}).get("lines") or []): # machine transcript: below the VLM's, above segment copyif isinstance(ln, dict) and _s(ln, "text"):- rows.append({"start": ln.get("start"), "end": ln.get("end"), "speaker": "", "text": _s(ln, "text", 200), "source": "asr"})+ voice = _s(ln, "speaker", 8) if turns else ""+ rows.append({"start": ln.get("start"), "end": ln.get("end"), "speaker": speaker_label(b, voice) if voice else "",+ "text": _s(ln, "text", 200), "source": "asr", **({"voice": voice} if voice else {})})if rows:return rowsfor seg in w.get("segments") or []:diff --git a/rea_video/evaluate.py b/rea_video/evaluate.pyindex 0d8875f..444f9bd 100644--- a/rea_video/evaluate.py+++ b/rea_video/evaluate.py@@ -167,18 +167,23 @@ def packaging_check(truth_path: str | Path, pack: dict, sfx: list[dict] | None =return out-def boundary_f1(pred: list[float], gt: list[float], tol: float = 0.1, ignore: list[float] | None = None) -> dict:+def boundary_f1(pred: list[float], gt: list[float], tol: float = 0.1, ignore: list[float] | None = None,+ spans: list[tuple[float, float] | None] | None = None) -> dict:"""Cut precision / recall. `ignore`: boundaries the labeller could not decide; a predicted cut there is- neither right nor wrong."""+ neither right nor wrong. `spans`: for each predicted boundary, the (start, end) of its transition when it is+ more than a cut; a labelled cut anywhere inside that transition is the same boundary (a labeller marks one+ frame of a half-second wipe, the detector another)."""used = set()tp = fp = 0- for p in pred:- near = [i for i, g in enumerate(gt) if i not in used and abs(p - g) <= tol]+ for k, p in enumerate(pred):+ a, z = (spans[k] if spans and spans[k] else (p, p))+ a, z = min(a, p) - tol, max(z, p) + tol+ near = [i for i, g in enumerate(gt) if i not in used and a <= g <= z]hit = min(near, key=lambda i: abs(p - gt[i])) if near else None # the closest true cut, not the first in rangeif hit is not None:used.add(hit)tp += 1- elif not any(abs(p - u) <= tol for u in ignore or []):+ elif not any(a <= u <= z for u in ignore or []):fp += 1prec = tp / (tp + fp) if tp + fp else 1.0rec = tp / len(gt) if gt else 1.0@@ -333,7 +338,9 @@ def evaluate(labels_path: Path, out: Path, use_vlm: bool = False, ocr: bool = Trrow["packaging"] = packaging_check(entry["packaging_truth"], b["packaging"], (b.get("audio_plan") or {}).get("sfx_merged", []), sfx_truth)if "cuts" in entry:row["cut_f1"] = boundary_f1([s["start"] for s in b["shots"][1:]], entry["cuts"], tol=float(entry.get("cut_tolerance", 0.1)),- ignore=entry.get("cuts_uncertain"))+ ignore=entry.get("cuts_uncertain"),+ spans=[(s["transition"]["start"], s["transition"]["end"]) if s.get("transition") else None+ for s in b["shots"][1:]])if entry.get("image_source"):srcs = {s["base"].get("image_source") for s in b["shots"]}row["image_source_ok"] = entry["image_source"] in srcsdiff --git a/rea_video/pipeline.py b/rea_video/pipeline.pyindex ad19157..bb7d8a7 100644--- a/rea_video/pipeline.py+++ b/rea_video/pipeline.py@@ -87,7 +87,7 @@ def decode_fingerprint() -> str:def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False, whole_vlm: bool = True,ocr: bool = True, workers: int = 3, engine: str = "seedance2.0", max_shots_vlm: int = 60,platform_meta: dict | None = None, stems: bool = True, memory: bool = True, packaging: bool = True, asr: bool = True,- lang: str = "zh") -> dict:+ lang: str = "zh", speakers: bool = True) -> dict:lang = set_lang(lang)require_tools()t0 = time.time()@@ -299,13 +299,28 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,stem_info: dict = stems_job.result() if stems_job else {}heard: dict = {}+ who: dict = {}+ on_stem = bool(stem_info.get("ok"))+ voice_src = stem_info["vocals"] if on_stem else video # music under the voice confuses speaker and speech models alike+ if speakers and info.has_audio and (audio.get("voice") or {}).get("style") != "singing": # a song: nothing to tell apart+ from . import speakers as spk++ if spk.available():+ LOG.info("separating speakers (%s)", "vocal stem" if on_stem else "full mix")+ who = dict(spk.diarize(voice_src), source="vocals_stem" if on_stem else "mix")+ if who.get("ok"):+ spk.name_speakers(who, [ln for ln in (((whole or {}).get("narration") or {}).get("lines") or []) if isinstance(ln, dict)])+ if on_stem and who.get("count", 0) >= 2: # one track per speaker; with a single voice that is vocals.wav itself+ who["tracks"] = spk.write_tracks(stem_info["vocals"], who["turns"], out)+ else:+ who = {"ok": False, "reason": "not_installed"}if asr and info.has_audio:from . import speechif speech.available(): # optional extra; on the vocal stem when there is one, music makes a recognizer invent words- on_stem = bool(stem_info.get("ok"))LOG.info("transcribing speech (%s)", "vocal stem" if on_stem else "full mix")- heard = dict(speech.transcribe(stem_info["vocals"] if on_stem else video), source="vocals_stem" if on_stem else "mix")+ heard = dict(speech.transcribe(voice_src, turns=who.get("turns") if who.get("count", 0) >= 2 else None),+ source="vocals_stem" if on_stem else "mix")else:heard = {"ok": False, "reason": "not_installed"}breakdown = {@@ -320,6 +335,7 @@ def decompose(video: str | Path, out_dir: str | Path, *, use_vlm: bool = False,"platform_meta": platform_meta or {},"stems": {k: (Path(v).name if k in ("original", "vocals", "music") else v) for k, v in stem_info.items()},"speech": heard,+ "speakers": who,"per_clip_audio": per_clip_audio(str(video), [s.start for s in shots[1:]], info.duration) if info.has_audio else {},}if pack is not None:diff --git a/rea_video/plan.py b/rea_video/plan.pyindex 6ef439d..2e6f68a 100644--- a/rea_video/plan.py+++ b/rea_video/plan.py@@ -178,7 +178,7 @@ def code_scene(shot: dict) -> dict:"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")}+ "flash_s": shot.get("flash_s"), **({"transition": shot["transition"]} if shot.get("transition") else {})}# how a code-rendered picture is built, from the measured look; keys of CODE_STYLESdiff --git a/rea_video/production.py b/rea_video/production.pyindex 5934f69..bdbec67 100644--- a/rea_video/production.py+++ b/rea_video/production.py@@ -33,6 +33,12 @@ SIZE_ORDER = {"远景": 0, "全景": 1, "中景": 2, "近景": 3, "特写": 4,PRODUCT_KINDS = ("product_photo", "logo")++# how a scene is entered, for the motion timeline headings+_TRANSITION_IN = {"dissolve": ("叠化", "dissolve"), "fade": ("淡入", "fade"), "wipe": ("划像", "wipe"), "slide": ("推移", "slide"),+ "whip": ("甩镜", "whip pan"), "zoom": ("缩放", "zoom"), "spin": ("旋转", "spin"), "blur": ("模糊", "blur"),+ "glitch": ("故障", "glitch"), "shake": ("抖动", "shake")}+def _norm(s: str) -> str:return s.replace("-", "").replace("_", "").replace(" ", "").lower()@@ -101,8 +107,8 @@ def code_motion_md(scenes: list[dict]) -> list[str]: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"))+ elif sc.get("transition_in") in _TRANSITION_IN:+ head += T("({t}切入)", " ({t} in)", t=T(*_TRANSITION_IN[sc["transition_in"]]))n_ev = len(sc.get("events") or [])L.append('<details class="ref"><summary>' + T("动效 {h} · {n} 个", "Motion {h} · {n} events", h=head, n=n_ev) + "</summary>")L.append("")diff --git a/rea_video/report.py b/rea_video/report.pyindex b3ec274..96938c3 100644--- a/rea_video/report.py+++ b/rea_video/report.py@@ -152,8 +152,31 @@ def _span(a, z) -> str:# ------------------------------------------------------------------ sections ---------------------------------------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"})+TRANS_ZH = LangDict({"cut": "硬切", "jump": "跳剪", "flash": "闪亮切", "fade": "淡入淡出", "dissolve": "叠化", "wipe": "划像",+ "slide": "推移", "whip": "甩镜", "zoom": "缩放转场", "spin": "旋转转场", "blur": "模糊转场", "glitch": "故障转场",+ "shake": "抖动转场", "effect": "转场特效", "mg_transition": "版式切换"},+ en={"cut": "cut", "jump": "jump cut", "flash": "flash cut", "fade": "fade", "dissolve": "dissolve", "wipe": "wipe",+ "slide": "slide", "whip": "whip pan", "zoom": "zoom transition", "spin": "spin transition",+ "blur": "blur transition", "glitch": "glitch transition", "shake": "shake transition",+ "effect": "transition effect", "mg_transition": "layout change"})+# which way a transition moves: the direction the edge or the picture travels+TRANS_DIR_ZH = LangDict({"left": "向左", "right": "向右", "up": "向上", "down": "向下", "diagonal": "斜向", "center_out": "从中心展开",+ "edges_in": "向中心收拢"},+ en={"left": "leftwards", "right": "rightwards", "up": "upwards", "down": "downwards", "diagonal": "diagonal",+ "center_out": "opening from the centre", "edges_in": "closing in to the centre"})+TRANS_MODE_ZH = LangDict({"push": "新旧画面一起移动", "cover": "新画面滑入盖住旧画面", "reveal": "旧画面滑走露出新画面"},+ en={"push": "both pictures move", "cover": "the new picture slides in over the old one",+ "reveal": "the old picture slides away"})+TRANS_VIA_ZH = LangDict({"black": "经黑场", "white": "经白场"}, en={"black": "through black", "white": "through white"})+++def transition_text(tr: dict) -> str:+ """One transition in words: kind, direction / mode, length."""+ bits = [TRANS_ZH[tr["type"]] if tr["type"] in TRANS_ZH else tr["type"]]+ bits += [d[tr[k]] for k, d in (("via", TRANS_VIA_ZH), ("direction", TRANS_DIR_ZH), ("mode", TRANS_MODE_ZH)) if tr.get(k) in d]+ if tr.get("duration"):+ bits.append(T("{d:.1f} 秒", "{d:.1f}s", d=tr["duration"]) if tr["duration"] >= 0.1 else T("几帧", "a few frames"))+ return T(",", ", ").join(bits)_AGENTS = ("agent", "claude", "claude code", "codex", "gpt", "chatgpt", "gemini", "cursor", "copilot", "dsh", "zcode", "deepseek", "kimi", "qwen")@@ -352,6 +375,37 @@ def _materials_md(b: dict) -> list[str]:return L+def _speakers_md(b: dict) -> list[str]:+ """Who speaks: one line per separated voice, with its share, pitch and track."""+ who = b.get("speakers") or {}+ people = who.get("speakers") or []+ if not who.get("ok") or len(people) < 2:+ return []+ from .entities import speaker_label++ main = [p for p in people if not p.get("minor")]+ tracks = who.get("tracks") or {}+ L = [T("- 说话人:按音色分出 {n} 个声音", "- Speakers: {n} voices told apart by timbre", n=len(main) or len(people))+ + (T(",另有 {m} 个只出现几秒", ", plus {m} heard for a few seconds only", m=len(people) - len(main)) if main and len(main) < len(people) else "")]+ for p in people:+ bits = [T("{s:.0f} 秒({r:.0%})", "{s:.0f}s ({r:.0%})", s=p["seconds"], r=p["share"]),+ T("{n} 段", "{n} turns", n=p["turns"]), T("第一次出现 {t:.1f}s", "first heard at {t:.1f}s", t=p["first"])]+ if p.get("f0_median_hz"):+ bits.append(T("基频约 {f:.0f}Hz({g})", "pitch about {f:.0f}Hz ({g})", f=p["f0_median_hz"],+ g=GENDER_ZH.get(p.get("gender_hint"), T("性别不确定", "gender unclear"))))+ if tracks.get(p["id"]):+ bits.append(f"`stems/{tracks[p['id']]}`")+ L.append(f" - {speaker_label(b, p['id'])}{_colon()}" + T(",", ", ").join(bits))+ ov = who.get("overlaps") or []+ if ov:+ L.append(T(" - 有 {n} 处两人同时说话({t}),这几处在两人的音轨里都保留着",+ " - Two people talk at once in {n} places ({t}); those stay in both speakers' tracks",+ n=len(ov), t=T("、", ", ").join(_span(a, z) for a, z in ov[:4]) + ("…" if len(ov) > 4 else "")))+ L.append(T(" - 音色相近的两个人可能被并成一个,同一个人换语气也可能被拆成两个;人数要紧时听各人的音轨确认",+ " - Two people with similar voices may be merged, and one person changing tone may be split; listen to the tracks when the head count matters"))+ return L++def _edit_md(b: dict) -> list[str]:s = b["summary"]edit = next((x for x in s.get("aspects") or [] if x.startswith(T("剪辑", "Edit"))), "")@@ -362,6 +416,13 @@ def _edit_md(b: dict) -> list[str]:L.append(T("- 手法:{h}", "- Approach: {h}", h=how))L.append(T("- 节奏:{e}", "- Rhythm: {e}", e=edit.split(T(":", ": "), 1)[-1] if edit else T("平均 {a} 秒一刀", "{a}s per shot", a=f"{float(s['avg_shot_s']):.1f}"))+ (T(";转场 {t}", "; transitions {t}", t=trans) if trans else ""))+ # every transition that is more than a cut: where, what kind, which way, how long+ fx = [(r, r["transition"]) for r in b.get("shots", []) if (r.get("transition") or {}).get("type") not in (None, "cut", "jump")]+ if fx:+ L += ["", T("**转场**", "**Transitions**")]+ L += _table([T("时间", "Time"), T("进入镜头", "Into shot"), T("转场", "Transition")],+ [[_span(tr.get("start"), tr.get("end")), f"#{r['index']}", transition_text(tr)] for r, tr in fx],+ fold_title=T("全部 {n} 处", "all {n}", n=len(fx)))return L@@ -461,6 +522,9 @@ def _content_md(b: dict, user: bool = False) -> list[str]:L += ["", head]L += _table([T("时间", "Time"), T("谁", "Who"), T("台词 / 旁白", "Line")],[[_span(ln["start"], ln["end"]), ln["speaker"] or T("旁白", "narration"), ln["text"]] for ln in lines], fold_title=T("全部 {n} 句", "all {n} lines", n=len(lines)))+ if any(ln.get("voice") for ln in lines) and lines[0].get("source") == "asr":+ L.append(T("- 「谁」这一列按音色分出来的说话人填写,对应的单人音轨见「声音」",+ "- The “Who” column is filled from the voices separated by timbre; each one's own track is under “Sound”"))return L@@ -554,6 +618,7 @@ def _audio_md(b: dict) -> list[str]:if v.get("sung"):bits.append(T("是唱的", "sung"))L.append("- " + semi().join(bits))+ L += _speakers_md(b)L += _source_lines("voice")vs = (src.get("voice") or {}).get("source")if vs in _USER_VOICE_HOW:@@ -563,7 +628,16 @@ def _audio_md(b: dict) -> list[str]:if entities.script(b):L.append(T("- 台词见「内容与结构」的脚本表", "- Lines are in the script table under “Content and structure”"))else:- L.append(T("- 无 / 很少", "- None / very little"))+ who = _speakers_md(b)+ if who or (b.get("speech") or {}).get("lines"):+ # the mix is mostly music, so the voice measure says "little"; the separated voice track still has lines on it+ L.append(T("- 占时长很少(混音里以配乐为主),在分离出的人声干声上能听到台词",+ "- A small share of the duration (the mix is mostly music); lines can be heard on the separated voice track"))+ L += who+ if entities.script(b):+ L.append(T("- 台词见「内容与结构」的脚本表", "- Lines are in the script table under “Content and structure”"))+ else:+ L.append(T("- 无 / 很少", "- None / very little"))# musicmu = a.get("music", {})@@ -1078,7 +1152,14 @@ def _stems_html(b: dict) -> str:return "<div class='stems'>" + "".join(f"<div>{name}{_colon()}<audio controls preload='none' src='stems/{f}'></audio></div>"for f, name in (("original.wav", T("原声", "original")), ("vocals.wav", T("人声干声", "dry voice")), ("music.wav", T("配乐 + 环境声", "music + ambience")),- *((("effects.wav", T("音效", "effects")),) if (b.get("stems") or {}).get("effects") else ()))) + "</div>"+ *((("effects.wav", T("音效", "effects")),) if (b.get("stems") or {}).get("effects") else ()),+ *_speaker_tracks(b))) + "</div>"+++def _speaker_tracks(b: dict) -> list[tuple[str, str]]:+ from .entities import speaker_label++ return [(f, speaker_label(b, sid)) for sid, f in ((b.get("speakers") or {}).get("tracks") or {}).items()]_CSS = """diff --git a/rea_video/shots.py b/rea_video/shots.pyindex 29abd1b..564fa3f 100644--- a/rea_video/shots.py+++ b/rea_video/shots.py@@ -11,6 +11,7 @@ import cv2import numpy as npfrom .media import VideoInfo, frame_times, iter_frames+from .transitions import block_diff as _block_diff, crop_box, find_gradual, motion_explains as _motion_explains, resolve, same_structureTHUMB_W = 96# jump cuts (same camera, subject jumps): share of the frame that changes, how far above the frames on both@@ -46,6 +47,8 @@ class Shot:beats: list[int] = field(default_factory=list) # frame indices of MG/slide beat changes inside the shotflash_s: float = 0.0 # "flash" transitions: how long the white / grey flash takes to decaytimes: np.ndarray | None = field(repr=False, default=None) # FrameTrack.times+ # how this shot is entered: {"type", "start_frame", "end_frame", "direction"?, "via"?, "mode"?} (transitions.py)+ transition: dict = field(default_factory=dict)def t(self, frame: int) -> float:"""Time of a frame index. Variable-frame-rate video uses the real pts; past the last frame,@@ -69,11 +72,24 @@ class Shot:def duration(self) -> float:return self.end - self.start+ def transition_dict(self) -> dict:+ """The transition into this shot with times, or {} for a plain cut."""+ tr = self.transition+ if not tr or self.transition_in in ("start", "cut", "jump"):+ return {}+ a, z = self.t(tr["start_frame"] + 1), self.t(tr["end_frame"])+ if self.flash_s: # a cut that opens bright and settles+ a, z = self.start, self.start + self.flash_s+ return {"type": self.transition_in, "start": round(a, 3), "end": round(max(a, z), 3), "duration": round(max(0.0, z - a), 3),+ **{k: tr[k] for k in ("direction", "via", "mode") if tr.get(k)}}+def to_dict(self) -> dict:+ tr = self.transition_dict()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]} | ({"flash_s": round(self.flash_s, 2)} if self.flash_s else {})+ "beats": [round(self.t(b), 3) for b in self.beats]} | ({"flash_s": round(self.flash_s, 2)} if self.flash_s else {}) \+ | ({"transition": tr} if tr else {})def _hist(bgr: np.ndarray) -> np.ndarray:@@ -177,11 +193,13 @@ def detect_shots(track: FrameTrack, min_shot_s: float = 0.35, cut_threshold: flo# 3) dissolves / cross-fades: frame i is a linear blend of frames i-k and i+k.# (camera or subject motion also changes the picture over 2k frames, but the middle# frame of a move is not a blend of its endpoints, so the blend residual separates them)+ y0, y1, x0, x1 = crop_box(track.thumbs, cuts=sum(1 for k, _ in boundaries.values() if k == "cut"))+ T = track.thumbs if (y0, x0, y1, x1) == (0, 0) + track.thumbs[0].shape else [t[y0:y1, x0:x1] for t in track.thumbs]if dissolve and n > 2 * fps:for k in sorted({max(2, int(round(fps * 0.12))), max(3, int(round(fps * 0.2))), max(5, int(round(fps * 0.45)))}):cand = []for i in range(k, n - k):- A, B, M = (track.thumbs[j].astype(np.float32) for j in (i - k, i + k, i))+ A, B, M = (T[j].astype(np.float32) for j in (i - k, i + k, i))D = B - Athr = max(6.0, 0.35 * float(min(A.std(), B.std())))far = float((np.abs(D) > thr).mean())@@ -196,7 +214,7 @@ def detect_shots(track: FrameTrack, min_shot_s: float = 0.35, cut_threshold: floresid = float(np.abs(M - (A + alpha * D)).mean() / (np.abs(D).mean() + 1e-6))# 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):+ if resid < 0.20 and not _steady_morph(T, i, k) and not _motion_explains(A, B) and not same_structure(A, B):cand.append((i, resid, far))cand.sort(key=lambda t: t[1])for i, resid, far in cand:@@ -206,9 +224,22 @@ def detect_shots(track: FrameTrack, min_shot_s: float = 0.35, cut_threshold: flo# 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 othersif dissolve and n > 2 * fps:- for i, strength in _wipes(track, score, cut_threshold, boundaries):+ for i, strength in _wipes(track, T, score, cut_threshold, boundaries):boundaries[i] = ("wipe", strength)+ # 5) any other transition without a hard cut inside (slides, shaped wipes, long or partial blends): a steady+ # picture, a ramp, another steady picture. Then every boundary gets its span, kind and direction, and+ # boundaries that are parts of one transition are joined+ spans: dict[int, tuple[int, int]] = {}+ if dissolve and n > 2 * fps:+ for a, z, mid in find_gradual(T, fps, sorted(boundaries)):+ if float(score[a + 1:z + 1].max()) < cut_threshold or z - a > 2:+ boundaries[mid] = ("gradual", 0.5)+ spans[mid] = (a, z)+ described = resolve(T, fps, boundaries, spans) if dissolve else {b: ({"type": k, "start_frame": b - 1, "end_frame": b}, v)+ for b, (k, v) in boundaries.items()}+ boundaries = {b: (d["type"], strength) for b, (d, strength) in described.items()}+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@@ -233,12 +264,13 @@ def detect_shots(track: FrameTrack, min_shot_s: float = 0.35, cut_threshold: flofor b in kept + [n]:shots.append(Shot(index=len(shots) + 1, start_frame=start, end_frame=b, fps=fps, transition_in=trans, boundary_score=bscore,times=track.times))+ shots[-1].transition = described[start][0] if start in described else {}if b < n:trans, bscore = boundaries[b]start = bfor 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":+ if shot.transition_in in ("cut", "flash"):shot.flash_s = _flash(track.luma, shot.start_frame, shot.end_frame, fps)if shot.flash_s:shot.transition_in = "flash"@@ -373,27 +405,13 @@ def _texture(g: np.ndarray) -> float: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,+def _wipes(track: FrameTrack, thumbs: list[np.ndarray], 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 otheror sits between them (camera / subject motion inside one shot gives blocks that match neither), and the share of blocksalready showing the new picture grows from ~0 to ~1 across the window."""- n, fps, thumbs = track.n, track.fps, track.thumbs+ n, fps = track.n, track.fpstiny = [cv2.resize(t, WIPE_GRID, interpolation=cv2.INTER_AREA).astype(np.float32) for t in thumbs]taken = sorted(boundaries)found: list[tuple[int, float]] = []@@ -461,18 +479,3 @@ def _steady_morph(thumbs: list[np.ndarray], i: int, k: int) -> bool: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."""- a8 = np.clip(a, 0, 255).astype(np.uint8)- b8 = np.clip(b, 0, 255).astype(np.uint8)- flow = cv2.calcOpticalFlowFarneback(a8, b8, None, 0.5, 3, 9, 3, 5, 1.1, 0)- h, w = a8.shape- gx, gy = np.meshgrid(np.arange(w, dtype=np.float32), np.arange(h, dtype=np.float32))- warped = cv2.remap(b8, gx + flow[..., 0], gy + flow[..., 1], cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT)- m = 4 # ignore borders- before = float(np.abs(b8.astype(np.float32) - a8.astype(np.float32))[m:-m, m:-m].mean())- after = float(np.abs(warped.astype(np.float32) - a8.astype(np.float32))[m:-m, m:-m].mean())- return after < 0.45 * beforediff --git a/rea_video/speakers.py b/rea_video/speakers.pynew file mode 100644index 0000000..624436e--- /dev/null+++ b/rea_video/speakers.py@@ -0,0 +1,442 @@+"""Who speaks when: split the voice track by speaker, and give each speaker a track of their own.++Runs on the separated vocal stem (music under the voice confuses a speaker model as much as a recognizer).+Three steps, all local on the sherpa-onnx stack the speech recognizer uses (`pip install "rea-video[asr]"`):++1. turns: a pyannote segmentation model finds speech, pauses and speaker changes, including two people talking+ at once. Its own grouping of the turns is not used: with several people taking quick turns it mixes them up.+2. voices: every turn is cut into pieces of about 1.5 s, each piece gets a speaker embedding (3D-Speaker CAM++,+ Chinese + English), and the pieces are grouped by how alike they sound. Then each group's audio is pooled and+ embedded again as one long sample, which is a far better measure of a voice: groups that sound alike are+ merged (one person shouting and whispering), and a voice heard for a moment only is given to the nearest one+ or dropped.+3. per speaker: time on air, pitch, and stems/voice_S1.wav ... (the vocal stem with everyone else muted).++About 35 MB of models are downloaded on first use. Stretches where two people talk at once are listed, and stay+in both speakers' tracks: pulling overlapping voices apart is not attempted.++What this cannot know: which on-screen character a voice belongs to (the VLM's speaker names are matched onto+the voices by time when there are any), and whether two voices are one actor or one TTS engine in two styles.+"""+from __future__ import annotations++import importlib.util+import os+import subprocess+import tarfile+import uuid+from pathlib import Path++import numpy as np++from .media import extract_audio+from .stems import ensure_file, models_dir+from .util import LOG, fetch, sha256_file++SR = 16000+SEG_DIR = "sherpa-onnx-pyannote-segmentation-3-0"+SEG_URL = f"https://github.com/k2-fsa/sherpa-onnx/releases/download/speaker-segmentation-models/{SEG_DIR}.tar.bz2"+SEG_ARCHIVE_SHA256 = "24615ee884c897d9d2ba09bb4d30da6bb1b15e685065962db5b02e76e4996488"+SEG_FILE = "model.onnx"+EMB_NAME = "3dspeaker_speech_campplus_sv_zh_en_16k-common_advanced.onnx"+EMB_URL = f"https://github.com/k2-fsa/sherpa-onnx/releases/download/speaker-recongition-models/{EMB_NAME}"+EMB_SHA256 = "aa3cfc16963a10586a9393f5035d6d6b57e98d358b347f80c2a30bf4f00ceba2"++PIECE_S = 1.5 # length of the pieces that are embedded one by one+MAX_PIECES = 600 # longer soundtracks use longer pieces+PIECE_SIMILARITY = 0.42 # first pass: groups of pieces at least this alike (average cosine) are joined+MERGE_SIMILARITY = 0.62 # second pass, on pooled audio: parts of one voice score 0.58-0.97, two voices up to 0.59+FOLD_S = 2.5 # a voice with less audio than this is measured too poorly to stand as a group of its own+FOLD_SIMILARITY = 0.3 # ... it joins the speaker it is most like, when it is at least this alike+MIN_SPEAKER_S = 1.2 # a voice heard for less than this in total is not a speaker of its own+MINOR_S, MINOR_SHARE = 5.0, 0.08 # heard for less than both: a voice in passing+MIN_SPEECH_S = 3.0 # less speech than this in the whole track: no speakers are reported+MIN_TURN_S = 0.25+JOIN_GAP_S = 0.35 # same speaker again after a gap this short: one turn+MAX_SPEAKERS = 12+++def available() -> bool:+ return importlib.util.find_spec("sherpa_onnx") is not None+++def ensure_models() -> tuple[Path, Path]:+ """-> (segmentation model, speaker-embedding model), downloaded and checked on first use."""+ root = models_dir()+ seg = root / SEG_DIR / SEG_FILE+ if not seg.is_file():+ root.mkdir(parents=True, exist_ok=True)+ LOG.info("downloading speaker models (~35 MB) -> %s", root)+ arc = root / f"{SEG_DIR}.{os.getpid()}.{uuid.uuid4().hex[:8]}.part"+ tmp = root / f"{SEG_FILE}.{os.getpid()}.{uuid.uuid4().hex[:8]}.part"+ try:+ fetch(SEG_URL, arc, timeout=120)+ if sha256_file(arc) != SEG_ARCHIVE_SHA256:+ raise OSError(f"checksum mismatch for {SEG_DIR}.tar.bz2")+ with tarfile.open(arc, "r:bz2") as tar: # the one file needed, written under our own name: no archive path is trusted+ src = tar.extractfile(f"{SEG_DIR}/{SEG_FILE}")+ if src is None:+ raise OSError(f"{SEG_FILE} missing from the model archive")+ with open(tmp, "wb") as f:+ while chunk := src.read(1 << 20):+ f.write(chunk)+ seg.parent.mkdir(parents=True, exist_ok=True)+ tmp.replace(seg)+ finally:+ arc.unlink(missing_ok=True)+ tmp.unlink(missing_ok=True)+ return seg, ensure_file(EMB_NAME, EMB_URL, EMB_SHA256, "~28 MB")+++def _raw_turns(x: np.ndarray, seg: Path, emb: Path, threads: int) -> list[tuple[float, float]]:+ """Stretches of speech by one person, in time order (two may overlap when two people talk at once)."""+ import sherpa_onnx++ cfg = sherpa_onnx.OfflineSpeakerDiarizationConfig(+ segmentation=sherpa_onnx.OfflineSpeakerSegmentationModelConfig(+ pyannote=sherpa_onnx.OfflineSpeakerSegmentationPyannoteModelConfig(model=str(seg)), num_threads=threads),+ embedding=sherpa_onnx.SpeakerEmbeddingExtractorConfig(model=str(emb), num_threads=threads),+ clustering=sherpa_onnx.FastClusteringConfig(num_clusters=-1, threshold=0.3), # split freely: only the boundaries are kept+ min_duration_on=MIN_TURN_S, min_duration_off=0.3)+ if not cfg.validate():+ raise OSError("speaker models failed to load")+ sd = sherpa_onnx.OfflineSpeakerDiarization(cfg)+ return sorted((float(r.start), float(r.end)) for r in sd.process(x).sort_by_start_time())+++def _pieces(raw: list[tuple[float, float]], piece_s: float) -> list[tuple[float, float, int]]:+ """Cut every turn into equal pieces of about piece_s: (start, end, index of the turn)."""+ out = []+ for i, (a, b) in enumerate(raw):+ n = max(1, int(round((b - a) / piece_s)))+ step = (b - a) / n+ out += [(a + k * step, a + (k + 1) * step, i) for k in range(n)]+ return out+++def group_pieces(V: np.ndarray, similarity: float = PIECE_SIMILARITY, k: int | None = None) -> np.ndarray:+ """Average-linkage grouping of unit vectors by cosine similarity. Stops when no two groups are at least+ `similarity` alike, or at k groups when k is given. -> a group label per row."""+ n = len(V)+ labels = np.arange(n)+ if n < 2:+ return labels+ S = (V @ V.T).astype(np.float64)+ np.fill_diagonal(S, -np.inf)+ size = np.ones(n)+ alive = np.ones(n, bool)+ left = n+ while left > (k or 1):+ i, j = np.unravel_index(int(np.argmax(S)), S.shape)+ if not k and S[i, j] < similarity:+ break+ row = (S[i] * size[i] + S[j] * size[j]) / (size[i] + size[j]) # average similarity to the joined group+ S[i], S[:, i] = row, row+ S[j], S[:, j] = -np.inf, -np.inf+ S[i, i] = -np.inf+ size[i] += size[j]+ alive[j] = False+ labels[labels == labels[j]] = labels[i]+ left -= 1+ return labels+++def _settle(V: np.ndarray, labels: np.ndarray, rounds: int = 3) -> np.ndarray:+ """Move each piece to the group whose average voice it is closest to (a few k-means rounds on the sphere)."""+ for _ in range(rounds):+ ids = np.unique(labels)+ C = np.stack([V[labels == g].mean(axis=0) for g in ids])+ C /= np.linalg.norm(C, axis=1, keepdims=True) + 1e-9+ new = ids[np.argmax(V @ C.T, axis=1)]+ if (new == labels).all():+ break+ labels = new+ return labels+++def _smooth(pieces: list[tuple[float, float, int]], labels: np.ndarray) -> np.ndarray:+ """One piece inside a turn that disagrees with the pieces on both sides is a mismeasured piece, not a+ 1.5 s interjection in the middle of someone's sentence (those arrive as turns of their own)."""+ out = labels.copy()+ for i in range(1, len(pieces) - 1):+ if pieces[i - 1][2] == pieces[i][2] == pieces[i + 1][2] and labels[i - 1] == labels[i + 1] != labels[i]:+ out[i] = labels[i - 1]+ return out+++def _embedder(emb: Path, threads: int):+ import sherpa_onnx++ ex = sherpa_onnx.SpeakerEmbeddingExtractor(sherpa_onnx.SpeakerEmbeddingExtractorConfig(model=str(emb), num_threads=threads))++ def embed(samples: np.ndarray) -> np.ndarray | None:+ if len(samples) < SR * 0.4:+ return None+ st = ex.create_stream()+ st.accept_waveform(SR, samples[:SR * 60]) # a minute of one voice is plenty+ st.input_finished()+ v = np.array(ex.compute(st), np.float32)+ n = float(np.linalg.norm(v))+ return v / n if n > 0 else None++ return embed+++def _solo_ranges(turns: list[tuple[float, float, int]]) -> dict[int, list[tuple[float, float]]]:+ """Per speaker, the parts of their turns where nobody else is talking (the clean samples of that voice)."""+ out: dict[int, list[tuple[float, float]]] = {}+ for a, b, s in turns:+ cuts = sorted((max(a, c), min(b, d)) for c, d, o in turns if o != s and c < b and d > a)+ t = a+ for c, d in cuts:+ if c - t >= 0.2:+ out.setdefault(s, []).append((t, c))+ t = max(t, d)+ if b - t >= 0.2:+ out.setdefault(s, []).append((t, b))+ return out+++def _pool(x: np.ndarray, ranges: list[tuple[float, float]]) -> np.ndarray:+ return np.concatenate([x[int(a * SR):int(b * SR)] for a, b in ranges]) if ranges else np.zeros(0, np.float32)+++def regroup(turns: list[tuple[float, float, int]], measure, fixed: bool = False) -> list[tuple[float, float, int]]:+ """Merge voices that sound alike and fold away voices heard only for a moment.+ `measure(ranges)` -> unit-length embedding of that audio pooled into one sample, or None when there is too+ little to measure. The most alike pair is merged first and the merged voice is measured again, so a voice+ split three ways comes back together even when its two most different parts would not merge directly.+ `fixed`: the caller named the number of speakers, so nothing is merged or dropped."""+ if fixed or len({s for _, _, s in turns}) < 2:+ return turns+ solo = _solo_ranges(turns)+ ranges: dict[int, list[tuple[float, float]]] = {s: solo.get(s, []) for s in {s for _, _, s in turns}}+ secs = {s: sum(b - a for a, b, o in turns if o == s) for s in ranges}+ vec = {s: measure(r) for s, r in ranges.items()}+ label = {s: s for s in ranges}++ def sim(g: int, h: int) -> float:+ return float(vec[g] @ vec[h]) if vec[g] is not None and vec[h] is not None else -1.0++ while True:+ big = [g for g in ranges if secs[g] >= FOLD_S]+ best = max(((sim(g, h), g, h) for i, g in enumerate(big) for h in big[i + 1:]), default=None)+ if best is None or best[0] < MERGE_SIMILARITY:+ break+ _, g, h = best+ keep, gone = (g, h) if secs[g] >= secs[h] else (h, g)+ ranges[keep] = sorted(ranges[keep] + ranges.pop(gone))+ secs[keep] += secs.pop(gone)+ vec[keep] = measure(ranges[keep])+ label[gone] = keep+ # a voice heard only briefly: a short sample measures poorly, so it goes to the speaker it is most like+ # unless it is clearly nobody's (then it is a one-line voice of its own, or too short to keep at all)+ real = [g for g in ranges if secs[g] >= FOLD_S] or [max(secs, key=secs.get)]+ drop = set()+ for g in list(ranges):+ if g in real:+ continue+ near = max(((sim(g, r), r) for r in real), default=(-1.0, None))+ if near[0] >= FOLD_SIMILARITY:+ label[g] = near[1]+ elif secs[g] < MIN_SPEAKER_S:+ drop.add(g)++ def root(s: int) -> int:+ while label[s] != s:+ s = label[s]+ return s++ return [(a, b, root(s)) for a, b, s in turns if root(s) not in drop]+++def _tidy(turns: list[tuple[float, float, int]]) -> list[dict]:+ """Number the speakers by first appearance (S1, S2, ...) and join a speaker's turns across short gaps."""+ order: dict[int, str] = {}+ out: list[dict] = []+ last: dict[str, dict] = {}+ for a, b, s in sorted(turns):+ name = order.setdefault(s, f"S{len(order) + 1}")+ prev = last.get(name)+ if prev and a - prev["end"] <= JOIN_GAP_S:+ prev["end"] = round(max(prev["end"], b), 2)+ continue+ row = {"start": round(a, 2), "end": round(b, 2), "speaker": name}+ out.append(row)+ last[name] = row+ return [t for t in out if t["end"] - t["start"] >= MIN_TURN_S]+++def overlaps(turns: list[dict]) -> list[list[float]]:+ """Stretches where two speakers talk at once."""+ out: list[list[float]] = []+ for i, t in enumerate(turns):+ for u in turns[i + 1:]:+ if u["start"] >= t["end"]:+ break+ if u["speaker"] != t["speaker"]:+ a, b = max(t["start"], u["start"]), min(t["end"], u["end"])+ if b - a >= 0.15:+ out.append([round(a, 2), round(b, 2)])+ return out+++def _pitch(x: np.ndarray, ranges: list[tuple[float, float]]) -> dict:+ """Median pitch of one voice (autocorrelation on 40 ms frames) and what it suggests."""+ frame = int(0.04 * SR)+ lo, hi = int(SR / 400), int(SR / 70)+ f0 = []+ for a, b in ranges:+ for s in range(int(a * SR), int(b * SR) - frame, frame):+ seg = x[s:s + frame]+ if np.sqrt(np.mean(seg ** 2)) < 0.01:+ continue+ seg = seg - seg.mean()+ ac = np.correlate(seg, seg, "full")[frame - 1:]+ if ac[0] <= 0:+ continue+ lag = lo + int(np.argmax(ac[lo:hi]))+ if ac[lag] / ac[0] > 0.45:+ f0.append(SR / lag)+ if len(f0) > 400:+ break+ if len(f0) < 8:+ return {}+ med = float(np.median(f0))+ return {"f0_median_hz": round(med, 1), "gender_hint": "male" if med < 150 else ("female" if med > 200 else "uncertain")}+++def diarize(audio: str | Path, num_speakers: int | None = None, threads: int = 2) -> dict:+ """{"ok", "count", "speakers": [{"id", "seconds", "share", "turns", "first", ...}], "turns": [{"start", "end",+ "speaker"}], "overlaps": [[start, end]]}; ok=False with a reason when it cannot run."""+ if not available():+ return {"ok": False, "reason": "not_installed"}+ x = extract_audio(audio, SR)+ if x is None or len(x) < SR:+ return {"ok": False, "reason": "no audio"}+ try:+ seg, emb = ensure_models()+ raw = _raw_turns(x, seg, emb, threads)+ if not raw:+ return {"ok": True, "count": 0, "speakers": [], "turns": [], "overlaps": []}+ embed = _embedder(emb, threads)+ spoken_s = sum(b - a for a, b in raw)+ pieces = _pieces(raw, max(PIECE_S, spoken_s / MAX_PIECES))+ vecs = [embed(x[int(a * SR):int(b * SR)]) for a, b, _ in pieces]+ known = [i for i, v in enumerate(vecs) if v is not None]+ if not known:+ return {"ok": True, "count": 0, "speakers": [], "turns": [], "overlaps": []}+ V = np.stack([vecs[i] for i in known])+ got = _settle(V, group_pieces(V, k=num_speakers))+ labels = np.full(len(pieces), -1)+ labels[known] = got+ for i in np.where(labels < 0)[0]: # too short to measure: the speaker of the nearest piece in time+ j = min(known, key=lambda q: abs(pieces[q][0] - pieces[i][0]))+ labels[i] = labels[j]+ labels = _smooth(pieces, labels)+ first = [(a, b, int(g)) for (a, b, _), g in zip(pieces, labels)]+ turns = _tidy(regroup(first, lambda ranges: embed(_pool(x, ranges)), fixed=bool(num_speakers)))+ except Exception as exc: # offline on first use, a broken wheel: the breakdown goes on without speakers+ LOG.warning("speaker separation failed: %s", str(exc)[:200])+ return {"ok": False, "reason": f"{type(exc).__name__}: {str(exc)[:120]}"}+ if sum(t["end"] - t["start"] for t in turns) < MIN_SPEECH_S:+ turns = [] # a cough, a shout in the music: nobody is speaking in this video+ names = sorted({t["speaker"] for t in turns}, key=lambda n: int(n[1:]))[:MAX_SPEAKERS]+ turns = [t for t in turns if t["speaker"] in names]+ spoken = sum(t["end"] - t["start"] for t in turns) or 1.0+ speakers = []+ for n in names:+ mine = [t for t in turns if t["speaker"] == n]+ secs = sum(t["end"] - t["start"] for t in mine)+ speakers.append({"id": n, "seconds": round(secs, 2), "share": round(secs / spoken, 3), "turns": len(mine),+ "first": mine[0]["start"], **_pitch(x, [(t["start"], t["end"]) for t in mine]),+ # a few seconds in passing (a clip inside the video, a bystander): not one of the people who carry it+ **({"minor": True} if secs < MINOR_S and secs / spoken < MINOR_SHARE else {})})+ return {"ok": True, "engine": "pyannote-segmentation-3.0 + 3D-Speaker CAM++ (sherpa-onnx)", "count": len(speakers),+ "speakers": speakers, "turns": turns, "overlaps": overlaps(turns)}+++def name_speakers(who: dict, lines: list[dict]) -> None:+ """Give each voice the name a viewer used for it. `lines`: a script with "start", "end" and "speaker" names+ (the VLM watched the video and wrote who says each line). A voice takes the name that covers most of its+ time, when that name is not already taken by a voice it covers better."""+ turns = who.get("turns") or []+ votes: dict[str, dict[str, float]] = {}+ for ln in lines:+ name = str(ln.get("speaker") or "").strip()+ try:+ a, b = float(ln.get("start")), float(ln.get("end"))+ except (TypeError, ValueError):+ continue+ if not name or b <= a:+ continue+ for t in turns:+ o = min(b, t["end"]) - max(a, t["start"])+ if o > 0:+ votes.setdefault(t["speaker"], {}).setdefault(name, 0.0)+ votes[t["speaker"]][name] += o+ taken: set[str] = set()+ pairs = sorted(((sec, sid, name) for sid, v in votes.items() for name, sec in v.items()), reverse=True)+ named: dict[str, str] = {}+ for sec, sid, name in pairs:+ if sid in named or name in taken or sec < 0.5 * sum(votes[sid].values()):+ continue+ named[sid] = name+ taken.add(name)+ for sp in who.get("speakers") or []:+ sp.pop("name", None)+ if sp["id"] in named:+ sp["name"] = named[sp["id"]][:20]+++def speaker_at(turns: list[dict], start: float, end: float) -> str:+ """The speaker who talks for most of [start, end], or "" when nobody does."""+ got: dict[str, float] = {}+ for t in turns:+ o = min(end, t["end"]) - max(start, t["start"])+ if o > 0:+ got[t["speaker"]] = got.get(t["speaker"], 0.0) + o+ return max(got, key=got.get) if got else ""+++def change_points(turns: list[dict], start: float, end: float, min_piece: float = 0.5) -> list[float]:+ """Times inside [start, end] where the speaker changes, for cutting one stretch of speech into lines:+ the middle of the silence between two turns, or of the stretch where both talk."""+ inside = [t for t in turns if t["end"] > start and t["start"] < end]+ cuts: list[float] = []+ for p, q in zip(inside, inside[1:]):+ if p["speaker"] == q["speaker"]:+ continue+ c = (min(p["end"], end) + max(q["start"], start)) / 2+ if c - (cuts[-1] if cuts else start) >= min_piece and end - c >= min_piece:+ cuts.append(round(c, 3))+ return cuts+++def write_tracks(vocals: str | Path, turns: list[dict], out_dir: str | Path, fade_s: float = 0.03) -> dict[str, str]:+ """stems/voice_S1.wav ...: the vocal stem with only that speaker's turns left in (same length as the video,+ so the tracks line up in an editor). -> {speaker id: file name}"""+ from .stems import SR as STEM_SR, load_stereo, save_wav++ mix = load_stereo(vocals)+ out = Path(out_dir) / "stems"+ for old in out.glob("voice_S*.wav"):+ old.unlink()+ if mix is None or not turns:+ return {}+ files: dict[str, str] = {}+ fade = max(1, int(fade_s * STEM_SR))+ for name in sorted({t["speaker"] for t in turns}, key=lambda n: int(n[1:])):+ gate = np.zeros(mix.shape[1], np.float32)+ for t in turns:+ if t["speaker"] == name:+ gate[max(0, int(t["start"] * STEM_SR) - fade):int(t["end"] * STEM_SR) + fade] = 1.0+ gate = np.convolve(gate, np.ones(fade, np.float32) / fade, mode="same") # short ramps instead of clicks+ f = out / f"voice_{name}.wav"+ try:+ save_wav(mix * gate[None, :], f)+ except (OSError, subprocess.CalledProcessError) as exc:+ LOG.warning("could not write %s: %s", f.name, exc)+ continue+ files[name] = f.name+ return filesdiff --git a/rea_video/speech.py b/rea_video/speech.pyindex 15255fb..869eb3d 100644--- a/rea_video/speech.py+++ b/rea_video/speech.py@@ -113,6 +113,23 @@ def _stretches(x: np.ndarray, vad_model: Path) -> list[tuple[float, np.ndarray]]return out+def _by_speaker(stretches: list[tuple[float, np.ndarray]], turns: list[dict] | None) -> list[tuple[float, np.ndarray]]:+ """Cut each spoken stretch where the speaker changes inside it."""+ if not turns:+ return stretches+ from .speakers import change_points++ out: list[tuple[float, np.ndarray]] = []+ for start, samples in stretches:+ t = start+ for c in change_points(turns, start, start + len(samples) / SR) + [start + len(samples) / SR]:+ piece = samples[int(round((t - start) * SR)):int(round((c - start) * SR))]+ if len(piece):+ out.append((t, piece))+ t = c+ return out++def _sentences(start: float, end: float, text: str) -> list[dict]:"""One spoken stretch as lines. A long stretch is split at sentence ends, each sentence given its share ofthe time by length: inside a stretch the times are an estimate, the stretch's own start and end are measured."""@@ -140,8 +157,10 @@ def _sentences(start: float, end: float, text: str) -> list[dict]:return out-def transcribe(audio: str | Path, language: str = "auto", threads: int = 2) -> dict:- """{"ok", "engine", "language", "lines": [{"start", "end", "text"}]}; ok=False with a reason when it cannot run."""+def transcribe(audio: str | Path, language: str = "auto", threads: int = 2, turns: list[dict] | None = None) -> dict:+ """{"ok", "engine", "language", "lines": [{"start", "end", "text"}]}; ok=False with a reason when it cannot run.+ turns: who speaks when (speakers.diarize). A stretch of speech is then cut where the speaker changes, so two+ people answering each other without a pause become two lines, and every line carries its "speaker"."""if not available():return {"ok": False, "reason": "not_installed"}x = extract_audio(audio, SR)@@ -154,14 +173,20 @@ def transcribe(audio: str | Path, language: str = "auto", threads: int = 2) -> drec = sherpa_onnx.OfflineRecognizer.from_sense_voice(model=str(model), tokens=str(tokens), num_threads=threads, use_itn=True,language=language if language in LANGS else "")lines, langs = [], []- for start, samples in _stretches(x, vad_model):+ for start, samples in _by_speaker(_stretches(x, vad_model), turns):st = rec.create_stream()st.accept_waveform(SR, samples)rec.decode_stream(st)text = (st.result.text or "").strip()if len(text.strip("。,、!?.,!? ")) < 1:continue- lines += _sentences(start, start + len(samples) / SR, text)+ got = _sentences(start, start + len(samples) / SR, text)+ if turns:+ from .speakers import speaker_at++ who = speaker_at(turns, start, start + len(samples) / SR)+ got = [dict(ln, speaker=who) for ln in got] if who else got+ lines += gotlang = str(getattr(st.result, "lang", "") or "").strip("<|>")if lang:langs.append(lang)diff --git a/rea_video/transitions.py b/rea_video/transitions.pynew file mode 100644index 0000000..df9d39a--- /dev/null+++ b/rea_video/transitions.py@@ -0,0 +1,629 @@+"""Transitions between shots: where each one starts and ends, what kind it is, which way it moves.++The cut detector (shots.py) finds boundaries; this module adds the ones it cannot see frame by frame and+describes all of them.++- find_gradual: a transition without a hard cut inside is "steady picture A, a ramp, steady picture B": a+ window whose two ends are different pictures, with the picture holding still before and after and passing+ from one to the other in between. It counts as a boundary when the ramp reads as a fade, dissolve, wipe or+ slide; a push-in, a pan or a focus pull inside one take also goes from one steady picture to another.+- span: for one boundary, the frames over which the picture goes from the old shot to the new one.+- classify: what happens inside the span.+ fade through a flat black / white frame+ flash burns up to near white (a flash, a light leak) and the next shot comes out of it+ dissolve every frame is a blend of the two pictures+ wipe the new picture replaces the old one region by region (edge, iris, clock, blinds); direction+ slide the pictures move: push (both), cover (new one slides over), reveal (old one slides away); direction+ whip a fast pan with motion blur hides the cut; direction+ zoom a fast push in / pull out hides the cut+ spin a rotation hides the cut+ blur the picture goes out of focus and comes back as the next shot+ glitch a burst of displaced / alternating frames+ shake a burst of camera shake around the cut+- resolve: joins boundaries that are parts of one transition and drops candidates that are camera work.++Everything works on the small gray thumbs of the frame track. Letterbox bars and other static borders are+cropped away first, so a transition inside a letterboxed picture is measured on the picture, not on the bars."""+from __future__ import annotations++import cv2+import numpy as np++GRID = (6, 8) # blocks across, down+GRADUAL_SECONDS = (0.2, 0.35, 0.6, 1.0, 1.5)+PLATEAU = 0.3 # the picture just outside a transition differs from its end by at most this share of the change across it+MIN_CHANGED = 0.5 # share of the picture that must be different after a gradual transition+SPAN_PLATEAU = 0.4 # same idea for the span of a known boundary; looser, the boundary is already there+SPAN_SECONDS = (0.1, 0.2, 0.35, 0.6, 1.0, 1.5) # half-widths tried for the span of a gradual boundary+MIN_EFFECT_S = 0.25 # shortest span read as an editor's effect (wipe, slide, whip ...); shorter ones are cuts+DIRECTIONS = ("left", "right", "up", "down")+++def crop_box(thumbs: list[np.ndarray], cuts: int = 0, samples: int = 48) -> tuple[int, int, int, int]:+ """(y0, y1, x0, x1) of the picture without its static borders: letterbox bars, a fixed banner above and below+ a letterboxed film. `cuts`: how many hard cuts the video has. A border that stays the same across several+ shots is a border; in a video of one or two shots a still background is just as static, so there only+ plain bars (one flat colour) are taken off."""+ n = len(thumbs)+ h, w = thumbs[0].shape+ if n < 8:+ return 0, h, 0, w+ idx = np.linspace(0, n - 1, num=min(samples, n)).astype(int)+ stack = np.stack([thumbs[i] for i in idx]).astype(np.int16)+ moving = (stack.max(axis=0) - stack.min(axis=0)) > 16+ rows, cols = moving.mean(axis=1) > 0.08, moving.mean(axis=0) > 0.08+ if cuts < 3:+ mid = thumbs[n // 2].astype(np.float32)+ rows |= mid.std(axis=1) >= 8.0+ cols |= mid.std(axis=0) >= 8.0+ if not rows.any() or not cols.any():+ return 0, h, 0, w+ y0, y1 = int(np.argmax(rows)), int(h - np.argmax(rows[::-1]))+ x0, x1 = int(np.argmax(cols)), int(w - np.argmax(cols[::-1]))+ if (y1 - y0) < 0.15 * h or (x1 - x0) < 0.3 * w or (y1 - y0) < 24 or (x1 - x0) < 24:+ return 0, h, 0, w # hardly anything left: not a bordered picture+ return y0, y1, x0, x1+++def _f(t: np.ndarray) -> np.ndarray:+ return t.astype(np.float32)+++def _mad(a: np.ndarray, b: np.ndarray) -> float:+ return float(np.abs(_f(a) - _f(b)).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, b = _f(a), _f(b)+ 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], GRID, interpolation=cv2.INTER_AREA)+ best = d if best is None else np.minimum(best, d)+ return best+++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."""+ a8 = np.clip(a, 0, 255).astype(np.uint8)+ b8 = np.clip(b, 0, 255).astype(np.uint8)+ flow = cv2.calcOpticalFlowFarneback(a8, b8, None, 0.5, 3, 9, 3, 5, 1.1, 0)+ h, w = a8.shape+ gx, gy = np.meshgrid(np.arange(w, dtype=np.float32), np.arange(h, dtype=np.float32))+ warped = cv2.remap(b8, gx + flow[..., 0], gy + flow[..., 1], cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT)+ m = 4 # ignore borders+ before = float(np.abs(_f(b8) - _f(a8))[m:-m, m:-m].mean())+ after = float(np.abs(_f(warped) - _f(a8))[m:-m, m:-m].mean())+ return after < 0.45 * before+++def same_structure(a: np.ndarray, b: np.ndarray) -> bool:+ """The two frames show the same scene under different light (a lamp switched on, an exposure ramp, a+ colour flash over the picture): block by block the detail still lines up once brightness is taken out."""+ a, b = _f(a), _f(b)+ h, w = a.shape+ by, bx = max(4, h // GRID[1]), max(4, w // GRID[0])+ good = total = 0+ for y in range(0, h - by + 1, by):+ for x in range(0, w - bx + 1, bx):+ p, q = a[y:y + by, x:x + bx], b[y:y + by, x:x + bx]+ sp, sq = float(p.std()), float(q.std())+ if sp < 4 or sq < 4:+ continue # flat block: nothing to line up+ total += 1+ good += float(((p - p.mean()) * (q - q.mean())).mean() / (sp * sq)) > 0.6+ return total >= 6 and good / total > 0.5+++def progress(T: list[np.ndarray], s: int, e: int, lo: int, hi: int) -> np.ndarray:+ """For frames lo..hi: 0 = the picture at frame s, 1 = the picture at frame e."""+ A, B = _f(T[s]), _f(T[e])+ out = np.empty(hi - lo + 1, np.float32)+ for k, m in enumerate(range(lo, hi + 1)):+ M = _f(T[m])+ da, db = float(np.abs(M - A).mean()), float(np.abs(M - B).mean())+ out[k] = da / (da + db + 1e-6)+ return out+++def _tight(u: np.ndarray, lo: int) -> tuple[int, int, int]:+ """(last frame still the old picture, first frame fully the new one, frame where the new one takes over)."""+ half = int(np.argmax(u >= 0.5))+ s = half+ while s > 0 and u[s - 1] > 0.12:+ s -= 1+ e = half+ while e < len(u) - 1 and u[e] < 0.88:+ e += 1+ return lo + max(0, s - 1), lo + e, lo + half+++def find_gradual(T: list[np.ndarray], fps: float, taken: list[int]) -> list[tuple[int, int, int]]:+ """Transitions with no hard cut inside: (start frame, end frame, boundary frame). `taken`: boundaries+ already found; windows around them are left alone."""+ n = len(T)+ small = [cv2.resize(t, (12, 16), interpolation=cv2.INTER_AREA).astype(np.float32) for t in T] # block means: small motion averages out+ found: list[tuple[int, int, int]] = []+ for sec in GRADUAL_SECONDS:+ L = max(4, int(round(sec * fps)))+ pad = max(3, L // 2)+ for s in range(pad, n - L - pad, max(1, L // 5)):+ e = s + L+ if any(s - pad <= b <= e + pad for b in taken) or any(a - pad <= s + L // 2 <= z + pad for a, z, _ in found):+ continue+ dab = float(np.abs(small[s] - small[e]).mean())+ if dab < 10:+ continue # the two ends look alike at a glance+ # steady before and after, relative to how much changes across the window+ if (float(np.abs(small[s - pad] - small[s]).mean()) > PLATEAU * dab+ or float(np.abs(small[e + pad] - small[e]).mean()) > PLATEAU * dab):+ continue+ bd = block_diff(T[s], T[e])+ if float((bd > max(10.0, 0.5 * float(np.median(bd)))).mean()) < MIN_CHANGED:+ continue # part of the picture changes: someone walks in, a panel opens+ if same_structure(T[s], T[e]) or motion_explains(_f(T[s]), _f(T[e])):+ continue+ if min(float(T[s].std()), float(T[e].std())) < 12.0:+ continue # one end is an empty page: things fading in or out on a plain ground, not a change of shot+ u = progress(T, s, e, s - pad, e + pad)+ if float(u[:pad].max()) > 0.3 or float(u[-pad:].min()) < 0.7:+ continue+ a, z, mid = _tight(u, s - pad)+ # still the same story on the tight span: steady just outside it+ ra, rz = max(0, a - max(2, (z - a) // 2)), min(n - 1, z + max(2, (z - a) // 2))+ d2 = _mad(T[a], T[z])+ if _mad(T[ra], T[a]) > PLATEAU * d2 or _mad(T[rz], T[z]) > PLATEAU * d2:+ continue+ found.append((a, z, mid))+ return found+++def _detail(t: np.ndarray) -> float:+ gx, gy = _grad(t)+ return gx + gy+++def _active_span(T: list[np.ndarray], s: int, e: int, fps: float, lo: int, hi: int) -> tuple[int, int]:+ """Widen (s, e) (last old frame, first new frame; b - 1, b for a hard cut at b) over the frames on either+ side that are not their shot's normal picture: changing much faster than the shot usually does (the travel+ of a whip, a zoom punch, a shake), much softer than it usually is (a defocus into the cut), or flat (the+ black or white a fade passes through, with the ramp on its far side). A cut inside a fight keeps its one+ frame: the shot is that busy everywhere."""+ far, reach = max(2, int(round(0.2 * fps))), int(round(1.5 * fps))++ def change(m: int) -> float:+ return _mad(T[m], T[m - 1])++ def flat(m: int) -> bool:+ return float(T[m].std()) < 8.0++ s0, e0 = s, e+ while s - 1 > lo and s0 - s < reach and flat(s):+ s -= 1+ if flat(s):+ s = s0 # flat as far back as we look: the old shot is a plain card, not something a fade passes through+ while e + 1 < hi and e - e0 < reach and flat(e):+ e += 1+ if flat(e):+ e = e0+ s1, e1 = s, e+ old = list(range(max(lo + 1, s1 + 1 - reach), s1 + 1 - far))+ if len(old) >= 3:+ level = float(np.median([change(m) for m in old]))+ thr = max(2.5 * level, level + 1.0)+ soft = 0.6 * float(np.median([_detail(T[m]) for m in old]))+ while s - 1 > lo and s1 - s < reach and (change(s) > thr or _detail(T[s]) < soft):+ s -= 1+ new = list(range(e1 + far + 1, min(hi, e1 + reach) + 1))+ if len(new) >= 3:+ level = float(np.median([change(m) for m in new]))+ thr = max(2.5 * level, level + 1.0)+ soft = 0.6 * float(np.median([_detail(T[m]) for m in new]))+ while e + 1 < hi and e - e1 < reach and (change(e + 1) > thr or _detail(T[e]) < soft):+ e += 1+ return max(lo, s), min(hi, e)+++def span(T: list[np.ndarray], b: int, fps: float, lo: int, hi: int, kind: str = "cut") -> tuple[int, int]:+ """Frames over which the boundary at b turns the old shot into the new one: (last old frame, first new+ frame). A hard cut gives (b - 1, b). lo / hi: the neighbouring boundaries (the span stays between them).+ A cut is measured by how long the picture stays unusually busy around it. A gradual transition by the+ smallest window around b that has the old picture holding before it, the new one holding after it, and+ the whole ramp inside (inside a longer ramp the frames outside a window keep changing, and the ramp runs+ up to the window's edges: too small a window does not qualify)."""+ if kind in ("cut", "jump"):+ return _active_span(T, b - 1, b, fps, lo, hi)+ best = None+ for sec in SPAN_SECONDS:+ w = max(2, int(round(sec * fps)))+ s, e = max(lo, b - w), min(hi, b + w - 1)+ p = max(2, min(w, int(round(0.2 * fps))))+ a, z = max(lo, s - p), min(hi, e + p)+ if s >= e or a == s or z == e:+ break # no room left to look outside the window+ dab = _mad(T[s], T[e]) + 1e-6+ if (max(_mad(T[i], T[s]) for i in range(a, s)) > SPAN_PLATEAU * dab+ or max(_mad(T[i], T[e]) for i in range(e + 1, z + 1)) > SPAN_PLATEAU * dab):+ continue+ inner = progress(T, s, e, s, e)+ k = int(np.argmax(inner >= 0.5))+ i = k+ while i > 0 and inner[i - 1] > 0.12:+ i -= 1+ j = k+ while j < len(inner) - 1 and inner[j] < 0.88:+ j += 1+ best = (s + max(0, i - 1), s + j)+ if i >= 2 and j <= len(inner) - 3:+ break # the ramp starts and ends inside the window: this is all of it+ return best or _active_span(T, b - 1, b, fps, lo, hi)+++# ------------------------------------------------------------------ what kind ------------------------------------++def _compose(A: np.ndarray, B: np.ndarray, mode: str, direction: str, d: int) -> np.ndarray:+ """The frame a straight-edge transition shows when the edge has travelled d pixels. direction: the way+ the edge (and whatever moves) travels. mode: wipe (nothing moves), push (both pictures move), cover (the+ new picture slides in over the old one), reveal (the old picture slides away off the new one)."""+ if direction in ("up", "down"):+ return _compose(A.T, B.T, mode, "left" if direction == "up" else "right", d).T+ if direction == "right":+ return _compose(A[:, ::-1], B[:, ::-1], mode, "left", d)[:, ::-1]+ w = A.shape[1]+ P = np.empty_like(A)+ if d <= 0:+ return A.copy()+ if d >= w:+ return B.copy()+ P[:, :w - d] = A[:, d:] if mode in ("push", "reveal") else A[:, :w - d]+ P[:, w - d:] = B[:, :d] if mode in ("push", "cover") else B[:, w - d:]+ return P+++def _edge_fit(A: np.ndarray, B: np.ndarray, mids: list[np.ndarray]) -> dict | None:+ """Best straight-edge explanation of the in-between frames, or None."""+ dab = float(np.abs(A - B).mean()) + 1e-6+ best = None+ for direction in DIRECTIONS:+ size = A.shape[1] if direction in ("left", "right") else A.shape[0]+ steps = np.unique(np.linspace(0, size, num=min(size + 1, 33)).astype(int))+ for mode in ("wipe", "push", "cover", "reveal"):+ frames = [_compose(A, B, mode, direction, int(d)) for d in steps]+ res, pos = [], []+ for M in mids:+ errs = [float(np.abs(M - P).mean()) for P in frames]+ k = int(np.argmin(errs))+ res.append(errs[k] / dab)+ pos.append(steps[k] / size)+ r = float(np.median(res))+ # nothing moving is the simpler reading: a moving mode has to fit clearly better to be chosen over it+ if best is None or r < best["resid"] * (0.8 if best["mode"] == "wipe" and mode != "wipe" else 1.0):+ best = {"mode": mode, "direction": direction, "resid": r, "pos": pos}+ if best is None or best["resid"] > 0.38:+ return None+ pos = np.array(best["pos"])+ if len(pos) >= 3 and (float(np.corrcoef(pos, np.arange(len(pos)))[0, 1]) < 0.8 or pos[-1] - pos[0] < 0.3):+ return None # the edge has to travel across the frame+ return best+++def _blend_fit(A: np.ndarray, B: np.ndarray, mids: list[np.ndarray]) -> tuple[float, bool]:+ """(median residual of 'frame = A + alpha (B - A)', alpha rises through the span)."""+ D = B - A+ denom = float((D * D).sum()) + 1e-6+ scale = float(np.abs(D).mean()) + 1e-6+ res, alphas = [], []+ for M in mids:+ alpha = float(((M - A) * D).sum() / denom)+ alphas.append(alpha)+ res.append(float(np.abs(M - (A + alpha * D)).mean()) / scale)+ al = np.array(alphas)+ rising = len(al) < 3 or (float(np.corrcoef(al, np.arange(len(al)))[0, 1]) > 0.85 and al[0] < 0.6 and al[-1] > 0.4)+ return float(np.median(res)), bool(rising)+++def _region_fit(A: np.ndarray, B: np.ndarray, mids: list[np.ndarray]) -> dict | None:+ """Wipes of any shape: block by block every in-between frame is the old picture or the new one, and the+ new part grows. Direction from the order in which the blocks turn."""+ dab = block_diff(A, B)+ sig = dab > max(10.0, 0.5 * float(np.median(dab)))+ if sig.mean() < 0.4 or len(mids) < 2:+ return None+ pure, new = [], []+ for M in mids:+ da, db = block_diff(M, A), block_diff(M, B)+ pure.append(float((np.minimum(da, db)[sig] < 0.4 * dab[sig]).mean()))+ new.append(db < da)+ share = [float(v[sig].mean()) for v in new]+ # judged where the two pictures share the frame: half-way through a dissolve no block is the old picture+ # or the new one, however clean the first and last frames look+ central = [p for p, u in zip(pure, share) if 0.2 < u < 0.8] or pure+ if min(central) < 0.6 or float(np.percentile(pure, 20)) < 0.7 or share[-1] - share[0] < 0.3:+ return None+ flips = np.diff(np.array(new, np.int8), axis=0)+ if float((flips < 0).any(axis=0)[sig].mean()) > 0.2:+ return None # blocks turn once and stay+ when = np.array(new, np.float32).argmax(axis=0).astype(np.float32) # first in-between frame showing the new picture+ when[~np.array(new).any(axis=0)] = len(mids)+ gh, gw = when.shape+ ys, xs = np.mgrid[0:gh, 0:gw].astype(np.float32)+ rad = np.hypot((xs - (gw - 1) / 2) / gw, (ys - (gh - 1) / 2) / gh)++ def corr(v: np.ndarray) -> float:+ a, b = when[sig], v[sig]+ return float(np.corrcoef(a, b)[0, 1]) if a.std() > 0 and b.std() > 0 else 0.0++ cx, cy, cr = corr(xs), corr(ys), corr(rad)+ direction = ""+ if max(abs(cx), abs(cy), abs(cr)) >= 0.55:+ if abs(cr) >= max(abs(cx), abs(cy)):+ direction = "center_out" if cr > 0 else "edges_in"+ elif min(abs(cx), abs(cy)) >= 0.45:+ direction = "diagonal"+ elif abs(cx) > abs(cy):+ direction = "right" if cx > 0 else "left"+ else:+ direction = "down" if cy > 0 else "up"+ return {"direction": direction, "pure": float(np.median(pure))}+++def _similarity(a: np.ndarray, b: np.ndarray) -> tuple[float, float, float, float] | None:+ """Camera motion from a to b as (log scale, rotation in degrees, dx, dy as shares of the frame), or None+ when too little can be tracked."""+ pts = cv2.goodFeaturesToTrack(a, 80, 0.01, 4)+ if pts is None or len(pts) < 10:+ return None+ nxt, st, _ = cv2.calcOpticalFlowPyrLK(a, b, pts, None, winSize=(15, 15), maxLevel=2)+ ok = st.ravel() == 1+ if ok.sum() < 10:+ return None+ M, inl = cv2.estimateAffinePartial2D(pts[ok], nxt[ok], ransacReprojThreshold=2.0)+ if M is None or inl is None or float(inl.mean()) < 0.5:+ return None+ h, w = a.shape+ c = np.array([w / 2, h / 2, 1.0])+ moved = M @ c+ return (float(np.log(np.hypot(M[0, 0], M[1, 0]) + 1e-9)), float(np.degrees(np.arctan2(M[1, 0], M[0, 0]))),+ float((moved[0] - c[0]) / w), float((moved[1] - c[1]) / h))+++def _grad(t: np.ndarray) -> tuple[float, float]:+ g = _f(t)+ return float(np.abs(np.diff(g, axis=1)).mean()), float(np.abs(np.diff(g, axis=0)).mean())+++def _motion(T: list[np.ndarray], s: int, e: int) -> dict:+ """What moves and blurs inside the span: detail left at the blurriest frame (rx across, ry down, 1 = as+ sharp as outside), summed camera motion between consecutive frames (zoom as |log scale|, rot / turn in+ degrees, path and net travel as shares of the frame), and frames that swing back towards the old picture."""+ n = len(T)+ outside = [i for i in list(range(max(0, s - 6), s)) + list(range(e + 1, min(n, e + 7)))] or [s, e]+ gx0, gy0 = (float(np.median(v)) + 1e-6 for v in zip(*[_grad(T[i]) for i in outside]))+ g = [_grad(T[i]) for i in (list(range(s + 1, e)) or [s])]+ f = {"rx": min(v[0] for v in g) / gx0, "ry": min(v[1] for v in g) / gy0, "zoom": 0.0, "rot": 0.0, "turn": 0.0, "path": 0.0,+ "tracked": 0}+ net = np.zeros(2)+ for i in range(max(0, s - 1), min(n - 1, e + 1)):+ m = _similarity(T[i], T[i + 1])+ if m is None:+ continue+ f["tracked"] += 1+ f["zoom"] += abs(m[0])+ f["rot"] += abs(m[1])+ f["turn"] += m[1]+ f["path"] += float(np.hypot(m[2], m[3]))+ net += (m[2], m[3])+ f["net"] = float(np.hypot(*net))+ f["heading"] = ("left" if net[0] < 0 else "right") if abs(net[0]) > abs(net[1]) else ("up" if net[1] < 0 else "down")+ f["back"] = int((np.diff(progress(T, s, e, s, e)) < -0.25).sum())+ # hard switches inside the span: frames that differ from the one before by half of the whole change+ whole = _mad(T[s], T[e]) + 1e-6+ f["jumps"] = int(sum(_mad(T[m], T[m - 1]) > 0.5 * whole for m in range(s + 1, e + 1)))+ # soft on both sides of the switch (out of focus and back), not only running into it+ inside = list(range(s + 1, e)) or [s]+ half = max(1, len(inside) // 2)+ base = gx0 + gy0+ f["soft_both"] = (min(_detail(T[i]) for i in inside[:half]) < 0.6 * base+ and min(_detail(T[i]) for i in inside[half:] or inside[-1:]) < 0.6 * base)+ return f+++def _moving_kind(f: dict) -> dict | None:+ """Effects that hide the cut in camera movement: spin / zoom / whip / shake, and a glitch of several+ displaced frames."""+ calm = f["path"] < 0.3 and f["zoom"] < 0.3 and f["rot"] < 20+ # several hard switches with the picture swinging back to the old shot in between (two cuts in a row never go back)+ if (f["back"] >= 2 or (f["back"] >= 1 and f["jumps"] >= 2)) and calm:+ return {"type": "glitch"}+ if f["rot"] >= 25 and abs(f["turn"]) >= 0.7 * f["rot"]:+ return {"type": "spin"}+ if f["zoom"] >= 0.5:+ return {"type": "zoom"}+ if f["net"] >= 0.3 and f["path"] < 1.5 * f["net"] and min(f["rx"], f["ry"]) < 0.7:+ return {"type": "whip", "direction": f["heading"]}+ if f["path"] >= 0.4 and f["path"] > 3 * f["net"] and f["tracked"] >= 3:+ return {"type": "shake"}+ return None+++def classify(T: list[np.ndarray], s: int, e: int, fps: float, found_as: str) -> dict:+ """Kind of the transition over frames s..e (s: last old frame, e: first new frame). found_as: what the+ detector called the boundary (cut / jump / fade / dissolve / wipe / gradual)."""+ A, B = _f(T[s]), _f(T[e])+ inner = list(range(s + 1, e))+ if len(inner) < 2:+ return {"type": found_as if found_as != "gradual" else "cut"}+ pick = [inner[i] for i in np.unique(np.linspace(0, len(inner) - 1, num=min(9, len(inner))).astype(int))]+ mids = [_f(T[i]) for i in pick]+ flat = [M for M in mids if float(M.std()) < 8.0]+ level = float(np.mean([M.mean() for M in flat])) if flat else 128.0+ if flat and (level < 45 or level > 210) and float(A.std()) > 12 and float(B.std()) > 12:+ # a fade dims or bleaches the picture in place: the frames on the way are still the old shot (or already the+ # new one), only darker. A whip through a dark corner or a hand over the lens also passes through flat+ # frames, but the picture is gone before it gets there+ ramp = [M for M in mids if float(M.std()) >= 12.0]+ kept = sum(same_structure(M, A) or same_structure(M, B) for M in ramp)+ if not ramp or kept >= 0.5 * len(ramp) or found_as == "fade":+ return {"type": "fade", "via": "white" if level > 210 else "black"}+ elif found_as == "fade":+ return {"type": "fade", "via": "white" if level > 210 else "black"}+ peak = max(float(M.mean()) for M in mids)+ if e - s >= 0.15 * fps and peak > 170 and peak > max(float(A.mean()), float(B.mean())) + 50:+ return {"type": "flash"} # burns up to (near) white and the next shot comes out of it: a flash or light-leak transition+ if found_as in ("cut", "jump", "burst") and e - s < MIN_EFFECT_S * fps:+ return {"type": found_as if found_as != "burst" else "cut"} # too short for an editor's effect around a cut+ edge = _edge_fit(A, B, mids)+ resid, rising = _blend_fit(A, B, mids)++ def edged() -> dict:+ if edge["mode"] == "wipe":+ return {"type": "wipe", "direction": edge["direction"]}+ return {"type": "slide", "mode": edge["mode"], "direction": edge["direction"]}++ region = _region_fit(A, B, mids)+ iris = bool(region) and region["direction"] in ("center_out", "edges_in")+ if iris and not (edge and edge["resid"] < 0.1):+ return {"type": "wipe", "direction": region["direction"]} # grows from, or closes on, the middle: no straight edge does that+ if edge and edge["resid"] < 0.25 and edge["resid"] < 0.6 * resid:+ return edged() # a straight edge crossing the frame explains every in-between frame+ f = _motion(T, s, e)+ m = _moving_kind(f)+ if m:+ return m+ if max(f["rx"], f["ry"]) < 0.5 and f["soft_both"]:+ return {"type": "blur"} # detail gone in both directions, nothing travelling: out of focus and back+ if region: # every in-between frame is old or new block by block (in a dissolve the middle frames are neither)+ if edge and edge["resid"] < 0.8 * resid and not region["direction"]:+ return edged()+ return {"type": "wipe", **({"direction": region["direction"]} if region["direction"] else {})}+ if resid < 0.25 and rising and (not edge or resid <= edge["resid"]):+ return {"type": "dissolve"}+ if edge and edge["resid"] < 0.8 * resid:+ return edged()+ if f["back"] >= 1 and f["path"] < 0.3 and f["zoom"] < 0.3:+ return {"type": "glitch"}+ if flat or (min(f["rx"], f["ry"]) < 0.35 and f["soft_both"]):+ return {"type": "blur"} # down to a flat or smeared frame that is neither black nor white+ if found_as in ("cut", "jump", "dissolve", "wipe"):+ return {"type": found_as}+ return {"type": "cut" if found_as == "burst" else "effect"}+++TOUCH_GAP_S = 0.4 # two boundaries whose spans run into each other are one transition only when this close+BURST_GAP_S = 0.6 # cuts closer than this with the picture churning all the way between them are one effect+BURST_BUSY = 0.35 # ... churning: every frame in between differs from the one before by this share of the whole change+REPLACING = ("fade", "flash", "dissolve", "wipe", "slide") # the new picture replaces the old one with no cut needed+SPECIFIC = REPLACING + ("whip", "zoom", "spin", "blur", "glitch", "shake")+++def _one_move(T: list[np.ndarray], s: int, e: int) -> bool:+ """The picture gets from frame s to frame e in steps that are each a small warp of the one before: a push-in+ on a page, a pull back, a focus pull. Each step of a wipe or a dissolve brings in picture that was not+ there, which no warp explains."""+ picks = np.unique(np.linspace(s, e, num=min(8, e - s + 1)).astype(int))+ return all(_mad(T[i], T[j]) < 1.5 or motion_explains(_f(T[i]), _f(T[j])) for i, j in zip(picks, picks[1:]))+++def _burst_link(T: list[np.ndarray], fps: float, first: int, prev: int, b: int) -> bool:+ """Two hard cuts that may be one effect seen as several jumps (a fast slide, a glitch, a strobe of displaced+ frames): between two real cuts the picture holds still for at least a frame, inside an effect it never does."""+ if not 2 <= b - prev <= BURST_GAP_S * fps:+ return b - prev == 1+ whole = _mad(T[max(0, first - 1)], T[b]) + 1e-6+ return min(_mad(T[m], T[m - 1]) for m in range(prev + 1, b)) > BURST_BUSY * whole+++def resolve(T: list[np.ndarray], fps: float, boundaries: dict[int, tuple[str, float]],+ spans: dict[int, tuple[int, int]]) -> dict[int, tuple[dict, float]]:+ """Describe every boundary: {frame: ({"type", "start_frame", "end_frame", ...}, strength)}.+ - Boundaries that are parts of one transition become one (the several jumps of a fast slide or a glitch, the+ two sides of a fade through black, a cut found inside an effect that also shows as a ramp), but only when+ the joined span reads as a known kind of transition; otherwise they stay separate cuts.+ - A boundary that came from find_gradual (keys of `spans`) has no cut to stand on: it is kept only when its+ span reads as a fade, dissolve, wipe or slide. A push-in or a whip inside one take is camera work."""+ n = len(T)+ order = sorted(boundaries)+ items: list[dict] = []+ for i, b in enumerate(order):+ kind, strength = boundaries[b]+ lo = order[i - 1] if i else 0+ hi = order[i + 1] - 1 if i + 1 < len(order) else n - 1+ if kind in ("cut", "jump"):+ # boundaries right next to this one may be more jumps of the same effect, so the span may run past+ # them (and the shot's normal pace is read from beyond them); a boundary further away is another shot+ near = TOUCH_GAP_S * fps+ far_lo = max([o for o in order[:i] if b - o > near], default=0)+ far_hi = min([o for o in order[i + 1:] if o - b > near], default=n) - 1+ s, e = _active_span(T, b - 1, b, fps, far_lo, far_hi)+ else:+ s, e = spans.get(b) or span(T, b, fps, lo, hi, kind)+ items.append({"b": b, "kind": kind, "strength": strength, "s": max(0, s), "e": min(n - 1, e), "gradual": b in spans})+ chains: list[list[dict]] = []+ for it in items:+ if chains:+ c = chains[-1]+ p = c[-1]+ cuts = p["kind"] in ("cut", "jump") and it["kind"] in ("cut", "jump")+ burst = cuts and _burst_link(T, fps, c[0]["b"], p["b"], it["b"])+ touching = (it["s"] <= p["e"] + 1 and (p["e"] - p["s"] > 1 or it["e"] - it["s"] > 1)+ and it["b"] - p["b"] <= TOUCH_GAP_S * fps)+ flat = (not touching and 0 < it["s"] - p["e"] <= 2.5 * fps+ and all(float(T[k].std()) < 8.0 for k in range(p["e"], it["s"] + 1)))+ if burst or touching or flat:+ it["link"] = "flat" if flat else ("burst" if burst else "touching")+ c.append(it)+ continue+ chains.append([it])+ out: dict[int, tuple[dict, float]] = {}++ def emit(b: int, d: dict, s: int, e: int, strength: float) -> None:+ d.update(start_frame=min(s, b - 1), end_frame=max(e, b))+ out[b] = (d, strength)++ def takeover(d: dict, s: int, e: int, b: int) -> int:+ """Where the new shot starts: where its picture takes over; after a fade through a flat frame, where it comes up."""+ if e - s <= 2:+ return b+ if d["type"] == "fade":+ flat = [k for k in range(s, e + 1) if float(T[k].std()) < 8.0]+ return min(e, flat[-1] + 1) if flat else b+ return min(max(s + int(np.argmax(progress(T, s, e, s, e) >= 0.5)), s + 1), e)++ for ci, c in enumerate(chains):+ lo = chains[ci - 1][-1]["b"] if ci else 0+ hi = chains[ci + 1][0]["b"] - 1 if ci + 1 < len(chains) else n - 1+ if len(c) > 1:+ s, e = c[0]["s"], max(x["e"] for x in c)+ if any(x.get("link") == "burst" for x in c):+ s, e = _active_span(T, min(s, c[0]["b"] - 1), max(e, c[-1]["b"]), fps, lo, hi)+ s, e = max(s, lo), min(e, hi) # never across a neighbouring boundary+ through_flat = any(x.get("link") == "flat" for x in c) or any(x["kind"] == "fade" for x in c)+ ramps = any(x["kind"] not in ("cut", "jump") for x in c) # a gradual detector saw it too+ d = classify(T, s, e, fps, "fade" if through_flat else ("gradual" if ramps else "burst"))+ if d["type"] not in REPLACING + ("glitch",):+ # movement or blur hides one cut. Two hard switches are two cuts with a short shot between them+ # (a few dark, blurred frames of an insert look just like the middle of a blur transition)+ whole = _mad(T[s], T[e]) + 1e-6+ if sum(_mad(T[m], T[m - 1]) > 0.5 * whole for m in range(s + 1, e + 1)) >= 2:+ d = {"type": "cut"}+ if d["type"] in SPECIFIC:+ b = takeover(d, s, e, c[-1]["b"])+ emit(b, d, s, e, max(x["strength"] for x in c))+ continue+ for k, x in enumerate(c): # on its own+ lo = c[k - 1]["b"] if k else (chains[ci - 1][-1]["b"] if ci else 0)+ hi = c[k + 1]["b"] - 1 if k + 1 < len(c) else (chains[ci + 1][0]["b"] - 1 if ci + 1 < len(chains) else n - 1)+ d = classify(T, x["s"], x["e"], fps, x["kind"])+ if x["gradual"] and (d["type"] not in REPLACING or (d["type"] in ("wipe", "dissolve") and _one_move(T, x["s"], x["e"]))):+ continue+ # the span may have run past a neighbouring boundary that turned out to be its own cut: report the part+ # on this side of it+ x["s"], x["e"] = min(max(x["s"], lo), x["b"] - 1), max(min(x["e"], hi), x["b"])+ if d["type"] not in SPECIFIC and x["kind"] in ("cut", "jump") and x["e"] - x["s"] > 1:+ x["s"], x["e"] = x["b"] - 1, x["b"] # a cut in a busy stretch: nothing to say about the frames around it+ emit(x["b"], d, x["s"], x["e"], x["strength"])+ return outdiff --git a/rea_video/videomd.py b/rea_video/videomd.pyindex 1058fdb..3fd1dba 100644--- a/rea_video/videomd.py+++ b/rea_video/videomd.py@@ -34,7 +34,9 @@ MAP_BLOCK = "videomd-map"DECIDED_BY = {"deterministic": "tools", "fused": "model", "fused_agent": "agent", "user": "human"}OVERLAY_ID = {"huazi": "styled_text"}# shot-boundary kinds from the cut detector -> transition ids in the spec; plain cuts are not written-TRANSITION_ID = {"jump": "jump_cut", "fade": "fade_through", "dissolve": "dissolve", "wipe": "wipe", "flash": "flash"}+TRANSITION_ID = {"jump": "jump_cut", "fade": "fade_through", "dissolve": "dissolve", "wipe": "wipe", "flash": "flash",+ "slide": "slide", "whip": "whip_pan", "zoom": "zoom", "spin": "spin", "blur": "blur", "glitch": "glitch",+ "shake": "shake", "effect": "effect"}# timeline keys, in line order; `~` = inferred by the toolsKEYS = ("story", "seen", "layers", "camera", "transition", "overlay", "made~", "material~", "remake", "flag")@@ -85,7 +87,19 @@ def _shot_name(i: int) -> str:# ------------------------------------------------------------------ timeline (the spine) --------------------------_TRANSITION_WORDS = {"jump_cut": ("跳切", "jump cut"), "fade_through": ("黑场/白场过渡", "fade through"), "dissolve": ("叠化", "dissolve"),- "wipe": ("划像", "wipe"), "flash": ("闪白", "flash")}+ "wipe": ("划像", "wipe"), "flash": ("闪白", "flash"), "slide": ("推移", "slide"), "whip_pan": ("甩镜", "whip pan"),+ "zoom": ("缩放转场", "zoom"), "spin": ("旋转转场", "spin"), "blur": ("模糊转场", "blur"), "glitch": ("故障转场", "glitch"),+ "shake": ("抖动转场", "shake"), "effect": ("转场特效", "transition effect")}+++def _transition_in(r: dict) -> dict:+ """The spec's transition_in for a shot record: type, and length / direction when measured; {} for a plain cut."""+ tid = TRANSITION_ID.get(r.get("transition_in") or "cut")+ if not tid:+ return {}+ tr = r.get("transition") or {}+ return {"type": tid, **({"duration": tr["duration"]} if tr.get("duration") else {}),+ **{k: tr[k] for k in ("direction", "via", "mode") if tr.get(k)}}def timeline_line(r: dict, roles: dict, units: dict) -> str:@@ -102,7 +116,8 @@ def timeline_line(r: dict, roles: dict, units: dict) -> str:f["camera"] = CAMERA_ZH.get((r.get("features") or {}).get("camera", "unknown"), "—")trans = TRANSITION_ID.get(r.get("transition_in") or "cut")if trans:- f["transition"] = T(*_TRANSITION_WORDS[trans])+ dur = (r.get("transition") or {}).get("duration")+ f["transition"] = T(*_TRANSITION_WORDS[trans]) + (f" {dur:.1f}s" if dur and dur >= 0.1 else "")if _layers(r) != "—":f["overlay"] = _layers(r)made = f"{base['label_zh']} {base['confidence']:.0%}"@@ -153,7 +168,7 @@ def _shot_file(r: dict) -> str:"alternatives": dict([(k, v) for k, v in probs if k != base["label"] and v > 0][:2]),"decided_by": DECIDED_BY.get(base["decided_by"], base["decided_by"]), "real_material": bool((r.get("material") or {}).get("has_real_material"))},"flags": [k for k in ("uncertain", "disputed") if base.get(k)] + (["low_confidence"] if base["confidence"] < 0.6 and base["decided_by"] != "user" else []),- **({"transition_in": {"type": TRANSITION_ID[r["transition_in"]]}} if TRANSITION_ID.get(r.get("transition_in") or "cut") else {}),+ **({"transition_in": _transition_in(r)} if _transition_in(r) else {}),"frames": {k: v for k, v in (("sheet", assets.get("sheet")), ("first", assets.get("first_frame")), ("last", assets.get("last_frame"))) if v},}title = T("# 镜头 {i} · {a}–{z}s · {v}", "# Shot {i} · {a}–{z}s · {v}", i=r["index"], a=f"{r['start']:.1f}", z=f"{r['end']:.1f}", v=r.get("verdict", ""))diff --git a/scripts/bench_speakers.py b/scripts/bench_speakers.pynew file mode 100644index 0000000..e999cb7--- /dev/null+++ b/scripts/bench_speakers.py@@ -0,0 +1,128 @@+"""Speaker benchmark: build a conversation with known turns out of single-speaker videos and score the speaker split.++ python3 scripts/bench_speakers.py a.mp4 b.mp4 c.mp4 --out /tmp/sb [--music bgm.mp4] [--overlap 0.4]++Each input must be one person talking (a talking head, a voice-over). Their dry voices are cut into turns of+2-7 s and dealt out in turn; with --music a music bed is laid under the result and the vocal stem is separated+again, as the pipeline does. Reports the number of speakers found and the share of speech time given to the+wrong speaker (best one-to-one mapping between found and true speakers)."""+from __future__ import annotations++import argparse+import itertools+import json+import subprocess+import sys+from pathlib import Path++import numpy as np++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from rea_video import speakers # noqa: E402+from rea_video.stems import SR, load_stereo, save_wav, separate # noqa: E402+++def dry_voice(video: str, out: Path, seconds: float) -> np.ndarray:+ f = out / f"{Path(video).stem}_voice.wav"+ if not f.is_file():+ clip = out / f"{Path(video).stem}_src.wav"+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-ss", "5", "-t", str(seconds), "-i", video, "-vn", "-ac", "2", "-ar", str(SR),+ str(clip)], check=True)+ save_wav(separate(load_stereo(clip))[0], f)+ return load_stereo(f)+++def main_turns(voice_wav: Path) -> list[tuple[float, float]]:+ """Stretches of the main speaker of a single-speaker source (stray voices in it are left out)."""+ r = speakers.diarize(voice_wav)+ if not r.get("ok") or not r["speakers"]:+ return []+ main = max(r["speakers"], key=lambda s: s["seconds"])["id"]+ return [(t["start"], t["end"]) for t in r["turns"] if t["speaker"] == main and t["end"] - t["start"] >= 2.0]+++def score(truth: list[tuple[float, float, int]], found: list[dict], step: float = 0.02) -> dict:+ end = max([b for _, b, _ in truth] + [t["end"] for t in found] + [0.0])+ n = int(end / step) + 1+ names = sorted({t["speaker"] for t in found})+ k_true = max(s for _, _, s in truth) + 1+ T = np.zeros((k_true, n), bool)+ F = np.zeros((max(1, len(names)), n), bool)+ for a, b, s in truth:+ T[s, int(a / step):int(b / step)] = True+ for t in found:+ F[names.index(t["speaker"]), int(t["start"] / step):int(t["end"] / step)] = True+ solo = T.sum(0) == 1 # scored where exactly one person speaks+ best = 0+ for perm in itertools.permutations(range(max(k_true, len(F))), k_true):+ hit = sum(int((T[i] & F[j] & solo).sum()) for i, j in enumerate(perm) if j < len(F))+ best = max(best, hit)+ spoken = int(solo.sum()) or 1+ return {"true_speakers": k_true, "found_speakers": len(names), "wrong_or_missed": round(1 - best / spoken, 3),+ "false_speech_s": round(float((F.any(0) & ~T.any(0)).sum() * step), 2)}+++def main() -> None:+ ap = argparse.ArgumentParser()+ ap.add_argument("videos", nargs="+")+ ap.add_argument("--out", required=True)+ ap.add_argument("--music", default="", help="a video or audio file whose sound is laid under the conversation")+ ap.add_argument("--music-db", type=float, default=-8.0, help="music level relative to the voices")+ ap.add_argument("--seconds", type=float, default=70.0, help="how much of each source to use")+ ap.add_argument("--overlap", type=float, default=0.0, help="seconds by which each turn starts before the last one ends")+ ap.add_argument("--seed", type=int, default=0)+ args = ap.parse_args()+ out = Path(args.out)+ out.mkdir(parents=True, exist_ok=True)+ rng = np.random.default_rng(args.seed)+ voices, pools = [], []+ for v in args.videos:+ voices.append(dry_voice(v, out, args.seconds))+ turns = []+ for a, b in main_turns(out / f"{Path(v).stem}_voice.wav"):+ while b - a >= 2.0: # pieces of 2-7 s+ d = min(b - a, float(rng.uniform(2.0, 7.0)))+ turns.append((a, a + d))+ a += d+ pools.append(turns)+ print(f"{Path(v).stem}: {len(turns)} turns")+ rounds = min(len(p) for p in pools)+ assert rounds >= 2, "a source has too little clean speech"+ total = sum(b - a + 0.7 for p in pools for a, b in p[:rounds]) + 2+ mix = np.zeros((2, int(total * SR)), np.float32)+ truth: list[tuple[float, float, int]] = []+ t = 0.5+ for r in range(rounds):+ for s in rng.permutation(len(pools)):+ a, b = pools[s][r]+ piece = voices[s][:, int(a * SR):int(b * SR)]+ start = max(0.0, t - (args.overlap if truth else 0.0))+ i = int(start * SR)+ mix[:, i:i + piece.shape[1]] += piece+ truth.append((start, start + piece.shape[1] / SR, int(s)))+ t = start + piece.shape[1] / SR + (0.0 if args.overlap else float(rng.uniform(0.1, 0.6)))+ mix = mix[:, :int((t + 0.5) * SR)]+ target = out / "conversation.wav"+ if args.music:+ src = out / "music_src.wav"+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-stream_loop", "-1", "-i", args.music, "-t", f"{mix.shape[1] / SR:.2f}", "-vn",+ "-ac", "2", "-ar", str(SR), str(src)], check=True)+ bed = load_stereo(src)[:, :mix.shape[1]]+ gain = 10 ** (args.music_db / 20) * float(np.sqrt(np.mean(mix ** 2))) / (float(np.sqrt(np.mean(bed ** 2))) + 1e-9)+ full = mix.copy()+ full[:, :bed.shape[1]] += bed * gain+ save_wav(full, out / "conversation_mix.wav")+ save_wav(separate(full)[0], target) # what the pipeline hears: the vocal stem of the mix+ else:+ save_wav(mix, target)+ got = speakers.diarize(target)+ assert got.get("ok"), got+ res = score(truth, got["turns"])+ res["speakers"] = [(s["id"], s["seconds"], s.get("f0_median_hz")) for s in got["speakers"]]+ (out / "truth.json").write_text(json.dumps({"truth": truth, "found": got["turns"]}, indent=1))+ print(json.dumps(res, ensure_ascii=False))+++if __name__ == "__main__":+ main()diff --git a/scripts/bench_transitions.py b/scripts/bench_transitions.pynew file mode 100644index 0000000..9ee1979--- /dev/null+++ b/scripts/bench_transitions.py@@ -0,0 +1,251 @@+"""Transition benchmark: join real shots with known transitions and check what the cut detector reports.++ python3 scripts/bench_transitions.py a.mp4 b.mp4 c.mp4 --out out/bench_transitions --pairs 5++Source shots are taken from the given videos (stretches without a cut). Each case is A (hold) -> transition+(0.3 / 0.6 / 1.0 s) -> B (hold). Editor transitions come from ffmpeg's xfade filter; whip pans, spins, zoom+punches, glitches and shakes are composed here. A case passes detection when exactly one boundary is found+and it sits inside the transition; it passes typing when the reported kind is the expected family."""+from __future__ import annotations++import argparse+import json+import pickle+import subprocess+import sys+from collections import defaultdict+from pathlib import Path++import cv2+import numpy as np++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from rea_video.media import video_info # noqa: E402+from rea_video.shots import build_track, detect_shots # noqa: E402++W, H, FPS = 360, 640, 30+HOLD = 2.0++XFADE = {+ "dissolve": ["fade", "fadefast", "fadeslow", "fadegrays", "dissolve"],+ "fade": ["fadeblack", "fadewhite"],+ "wipe": ["wipeleft", "wiperight", "wipeup", "wipedown", "smoothleft", "smoothup", "circleopen", "circleclose", "vertopen",+ "horzclose", "radial", "diagtl", "diagbr", "wipetl", "rectcrop", "circlecrop", "hlslice", "vuslice", "hlwind",+ "coverleft", "coverup", "revealright", "revealdown"],+ "slide": ["slideleft", "slideright", "slideup", "slidedown", "squeezeh", "squeezev"],+ "zoom": ["zoomin"],+ "blur": ["hblur", "pixelize", "distance"],+}+CUSTOM = ["whip_left", "whip_up", "spin", "zoom_punch", "glitch", "shake", "blur"]+CUSTOM_FAMILY = {"whip_left": "whip", "whip_up": "whip", "spin": "spin", "zoom_punch": "zoom", "glitch": "glitch", "shake": "shake",+ "blur": "blur"}+# kinds the detector may report for each family and still be right; a few effects sit between two families+ACCEPT = {"dissolve": {"dissolve"}, "fade": {"fade"}, "wipe": {"wipe"}, "slide": {"slide"}, "zoom": {"zoom"}, "blur": {"blur"},+ "whip": {"whip"}, "spin": {"spin"}, "glitch": {"glitch"}, "shake": {"shake"}}+ACCEPT_KIND = {"coverleft": {"slide", "wipe"}, "coverup": {"slide", "wipe"}, "revealright": {"slide", "wipe"},+ "revealdown": {"slide", "wipe"}, "squeezeh": {"slide", "wipe"}, "squeezev": {"slide", "wipe"},+ "rectcrop": {"wipe", "fade"}, "circlecrop": {"wipe", "fade"}, # the old shot closes down to black first+ "distance": {"dissolve", "blur", "effect"}, "pixelize": {"blur", "dissolve", "effect"}, "hblur": {"blur", "effect"},+ "zoomin": {"zoom", "effect"}}+++STEADY = 14.0 # largest change (mean |difference| of 12x16 block means) allowed between frames 0.3 s apart in a source shot+++def source_shots(path: str, n: int, need: int) -> list[np.ndarray]:+ """Up to n stretches of `need` frames without a cut, as [need, H, W, 3] uint8 (centre-cropped to 9:16).+ Only steady stretches are used: when the shot itself lurches (a fight, a whip, a caption card popping in)+ there is no telling where the added transition starts or ends, for a viewer or for the detector."""+ info = video_info(path)+ track = build_track(path, info)+ shots = detect_shots(track)+ fps = info.fps or 30.0+ small = [cv2.resize(t, (12, 16), interpolation=cv2.INTER_AREA).astype(np.float32) for t in track.thumbs]+ k = max(1, int(round(0.3 * fps)))++ def steady(s) -> bool:+ a = s.start_frame + int(round(0.25 * fps))+ z = min(len(small) - k, a + int(round(need / FPS * fps)))+ return z > a and max(float(np.abs(small[i] - small[i + k]).mean()) for i in range(a, z)) <= STEADY++ long = [s for s in shots if s.duration >= need / FPS + 0.6 and steady(s)]+ picks = long[:: max(1, len(long) // n)][:n]+ out = []+ for s in picks:+ r = subprocess.run(["ffmpeg", "-v", "error", "-ss", f"{s.start + 0.25:.3f}", "-i", path, "-frames:v", str(need), "-r", str(FPS),+ "-vf", f"scale={W}:{H}:force_original_aspect_ratio=increase,crop={W}:{H}", "-f", "rawvideo",+ "-pix_fmt", "bgr24", "-"], capture_output=True)+ a = np.frombuffer(r.stdout, np.uint8)+ if len(a) >= need * H * W * 3:+ out.append(a[:need * H * W * 3].reshape(need, H, W, 3).copy())+ return out+++def pairs_from(videos: list[str], n: int, need: int) -> list[tuple[np.ndarray, np.ndarray]]:+ """n pairs of shots that are different pictures, taking the videos in turn."""+ per = [source_shots(v, n, need) for v in videos]+ pool = [s for i in range(n) for shots in per for s in shots[i:i + 1]]+ pairs = []+ while len(pool) >= 2 and len(pairs) < n:+ a = pool.pop(0)+ small = cv2.resize(a[0], (48, 85)).astype(np.float32)+ j = next((j for j, b in enumerate(pool) if np.abs(cv2.resize(b[0], (48, 85)).astype(np.float32) - small).mean() > 25), None)+ if j is not None:+ pairs.append((a, pool.pop(j)))+ assert len(pairs) == n, f"only {len(pairs)} pairs of different shots in the source videos"+ return pairs+++def write(frames, path: Path) -> None:+ p = subprocess.Popen(["ffmpeg", "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "bgr24", "-s", f"{W}x{H}", "-r", str(FPS),+ "-i", "-", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", str(path)], stdin=subprocess.PIPE)+ for f in frames:+ p.stdin.write(np.ascontiguousarray(f).tobytes())+ p.stdin.close()+ p.wait()+++def xfade(a: np.ndarray, b: np.ndarray, kind: str, d: int, tmp: Path, out: Path) -> None:+ hold = int(HOLD * FPS)+ write(a[:hold + d], tmp / "a.mp4")+ write(b[:hold + d], tmp / "b.mp4")+ subprocess.run(["ffmpeg", "-v", "error", "-y", "-i", str(tmp / "a.mp4"), "-i", str(tmp / "b.mp4"), "-filter_complex",+ f"[0:v][1:v]xfade=transition={kind}:duration={d / FPS:.4f}:offset={HOLD:.4f},format=yuv420p", "-c:v", "libx264",+ "-crf", "18", str(out)], check=True)+++def _shift(img: np.ndarray, dx: float, dy: float) -> np.ndarray:+ return np.roll(img, (int(round(dy)), int(round(dx))), axis=(0, 1))+++def _mblur(img: np.ndarray, dx: float, dy: float) -> np.ndarray:+ k = int(max(abs(dx), abs(dy)))+ if k < 2:+ return img+ ker = np.zeros((k, k), np.float32)+ if abs(dx) >= abs(dy):+ ker[k // 2, :] = 1 / k+ else:+ ker[:, k // 2] = 1 / k+ return cv2.filter2D(img, -1, ker)+++def _ease(u: float) -> float:+ return u * u * (3 - 2 * u)+++def custom(a: np.ndarray, b: np.ndarray, kind: str, d: int) -> list[np.ndarray]:+ hold = int(HOLD * FPS)+ frames = list(a[:hold])+ rng = np.random.default_rng(d)+ for k in range(d):+ u = (k + 0.5) / d+ src = a[hold + k] if u < 0.5 else b[k]+ if kind in ("whip_left", "whip_up"):+ # the picture streaks away, the cut hides in the blur, the next shot streaks in and settles+ speed = np.sin(np.pi * u) * (W if kind == "whip_left" else H) * 0.9 / max(1, d / 6)+ pos = (_ease(u) - (0 if u < 0.5 else 1)) * (W if kind == "whip_left" else H) * 1.5+ dx, dy = (-pos, 0) if kind == "whip_left" else (0, -pos)+ sx, sy = (speed, 0) if kind == "whip_left" else (0, speed)+ f = _mblur(_shift(src, dx, dy), sx, sy)+ elif kind == "spin":+ ang = (_ease(u) - (0 if u < 0.5 else 1)) * 180+ M = cv2.getRotationMatrix2D((W / 2, H / 2), ang, 1.0 + 0.6 * np.sin(np.pi * u))+ f = cv2.warpAffine(src, M, (W, H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT)+ f = cv2.GaussianBlur(f, (0, 0), 0.5 + 4 * np.sin(np.pi * u))+ elif kind == "zoom_punch":+ s = 1 + 2.5 * _ease(u * 2) if u < 0.5 else 3.5 - 2.5 * _ease(u * 2 - 1)+ if u >= 0.5:+ s = 1 + (s - 1) * 0.6+ M = cv2.getRotationMatrix2D((W / 2, H / 2), 0, s)+ f = cv2.warpAffine(src, M, (W, H), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT)+ f = cv2.GaussianBlur(f, (0, 0), 0.5 + 3 * np.sin(np.pi * u))+ elif kind == "glitch":+ src = a[hold + k] if rng.random() > u else b[k]+ f = src.copy()+ for _ in range(6): # displaced slices and split colour channels+ y0 = int(rng.integers(0, H - 40))+ hh = int(rng.integers(10, 60))+ f[y0:y0 + hh] = np.roll(f[y0:y0 + hh], int(rng.integers(-60, 60)), axis=1)+ f[..., 2] = np.roll(f[..., 2], int(rng.integers(4, 14)), axis=1)+ f[..., 0] = np.roll(f[..., 0], -int(rng.integers(4, 14)), axis=1)+ elif kind == "shake":+ amp = 40 * np.sin(np.pi * u)+ f = _shift(src, rng.normal(0, amp), rng.normal(0, amp))+ f = cv2.GaussianBlur(f, (0, 0), 0.5 + 1.5 * np.sin(np.pi * u))+ else: # blur: defocus out of A, cut, focus in on B+ f = cv2.GaussianBlur(src, (0, 0), 0.5 + 14 * np.sin(np.pi * u))+ frames.append(f)+ frames += list(b[d:d + hold])+ return frames+++def main() -> None:+ ap = argparse.ArgumentParser()+ ap.add_argument("videos", nargs="+")+ ap.add_argument("--out", required=True)+ ap.add_argument("--pairs", type=int, default=3)+ ap.add_argument("--durations", default="0.3,0.6,1.0")+ ap.add_argument("--only", default="", help="comma-separated transition names")+ ap.add_argument("--reuse", action="store_true", help="keep clips already rendered in --out")+ ap.add_argument("--verbose", action="store_true")+ args = ap.parse_args()+ out = Path(args.out)+ out.mkdir(parents=True, exist_ok=True)+ durs = [int(round(float(x) * FPS)) for x in args.durations.split(",")]+ need = int(HOLD * FPS) + max(durs) + 2+ only = set(filter(None, args.only.split(",")))+ cases = [(fam, k, True) for fam, ks in XFADE.items() for k in ks] + [(CUSTOM_FAMILY[k], k, False) for k in CUSTOM]+ cases = [c for c in cases if not only or c[1] in only]+ shots = None+ hold = int(HOLD * FPS)+ rows = []+ for p in range(args.pairs):+ for fam, kind, is_x in cases:+ for d in durs:+ f = out / f"{kind}_{d}_{p}.mp4"+ if not (args.reuse and f.is_file()):+ if shots is None:+ shots = pairs_from(args.videos, args.pairs, need)+ a, b = shots[p]+ if is_x:+ xfade(a, b, kind, d, out, f)+ else:+ write(custom(a, b, kind, d), f)+ cache = f.with_suffix(".track")+ if args.reuse and cache.is_file() and cache.stat().st_mtime >= f.stat().st_mtime:+ track = pickle.loads(cache.read_bytes())+ else:+ track = build_track(str(f), video_info(str(f)))+ cache.write_bytes(pickle.dumps(track))+ found = detect_shots(track)[1:]+ inside = [s for s in found if hold - 2 <= s.start_frame <= hold + d + 2]+ ok = len(found) == 1 and len(inside) == 1+ got = inside[0].transition_in if inside else (found[0].transition_in if found else "none")+ tr = (inside[0].to_dict().get("transition") or {}) if inside else {}+ rows.append({"family": fam, "kind": kind, "frames": d, "pair": p, "found": len(found), "detected": ok, "got": got,+ "typed": ok and got in ACCEPT_KIND.get(kind, ACCEPT[fam]), "at": [s.start_frame - hold for s in found],+ "span": [round(tr["start"] - HOLD, 2), round(tr["end"] - HOLD, 2)] if tr.get("end") else None,+ "direction": tr.get("direction")})+ (out / "results.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1))+ by = defaultdict(list)+ for r in rows:+ by[r["family"]].append(r)+ print(f"{'family':10} {'cases':>5} {'found':>6} {'typed':>6}")+ for fam, rs in by.items():+ print(f"{fam:10} {len(rs):5d} {sum(r['detected'] for r in rs) / len(rs):6.2f} {sum(r['typed'] for r in rs) / len(rs):6.2f}")+ print(f"{'all':10} {len(rows):5d} {sum(r['detected'] for r in rows) / len(rows):6.2f} {sum(r['typed'] for r in rows) / len(rows):6.2f}")+ bad = defaultdict(list)+ for r in rows:+ if not r["typed"]:+ bad[r["kind"]].append(f"{r['frames']}f:{r['got']}x{r['found']}")+ if args.verbose:+ for r in rows:+ print(r)+ for k, v in bad.items():+ print(f" {k}: {' '.join(v)}")+++if __name__ == "__main__":+ main()diff --git a/skills/rea-video/references/audio.md b/skills/rea-video/references/audio.mdindex 1be60f4..090f141 100644--- a/skills/rea-video/references/audio.md+++ b/skills/rea-video/references/audio.md@@ -25,11 +25,22 @@| `original.wav` | 原声(视频里的完整混音) || `vocals.wav` | 人声干声:旁白、口播、歌声。注意:键盘声、"叮"之类的瞬态音效也会落在这里 || `music.wav` | 配乐 + 环境声 |+| `voice_S1.wav`、`voice_S2.wav` … | 有两个以上说话人时,每人一条:人声干声里只留这个人说话的段落,长度和原片一致 |模型是 UVR MDX-Net Inst HQ 3(ONNX,CPU 即可,首次运行从 GitHub 下载约 67 MB,缓存在 `~/.cache/rea-video/models`,可用 `REA_VIDEO_MODELS` 改位置)。实测 TTS + Suno BGM 混音分离 SDR 约 19.7 dB;纯 BGM 漏进人声轨 −42 dB。约 0.6 倍实时(4 核)。复核时**直接听 vocals.wav 和 music.wav**,比听混音容易判断:人声是唱还是说、是不是 TTS,配乐有没有人声、结尾是不是被截断。+### 说话人++装了 `rea-video[asr]` 时,`decompose` 在人声干声上分出谁在什么时候说话,结果在 `breakdown.json` 的 `speakers`:++- `speakers`:每个声音(`S1`、`S2`…,按出场顺序)的秒数、占比、基频和男 / 女声提示;只出现几秒的标 `minor`。+- `turns`:每一段的起止时间和说话人;`overlaps`:两人同时说话的时间段。+- 台词 `speech.lines` 每句带 `speaker`;开了 VLM 时角色名按时间对到声音上(`name`)。++音色很像的两个人可能被并成一个,同一个人换语气可能被拆成两个:人数要紧时听每个人的音轨确认。`--no-speakers` 可跳过。+## 来源判断:AI 生成还是现成的?**一句话结论**在 `sound_sources.summary_zh`,格式是"视频类型 → 人声 / 音乐 / 音效来源":diff --git a/skills/rea-video/references/setup.md b/skills/rea-video/references/setup.mdindex 96186f8..5d46a57 100644--- a/skills/rea-video/references/setup.md+++ b/skills/rea-video/references/setup.md@@ -26,6 +26,7 @@ pip install "rea-video[ocr,asr] @ git+https://github.com/JuneYaooo/rea-video"装了之后 `decompose` 会自动在分离出的人声干声上识别(SenseVoice,中 / 英 / 日 / 韩 / 粤;首次使用下载约 160 MB 模型到 `$REA_VIDEO_MODELS`,默认 `~/.cache/rea-video/models`),一分钟的片子几秒钟。结果在 `breakdown.json` 的 `speech.lines`(每句有起止时间),报告「脚本」表和 `review_tasks.json` 每镜的 `said` 会用它。`--no-asr` 可跳过。+同一个可选包还会分出说话人(另下约 35 MB 模型):多人对话时台词带上是谁说的,并给每人输出一条音轨,见 `audio.md`。这是机器听写,会有同音错字、专有名词听错:画面上有字幕时以字幕为准,VLM 给了台词时报告用 VLM 的;引用台词给用户时注明"语音识别,未校对"。长句里逐句的时间是按字数估的(`timing: estimated`),整段的起止是测出来的。没装时 `speech.reason` 是 `not_installed`,其余照常。diff --git a/skills/rea-video/references/taxonomy.md b/skills/rea-video/references/taxonomy.mdindex 6fc9dcd..5c17c3e 100644--- a/skills/rea-video/references/taxonomy.md+++ b/skills/rea-video/references/taxonomy.md@@ -136,4 +136,23 @@- 短镜头:两刀干净的硬切之间、画面稳定的镜头,最短保留 0.12 秒(快剪插入、开头封面帧);更近的几处边界属于同一个转场,保留最强的一处。- 交叉溶解:中间帧是两端帧的线性混合(α 在 0.2–0.8,残差 <0.2),并用光流排除推拉运动。- 淡入淡出:亮度降到极暗或极亮再回来。+- 没有硬切的转场:前面一段画面稳定、中间一段过渡、后面一段画面稳定,两端是不同的画面,且中间能解释成淡入淡出 / 叠化 / 划像 / 推移,才算一处边界。同一个场景只是变亮变暗、镜头内的推近和摇移不算。+- 黑边和上下固定的横幅先裁掉再量,黑边里的画面转场不会被黑边稀释。++**转场类型**(每镜的 `transition`:`type`、起止时间 `start` / `end`、`duration`,有方向的带 `direction`)++| type | 画面上是什么 | 怎么认 |+|---|---|---|+| `fade` | 经黑场 / 白场(`via`) | 中间有纯黑或纯白的平帧,前后是同一画面变暗变亮 |+| `flash` | 闪白、漏光烧白后露出新画面 | 中间亮到接近全白但不是平帧;或切进来第一帧很亮、随后回落 |+| `dissolve` | 叠化 | 每个中间帧都是两端的线性混合 |+| `wipe` | 划像(直边、圆形、百叶、时钟) | 逐块看,每块不是旧画面就是新画面,新画面的面积一路变大;`direction` 是边缘走的方向,`center_out` / `edges_in` 是圆形开合 |+| `slide` | 推移(`mode`:`push` 新旧一起动,`cover` 新画面滑入,`reveal` 旧画面滑走) | 中间帧能用两端画面按一条直边平移拼出来 |+| `whip` | 甩镜:快速摇移加运动模糊,切点藏在模糊里 | 硬切前后画面朝一个方向大幅平移,细节被抹掉 |+| `zoom` / `spin` | 缩放 / 旋转冲进下一镜 | 硬切前后逐帧估出的缩放量或旋转角很大 |+| `blur` | 虚焦再对回来 | 硬切两侧的细节都明显少于镜头平时 |+| `glitch` | 故障:错位、新旧画面来回闪 | 区间内有多次硬跳,且画面跳回过旧镜头 |+| `shake` | 切点前后一阵抖动 | 逐帧位移很大但来回抵消 |++甩镜、缩放、旋转、模糊、抖动只在硬切周围认:没有硬切的同类运动是镜头内的运镜。- MG 节拍:长镜头内"定格 → 动画 → 定格",两个定格内容差异超过 12%,记为镜头内节拍,不算切镜。diff --git a/tests/test_speakers.py b/tests/test_speakers.pynew file mode 100644index 0000000..973fd2c--- /dev/null+++ b/tests/test_speakers.py@@ -0,0 +1,106 @@+"""Speaker separation: grouping, merging, turn bookkeeping and how the result reaches the script and the report.+No model is loaded: voices are made-up unit vectors."""+import numpy as np++from rea_video import speakers+from rea_video.entities import script+from rea_video.report import _speakers_md+from rea_video.speech import SR, _by_speaker+++def _voice(axis: int, rng, spread: float = 0.12, dim: int = 16) -> np.ndarray:+ v = rng.normal(0, spread, dim)+ v[axis] += 1.0+ return (v / np.linalg.norm(v)).astype(np.float32)+++def test_pieces_of_three_voices_group_into_three():+ rng = np.random.default_rng(0)+ truth = [0, 1, 2, 0, 1, 2, 0, 0, 1, 2, 2, 1] * 3+ V = np.stack([_voice(k, rng) for k in truth])+ labels = speakers._settle(V, speakers.group_pieces(V))+ assert len(set(labels.tolist())) == 3+ for k in range(3): # every true voice sits in one group+ assert len({labels[i] for i, t in enumerate(truth) if t == k}) == 1+ # a named head count is honoured+ assert len(set(speakers.group_pieces(V, k=2).tolist())) == 2+++def test_one_voice_split_three_ways_is_merged_step_by_step_and_a_stray_moment_folded():+ # voice A arrives as three groups (0, 1, 2): 0-1 and 1-2 sound alike, 0-2 only after the first merge+ # voice B is group 3; group 4 is 0.8 s of something nearer to B than to anything else+ turns = [(0, 6, 0), (6, 12, 1), (12, 18, 2), (18, 30, 3), (30, 30.8, 4), (31, 37, 0)]+ base = {0: [1.0, 0.0, 0.0], 1: [0.8, 0.6, 0.0], 2: [0.45, 0.9, 0.0], 3: [0.0, 0.0, 1.0], 4: [0.0, 0.5, 0.86]}++ def measure(ranges):+ if not ranges:+ return None+ groups = {s for a, b, s in turns for x, y in ranges if a <= x and y <= b}+ v = np.sum([base[g] for g in groups], axis=0).astype(np.float32)+ return v / np.linalg.norm(v)++ out = speakers.regroup(turns, measure)+ assert len({s for _, _, s in out}) == 2+ assert len({s for a, _, s in out if a < 18 or a >= 31}) == 1 # all of A together+ assert {s for a, _, s in out if a == 30} == {s for a, _, s in out if a == 18} # the stray moment went to B+ # asked for a fixed number of speakers: nothing is merged+ assert speakers.regroup(turns, measure, fixed=True) == turns+++def test_turns_are_numbered_by_first_appearance_and_joined_across_short_gaps():+ turns = speakers._tidy([(5.0, 7.0, 9), (0.0, 2.0, 4), (2.2, 4.0, 4), (7.0, 7.1, 4), (6.5, 9.0, 4)])+ assert [(t["speaker"], t["start"], t["end"]) for t in turns] == [("S1", 0.0, 4.0), ("S2", 5.0, 7.0), ("S1", 6.5, 9.0)]+ assert speakers.overlaps(turns) == [[6.5, 7.0]]+ assert speakers.speaker_at(turns, 5.0, 6.4) == "S2" and speakers.speaker_at(turns, 20, 21) == ""+ # one stretch of speech 3.0-8.0 holds a change of speaker: cut in the middle of the gap between the turns+ assert speakers.change_points(turns[:2], 3.0, 8.0) == [4.5]+ assert speakers.change_points(turns[:2], 3.0, 4.6) == [] # the second piece would be too short to recognise+++def test_speech_is_cut_at_the_speaker_change():+ turns = [{"start": 0.0, "end": 2.0, "speaker": "S1"}, {"start": 2.0, "end": 5.0, "speaker": "S2"}]+ stretch = (0.0, np.zeros(5 * SR, np.float32))+ pieces = _by_speaker([stretch], turns)+ assert [(round(t, 2), len(x)) for t, x in pieces] == [(0.0, 2 * SR), (2.0, 3 * SR)]+ assert _by_speaker([stretch], None) == [stretch]+++def test_voices_take_the_names_a_viewer_gave_them():+ who = {"speakers": [{"id": "S1"}, {"id": "S2"}, {"id": "S3"}],+ "turns": [{"start": 0, "end": 4, "speaker": "S1"}, {"start": 4, "end": 9, "speaker": "S2"},+ {"start": 9, "end": 10, "speaker": "S3"}, {"start": 10, "end": 14, "speaker": "S1"}]}+ lines = [{"start": 0, "end": 4, "speaker": "店主", "text": "a"}, {"start": 4, "end": 9, "speaker": "顾客", "text": "b"},+ {"start": 9, "end": 10.2, "speaker": "顾客", "text": "c"}, {"start": 10.2, "end": 14, "speaker": "店主", "text": "d"}]+ speakers.name_speakers(who, lines)+ assert [sp.get("name") for sp in who["speakers"]] == ["店主", "顾客", None] # 顾客 is taken by the voice it fits best+++def _breakdown() -> dict:+ return {"speakers": {"ok": True, "count": 2, "tracks": {"S1": "voice_S1.wav", "S2": "voice_S2.wav"}, "overlaps": [[3.8, 4.1]],+ "speakers": [{"id": "S1", "seconds": 8.0, "share": 0.62, "turns": 2, "first": 0.0, "f0_median_hz": 120.0,+ "gender_hint": "male"},+ {"id": "S2", "seconds": 5.0, "share": 0.38, "turns": 1, "first": 4.0, "name": "顾客"}],+ "turns": [{"start": 0, "end": 4, "speaker": "S1"}, {"start": 4, "end": 9, "speaker": "S2"},+ {"start": 9, "end": 13, "speaker": "S1"}]},+ "speech": {"ok": True, "lines": [{"start": 0.2, "end": 3.9, "text": "欢迎光临", "speaker": "S1"},+ {"start": 4.1, "end": 8.8, "text": "这个怎么卖", "speaker": "S2"}]}}+++def test_script_and_report_name_the_separated_voices():+ b = _breakdown()+ rows = script(b)+ assert [(r["speaker"], r["voice"]) for r in rows] == [("说话人 1", "S1"), ("顾客", "S2")]+ md = "\n".join(_speakers_md(b))+ assert "2 个声音" in md and "stems/voice_S1.wav" in md and "顾客" in md and "同时说话" in md+ # a VLM script keeps its own names and gains the voice id+ b["whole_video_vlm"] = {"narration": {"lines": [{"start": 0.0, "end": 4.0, "speaker": "店主", "text": "欢迎光临"}]}}+ assert script(b) == [{"start": 0.0, "end": 4.0, "speaker": "店主", "text": "欢迎光临", "voice": "S1"}]+ # one voice only: nothing to tell apart, nothing printed+ b["speakers"]["speakers"] = b["speakers"]["speakers"][:1]+ b["speakers"]["count"] = 1+ assert _speakers_md(b) == [] and "voice" not in script({**b, "whole_video_vlm": {}})[0]+++def test_diarize_without_the_extra_says_so(monkeypatch, tmp_path):+ monkeypatch.setattr(speakers, "available", lambda: False)+ assert speakers.diarize(tmp_path / "none.wav") == {"ok": False, "reason": "not_installed"}diff --git a/tests/test_transitions.py b/tests/test_transitions.pynew file mode 100644index 0000000..e740642--- /dev/null+++ b/tests/test_transitions.py@@ -0,0 +1,173 @@+"""Transitions: what kind, which way, how long; and the cases that must stay one shot."""+import cv2+import numpy as np++from rea_video import transitions+from rea_video.media import video_info+from rea_video.report import transition_text+from rea_video.shots import build_track, detect_shots+from rea_video.videomd import _transition_in+from tests.conftest import _photo_like, _write++W, H, FPS = 360, 640, 30+++def _drift(img: np.ndarray, t: int) -> np.ndarray:+ return np.roll(img, t // 3, axis=1) # slow camera drift+++def _two(seed: int) -> tuple[np.ndarray, np.ndarray]:+ a = _photo_like(W, H, seed)+ b = np.clip(_photo_like(W, H, seed + 1).astype(np.int16) + 45, 0, 255).astype(np.uint8) # another shot, another tone+ return a, b+++def _clip(a: np.ndarray, b: np.ndarray, middle: list[np.ndarray], hold: int = 60) -> list[np.ndarray]:+ """a drifting up to where the transition frames pick it up, the transition, b drifting on."""+ return [_drift(a, t - hold) for t in range(hold)] + middle + [_drift(b, t) for t in range(hold)]+++def _shots(frames, tmp_path, name: str):+ p = str(_write(frames, tmp_path / f"{name}.mp4", FPS))+ return detect_shots(build_track(p, video_info(p)))+++def test_push_slide_has_kind_direction_and_length(tmp_path):+ a, b = _two(41)+ mid = []+ for k in range(1, 13): # 0.4 s: both pictures travel left, the new one coming in from the right+ d = int(W * k / 13)+ mid.append(np.concatenate([a[:, d:], b[:, :d]], axis=1))+ shots = _shots(_clip(a, b, mid), tmp_path, "push")+ assert len(shots) == 2+ tr = shots[1].to_dict()["transition"]+ assert tr["type"] == "slide" and tr["mode"] == "push" and tr["direction"] == "left"+ assert 0.25 <= tr["duration"] <= 0.6 and 1.9 <= tr["start"] <= 2.1+ assert "推移" in transition_text(tr) and "向左" in transition_text(tr)+ assert _transition_in(shots[1].to_dict())["type"] == "slide"+++def test_iris_wipe_opens_from_the_centre(tmp_path):+ a, b = _two(43)+ yy, xx = np.mgrid[0:H, 0:W]+ rad = np.hypot(xx - W / 2, yy - H / 2)+ mid = [np.where((rad < rad.max() * k / 16)[..., None], b, a) for k in range(1, 16)]+ shots = _shots(_clip(a, b, mid), tmp_path, "iris")+ assert len(shots) == 2 and shots[1].transition_in == "wipe"+ assert shots[1].transition.get("direction") == "center_out"+++def test_fade_through_black_is_one_transition(tmp_path):+ a, b = _two(45)+ black = np.zeros_like(a)+ mid = [cv2.addWeighted(a, 1 - k / 8, black, k / 8, 0) for k in range(1, 8)] + [black] * 5 \+ + [cv2.addWeighted(b, k / 8, black, 1 - k / 8, 0) for k in range(1, 8)]+ shots = _shots(_clip(a, b, mid), tmp_path, "fade")+ assert len(shots) == 2 and shots[1].transition_in == "fade" and shots[1].transition["via"] == "black"+ assert shots[1].to_dict()["transition"]["duration"] >= 0.4+++def test_whip_pan_hides_the_cut(tmp_path):+ a, b = _two(47)+ mid = []+ for k in range(12): # the old shot streaks off to the left, the new one streaks in and settles+ u = (k + 0.5) / 12+ src, pos = (a, u * u * 4 * W * 0.6) if u < 0.5 else (b, -(1 - u) ** 2 * 4 * W * 0.6)+ f = np.roll(src, -int(pos), axis=1)+ n = max(3, int(60 * np.sin(np.pi * u)))+ mid.append(cv2.blur(f, (n, 1)))+ shots = _shots(_clip(a, b, mid), tmp_path, "whip")+ assert len(shots) == 2 and shots[1].transition_in == "whip"+++def test_dissolve_inside_a_letterboxed_picture(tmp_path):+ a, b = _two(49)+ bar = int(H * 0.32)++ def boxed(f: np.ndarray) -> np.ndarray:+ g = f.copy()+ g[:bar] = 0+ g[H - bar:] = 0+ return g++ mid = [cv2.addWeighted(a, 1 - k / 16, b, k / 16, 0) for k in range(1, 16)]+ frames = [boxed(f) for f in _clip(a, b, mid)]+ p = str(_write(frames, tmp_path / "boxed.mp4", FPS))+ track = build_track(p, video_info(p))+ y0, y1, _, _ = transitions.crop_box(track.thumbs)+ h = track.thumbs[0].shape[0]+ assert 0.25 * h < y0 < 0.4 * h and 0.6 * h < y1 < 0.75 * h # the bars are left out+ shots = detect_shots(track)+ assert len(shots) == 2 and shots[1].transition_in == "dissolve"+ assert 0.3 <= shots[1].to_dict()["transition"]["duration"] <= 0.7+++def test_plain_cut_carries_no_transition_details(tmp_path):+ a, b = _two(51)+ shots = _shots(_clip(a, b, []), tmp_path, "cut")+ assert len(shots) == 2 and shots[1].transition_in == "cut" and "transition" not in shots[1].to_dict()+ assert _transition_in(shots[1].to_dict()) == {}+++def test_light_change_and_a_hold_pan_hold_stay_one_shot(tmp_path):+ a = _photo_like(W * 2, H, 53)+ # the lamp comes up over half a second: same scene, brighter+ lit = [np.clip(a[:, :W].astype(np.float32) * (1 + 0.6 * min(1.0, max(0.0, (t - 50) / 15))), 0, 255).astype(np.uint8)+ for t in range(120)]+ assert len(_shots(lit, tmp_path, "lamp")) == 1+ # hold, a slow pan across the same wide picture, hold: movement, not a new shot+ pan = [a[:, :W]] * 40 + [a[:, 4 * t:4 * t + W] for t in range(1, 40)] + [a[:, 160:160 + W]] * 40+ assert len(_shots(pan, tmp_path, "pan")) == 1+++def test_edge_composition_directions():+ a = np.zeros((8, 10), np.float32)+ b = np.ones((8, 10), np.float32)+ left = transitions._compose(a, b, "wipe", "left", 3) # the edge travels left: the new picture grows from the right+ assert left[:, :7].sum() == 0 and left[:, 7:].all()+ down = transitions._compose(a, b, "wipe", "down", 2) # the edge travels down: the new picture grows from the top+ assert down[:2].all() and down[2:].sum() == 0+ ramp = np.tile(np.arange(10, dtype=np.float32), (8, 1))+ push = transitions._compose(ramp, ramp + 100, "push", "left", 4)+ assert push[0].tolist() == [4, 5, 6, 7, 8, 9, 100, 101, 102, 103]+++def test_push_in_on_a_page_stays_one_shot(tmp_path):+ page = np.full((H * 3, W * 3, 3), 245, np.uint8)+ rng = np.random.default_rng(5)+ for _ in range(140): # a page of blocks and lines+ x, y = int(rng.integers(0, W * 3 - 120)), int(rng.integers(0, H * 3 - 40))+ cv2.rectangle(page, (x, y), (x + int(rng.integers(30, 120)), y + int(rng.integers(8, 40))),+ tuple(int(c) for c in rng.integers(30, 220, 3)), -1)++ def view(scale: float) -> np.ndarray:+ w, h = int(W * 3 / scale), int(H * 3 / scale)+ x0, y0 = (W * 3 - w) // 2, (H * 3 - h) // 2+ return cv2.resize(page[y0:y0 + h, x0:x0 + w], (W, H), interpolation=cv2.INTER_AREA)++ frames = [view(1.0)] * 45 + [view(1.0 + 1.6 * k / 18) for k in range(1, 18)] + [view(2.6)] * 45+ assert len(_shots(frames, tmp_path, "pushin")) == 1+++def test_still_background_is_not_a_border():+ rng = np.random.default_rng(7)+ back = cv2.resize(rng.integers(0, 255, (20, 12)).astype(np.uint8), (96, 170), interpolation=cv2.INTER_CUBIC)+ thumbs = []+ for t in range(60): # one shot: only a small figure moves in front of a still, detailed background+ f = back.copy()+ cv2.circle(f, (40 + t // 4, 80), 12, 255, -1)+ thumbs.append(f)+ assert transitions.crop_box(thumbs) == (0, 170, 0, 96)+ boxed = [np.pad(f[40:130], ((40, 40), (0, 0))) for f in thumbs] # the same picture between plain black bars+ y0, y1, _, _ = transitions.crop_box(boxed)+ assert (y0, y1) == (40, 130)+++def test_a_labelled_cut_inside_a_transition_counts_as_found():+ from rea_video.evaluate import boundary_f1++ # the detector puts a half-second wipe at 10.0 (9.8-10.3); the labeller marked 10.25+ assert boundary_f1([10.0], [10.25])["tp"] == 0+ assert boundary_f1([10.0], [10.25], spans=[(9.8, 10.3)])["tp"] == 1+ assert boundary_f1([10.0, 12.0], [10.25, 12.05], spans=[(9.8, 10.3), None]) | {} == {+ "precision": 1.0, "recall": 1.0, "f1": 1.0, "tp": 2, "fp": 0, "fn": 0}