Files
video-analyse/tests/test_transcribe.py
T

962 lines
35 KiB
Python

"""Unit tests for the STT backends, the transcriber registry and SRT rendering.
Nothing here downloads a model or opens a network connection: the hosted backend runs
against ``httpx.MockTransport`` and the local model backends are exercised through
their pure mapping helpers. Tests that need a real model are opt-in (``VA_HEAVY_TESTS=1``).
"""
from __future__ import annotations
import itertools
import math
import os
import re
import shutil
import wave
from collections.abc import Iterator
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import httpx
import pytest
from video_analyse.cache import StageCache
from video_analyse.config import Settings
from video_analyse.models import Segment, Transcript, Word
from video_analyse.pipeline import _transcribe_params
from video_analyse.srt import format_timestamp, render_srt
from video_analyse.transcribe import STT_BACKENDS, SttOptions, get_transcriber
from video_analyse.transcribe import faster_whisper as faster_whisper_module
from video_analyse.transcribe import openai_transcriptions as openai_module
from video_analyse.transcribe import parakeet_onnx as parakeet_module
from video_analyse.transcribe.base import ModelIdentity, Readiness, Requirement, Transcriber
from video_analyse.transcribe.faster_whisper import (
FasterWhisperTranscriber,
segments_to_transcript,
)
from video_analyse.transcribe.openai_transcriptions import (
OpenAITranscriptionsTranscriber,
compute_chunk_offsets,
verbose_json_to_transcript,
)
from video_analyse.transcribe.parakeet_onnx import (
ENGLISH_MODEL,
MULTILINGUAL_MODEL,
ParakeetOnnxTranscriber,
results_to_transcript,
select_model_name,
tokens_to_words,
)
FFMPEG = shutil.which("ffmpeg")
FFPROBE = shutil.which("ffprobe")
requires_ffmpeg = pytest.mark.skipif(
FFMPEG is None or FFPROBE is None,
reason="ffmpeg and ffprobe are required to convert/split upload audio",
)
HEAVY_TESTS = os.environ.get("VA_HEAVY_TESTS", "").strip().lower() not in {
"",
"0",
"false",
"no",
}
heavy = pytest.mark.skipif(
not HEAVY_TESTS,
reason="set VA_HEAVY_TESTS=1 to run tests that load real models",
)
CUE_PATTERN = re.compile(
r"(?P<index>\d+)\n"
r"(?P<start>\d{2}:\d{2}:\d{2},\d{3}) --> (?P<end>\d{2}:\d{2}:\d{2},\d{3})\n"
r"(?P<text>.+)",
re.DOTALL,
)
def _stt_options(**overrides: Any) -> SttOptions:
"""Build the stage option value the way the pipeline does."""
return Settings(**overrides).options_for("stt")
@pytest.fixture(autouse=True)
def _isolated_state(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
"""Drop ``VA_*`` overrides and reset the process-wide model caches per test."""
for name in list(os.environ):
if name.startswith("VA_"):
monkeypatch.delenv(name, raising=False)
_clear_model_caches()
yield
_clear_model_caches()
def _clear_model_caches() -> None:
faster_whisper_module._MODEL_CACHE.clear()
parakeet_module._RECOGNIZER_CACHE.clear()
parakeet_module._VAD_CACHE.clear()
def write_silent_wav(path: Path, seconds: float = 1.0, rate: int = 16_000) -> Path:
"""Write a silent 16-bit mono PCM WAV of exactly ``seconds`` seconds."""
frames = round(rate * seconds)
with wave.open(str(path), "wb") as handle:
handle.setnchannels(1)
handle.setsampwidth(2)
handle.setframerate(rate)
handle.writeframes(b"\x00\x00" * frames)
return path
def parse_srt(text: str) -> list[dict[str, str]]:
"""Parse an SRT document into cue dicts, asserting every cue is well formed."""
blocks = [block for block in text.strip("\n").split("\n\n") if block]
cues: list[dict[str, str]] = []
for block in blocks:
match = CUE_PATTERN.fullmatch(block)
assert match is not None, f"invalid SRT cue: {block!r}"
cues.append(match.groupdict())
return cues
def verbose_payload(*, duration: float = 0.4) -> dict[str, Any]:
"""A canned Groq/OpenAI ``verbose_json`` response with words and one segment."""
return {
"task": "transcribe",
"language": "english",
"duration": duration,
"text": " Hello world.",
"segments": [
{
"id": 0,
"start": 0.0,
"end": duration,
"text": " Hello world.",
"no_speech_prob": 0.01,
}
],
"words": [
{"word": " Hello", "start": 0.0, "end": 0.2},
{"word": " world.", "start": 0.22, "end": duration},
],
}
# --------------------------------------------------------------------------- SRT
def test_render_srt_is_valid_and_sequential() -> None:
transcript = Transcript(
duration=62.0,
segments=[
Segment(start=0.0, end=1.25, text=" First line."),
Segment(start=1.5, end=2.0, text=" Second line."),
Segment(start=61.5, end=62.0, text=" Last line."),
],
)
text = render_srt(transcript)
assert text.endswith("\n")
cues = parse_srt(text)
assert [cue["index"] for cue in cues] == ["1", "2", "3"]
assert cues[0]["start"] == "00:00:00,000"
assert cues[0]["end"] == "00:00:01,250"
assert cues[1]["start"] == "00:00:01,500"
assert cues[2]["start"] == "00:01:01,500"
assert cues[2]["end"] == "00:01:02,000"
assert [cue["text"] for cue in cues] == ["First line.", "Second line.", "Last line."]
def test_render_srt_speaker_labels() -> None:
transcript = Transcript(
duration=3.0,
segments=[
Segment(start=0.0, end=1.0, text="Hello there", speaker="S1"),
Segment(start=1.0, end=2.0, text="Hi", speaker="S2"),
Segment(start=2.0, end=3.0, text="Bye"),
],
)
labelled = parse_srt(render_srt(transcript, speaker_labels=True))
assert [cue["text"] for cue in labelled] == ["[S1] Hello there", "[S2] Hi", "Bye"]
plain = parse_srt(render_srt(transcript))
assert [cue["text"] for cue in plain] == ["Hello there", "Hi", "Bye"]
def test_render_srt_uses_words_when_segment_text_is_empty() -> None:
transcript = Transcript(
duration=2.0,
segments=[
Segment(
start=0.0,
end=1.0,
text="",
words=[Word(text="Word", start=0.0, end=0.5)],
),
Segment(start=1.0, end=1.5, text=" "),
Segment(start=1.5, end=2.0, text=" done "),
],
)
cues = parse_srt(render_srt(transcript))
assert [cue["text"] for cue in cues] == ["Word", "done"]
assert [cue["index"] for cue in cues] == ["1", "2"]
def test_render_srt_empty_transcript() -> None:
assert render_srt(Transcript(duration=0.0, segments=[])) == ""
def test_render_srt_collapses_whitespace_and_fixes_zero_duration() -> None:
transcript = Transcript(
duration=2.0,
segments=[Segment(start=2.0, end=2.0, text="line one\n line two")],
)
cues = parse_srt(render_srt(transcript))
assert cues[0]["text"] == "line one line two"
assert cues[0]["start"] == "00:00:02,000"
assert cues[0]["end"] == "00:00:02,001"
@pytest.mark.parametrize(
("seconds", "expected"),
[
(0.0, "00:00:00,000"),
(1.0006, "00:00:01,001"),
(59.9996, "00:01:00,000"),
(3661.5, "01:01:01,500"),
(-5.0, "00:00:00,000"),
(float("nan"), "00:00:00,000"),
(float("inf"), "00:00:00,000"),
],
)
def test_format_timestamp(seconds: float, expected: str) -> None:
assert format_timestamp(seconds) == expected
# ---------------------------------------------------------------------- registry
def test_registry_defaults_to_parakeet_in_the_local_profile() -> None:
settings = Settings()
assert settings.resolved_stt() == "parakeet"
transcriber = get_transcriber(settings.options_for("stt"))
assert isinstance(transcriber, ParakeetOnnxTranscriber)
assert isinstance(transcriber, Transcriber)
def test_registry_honours_explicit_backends() -> None:
whisper = get_transcriber(_stt_options(stt_backend="whisper"))
assert isinstance(whisper, FasterWhisperTranscriber)
assert whisper.model_name == Settings(stt_backend="whisper").whisper_model
parakeet = get_transcriber(_stt_options(stt_backend="parakeet"))
assert isinstance(parakeet, ParakeetOnnxTranscriber)
hosted = get_transcriber(_stt_options(stt_backend="openai-transcriptions"))
assert isinstance(hosted, OpenAITranscriptionsTranscriber)
assert hosted.model == Settings(stt_backend="openai-transcriptions").stt_api_model
def test_registry_hosted_profile_uses_hosted_stt() -> None:
settings = Settings(profile="hosted")
assert settings.resolved_stt() == "openai-transcriptions"
transcriber = get_transcriber(settings.options_for("stt"))
assert isinstance(transcriber, OpenAITranscriptionsTranscriber)
assert transcriber.endpoint == "https://api.groq.com/openai/v1/audio/transcriptions"
def test_registry_rejects_unknown_backend() -> None:
with pytest.raises(ValueError, match="nope"):
get_transcriber(SimpleNamespace(backend="nope")) # type: ignore[arg-type]
def test_every_registered_backend_satisfies_the_protocol() -> None:
for backend in STT_BACKENDS:
transcriber = get_transcriber(_stt_options(stt_backend=backend))
assert isinstance(transcriber, Transcriber)
identity = transcriber.identity()
assert isinstance(identity, ModelIdentity)
assert identity.backend == backend
assert identity.model
readiness = transcriber.readiness()
assert isinstance(readiness, Readiness)
assert isinstance(readiness.weights_present, bool)
assert readiness.weights_location
assert all(isinstance(item, Requirement) for item in readiness.requirements)
def test_identities_report_the_checkpoint_each_adapter_uses() -> None:
whisper = get_transcriber(_stt_options(stt_backend="whisper", whisper_model="tiny"))
assert whisper.identity() == ModelIdentity(backend="whisper", model="tiny")
english = get_transcriber(_stt_options(stt_backend="parakeet", language="en"))
assert english.identity().model == ENGLISH_MODEL
german = get_transcriber(_stt_options(stt_backend="parakeet", language="de"))
assert german.identity().model == MULTILINGUAL_MODEL
hosted = get_transcriber(
_stt_options(
stt_backend="openai-transcriptions",
stt_api_base_url="https://example.test/v1",
stt_api_model="whisper-test",
)
)
assert hosted.identity() == ModelIdentity(
backend="openai-transcriptions",
model="whisper-test",
endpoint="https://example.test/v1/audio/transcriptions",
)
def test_hosted_readiness_reports_the_credential_requirement(
monkeypatch: pytest.MonkeyPatch,
) -> None:
for name in openai_module.API_KEY_ENV_VARS:
monkeypatch.delenv(name, raising=False)
transcriber = get_transcriber(_stt_options(stt_backend="openai-transcriptions"))
readiness = transcriber.readiness()
assert readiness.weights_present is True
assert "https://" in readiness.weights_location
(key_requirement,) = [item for item in readiness.requirements if "key" in item.name]
assert key_requirement.ok is False
assert "GROQ_API_KEY" in key_requirement.hint
monkeypatch.setenv("GROQ_API_KEY", "test-key")
assert all(item.ok for item in transcriber.readiness().requirements)
def test_local_readiness_follows_the_huggingface_cache_without_downloading(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setenv("HF_HOME", str(tmp_path / "hf"))
transcriber = get_transcriber(_stt_options(stt_backend="whisper", whisper_model="tiny"))
readiness = transcriber.readiness()
assert readiness.weights_present is False
assert "models--Systran--faster-whisper-tiny" in readiness.weights_location
snapshot = Path(readiness.weights_location) / "snapshots" / "abc123"
snapshot.mkdir(parents=True)
(snapshot / "model.bin").write_bytes(b"weights")
assert transcriber.readiness().weights_present is True
def _transcribe_cache_params(options: SttOptions) -> dict[str, Any]:
"""Call the pipeline's key builder with the options the adapter was built from."""
ctx = SimpleNamespace(
audio_sha="a" * 64,
settings=SimpleNamespace(options_for=lambda _stage: options),
)
params = _transcribe_params(ctx) # type: ignore[arg-type]
assert params is not None
return params
def test_transcribe_cache_params_use_the_adapter_identity(tmp_path: Path) -> None:
options = _stt_options(stt_backend="whisper", whisper_model="tiny")
identity = get_transcriber(options).identity()
params = _transcribe_cache_params(options)
assert params["backend"] == identity.backend
assert params["model"] == identity.model
assert params["endpoint"] == identity.endpoint
def test_a_fourth_registered_backend_cannot_alias_another_cache_key(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from video_analyse import transcribe as registry
class StubTranscriber:
async def transcribe(self, wav: Path, *, language: str | None = None) -> Transcript:
raise AssertionError("not called by this test")
def identity(self) -> ModelIdentity:
# Deliberately claims Parakeet's checkpoint: the backend must still differ.
return ModelIdentity(backend="stub", model=MULTILINGUAL_MODEL)
def readiness(self) -> Readiness:
return Readiness(weights_present=True, weights_location="stub", requirements=[])
monkeypatch.setattr(registry, "STT_BACKENDS", (*registry.STT_BACKENDS, "stub"))
monkeypatch.setitem(registry._STT_FACTORIES, "stub", lambda options: StubTranscriber())
parakeet_options = _stt_options(stt_backend="parakeet")
stub_options = parakeet_options.model_copy(update={"backend": "stub"})
parakeet = get_transcriber(parakeet_options)
stub = get_transcriber(stub_options)
assert isinstance(stub, StubTranscriber)
assert stub.identity().model == parakeet.identity().model
cache = StageCache(tmp_path)
parakeet_key = cache.stage_key("transcribe", _transcribe_cache_params(parakeet_options))
stub_key = cache.stage_key("transcribe", _transcribe_cache_params(stub_options))
assert stub_key != parakeet_key
async def test_transcribers_reject_missing_audio(tmp_path: Path) -> None:
missing = tmp_path / "missing.wav"
for backend in STT_BACKENDS:
transcriber = get_transcriber(_stt_options(stt_backend=backend))
with pytest.raises(ValueError, match="audio file not found"):
await transcriber.transcribe(missing)
async def test_transcribers_normalise_environment_failures_to_runtime_error(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
wav = write_silent_wav(tmp_path / "audio.wav")
def broken_whisper(model_name: str) -> Any:
raise OSError("faster-whisper model is unavailable")
monkeypatch.setattr(faster_whisper_module, "_get_model", broken_whisper)
with pytest.raises(RuntimeError, match="faster-whisper"):
await FasterWhisperTranscriber(_stt_options()).transcribe(wav)
def broken_parakeet(model_name: str) -> Any:
raise OSError("onnx-asr model is unavailable")
monkeypatch.setattr(parakeet_module, "_get_recognizer", broken_parakeet)
with pytest.raises(RuntimeError, match="parakeet"):
await ParakeetOnnxTranscriber(_stt_options()).transcribe(wav)
for name in openai_module.API_KEY_ENV_VARS:
monkeypatch.delenv(name, raising=False)
hosted = OpenAITranscriptionsTranscriber(_stt_options(stt_backend="openai-transcriptions"))
with pytest.raises(RuntimeError, match="API key"):
await hosted.transcribe(wav)
# ---------------------------------------------------------------- faster-whisper
def test_segments_to_transcript_maps_segments_and_words() -> None:
raw_segments = [
SimpleNamespace(
start=0.0,
end=2.0,
text=" Hello world.",
words=[
SimpleNamespace(word=" Hello", start=0.1, end=0.4, probability=0.9),
SimpleNamespace(word=" world.", start=0.5, end=1.1, probability=0.8),
SimpleNamespace(word=" ", start=1.2, end=1.3, probability=0.5),
],
),
SimpleNamespace(start=2.2, end=3.0, text=" Bye.", words=None),
]
info = SimpleNamespace(language="en", duration=3.0)
transcript = segments_to_transcript(raw_segments, info, model="small")
assert transcript.backend == "whisper"
assert transcript.model == "small"
assert transcript.language == "en"
assert transcript.duration == pytest.approx(3.0)
assert [segment.text for segment in transcript.segments] == ["Hello world.", "Bye."]
assert transcript.segments[1].words == []
words = transcript.segments[0].words
assert [word.text for word in words] == ["Hello", "world."]
assert [word.probability for word in words] == pytest.approx([0.9, 0.8])
assert words[0].start == pytest.approx(0.1)
assert words[0].end == pytest.approx(0.4)
def test_segments_to_transcript_clamps_word_times_and_keeps_unknown_probability() -> None:
raw_segments = [
SimpleNamespace(
start=1.0,
end=2.0,
text=" x",
words=[SimpleNamespace(word="x", start=0.2, end=5.0)],
)
]
transcript = segments_to_transcript(
raw_segments, SimpleNamespace(language="de", duration=2.0), model="m"
)
word = transcript.segments[0].words[0]
assert (word.start, word.end) == (1.0, 2.0)
assert word.probability is None
assert transcript.language == "de"
def test_segments_to_transcript_falls_back_to_last_segment_end() -> None:
raw_segments = [SimpleNamespace(start=0.0, end=1.75, text=" a", words=[])]
transcript = segments_to_transcript(
raw_segments, SimpleNamespace(language=None, duration=0.0), model="m"
)
assert transcript.duration == pytest.approx(1.75)
assert transcript.language is None
assert transcript.segments[0].words == []
def test_faster_whisper_model_cache_loads_once(monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[str] = []
def fake_build(name: str) -> Any:
calls.append(name)
return SimpleNamespace(name=name)
monkeypatch.setattr(faster_whisper_module, "_build_model", fake_build)
first = faster_whisper_module._get_model("tiny")
second = faster_whisper_module._get_model("tiny")
assert first is second
assert calls == ["tiny"]
async def test_faster_whisper_transcriber_consumes_generator(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
wav = write_silent_wav(tmp_path / "audio.wav", seconds=0.5)
captured: dict[str, Any] = {}
def generator() -> Iterator[Any]:
yield SimpleNamespace(
start=0.0,
end=0.5,
text=" Hi.",
words=[SimpleNamespace(word=" Hi.", start=0.0, end=0.5, probability=0.9)],
)
class FakeModel:
def transcribe(self, audio: Any, **kwargs: Any) -> tuple[Iterator[Any], Any]:
captured.update(kwargs)
captured["audio"] = audio
return generator(), SimpleNamespace(language="en", duration=0.5)
monkeypatch.setattr(faster_whisper_module, "_get_model", lambda name: FakeModel())
transcript = await FasterWhisperTranscriber(_stt_options()).transcribe(wav, language="en")
assert captured["audio"].shape == (8_000,)
assert captured["audio"].dtype == "float32"
assert captured["word_timestamps"] is True
assert captured["vad_filter"] is True
assert captured["language"] == "en"
assert transcript.backend == "whisper"
assert transcript.segments[0].words[0].text == "Hi."
# -------------------------------------------------------------------- parakeet
def test_select_model_name() -> None:
assert select_model_name(None) == MULTILINGUAL_MODEL
assert select_model_name("en") == ENGLISH_MODEL
assert select_model_name("EN-us") == ENGLISH_MODEL
assert select_model_name("de") == MULTILINGUAL_MODEL
assert select_model_name("fr") == MULTILINGUAL_MODEL
def test_tokens_to_words_merges_pieces_and_derives_boundaries() -> None:
tokens = [" Hel", "lo", " world", "."]
timestamps = [0.0, 0.16, 0.8, 1.12]
logprobs = [-0.1, -0.2, -0.3, -0.4]
words = tokens_to_words(tokens, timestamps, logprobs, start=10.0, end=12.0)
assert [word.text for word in words] == ["Hello", "world."]
assert words[0].start == pytest.approx(10.0)
assert words[0].end == pytest.approx(10.8)
assert words[1].start == pytest.approx(10.8)
assert words[1].end == pytest.approx(12.0)
assert words[0].probability == pytest.approx(math.exp((-0.1 - 0.2) / 2))
assert words[1].probability == pytest.approx(math.exp((-0.3 - 0.4) / 2))
def test_tokens_to_words_accepts_sentencepiece_boundary_markers() -> None:
tokens = ["\u2581Hel", "lo", "\u2581there", "\u2581"]
timestamps = [0.0, 0.2, 0.5, 0.6]
words = tokens_to_words(tokens, timestamps, None, start=0.0, end=1.0)
assert [word.text for word in words] == ["Hello", "there"]
assert words[0].probability is None
assert words[1].end == pytest.approx(1.0)
def test_tokens_to_words_without_timestamps_returns_nothing() -> None:
assert tokens_to_words([" hello"], None) == []
assert tokens_to_words(None, [0.0]) == []
assert tokens_to_words([], []) == []
def test_results_to_transcript_maps_vad_segments() -> None:
results = [
SimpleNamespace(
start=0.0,
end=2.0,
text=" Hello world.",
timestamps=[0.0, 0.5],
tokens=[" Hello", " world."],
logprobs=[-0.1, -0.2],
),
SimpleNamespace(
start=2.5,
end=3.0,
text=" Bye.",
timestamps=[0.0],
tokens=[" Bye."],
logprobs=[-0.3],
),
SimpleNamespace(
start=3.0,
end=3.1,
text=" ",
timestamps=None,
tokens=None,
logprobs=None,
),
]
transcript = results_to_transcript(
(result for result in results), model=MULTILINGUAL_MODEL, language=None, duration=3.1
)
assert transcript.backend == "parakeet"
assert transcript.model == MULTILINGUAL_MODEL
assert transcript.language is None
assert transcript.duration == pytest.approx(3.1)
assert [segment.text for segment in transcript.segments] == ["Hello world.", "Bye."]
first = transcript.segments[0]
assert [word.text for word in first.words] == ["Hello", "world."]
assert first.words[0].end == pytest.approx(0.5)
assert first.words[1].start == pytest.approx(0.5)
assert first.words[1].end == pytest.approx(2.0)
assert first.words[0].probability == pytest.approx(math.exp(-0.1))
def test_results_to_transcript_reports_english_for_v2_and_uses_last_end() -> None:
results = [
SimpleNamespace(
start=0.5,
end=1.5,
text=" Hi.",
timestamps=[0.0],
tokens=[" Hi."],
logprobs=None,
)
]
transcript = results_to_transcript(results, model=ENGLISH_MODEL, language=None, duration=None)
assert transcript.language == "en"
assert transcript.duration == pytest.approx(1.5)
def test_parakeet_recognizer_cache_is_keyed_by_model(monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[str] = []
def fake_build(name: str) -> Any:
calls.append(name)
return SimpleNamespace(name=name)
monkeypatch.setattr(parakeet_module, "_build_recognizer", fake_build)
first = parakeet_module._get_recognizer(MULTILINGUAL_MODEL)
second = parakeet_module._get_recognizer(MULTILINGUAL_MODEL)
third = parakeet_module._get_recognizer(ENGLISH_MODEL)
assert first is second
assert third is not first
assert calls == [MULTILINGUAL_MODEL, ENGLISH_MODEL]
def test_wav_duration_reads_pcm_headers(tmp_path: Path) -> None:
wav = write_silent_wav(tmp_path / "silence.wav", seconds=1.25)
assert parakeet_module._wav_duration(wav) == pytest.approx(1.25)
assert parakeet_module._wav_duration(tmp_path / "nope.wav") is None
async def test_parakeet_transcriber_selects_checkpoint_from_language(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
wav = write_silent_wav(tmp_path / "audio.wav", seconds=0.5)
calls: list[str] = []
class FakeRecognizer:
def recognize(self, path: str) -> list[Any]:
calls.append(path)
return [
SimpleNamespace(
start=0.0,
end=0.5,
text=" Hi.",
timestamps=[0.0],
tokens=[" Hi."],
logprobs=[-0.2],
)
]
def fake_get_recognizer(name: str) -> FakeRecognizer:
calls.append(name)
return FakeRecognizer()
monkeypatch.setattr(parakeet_module, "_get_recognizer", fake_get_recognizer)
transcript = await ParakeetOnnxTranscriber(_stt_options(language="en")).transcribe(wav)
assert calls == [ENGLISH_MODEL, str(wav)]
assert transcript.backend == "parakeet"
assert transcript.model == ENGLISH_MODEL
assert transcript.language == "en"
assert transcript.duration == pytest.approx(0.5)
assert transcript.segments[0].words[0].text == "Hi."
# ----------------------------------------------------- openai transcriptions
def test_compute_chunk_offsets() -> None:
assert compute_chunk_offsets([]) == []
assert compute_chunk_offsets([10.0]) == [0.0]
assert compute_chunk_offsets([10.0, 20.0, 5.0]) == pytest.approx([0.0, 10.0, 30.0])
assert compute_chunk_offsets([10.0, -3.0, 2.0]) == pytest.approx([0.0, 10.0, 10.0])
def test_verbose_json_to_transcript_maps_words_and_segments() -> None:
payload = {
"language": "english",
"duration": 2.5,
"text": " Hello world.",
"segments": [
{"start": 0.0, "end": 1.2, "text": " Hello"},
{"start": 1.2, "end": 2.5, "text": " world."},
],
"words": [
{"word": " Hello", "start": 0.1, "end": 0.4},
{"word": " world.", "start": 1.3, "end": 1.8, "probability": 0.7},
],
}
transcript = verbose_json_to_transcript([payload], [0.0], model="whisper-large-v3-turbo")
assert transcript.backend == "openai-transcriptions"
assert transcript.model == "whisper-large-v3-turbo"
assert transcript.language == "english"
assert transcript.duration == pytest.approx(2.5)
assert [segment.text for segment in transcript.segments] == ["Hello", "world."]
assert [word.text for word in transcript.segments[0].words] == ["Hello"]
assert [word.text for word in transcript.segments[1].words] == ["world."]
assert transcript.segments[0].words[0].probability is None
assert transcript.segments[1].words[0].probability == pytest.approx(0.7)
def test_verbose_json_to_transcript_stitches_chunks_with_offsets() -> None:
payloads = [verbose_payload(duration=2.0), verbose_payload(duration=1.5)]
offsets = compute_chunk_offsets([2.0, 1.5])
transcript = verbose_json_to_transcript(payloads, offsets, model="whisper-1")
assert offsets == pytest.approx([0.0, 2.0])
assert transcript.duration == pytest.approx(3.5)
assert [segment.start for segment in transcript.segments] == pytest.approx([0.0, 2.0])
assert [segment.end for segment in transcript.segments] == pytest.approx([2.0, 3.5])
assert [segment.words[0].start for segment in transcript.segments] == pytest.approx([0.0, 2.0])
assert transcript.segments[1].words[1].start == pytest.approx(2.22)
def test_verbose_json_to_transcript_synthesises_segment_from_words() -> None:
payload = {"language": "en", "words": [{"word": "Hi", "start": 0.0, "end": 0.3}]}
transcript = verbose_json_to_transcript([payload], [0.0], model="whisper-1")
assert transcript.duration == pytest.approx(0.3)
assert len(transcript.segments) == 1
assert transcript.segments[0].text == "Hi"
assert transcript.segments[0].words[0].start == pytest.approx(0.0)
def test_verbose_json_to_transcript_reads_nested_words() -> None:
payload = {
"language": "en",
"duration": 1.0,
"segments": [
{
"start": 0.0,
"end": 1.0,
"text": "Hello",
"words": [{"word": "Hello", "start": 0.0, "end": 0.5}],
}
],
}
transcript = verbose_json_to_transcript([payload], [0.0], model="whisper-1")
assert transcript.segments[0].words[0].text == "Hello"
def test_verbose_json_to_transcript_requires_matching_offsets() -> None:
with pytest.raises(ValueError, match="offset"):
verbose_json_to_transcript([verbose_payload()], [], model="m")
def test_openai_transcriber_endpoint_normalises_trailing_slash() -> None:
settings = Settings(stt_api_base_url="https://example.test/v1/", stt_api_model="m")
transcriber = OpenAITranscriptionsTranscriber(settings.options_for("stt"), api_key="k")
assert transcriber.endpoint == "https://example.test/v1/audio/transcriptions"
def test_openai_transcriber_requires_an_api_key(monkeypatch: pytest.MonkeyPatch) -> None:
for name in openai_module.API_KEY_ENV_VARS:
monkeypatch.delenv(name, raising=False)
transcriber = OpenAITranscriptionsTranscriber(_stt_options())
with pytest.raises(RuntimeError, match="GROQ_API_KEY"):
transcriber._resolve_api_key()
def test_openai_transcriber_api_key_from_environment(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.delenv("VA_STT_API_KEY", raising=False)
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
monkeypatch.setenv("GROQ_API_KEY", "from-env")
assert OpenAITranscriptionsTranscriber(_stt_options())._resolve_api_key() == "from-env"
monkeypatch.delenv("GROQ_API_KEY")
monkeypatch.setenv("VA_STT_API_KEY", "from-va")
assert OpenAITranscriptionsTranscriber(_stt_options())._resolve_api_key() == "from-va"
@requires_ffmpeg
async def test_openai_transcriber_posts_multipart_and_maps_response(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setenv("GROQ_API_KEY", "secret-key")
wav = write_silent_wav(tmp_path / "audio.wav", seconds=0.6)
requests: list[httpx.Request] = []
bodies: list[bytes] = []
async def handler(request: httpx.Request) -> httpx.Response:
requests.append(request)
bodies.append(await request.aread())
return httpx.Response(200, json=verbose_payload(duration=0.6))
transport = httpx.MockTransport(handler)
async with httpx.AsyncClient(transport=transport) as client:
transcriber = OpenAITranscriptionsTranscriber(_stt_options(), client=client)
transcript = await transcriber.transcribe(wav)
assert len(requests) == 1
request = requests[0]
body = bodies[0]
assert str(request.url) == "https://api.groq.com/openai/v1/audio/transcriptions"
assert request.headers["authorization"] == "Bearer secret-key"
assert body.count(b'name="timestamp_granularities[]"') == 2
assert b"verbose_json" in body
assert b"whisper-large-v3-turbo" in body
assert b'filename="audio.flac"' in body
assert b"fLaC" in body
assert transcript.backend == "openai-transcriptions"
assert transcript.model == "whisper-large-v3-turbo"
assert transcript.language == "english"
assert transcript.duration == pytest.approx(0.6)
assert [segment.text for segment in transcript.segments] == ["Hello world."]
assert [word.text for word in transcript.segments[0].words] == ["Hello", "world."]
@requires_ffmpeg
async def test_openai_transcriber_forwards_language(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setenv("GROQ_API_KEY", "secret-key")
wav = write_silent_wav(tmp_path / "audio.wav", seconds=0.3)
bodies: list[bytes] = []
async def handler(request: httpx.Request) -> httpx.Response:
bodies.append(await request.aread())
return httpx.Response(200, json=verbose_payload(duration=0.3))
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
transcriber = OpenAITranscriptionsTranscriber(_stt_options(), client=client)
transcript = await transcriber.transcribe(wav, language="de")
assert b'name="language"' in bodies[0]
assert b"\r\n\r\nde\r\n" in bodies[0]
assert transcript.language == "de"
@requires_ffmpeg
async def test_openai_transcriber_raises_on_http_error(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setenv("GROQ_API_KEY", "bad-key")
wav = write_silent_wav(tmp_path / "audio.wav", seconds=0.3)
async def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(401, json={"error": {"message": "Invalid API key"}})
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
transcriber = OpenAITranscriptionsTranscriber(_stt_options(), client=client)
with pytest.raises(RuntimeError, match="401"):
await transcriber.transcribe(wav)
@requires_ffmpeg
async def test_openai_transcriber_splits_and_stitches_long_audio(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setenv("GROQ_API_KEY", "secret-key")
# Force the splitting branch and use sub-second chunks so a tiny WAV exercises it.
monkeypatch.setattr(openai_module, "MAX_UPLOAD_BYTES", 1)
monkeypatch.setattr(openai_module, "CHUNK_SECONDS", 0.4)
wav = write_silent_wav(tmp_path / "audio.wav", seconds=1.2)
bodies: list[bytes] = []
async def handler(request: httpx.Request) -> httpx.Response:
bodies.append(await request.aread())
return httpx.Response(200, json=verbose_payload(duration=0.4))
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
transcriber = OpenAITranscriptionsTranscriber(_stt_options(), client=client)
transcript = await transcriber.transcribe(wav)
assert len(bodies) >= 3
assert all(b"fLaC" in body for body in bodies)
starts = [segment.start for segment in transcript.segments]
assert len(starts) == len(bodies)
assert starts[0] == pytest.approx(0.0)
assert starts == sorted(starts)
for previous, current in itertools.pairwise(starts):
assert 0.2 < current - previous < 0.7
assert transcript.duration == pytest.approx(1.2, abs=0.15)
assert transcript.segments[-1].words[0].start > 0.6
# ------------------------------------------------------------------ heavy tests
@heavy
async def test_faster_whisper_real_model_smoke(tmp_path: Path) -> None:
pytest.importorskip("faster_whisper")
model_name = os.environ.get("VA_HEAVY_WHISPER_MODEL", "tiny")
settings = Settings(profile="local", stt_backend="whisper", whisper_model=model_name)
wav = write_silent_wav(tmp_path / "silence.wav", seconds=1.0)
transcript = await FasterWhisperTranscriber(settings.options_for("stt")).transcribe(wav)
assert transcript.backend == "whisper"
assert transcript.model == model_name
assert transcript.duration > 0.0
@heavy
async def test_parakeet_real_model_smoke(tmp_path: Path) -> None:
pytest.importorskip("onnx_asr")
settings = Settings(profile="local", stt_backend="parakeet", language="en")
wav = write_silent_wav(tmp_path / "silence.wav", seconds=1.0)
transcript = await ParakeetOnnxTranscriber(settings.options_for("stt")).transcribe(wav)
assert transcript.backend == "parakeet"
assert transcript.model == ENGLISH_MODEL
assert transcript.language == "en"
assert transcript.duration == pytest.approx(1.0)