Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Claude Opus 5.5
VibeVoice: streaming decoder for ASR-Streaming, offline recipe for VibeVoice-ASR
377037a Download tests/test_streaming.py from treble-technologies/ffasr: direct link, hf CLI and curl.
- Browser
- Download file 16.4 kB
-
https://huggingface.co/spaces/treble-technologies/ffasr/resolve/main/tests/test_streaming.py
- Command line
-
hf download hf://spaces/treble-technologies/ffasr/tests/test_streaming.py
-
curl -L -o test_streaming.py https://huggingface.co/spaces/treble-technologies/ffasr/resolve/main/tests/test_streaming.py
16.4 kB
| """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) | |
| # --------------------------------------------------------------------------- | |
| 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</span>" 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"<tr data-model='([^']+)'", html) == [key, "org/a"] | |
| assert html.count("data-streaming=1") == 1 | |
| assert "Streaming · 560 ms" in html | |
| assert "aria-checked='true'" in html | |
| assert "1 streaming model is ranked with the offline models" in html | |
| # The name shown is the Hub id, without the key suffix. | |
| assert "(streaming)</span>" not in html.split("<tbody>")[1].split("ff-sr")[0] | |
| chart = lv.render_wer_chart(df, {}, {}, streaming=info) | |
| assert "ff-col is-stream" in chart and "data-latency='560'" in chart | |
| assert "Striped bars are streaming models." in chart | |
| assert ", streaming'" in chart | |
| def test_board_combines_streaming_rows_when_switched_on(monkeypatch): | |
| import app | |
| offline = [ | |
| {"model_id": "org/off", "wer_anechoic_speech": "0.10", "wer_realistic_high_snr": "0.10", | |
| "wer_realistic_mid_snr": "0.10", "wer_realistic_low_snr": "0.10", "submitted_at": "2026-01-01"}, | |
| ] | |
| stream = [{ | |
| "model_id": "org/off", "wer_anechoic_speech": "0.05", "wer_realistic_high_snr": "0.05", | |
| "wer_realistic_mid_snr": "0.05", "wer_realistic_low_snr": "0.05", | |
| "stream_family": sc.NEMO_CACHE_AWARE, "stream_mode": "incremental", "stream_latency_ms": "560", | |
| }] | |
| monkeypatch.setattr(app, "load_raw_results", lambda *a, **k: [dict(r) for r in offline]) | |
| monkeypatch.setattr(app, "load_results", lambda *a, **k: app._display_df_from_raw_rows(offline)) | |
| monkeypatch.setattr(app.streaming_results, "load_rows", lambda *a, **k: [dict(r) for r in stream]) | |
| monkeypatch.setattr(app, "_lineage_chains", lambda snap: {}) | |
| html_off, _ = app._leaderboard_table_update("", app.DEFAULT_VISIBLE_COLS, None, False) | |
| assert "(streaming)'" not in html_off and "aria-checked='false'" in html_off | |
| html_on, _ = app._leaderboard_table_update("", app.DEFAULT_VISIBLE_COLS, None, True) | |
| keys = re.findall(r"<tr data-model='([^']+)'", html_on) | |
| # Same model, both rows; the streaming run (lower WER here) ranks first. | |
| assert keys == ["org/off (streaming)", "org/off"] | |
| assert "Streaming · 560 ms" in html_on and "aria-checked='true'" in html_on | |
| # --------------------------------------------------------------------------- | |
| # VibeVoice | |
| # --------------------------------------------------------------------------- | |
| def test_vibevoice_routing_and_hardware(): | |
| import remote_jobs | |
| from recipes.registry import resolve_recipe_id | |
| assert sc.classify("microsoft/VibeVoice-ASR-Streaming-7B", model_type="vibevoice") == sc.VIBEVOICE | |
| assert resolve_recipe_id("microsoft/VibeVoice-ASR") == "vibevoice_asr" | |
| for other in ("microsoft/VibeVoice-ASR-Streaming-7B", "microsoft/VibeVoice-ASR-HF", "microsoft/VibeVoice-ASR-BitNet"): | |
| assert resolve_recipe_id(other) is None | |
| assert remote_jobs._flavor_for_submission("l4x1", "microsoft/VibeVoice-ASR-Streaming-7B", None) == "l40sx1" | |
| assert remote_jobs._flavor_for_submission("l4x1", "microsoft/VibeVoice-ASR-Streaming-1.5B", None) == "l4x1" | |
| assert remote_jobs._flavor_for_submission("a100-large", "microsoft/VibeVoice-ASR", "vibevoice_asr") == "a100-large" | |
| def test_vibevoice_text_cleanup(): | |
| from recipes.vibevoice_asr.evaluate import transcript_text | |
| chunks = ["Speaker 0: Hello the", "re, how are", " you? [Noise] Speaker 1: Fine."] | |
| assert bs.vibevoice_stream_text(chunks) == "Hello there, how are you? Fine." | |
| segs = [{"speaker_id": 0, "text": "Hello there."}, {"speaker_id": 1, "text": "[Laughter] Fine."}] | |
| assert transcript_text("ignored", segs) == "Hello there. Fine." | |
| raw = '[{"Start time": 0.0, "End time": 1.2, "Speaker ID": 0, "Content": "Hi all."}]' | |
| assert transcript_text(raw, []) == "Hi all." | |