"""Streaming ASR: family matching, decoder helpers, the streaming board and the board switch.""" from __future__ import annotations import csv import io import re import numpy as np import pandas as pd import pytest import init import job_queue import leaderboard_view as lv import streaming_config as sc import streaming_results from backends import streaming as bs from diarization_config import TASK_STREAMING, normalize_task from storage import RESULTS_PATH, STREAMING_RESULTS_PATH from utils_display import make_clickable_model, model_id_from_leaderboard_cell, split_streaming_key, streaming_key # --------------------------------------------------------------------------- # Family matching (Hub metadata -> decoder) # --------------------------------------------------------------------------- @pytest.mark.parametrize( "model_id, model_type, library, files, family", [ ("nvidia/nemotron-speech-streaming-en-0.6b", "nemotron_asr_streaming", "nemo", ["config.json", "m.nemo"], sc.TRANSFORMERS_RNNT), ("nvidia/nemotron-3.5-asr-streaming-0.6b", "nemotron3_5_asr", "nemo", ["config.json", "m.nemo"], sc.TRANSFORMERS_RNNT), ("nvidia/parakeet_realtime_eou_120m-v1", "", "nemo", ["parakeet.nemo"], sc.NEMO_CACHE_AWARE), ("nvidia/stt_en_fastconformer_hybrid_large_streaming_multi", "", "", ["x.nemo"], sc.NEMO_CACHE_AWARE), ("kyutai/stt-2.6b-en", "stt", "moshi", ["config.json"], sc.MOSHI), ("kyutai/stt-1b-en_fr-trfs", "kyutai_speech_to_text", "transformers", ["config.json"], sc.CAUSAL), ("mistralai/Voxtral-Mini-4B-Realtime-2602", "voxtral_realtime", "vllm", ["config.json"], sc.CAUSAL), ("moonshine-ai/moonshine-streaming-small", "moonshine_streaming", "transformers", ["config.json"], sc.CAUSAL), ( "csukuangfj/sherpa-onnx-streaming-zipformer-en-2023-06-26", "", "", ["tokens.txt", "encoder-epoch-99-avg-1-chunk-16-left-128.onnx"], sc.SHERPA_ONNX, ), ("openai/whisper-tiny", "whisper", "transformers", ["config.json"], None), ], ) def test_classify(model_id, model_type, library, files, family): assert sc.classify(model_id, model_type=model_type, library=library, files=files) == family def test_right_context_env(monkeypatch): monkeypatch.delenv("FFASR_STREAM_RIGHT_CONTEXT", raising=False) assert sc.right_context() == 6 monkeypatch.setenv("FFASR_STREAM_RIGHT_CONTEXT", "13") assert sc.right_context() == 13 monkeypatch.setenv("FFASR_STREAM_RIGHT_CONTEXT", "junk") assert sc.right_context() == 6 def test_streaming_task_is_a_task(): assert normalize_task("streaming") == TASK_STREAMING assert normalize_task("nonsense") == "asr" # --------------------------------------------------------------------------- # Decoder helpers (no torch / NeMo / moshi needed) # --------------------------------------------------------------------------- def test_pick_att_context_prefers_the_wanted_lookahead(): opts = [[70, 13], [70, 6], [70, 1], [70, 0]] assert bs.pick_att_context(opts, [70, 13], 6) == [70, 6] assert bs.pick_att_context(opts, [70, 13], 3) == [70, 13] # not offered: model default assert bs.pick_att_context(None, [70, 0], 6) == [70, 0] assert bs.pick_att_context([], None, 6) is None def test_nemo_chunk_ms(): class Cfg: class preprocessor: window_stride = 0.01 class Model: cfg = Cfg class encoder: subsampling_factor = 8 assert bs.nemo_chunk_ms(Model, [70, 6]) == pytest.approx(560.0) assert bs.nemo_chunk_ms(Model, [70, 0]) == pytest.approx(80.0) def test_pick_sherpa_files_prefers_fp32_and_widest_context(): files = [ "tokens.txt", "decoder-epoch-99-avg-1-chunk-16-left-128.int8.onnx", "decoder-epoch-99-avg-1-chunk-16-left-128.onnx", "decoder-epoch-99-avg-1-chunk-16-left-64.onnx", "encoder-epoch-99-avg-1-chunk-16-left-128.int8.onnx", "encoder-epoch-99-avg-1-chunk-16-left-128.onnx", "encoder-epoch-99-avg-1-chunk-16-left-64.onnx", "joiner-epoch-99-avg-1-chunk-16-left-128.onnx", "joiner-epoch-99-avg-1-chunk-16-left-64.onnx", ] picked = bs.pick_sherpa_files(files) assert picked == { "tokens": "tokens.txt", "encoder": "encoder-epoch-99-avg-1-chunk-16-left-128.onnx", "decoder": "decoder-epoch-99-avg-1-chunk-16-left-128.onnx", "joiner": "joiner-epoch-99-avg-1-chunk-16-left-128.onnx", } assert sc.sherpa_chunk_ms(picked["encoder"]) == 320 def test_decode_moshi_tokens_drops_padding(): class Tok: def decode(self, ids): return " ".join(str(i) for i in ids) assert bs.decode_moshi_tokens(Tok(), [0, 3, 11, 3, 12, 0], {0, 3}) == "11 12" assert bs.decode_moshi_tokens(Tok(), [3, 3], {0, 3}) == "" class _FakeInputs(dict): def __getattr__(self, k): return self[k] class _FakeProcessor: """Shape-only stand-in for the Nemotron streaming processor (mel frames == samples / hop).""" num_samples_first_audio_chunk = 1000 num_mel_frames_first_audio_chunk = 10 num_samples_per_audio_chunk = 800 num_mel_frames_per_audio_chunk = 8 class feature_extractor: hop_length = 100 n_fft = 400 def __init__(self): self.calls = [] def __call__(self, audio, **kw): self.calls.append((len(audio), kw)) frames = max(1, len(audio) // 100) return _FakeInputs(input_features=np.zeros((1, frames, 4))) def test_stream_feature_chunks_cover_the_whole_utterance(): proc = _FakeProcessor() audio = np.ones(5000, dtype=np.float32) first, features = bs.stream_feature_chunks(proc, audio, sampling_rate=16000, extra={"language": "en-US"}) chunks = list(features(lambda x: x)) assert chunks[0].shape[1] == proc.num_mel_frames_first_audio_chunk mel_frames = proc.num_mel_frames_first_audio_chunk + proc.num_mel_frames_per_audio_chunk * (len(chunks) - 1) # Every real sample (plus the lookahead tail) reached the model. assert mel_frames * proc.feature_extractor.hop_length >= len(audio) assert all(kw.get("is_streaming") and kw.get("language") == "en-US" for _, kw in proc.calls) assert [kw["is_first_audio_chunk"] for _, kw in proc.calls] == [True] + [False] * (len(proc.calls) - 1) # --------------------------------------------------------------------------- # Streaming board storage and queue routing # --------------------------------------------------------------------------- def _fake_storage(monkeypatch): files: dict[str, bytes] = {} def fake_download(path, **kwargs): blob = files.get(path) if blob is None: raise FileNotFoundError(path) import tempfile f = tempfile.NamedTemporaryFile("w", suffix=".csv", delete=False, encoding="utf-8") f.write(blob.decode("utf-8")) f.close() return f.name def fake_upload(bucket, *, add=None, **kwargs): for src, dst in add or []: files[dst] = bytes(src) for mod in (init, streaming_results): monkeypatch.setattr(mod, "download_bucket_file", fake_download) monkeypatch.setattr(mod, "upload_to_bucket", fake_upload) monkeypatch.setattr("storage.append_private_submission", lambda **kwargs: None) init.invalidate_results_cache() streaming_results.invalidate_cache() return files STREAM_RESULT = { "model_id": "nvidia/nemotron-speech-streaming-en-0.6b", "eval_family": "Streaming", "task": "streaming", # Wire keys, as the evaluation emits them (benchmark.dataset.wer_result_key). "wer_clean": 0.05, "wer_high": 0.08, "wer_mid": 0.1, "wer_low": 0.2, "eval_rtf": 40.0, "stream_family": sc.TRANSFORMERS_RNNT, "stream_mode": "incremental", "stream_latency_ms": 560, } def test_streaming_result_goes_to_its_own_board(monkeypatch): files = _fake_storage(monkeypatch) job_queue._merge_eval_result_to_leaderboard(dict(STREAM_RESULT), "2026-11-13T00:00:00Z", "") assert RESULTS_PATH not in files # offline board untouched rows = list(csv.DictReader(io.StringIO(files[STREAMING_RESULTS_PATH].decode("utf-8")))) assert len(rows) == 1 row = rows[0] assert row["model_id"] == STREAM_RESULT["model_id"] assert row["wer_realistic_low_snr"] == "0.2" assert row["stream_latency_ms"] == "560" and row["stream_family"] == sc.TRANSFORMERS_RNNT assert job_queue._task_has_model(TASK_STREAMING, STREAM_RESULT["model_id"]) assert not job_queue._task_has_model("asr", STREAM_RESULT["model_id"]) with pytest.raises(RuntimeError, match="already on the streaming leaderboard"): streaming_results.merge_eval_result(dict(STREAM_RESULT), "2026-11-14T00:00:00Z") streaming_results.merge_eval_result( {**STREAM_RESULT, "wer_low": 0.3}, "2026-11-14T00:00:00Z", replace_existing=True ) assert streaming_results.row_for_model(STREAM_RESULT["model_id"])["wer_realistic_low_snr"] == "0.3" def test_enqueue_streaming_uses_the_streaming_family_and_no_recipe(monkeypatch): monkeypatch.setattr(job_queue, "MODERATION_ENABLED", True) monkeypatch.setattr(job_queue, "MODERATOR_SECRET", "s") monkeypatch.setattr(job_queue, "_ensure_worker", lambda: None) monkeypatch.setattr(job_queue, "_persist_jobs", lambda: None) monkeypatch.setattr(job_queue, "_task_has_model", lambda *a, **k: False) monkeypatch.setattr(job_queue, "_record_submission_pii", lambda **kwargs: None) monkeypatch.setattr("remote_jobs.remote_jobs_enabled", lambda: True) job_queue._jobs.clear() job_queue._submit_hits.clear() # A model on the offline board can still be queued for streaming, and vice versa. jid, _pos, err, awaiting = job_queue.enqueue( "zhifeixie/Mega-ASR", "auto", contact_email="a@b.co", task=TASK_STREAMING ) assert err is None and awaiting job = job_queue._jobs[jid] assert job.task == TASK_STREAMING and job.family_id == "streaming" and job.recipe_id == "" assert "streaming" in job_queue.task_badge_html(job.task) assert not job_queue._model_in_flight("zhifeixie/Mega-ASR", "asr") assert job_queue._model_in_flight("zhifeixie/Mega-ASR", TASK_STREAMING) job_queue._jobs.clear() def test_streaming_deps_follow_the_family(monkeypatch): import remote_jobs for family, needle in ( (sc.NEMO_CACHE_AWARE, "nemo_toolkit"), (sc.MOSHI, "moshi"), (sc.SHERPA_ONNX, "sherpa-onnx"), (sc.TRANSFORMERS_RNNT, "transformers @ git+"), (sc.CAUSAL, "transformers @ git+"), ): monkeypatch.setattr(sc, "resolve_family", lambda mid, f=family: f) deps = remote_jobs._select_deps("org/model", "streaming", task="streaming") assert any(d.startswith(needle) for d in deps), (family, deps) assert "torch<2.11" in deps # --------------------------------------------------------------------------- # Board: streaming keys, tags and the switch # --------------------------------------------------------------------------- def test_streaming_key_round_trip_and_link(): key = streaming_key("org/m") assert split_streaming_key(key) == ("org/m", True) assert split_streaming_key("org/m") == ("org/m", False) cell = make_clickable_model(key) assert 'href="https://huggingface.co/org/m"' in cell assert model_id_from_leaderboard_cell(cell) == key def _frame(rows): return pd.DataFrame(rows, columns=[lv.RANK_COL, lv.MODEL_COL, lv.AutoEvalColumn.avg_wer_core.name]) def test_switch_replaces_the_changes_summary(): df = _frame([[1, make_clickable_model("org/a"), 5.0], [2, make_clickable_model("org/b"), 6.0]]) html = lv.render_asr_table(df, {}, newest="org/b", moves={"org/a": 1}, stream_switch={"on": False, "count": 3}) assert "changed position" not in html and "was added:" not in html assert "data-streaming aria-checked='false'" in html and ">3" in html assert "ff-stream'" not in html # no streaming rows while off off = lv.render_asr_table(df, {}, stream_switch={"on": False, "count": 0}) assert " disabled" in off and "No streaming model has results yet" in off assert "data-streaming" not in lv.render_asr_table(df, {}, version="v1", stream_switch=None) def test_streaming_rows_are_tagged_and_keyed_apart(): key = streaming_key("org/a") df = _frame([[1, make_clickable_model(key), 4.0], [2, make_clickable_model("org/a"), 5.0]]) info = {key: {"latency_ms": 560.0, "mode": "incremental", "family": "NeMo cache-aware streaming"}} html = lv.render_asr_table(df, {}, streaming=info, stream_switch={"on": True, "count": 1}) assert re.findall(r"