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
Add Bengali speech recognition (#41)
MD. DANIAL DIRAR8186ee0b948e
diff --git a/docs/cli.md b/docs/cli.mdindex e6c41bc..78b5a74 100644--- a/docs/cli.md+++ b/docs/cli.md@@ -92,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] [--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` 跳过 |+| `decompose VIDEO [--vlm] [--no-ocr] [--ocr-lang zh\|ja] [--lang zh\|en] [--no-packaging] [--max-vlm-shots N] [--no-asr] [--asr-lang auto\|bn] [--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` 跳过;台词是孟加拉语时加 `--asr-lang bn`,换用孟加拉语识别模型(SenseVoice 不认孟加拉语,会听成英/日/韩文;首次使用自动下载约 90 MB 到 `$REA_VIDEO_MODELS`),`rea-video prefs asr_lang bn` 可设成默认 || `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/rea_video/cli.py b/rea_video/cli.pyindex 70547d6..96ce083 100644--- a/rea_video/cli.py+++ b/rea_video/cli.py@@ -7,7 +7,7 @@ import osimport sysfrom pathlib import Path-from .util import LOG, OCR_LANGS, load_env_files, read_json, setup_logging, read_image+from .util import ASR_LANGS, LOG, OCR_LANGS, load_env_files, read_json, setup_logging, read_imagefrom .i18n import LANGS, T, set_langfrom .classify import LABELSfrom .vlm import vlm_note@@ -45,6 +45,17 @@ def _ocr_lang(args) -> None:os.environ["REA_OCR_LANG"] = lang+def _asr_lang(args) -> None:+ """--asr-lang (or prefs asr_lang) -> $REA_ASR_LANG, which speech.transcribe reads."""+ from .memory import pref++ lang = getattr(args, "asr_lang", None) or pref("asr_lang")+ if lang:+ if lang not in ASR_LANGS:+ raise SystemExit(f"错误:不支持的语音识别语言 {lang}(可选:{', '.join(ASR_LANGS)})")+ os.environ["REA_ASR_LANG"] = lang++def _check_vlm_config() -> None:"""Fail fast on a misconfigured VLM: a typo in REA_VLM_MEDIA must not silently run text-only."""from .vlm import VLMConfig@@ -59,6 +70,7 @@ def cmd_decompose(args) -> int:from .pipeline import decompose_ocr_lang(args)+ _asr_lang(args)out = Path(args.out) if args.out else Path("out") / Path(args.video).stemfrom .memory import pref@@ -585,6 +597,7 @@ def main(argv: list[str] | None = None) -> int:d.add_argument("--engine", help="复刻方案按哪个视频模型规划(rea-video models 列出的 id;默认 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("--asr-lang", choices=ASR_LANGS, help="台词的语言:auto(默认,SenseVoice 自动识别中/英/日/韩/粤)、bn 孟加拉语(换用孟加拉语识别模型,首次使用自动下载约 90 MB);也可用 prefs asr_lang 设成默认")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/memory.py b/rea_video/memory.pyindex 1884d4c..5798d2b 100644--- a/rea_video/memory.py+++ b/rea_video/memory.py@@ -18,7 +18,7 @@ from pathlib import Pathfrom .classify import LABEL_ZH, LABELS, topfrom .i18n import T, semi-from .util import OCR_LANGS+from .util import ASR_LANGS, OCR_LANGSPREF_KEYS = {"engine": "复刻计划默认的视频引擎(decompose / remake-plan 的 --engine)",@@ -27,6 +27,7 @@ PREF_KEYS = {"stems": "decompose 是否默认做人声/配乐分离:on / off","reviewer": "apply-review 默认的复核者名字","ocr_lang": "字幕/花字 OCR 的语言:zh(中英,默认)/ ja(日文,首次使用自动下载约 10 MB 识别模型)",+ "asr_lang": "本地语音识别的语言:auto(SenseVoice 自动识别中/英/日/韩/粤,默认)/ bn(孟加拉语,首次使用自动下载约 90 MB 识别模型)","capsule_root": "capsule-cinema 仓库位置(remake-plan / remake-run / capsule-draft 的 --capsule-root;也可设 $CAPSULE_CINEMA_ROOT)","lang": "报告和结论的语言:zh(默认)/ en;agent 应按用户提问的语言选,用户明确指定时以指定为准",}@@ -59,6 +60,8 @@ def set_pref(key: str, value: str | None) -> dict:raise ValueError(f"{key} 只能是 on / off")if value is not None and key == "ocr_lang" and value not in OCR_LANGS:raise ValueError(f"ocr_lang 只能是 {' / '.join(OCR_LANGS)}")+ if value is not None and key == "asr_lang" and value not in ASR_LANGS:+ raise ValueError(f"asr_lang 只能是 {' / '.join(ASR_LANGS)}")if value is not None and key in ("env_file", "capsule_root"):value = str(Path(value).expanduser().resolve())prefs = load_prefs()diff --git a/rea_video/speech.py b/rea_video/speech.pyindex 869eb3d..c818186 100644--- a/rea_video/speech.py+++ b/rea_video/speech.py@@ -6,6 +6,9 @@ detector cuts the track into spoken stretches first, so every line has a start adownloaded on first use. Run it on the separated vocal stem when there is one: music under the voice is whatmakes a recognizer invent words.+SenseVoice has no Bengali: it hears Bengali as English, Japanese or Korean and writes nonsense in those. `--asr-lang bn`+($REA_ASR_LANG) swaps in a Bengali streaming zipformer (about 90 MB, from Vosk) behind the same voice-activity cuts.+The text is a machine transcript. On-screen subtitles and a VLM's transcript outrank it wherever they exist."""from __future__ import annotations@@ -21,7 +24,7 @@ import numpy as npfrom .media import extract_audiofrom .stems import models_dir-from .util import LOG, fetch, sha256_file+from .util import ASR_LANGS, LOG, fetch, sha256_fileSR = 16000BASE_URL = "https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models"@@ -33,16 +36,27 @@ VAD_SHA256 = "9e2449e1087496d8d4caba907f23e0bd3f78d91fa552479bb9c23ac09cbb1fd6"MAX_SENTENCE_S = 6.0 # a longer stretch is shown sentence by sentenceMAX_LINE_S = 12.0 # a stretch of speech longer than this is split, so one line stays one subtitle-sized thoughtLANGS = ("zh", "en", "ja", "ko", "yue")+# --asr-lang bn: a streaming zipformer converted from Vosk's small Bengali model (alphacep/vosk-model-small-streaming-bn)+BN_MODEL_DIR = "sherpa-onnx-streaming-zipformer-bn-vosk-2026-02-09"+BN_ARCHIVE_SHA256 = "1bc89d81ee33ba7ddef8454736aeeb55e3cc1593274272485c6da342202b4b18"+BN_MODEL_FILES = ("encoder.onnx", "decoder.onnx", "joiner.onnx", "tokens.txt")+TAIL_PAD_S = 0.66 # silence fed after a stretch: a streaming encoder holds back its last frames until it sees what followsdef available() -> bool:return importlib.util.find_spec("sherpa_onnx") is not None-def ensure_models() -> tuple[Path, Path, Path]:- """-> (recognizer model, tokens, vad model), downloading and checking them on first use."""+def asr_lang() -> str:+ """Speech language: $REA_ASR_LANG (set by --asr-lang / prefs asr_lang), default auto."""+ lang = os.getenv("REA_ASR_LANG", "auto").strip().lower() or "auto"+ if lang not in ASR_LANGS:+ raise ValueError(f"unsupported speech language {lang!r} (choose from {', '.join(ASR_LANGS)})")+ return lang+++def _ensure_vad() -> Path:root = models_dir()- d = root / MODEL_DIRvad = root / VAD_NAMEroot.mkdir(parents=True, exist_ok=True)if not (vad.is_file() and sha256_file(vad) == VAD_SHA256):@@ -54,18 +68,25 @@ def ensure_models() -> tuple[Path, Path, Path]:tmp.replace(vad)finally:tmp.unlink(missing_ok=True)- if not all((d / f).is_file() for f in MODEL_FILES):- LOG.info("downloading speech model %s (~160 MB) -> %s", MODEL_DIR, d)- arc = root / f"{MODEL_DIR}.{os.getpid()}.{uuid.uuid4().hex[:8]}.part"- stage = root / f"{MODEL_DIR}.{os.getpid()}.{uuid.uuid4().hex[:8]}.tmp"+ return vad+++def _ensure_archive(model_dir: str, archive_sha256: str, files: tuple[str, ...], size: str) -> Path:+ """models_dir()/model_dir holding `files` from the release archive model_dir.tar.bz2, downloaded and checked once."""+ root = models_dir()+ d = root / model_dir+ if not all((d / f).is_file() for f in files):+ LOG.info("downloading speech model %s (~%s) -> %s", model_dir, size, d)+ arc = root / f"{model_dir}.{os.getpid()}.{uuid.uuid4().hex[:8]}.part"+ stage = root / f"{model_dir}.{os.getpid()}.{uuid.uuid4().hex[:8]}.tmp"try:- fetch(f"{BASE_URL}/{MODEL_DIR}.tar.bz2", arc, timeout=120)- if sha256_file(arc) != ARCHIVE_SHA256:- raise OSError(f"checksum mismatch for {MODEL_DIR}.tar.bz2")+ fetch(f"{BASE_URL}/{model_dir}.tar.bz2", arc, timeout=120)+ if sha256_file(arc) != archive_sha256:+ raise OSError(f"checksum mismatch for {model_dir}.tar.bz2")stage.mkdir()with tarfile.open(arc, "r:bz2") as tar:- for name in MODEL_FILES: # only the two files needed, written under our own names: no archive path is trusted- src = tar.extractfile(f"{MODEL_DIR}/{name}")+ for name in files: # only the files needed, written under our own names: no archive path is trusted+ src = tar.extractfile(f"{model_dir}/{name}")if src is None:raise OSError(f"{name} missing from the model archive")with open(stage / name, "wb") as f:@@ -82,9 +103,22 @@ def ensure_models() -> tuple[Path, Path, Path]:for f in stage.iterdir():f.unlink()stage.rmdir()+ return d+++def ensure_models() -> tuple[Path, Path, Path]:+ """-> (recognizer model, tokens, vad model), downloading and checking them on first use."""+ vad = _ensure_vad()+ d = _ensure_archive(MODEL_DIR, ARCHIVE_SHA256, MODEL_FILES, "160 MB")return d / MODEL_FILES[0], d / MODEL_FILES[1], vad+def ensure_bn_models() -> tuple[Path, Path]:+ """-> (folder with the Bengali zipformer's encoder / decoder / joiner / tokens, vad model)."""+ vad = _ensure_vad()+ return _ensure_archive(BN_MODEL_DIR, BN_ARCHIVE_SHA256, BN_MODEL_FILES, "90 MB"), vad++def _stretches(x: np.ndarray, vad_model: Path) -> list[tuple[float, np.ndarray]]:"""Spoken stretches of a 16 kHz mono track: (start second, samples)."""import sherpa_onnx@@ -157,8 +191,24 @@ def _sentences(start: float, end: float, text: str) -> list[dict]:return out-def transcribe(audio: str | Path, language: str = "auto", threads: int = 2, turns: list[dict] | None = None) -> dict:+def _decode(rec, samples: np.ndarray, streaming: bool) -> tuple[str, str]:+ """One spoken stretch -> (text, language heard; empty when the recognizer does not say)."""+ st = rec.create_stream()+ st.accept_waveform(SR, samples)+ if streaming:+ st.accept_waveform(SR, np.zeros(int(TAIL_PAD_S * SR), dtype=np.float32))+ st.input_finished()+ while rec.is_ready(st):+ rec.decode_stream(st)+ return (rec.get_result(st) or "").strip(), ""+ rec.decode_stream(st)+ return (st.result.text or "").strip(), str(getattr(st.result, "lang", "") or "").strip("<|>")+++def transcribe(audio: str | Path, language: str | None = None, 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.+ language: None follows --asr-lang ($REA_ASR_LANG, default auto); "bn" is the Bengali model, anything else is a hint+ for SenseVoice ("auto" lets it detect each line).turns: who speaks when (speakers.diarize). A stretch of speech is then cut where the speaker changes, so twopeople answering each other without a pause become two lines, and every line carries its "speaker"."""if not available():@@ -169,15 +219,21 @@ def transcribe(audio: str | Path, language: str = "auto", threads: int = 2, turntry:import sherpa_onnx- model, tokens, vad_model = ensure_models()- rec = 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 "")+ lang = language or asr_lang()+ if lang == "bn":+ d, vad_model = ensure_bn_models()+ rec = sherpa_onnx.OnlineRecognizer.from_transducer(+ tokens=str(d / "tokens.txt"), encoder=str(d / "encoder.onnx"), decoder=str(d / "decoder.onnx"),+ joiner=str(d / "joiner.onnx"), num_threads=threads, sample_rate=SR, feature_dim=80)+ engine = "zipformer-bn-vosk (sherpa-onnx)"+ else:+ model, tokens, vad_model = ensure_models()+ rec = sherpa_onnx.OfflineRecognizer.from_sense_voice(model=str(model), tokens=str(tokens), num_threads=threads, use_itn=True,+ language=lang if lang in LANGS else "")+ engine = "sensevoice-small-int8 (sherpa-onnx)"lines, langs = [], []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()+ text, heard = _decode(rec, samples, streaming=lang == "bn")if len(text.strip("。,、!?.,!? ")) < 1:continuegot = _sentences(start, start + len(samples) / SR, text)@@ -187,11 +243,10 @@ def transcribe(audio: str | Path, language: str = "auto", threads: int = 2, turnwho = speaker_at(turns, start, start + len(samples) / SR)got = [dict(ln, speaker=who) for ln in got] if who else gotlines += got- lang = str(getattr(st.result, "lang", "") or "").strip("<|>")- if lang:- langs.append(lang)+ if heard:+ langs.append(heard)except Exception as exc: # offline on first use, a broken wheel: the breakdown goes on without a transcriptLOG.warning("speech recognition failed: %s", str(exc)[:200])return {"ok": False, "reason": f"{type(exc).__name__}: {str(exc)[:120]}"}- return {"ok": True, "engine": "sensevoice-small-int8 (sherpa-onnx)", "language": max(set(langs), key=langs.count) if langs else "",+ return {"ok": True, "engine": engine, "language": "bn" if lang == "bn" else (max(set(langs), key=langs.count) if langs else ""),"lines": lines}diff --git a/rea_video/util.py b/rea_video/util.pyindex bc78c44..75725a9 100644--- a/rea_video/util.py+++ b/rea_video/util.py@@ -10,6 +10,7 @@ from typing import Any, IterableLOG = logging.getLogger("rea_video")OCR_LANGS = ("zh", "ja") # subtitle/huazi OCR languages; zh is the bundled recognizer, others are in overlay._REC_MODELS+ASR_LANGS = ("auto", "bn") # speech recognition: auto is SenseVoice (zh/en/ja/ko/yue, detected per line); bn is speech.BN_MODEL_DIRdef setup_logging(verbose: bool = False) -> None:diff --git a/skills/rea-video/SKILL.md b/skills/rea-video/SKILL.mdindex 7e63578..b9fb037 100644--- a/skills/rea-video/SKILL.md+++ b/skills/rea-video/SKILL.md@@ -32,7 +32,7 @@ VLM(能看图的多模态模型)建议配,不强制,配置方法也在 `# ⓪ 先看记住了什么:用户偏好(默认引擎、是否开 VLM、给你的偏好说明)和常见纠正类型rea-video memory# ① 拆解(产出 out/<名>/VIDEO.md + video/(给你读的拆片包)、report.html / report.md(给用户看)、breakdown.json、storyboard.jpg、audio.png、shots/、stems/)-rea-video --env-file <你的 .env> decompose ref.mp4 -o out/ref --vlm --lang <zh|en> # --lang 按用户提问的语言选(见「交付给用户」);没有 VLM 配置就去掉 --env-file 和 --vlm;字幕/花字是日文就加 --ocr-lang ja+rea-video --env-file <你的 .env> decompose ref.mp4 -o out/ref --vlm --lang <zh|en> # --lang 按用户提问的语言选(见「交付给用户」);没有 VLM 配置就去掉 --env-file 和 --vlm;字幕/花字是日文就加 --ocr-lang ja;台词是孟加拉语就加 --asr-lang bn# ② 看紧凑摘要:低置信镜头会被标出;先看 VLM: 那一行确认 VLM 是否生效rea-video summary out/ref/breakdown.json```diff --git a/skills/rea-video/references/setup.md b/skills/rea-video/references/setup.mdindex 5d46a57..e84f57e 100644--- a/skills/rea-video/references/setup.md+++ b/skills/rea-video/references/setup.md@@ -26,6 +26,8 @@ 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` 可跳过。+台词是孟加拉语时加 `--asr-lang bn`(或 `rea-video prefs asr_lang bn` 设成默认):SenseVoice 不认孟加拉语,会把它听成英 / 日 / 韩文的乱码;+`bn` 换用孟加拉语的流式识别模型(另下约 90 MB),`speech.language` 是 `bn`,识别出的句子不带标点。同一个可选包还会分出说话人(另下约 35 MB 模型):多人对话时台词带上是谁说的,并给每人输出一条音轨,见 `audio.md`。这是机器听写,会有同音错字、专有名词听错:画面上有字幕时以字幕为准,VLM 给了台词时报告用 VLM 的;引用台词给用户时注明"语音识别,未校对"。diff --git a/tests/test_asr_lang.py b/tests/test_asr_lang.pynew file mode 100644index 0000000..56e4526--- /dev/null+++ b/tests/test_asr_lang.py@@ -0,0 +1,152 @@+"""--asr-lang bn: the Bengali streaming model is chosen, checked, unpacked and decoded; auto stays SenseVoice."""+import hashlib+import io+import os+import sys+import tarfile+import types++import numpy as np+import pytest++from rea_video import speech+++def fake_sherpa(monkeypatch, tmp_path):+ """sherpa_onnx stand-in: records which recognizer is built and what each stream is fed."""+ made, streams = [], []++ class Stream:+ def __init__(self):+ self.fed, self.finished, self.decoded = [], False, False+ self.result = types.SimpleNamespace(text="", lang="")++ def accept_waveform(self, sr, samples):+ self.fed.append(len(samples))++ def input_finished(self):+ self.finished = True++ class OnlineRecognizer:+ @classmethod+ def from_transducer(cls, **kwargs):+ made.append(("online", kwargs))+ return cls()++ def create_stream(self):+ streams.append(Stream())+ return streams[-1]++ def is_ready(self, st):+ return st.finished and not st.decoded++ def decode_stream(self, st):+ st.decoded = True++ def get_result(self, st):+ return " আমি ভাত খাই " if st.decoded else ""++ class OfflineRecognizer:+ @classmethod+ def from_sense_voice(cls, **kwargs):+ made.append(("offline", kwargs))+ return cls()++ def create_stream(self):+ streams.append(Stream())+ return streams[-1]++ def decode_stream(self, st):+ st.result = types.SimpleNamespace(text="大家好", lang="<|zh|>")++ monkeypatch.setitem(sys.modules, "sherpa_onnx", types.SimpleNamespace(OnlineRecognizer=OnlineRecognizer,+ OfflineRecognizer=OfflineRecognizer))+ monkeypatch.setattr(speech, "available", lambda: True)+ monkeypatch.setattr(speech, "extract_audio", lambda audio, sr: np.zeros(sr * 3, np.float32))+ monkeypatch.setattr(speech, "_stretches", lambda x, vad: [(0.5, np.zeros(speech.SR * 2, np.float32))])+ monkeypatch.setattr(speech, "ensure_bn_models", lambda: (tmp_path / "bn", tmp_path / "vad.onnx"))+ monkeypatch.setattr(speech, "ensure_models", lambda: (tmp_path / "sv.onnx", tmp_path / "tokens.txt", tmp_path / "vad.onnx"))+ return made, streams+++def test_default_language_is_auto(monkeypatch):+ monkeypatch.delenv("REA_ASR_LANG", raising=False)+ assert speech.asr_lang() == "auto"+++def test_unknown_language_is_rejected(monkeypatch):+ monkeypatch.setenv("REA_ASR_LANG", "hi")+ with pytest.raises(ValueError):+ speech.asr_lang()+++def test_bn_uses_the_bengali_streaming_model(monkeypatch, tmp_path, fake_sherpa):+ made, streams = fake_sherpa+ monkeypatch.setenv("REA_ASR_LANG", "bn")+ res = speech.transcribe(tmp_path / "x.wav")+ assert res == {"ok": True, "engine": "zipformer-bn-vosk (sherpa-onnx)", "language": "bn",+ "lines": [{"start": 0.5, "end": 2.5, "text": "আমি ভাত খাই"}]}+ kind, kwargs = made[0]+ assert kind == "online" and len(made) == 1+ assert {k: kwargs[k] for k in ("tokens", "encoder", "decoder", "joiner")} == {+ n: str(tmp_path / "bn" / f"{n}{'.txt' if n == 'tokens' else '.onnx'}") for n in ("tokens", "encoder", "decoder", "joiner")}+ # the stretch, then silence so the streaming encoder lets go of its last frames, then end of input+ assert streams[0].fed == [speech.SR * 2, int(speech.TAIL_PAD_S * speech.SR)] and streams[0].finished+++def test_auto_keeps_sensevoice_and_an_explicit_language_wins(monkeypatch, tmp_path, fake_sherpa):+ made, _ = fake_sherpa+ monkeypatch.delenv("REA_ASR_LANG", raising=False)+ res = speech.transcribe(tmp_path / "x.wav")+ assert res["engine"] == "sensevoice-small-int8 (sherpa-onnx)" and res["language"] == "zh" and res["lines"][0]["text"] == "大家好"+ assert made[-1][0] == "offline" and made[-1][1]["language"] == ""+ assert speech.transcribe(tmp_path / "x.wav", language="bn")["language"] == "bn" and made[-1][0] == "online"+++def _archive(files: dict) -> bytes:+ buf = io.BytesIO()+ with tarfile.open(fileobj=buf, mode="w:bz2") as tar:+ for name, data in files.items():+ info = tarfile.TarInfo(name)+ info.size = len(data)+ tar.addfile(info, io.BytesIO(data))+ return buf.getvalue()+++def test_bengali_model_is_checked_and_only_the_needed_files_are_unpacked(monkeypatch, tmp_path):+ monkeypatch.setenv("REA_VIDEO_MODELS", str(tmp_path))+ d = speech.BN_MODEL_DIR+ arc = _archive({**{f"{d}/{n}": n.encode() for n in speech.BN_MODEL_FILES},+ f"{d}/test_wavs/0.wav": b"wav", f"{d}/bpe.model": b"bpe", "../escape.txt": b"x"})+ served = {speech.VAD_NAME: b"vad", f"{d}.tar.bz2": arc}+ monkeypatch.setattr(speech, "fetch", lambda url, dst, timeout=60: open(dst, "wb").write(served[url.rsplit("/", 1)[-1]]))+ monkeypatch.setattr(speech, "VAD_SHA256", hashlib.sha256(b"vad").hexdigest())+ with pytest.raises(OSError): # the archive does not match the pinned checksum+ speech.ensure_bn_models()+ assert sorted(p.name for p in tmp_path.iterdir()) == [speech.VAD_NAME]+ monkeypatch.setattr(speech, "BN_ARCHIVE_SHA256", hashlib.sha256(arc).hexdigest())+ model, vad = speech.ensure_bn_models()+ assert sorted(p.name for p in model.iterdir()) == sorted(speech.BN_MODEL_FILES)+ assert (model / "encoder.onnx").read_bytes() == b"encoder.onnx" and vad.read_bytes() == b"vad"+ assert sorted(p.name for p in tmp_path.iterdir()) == sorted([d, speech.VAD_NAME]) # SenseVoice is not fetched for Bengali+ assert not (tmp_path.parent / "escape.txt").exists()+ monkeypatch.setattr(speech, "fetch", lambda *a, **k: pytest.fail("should not download again"))+ speech.ensure_bn_models()+++def test_flag_and_pref_set_the_language(monkeypatch, tmp_path):+ from rea_video import cli, memory++ monkeypatch.setenv("REA_VIDEO_HOME", str(tmp_path))+ monkeypatch.setenv("REA_ASR_LANG", "auto") # recorded first, so whatever _asr_lang writes is undone after the test+ monkeypatch.delenv("REA_ASR_LANG")+ cli._asr_lang(types.SimpleNamespace(asr_lang=None))+ assert "REA_ASR_LANG" not in os.environ # no flag, no pref: transcribe falls back to auto+ memory.set_pref("asr_lang", "bn")+ cli._asr_lang(types.SimpleNamespace(asr_lang=None))+ assert os.environ["REA_ASR_LANG"] == "bn"+ cli._asr_lang(types.SimpleNamespace(asr_lang="auto")) # the flag beats the pref+ assert os.environ["REA_ASR_LANG"] == "auto"+ with pytest.raises(ValueError):+ memory.set_pref("asr_lang", "hi")