Diarizer.diarize(wav, options) took an option value its constructor already held, so every caller passed the same object twice. The two concrete backends also exposed supported_options/ignored_options frozensets that nothing read - speculative hooks that duplicated what cache_params already makes explicit. - Diarizer.diarize(wav) uses the DiarizeOptions value the diarizer was built with; the protocol docstring states that ownership and pyannote's applicable knobs (num_speakers only; cluster/merge are sherpa segmentation settings) - SherpaDiarizer/PyannoteDiarizer drop supported_options and ignored_options; applicability stays observable in the protocol docstring, cache_params and the pyannote cache-params test - diarize_audio and the pipeline's diarize stage call diarize(wav) (the injectable test-stage seam keeps its (wav, *, options) signature) - tests: each backend applies the option value it was constructed with (both were red: diarize() required the extra argument)
786 lines
27 KiB
Python
786 lines
27 KiB
Python
"""Diarization tests: speaker attribution, model cache, sherpa config (offline only)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import importlib.util
|
|
import io
|
|
import sys
|
|
import tarfile
|
|
import wave
|
|
from dataclasses import replace
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
from typing import Any, ClassVar
|
|
|
|
import httpx
|
|
import numpy as np
|
|
import pytest
|
|
|
|
from video_analyse import model_assets
|
|
from video_analyse.config import Settings
|
|
from video_analyse.diarize import (
|
|
DIARIZE_BACKENDS,
|
|
DiarizeOptions,
|
|
Diarizer,
|
|
PyannoteDiarizer,
|
|
SherpaDiarizer,
|
|
_labels_to_turns,
|
|
_load_wav_mono,
|
|
_pcm_to_float32,
|
|
_segments_to_turns,
|
|
attribute_speakers,
|
|
build_sherpa_config,
|
|
diarize_audio,
|
|
get_diarizer,
|
|
)
|
|
from video_analyse.model_assets import (
|
|
EMBEDDING_MODEL,
|
|
MODEL_ASSETS,
|
|
SEGMENTATION_MODEL,
|
|
DiarizationModels,
|
|
ModelAsset,
|
|
check_model,
|
|
ensure_diarization_models,
|
|
ensure_model,
|
|
model_path,
|
|
)
|
|
from video_analyse.models import Segment, SpeakerTurn, Transcript, Word
|
|
|
|
VA_ENV_VARS = (
|
|
"VA_PROFILE",
|
|
"VA_CACHE_DIR",
|
|
"VA_DIARIZE",
|
|
"VA_DIARIZE_BACKEND",
|
|
"VA_DIARIZE_CLUSTER_THRESHOLD",
|
|
"VA_DIARIZE_MIN_DURATION_ON",
|
|
"VA_DIARIZE_MIN_DURATION_OFF",
|
|
"HF_TOKEN",
|
|
"HUGGING_FACE_HUB_TOKEN",
|
|
"HUGGINGFACEHUB_API_TOKEN",
|
|
)
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def clean_va_env(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""Make every test independent of the developer's environment."""
|
|
for name in VA_ENV_VARS:
|
|
monkeypatch.delenv(name, raising=False)
|
|
|
|
|
|
def _settings(tmp_path: Path, **overrides: Any) -> Settings:
|
|
return Settings(cache_dir=tmp_path, **overrides)
|
|
|
|
|
|
def _word(text: str, start: float, end: float) -> Word:
|
|
return Word(text=text, start=start, end=end)
|
|
|
|
|
|
def _transcript(segments: list[Segment], **kwargs: Any) -> Transcript:
|
|
duration = max((segment.end for segment in segments), default=0.0)
|
|
return Transcript(duration=duration, segments=segments, **kwargs)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# attribute_speakers
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_attribute_speakers_uses_word_midpoints() -> None:
|
|
transcript = _transcript(
|
|
[
|
|
Segment(
|
|
start=0.0,
|
|
end=3.0,
|
|
text="one two three",
|
|
words=[
|
|
# midpoint 0.5 -> S1
|
|
_word("one", 0.0, 1.0),
|
|
# starts in S1 but the midpoint (1.2) is in S2 -> S2
|
|
_word("two", 0.8, 1.6),
|
|
# midpoint 2.5 -> S2
|
|
_word("three", 2.4, 2.6),
|
|
],
|
|
)
|
|
]
|
|
)
|
|
turns = [
|
|
SpeakerTurn(start=0.0, end=1.0, speaker="S1"),
|
|
SpeakerTurn(start=1.0, end=3.0, speaker="S2"),
|
|
]
|
|
|
|
result = attribute_speakers(transcript, turns)
|
|
|
|
assert result.segments[0].speaker == "S2"
|
|
assert result.speaker_turns == turns
|
|
# the input transcript is left untouched
|
|
assert transcript.segments[0].speaker is None
|
|
assert transcript.speaker_turns == []
|
|
assert result is not transcript
|
|
|
|
|
|
def test_attribute_speakers_majority_beats_first_word() -> None:
|
|
transcript = _transcript(
|
|
[
|
|
Segment(
|
|
start=0.0,
|
|
end=4.0,
|
|
text="a b c",
|
|
words=[
|
|
_word("a", 2.2, 2.4), # S2 (1 word)
|
|
_word("b", 0.2, 0.4), # S1
|
|
_word("c", 0.6, 0.8), # S1
|
|
],
|
|
)
|
|
]
|
|
)
|
|
turns = [
|
|
SpeakerTurn(start=0.0, end=2.0, speaker="S1"),
|
|
SpeakerTurn(start=2.0, end=4.0, speaker="S2"),
|
|
]
|
|
|
|
result = attribute_speakers(transcript, turns)
|
|
assert result.segments[0].speaker == "S1"
|
|
|
|
|
|
def test_attribute_speakers_tie_goes_to_first_attributed_word() -> None:
|
|
transcript = _transcript(
|
|
[
|
|
Segment(
|
|
start=0.0,
|
|
end=4.0,
|
|
text="a b",
|
|
words=[_word("a", 2.2, 2.4), _word("b", 0.2, 0.4)],
|
|
)
|
|
]
|
|
)
|
|
turns = [
|
|
SpeakerTurn(start=0.0, end=2.0, speaker="S1"),
|
|
SpeakerTurn(start=2.0, end=4.0, speaker="S2"),
|
|
]
|
|
|
|
result = attribute_speakers(transcript, turns)
|
|
# 1:1 tie -> the earliest attributed word is "a" (S2)
|
|
assert result.segments[0].speaker == "S2"
|
|
|
|
|
|
def test_attribute_speakers_without_turns_is_unchanged() -> None:
|
|
transcript = _transcript(
|
|
[
|
|
Segment(
|
|
start=0.0,
|
|
end=1.0,
|
|
text="hello",
|
|
words=[_word("hello", 0.1, 0.9)],
|
|
speaker="S7",
|
|
)
|
|
],
|
|
speaker_turns=[SpeakerTurn(start=0.0, end=1.0, speaker="S7")],
|
|
)
|
|
|
|
result = attribute_speakers(transcript, [])
|
|
|
|
assert result == transcript
|
|
assert result is not transcript
|
|
assert result.segments[0].speaker == "S7"
|
|
|
|
|
|
def test_attribute_speakers_words_without_a_turn_get_no_speaker() -> None:
|
|
transcript = _transcript(
|
|
[
|
|
Segment(
|
|
start=0.0,
|
|
end=2.0,
|
|
text="outside",
|
|
words=[_word("outside", 0.0, 2.0)],
|
|
speaker="S3",
|
|
),
|
|
Segment(start=2.0, end=3.0, text="no words"),
|
|
]
|
|
)
|
|
turns = [SpeakerTurn(start=10.0, end=12.0, speaker="S1")]
|
|
|
|
result = attribute_speakers(transcript, turns)
|
|
|
|
assert result.segments[0].speaker is None # stale label cleared
|
|
assert result.segments[1].speaker is None # no words -> no attribution
|
|
assert result.speaker_turns == turns
|
|
|
|
|
|
def test_attribute_speakers_boundary_midpoint_belongs_to_earliest_turn() -> None:
|
|
transcript = _transcript(
|
|
[
|
|
Segment(
|
|
start=0.0,
|
|
end=2.0,
|
|
text="edge",
|
|
# midpoint is exactly 1.0 = end of turn S1 and start of turn S2
|
|
words=[_word("edge", 0.6, 1.4)],
|
|
)
|
|
]
|
|
)
|
|
turns = [
|
|
SpeakerTurn(start=0.0, end=1.0, speaker="S1"),
|
|
SpeakerTurn(start=1.0, end=2.0, speaker="S2"),
|
|
]
|
|
|
|
result = attribute_speakers(transcript, turns)
|
|
assert result.segments[0].speaker == "S1"
|
|
|
|
|
|
def test_attribute_speakers_overlapping_turns_prefer_the_earliest() -> None:
|
|
transcript = _transcript(
|
|
[
|
|
Segment(
|
|
start=0.0,
|
|
end=4.0,
|
|
text="overlap",
|
|
words=[_word("overlap", 2.0, 3.0)], # midpoint 2.5 is in both turns
|
|
)
|
|
]
|
|
)
|
|
turns = [
|
|
SpeakerTurn(start=0.0, end=3.0, speaker="S1"),
|
|
SpeakerTurn(start=2.0, end=4.0, speaker="S2"),
|
|
]
|
|
|
|
result = attribute_speakers(transcript, turns)
|
|
assert result.segments[0].speaker == "S1"
|
|
|
|
|
|
def test_attribute_speakers_handles_turns_out_of_order() -> None:
|
|
transcript = _transcript(
|
|
[
|
|
Segment(
|
|
start=0.0,
|
|
end=4.0,
|
|
text="late early",
|
|
words=[_word("late", 3.0, 3.5), _word("early", 0.5, 1.0)],
|
|
)
|
|
]
|
|
)
|
|
turns = [
|
|
SpeakerTurn(start=2.0, end=4.0, speaker="S2"),
|
|
SpeakerTurn(start=0.0, end=2.0, speaker="S1"),
|
|
]
|
|
|
|
result = attribute_speakers(transcript, turns)
|
|
# tie 1:1 -> earliest word "late" is S2
|
|
assert result.segments[0].speaker == "S2"
|
|
assert [turn.speaker for turn in result.speaker_turns] == ["S2", "S1"]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# sherpa-onnx turn mapping / config construction (no inference, no download)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_labels_to_turns_assigns_ids_by_first_appearance() -> None:
|
|
spans = [
|
|
(0.0, 1.0, 7),
|
|
(1.0, 2.0, 3),
|
|
(2.0, 3.0, 7),
|
|
(3.0, 3.0, 9), # zero-length -> dropped
|
|
]
|
|
turns = _labels_to_turns(spans)
|
|
assert [turn.speaker for turn in turns] == ["S1", "S2", "S1"]
|
|
assert turns[0].start == 0.0 and turns[0].end == 1.0
|
|
|
|
|
|
def test_segments_to_turns_maps_sherpa_segments() -> None:
|
|
segments = [
|
|
SimpleNamespace(start=0.0, end=0.8, speaker=5),
|
|
SimpleNamespace(start=0.8, end=1.6, speaker=2),
|
|
SimpleNamespace(start=1.6, end=2.4, speaker=5),
|
|
]
|
|
turns = _segments_to_turns(segments)
|
|
assert [turn.speaker for turn in turns] == ["S1", "S2", "S1"]
|
|
|
|
|
|
def test_build_sherpa_config_from_dummy_model_paths(tmp_path: Path) -> None:
|
|
sherpa_onnx = pytest.importorskip("sherpa_onnx")
|
|
segmentation = tmp_path / "model.onnx"
|
|
embedding = tmp_path / "embedding.onnx"
|
|
segmentation.write_bytes(b"dummy segmentation placeholder")
|
|
embedding.write_bytes(b"dummy embedding placeholder")
|
|
|
|
options = DiarizeOptions(
|
|
backend="sherpa",
|
|
cluster_threshold=0.42,
|
|
min_duration_on=0.25,
|
|
min_duration_off=0.6,
|
|
cache_dir=tmp_path,
|
|
num_speakers=2,
|
|
)
|
|
config = build_sherpa_config(
|
|
segmentation,
|
|
embedding,
|
|
options=options,
|
|
num_threads=16,
|
|
)
|
|
|
|
assert isinstance(config, sherpa_onnx.OfflineSpeakerDiarizationConfig)
|
|
assert config.segmentation.pyannote.model == str(segmentation)
|
|
assert config.segmentation.pyannote.window_shift_ratio == pytest.approx(0.1, abs=1e-6)
|
|
assert config.segmentation.num_threads == 16
|
|
assert config.segmentation.provider == "cpu"
|
|
assert config.segmentation.debug is False
|
|
assert config.embedding.model == str(embedding)
|
|
assert config.embedding.num_threads == 16
|
|
assert config.embedding.provider == "cpu"
|
|
assert config.clustering.num_clusters == 2
|
|
assert config.clustering.threshold == pytest.approx(0.42, abs=1e-6)
|
|
assert config.clustering.compute_confidence is False
|
|
assert config.min_duration_on == pytest.approx(0.25, abs=1e-6)
|
|
assert config.min_duration_off == pytest.approx(0.6, abs=1e-6)
|
|
assert config.validate() is True
|
|
|
|
|
|
def test_build_sherpa_config_defaults(tmp_path: Path) -> None:
|
|
pytest.importorskip("sherpa_onnx")
|
|
segmentation = tmp_path / "model.onnx"
|
|
embedding = tmp_path / "embedding.onnx"
|
|
segmentation.write_bytes(b"x")
|
|
embedding.write_bytes(b"y")
|
|
|
|
options = _settings(tmp_path).options_for("diarize")
|
|
assert isinstance(options, DiarizeOptions)
|
|
config = build_sherpa_config(segmentation, embedding, options=options)
|
|
|
|
assert config.segmentation.num_threads == 1
|
|
assert config.clustering.num_clusters == -1
|
|
assert config.clustering.threshold == pytest.approx(0.7, abs=1e-6)
|
|
assert config.min_duration_on == pytest.approx(0.3, abs=1e-6)
|
|
assert config.min_duration_off == pytest.approx(0.5, abs=1e-6)
|
|
|
|
|
|
def test_build_sherpa_config_rejects_missing_models(tmp_path: Path) -> None:
|
|
options = _settings(tmp_path).options_for("diarize")
|
|
with pytest.raises(ValueError, match="does not exist"):
|
|
build_sherpa_config(
|
|
tmp_path / "missing-seg.onnx", tmp_path / "missing-emb.onnx", options=options
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# WAV loading
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _write_wav(path: Path, samples: np.ndarray, rate: int, channels: int = 1) -> Path:
|
|
with wave.open(str(path), "wb") as handle:
|
|
handle.setnchannels(channels)
|
|
handle.setsampwidth(2)
|
|
handle.setframerate(rate)
|
|
handle.writeframes(np.asarray(samples, dtype="<i2").tobytes())
|
|
return path
|
|
|
|
|
|
def test_load_wav_mono_decodes_16k_mono(tmp_path: Path) -> None:
|
|
samples = np.full(1600, 16384, dtype=np.int16) # 0.5 * 32768, 0.1 s
|
|
wav = _write_wav(tmp_path / "mono.wav", samples, 16_000)
|
|
|
|
loaded, rate = _load_wav_mono(wav)
|
|
|
|
assert rate == 16_000
|
|
assert loaded.dtype == np.float32
|
|
assert loaded.shape == (1600,)
|
|
assert float(loaded.mean()) == pytest.approx(0.5, abs=1e-4)
|
|
|
|
|
|
def test_load_wav_mono_downmixes_and_resamples(tmp_path: Path) -> None:
|
|
one_second = np.zeros((8000, 2), dtype=np.int16)
|
|
one_second[:, 0] = 16384 # left 0.5
|
|
one_second[:, 1] = -16384 # right -0.5 -> average 0.0
|
|
wav = _write_wav(tmp_path / "stereo8k.wav", one_second.reshape(-1), 8000, channels=2)
|
|
|
|
loaded, rate = _load_wav_mono(wav, target_sample_rate=16_000)
|
|
|
|
assert rate == 16_000
|
|
assert abs(loaded.size - 16_000) <= 2
|
|
assert float(np.abs(loaded).max()) < 1e-3
|
|
|
|
|
|
def test_pcm_to_float32_sign_extends_24_bit() -> None:
|
|
raw = b"\x00\x00\x40" + b"\x00\x00\xc0"
|
|
values = _pcm_to_float32(raw, 3)
|
|
assert values[0] == pytest.approx(0.5, abs=1e-6)
|
|
assert values[1] == pytest.approx(-0.5, abs=1e-6)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# model_assets: path layout, idempotency, mocked downloads (no real network)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_model_path_layout(tmp_path: Path) -> None:
|
|
segmentation = model_path(SEGMENTATION_MODEL, cache_dir=tmp_path)
|
|
embedding = model_path(EMBEDDING_MODEL, cache_dir=tmp_path)
|
|
|
|
assert segmentation == tmp_path / "models" / SEGMENTATION_MODEL / "model.onnx"
|
|
assert embedding == tmp_path / "models" / EMBEDDING_MODEL / f"{EMBEDDING_MODEL}.onnx"
|
|
# a trailing suffix is tolerated
|
|
assert model_path(f"{EMBEDDING_MODEL}.onnx", cache_dir=tmp_path) == embedding
|
|
|
|
|
|
def test_check_model_is_the_shared_validity_predicate(tmp_path: Path, monkeypatch) -> None:
|
|
payload = b"verified-model-bytes"
|
|
asset = _dummy_asset("unit-test-check-model", payload)
|
|
monkeypatch.setitem(MODEL_ASSETS, asset.name, asset)
|
|
target = model_path(asset.name, cache_dir=tmp_path)
|
|
|
|
missing = check_model(asset.name, cache_dir=tmp_path)
|
|
assert missing.present is False
|
|
assert missing.valid is False
|
|
|
|
target.parent.mkdir(parents=True)
|
|
target.write_bytes(payload)
|
|
valid = check_model(asset.name, cache_dir=tmp_path)
|
|
assert valid.present is True
|
|
assert valid.valid is True
|
|
assert valid.size_bytes == len(payload)
|
|
|
|
target.write_bytes(b"truncated")
|
|
invalid = check_model(asset.name, cache_dir=tmp_path)
|
|
assert invalid.present is True
|
|
assert invalid.valid is False
|
|
assert invalid.reason is not None and "expected" in invalid.reason
|
|
|
|
|
|
def test_every_registered_diarizer_satisfies_the_protocol(tmp_path: Path) -> None:
|
|
for backend in DIARIZE_BACKENDS:
|
|
options = _settings(tmp_path, diarize_backend=backend).options_for("diarize")
|
|
diarizer = get_diarizer(options)
|
|
assert isinstance(diarizer, Diarizer)
|
|
assert isinstance(diarizer.cache_params(), dict)
|
|
assert diarizer.cache_params()["backend"] == backend
|
|
|
|
|
|
def test_pyannote_cache_params_only_include_applicable_options(tmp_path: Path) -> None:
|
|
sherpa = get_diarizer(_settings(tmp_path, diarize_backend="sherpa").options_for("diarize"))
|
|
pyannote = get_diarizer(_settings(tmp_path, diarize_backend="pyannote").options_for("diarize"))
|
|
|
|
assert isinstance(sherpa, SherpaDiarizer)
|
|
assert isinstance(pyannote, PyannoteDiarizer)
|
|
assert {
|
|
"cluster_threshold",
|
|
"min_duration_on",
|
|
"min_duration_off",
|
|
} <= sherpa.cache_params().keys()
|
|
assert pyannote.cache_params() == {"backend": "pyannote", "num_speakers": -1}
|
|
|
|
|
|
async def test_sherpa_diarizer_uses_the_options_it_was_constructed_with(
|
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
"""The constructor owns the option value; diarize(wav) needs no second copy."""
|
|
options = _settings(tmp_path).options_for("diarize")
|
|
models = DiarizationModels(
|
|
segmentation=tmp_path / "segmentation.onnx",
|
|
embedding=tmp_path / "embedding.onnx",
|
|
)
|
|
seen: list[DiarizeOptions] = []
|
|
|
|
async def fake_ensure(*, cache_dir: Path) -> DiarizationModels:
|
|
assert cache_dir == options.cache_dir
|
|
return models
|
|
|
|
def fake_run(
|
|
wav: Path, run_models: DiarizationModels, *, options: DiarizeOptions, num_threads: int
|
|
) -> list[SpeakerTurn]:
|
|
seen.append(options)
|
|
return [SpeakerTurn(start=0.0, end=0.5, speaker="S1")]
|
|
|
|
monkeypatch.setattr("video_analyse.diarize.ensure_diarization_models", fake_ensure)
|
|
monkeypatch.setattr("video_analyse.diarize._run_sherpa_diarization", fake_run)
|
|
wav = _write_wav(tmp_path / "audio.wav", np.zeros(1600, dtype=np.int16), 16_000)
|
|
|
|
turns = await get_diarizer(options).diarize(wav)
|
|
|
|
assert turns == [SpeakerTurn(start=0.0, end=0.5, speaker="S1")]
|
|
assert seen == [options]
|
|
|
|
|
|
async def test_pyannote_diarizer_uses_its_constructed_num_speakers(
|
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
"""pyannote's only applicable knob comes from the constructed option value too."""
|
|
options = (
|
|
_settings(tmp_path, diarize_backend="pyannote")
|
|
.options_for("diarize")
|
|
.model_copy(update={"num_speakers": 3})
|
|
)
|
|
seen: list[int] = []
|
|
|
|
async def fake_diarize(wav: Path, *, num_speakers: int = -1) -> list[SpeakerTurn]:
|
|
seen.append(num_speakers)
|
|
return []
|
|
|
|
monkeypatch.setattr("video_analyse.diarize._pyannote_available", lambda: True)
|
|
monkeypatch.setattr("video_analyse.diarize._diarize_with_pyannote", fake_diarize)
|
|
wav = tmp_path / "audio.wav"
|
|
wav.write_bytes(b"RIFF-not-really-a-wav")
|
|
|
|
assert await get_diarizer(options).diarize(wav) == []
|
|
assert seen == [3]
|
|
|
|
|
|
def test_get_diarizer_rejects_an_unknown_backend(tmp_path: Path) -> None:
|
|
options = _settings(tmp_path).options_for("diarize")
|
|
with pytest.raises(ValueError, match="nope"):
|
|
get_diarizer(options.model_copy(update={"backend": "nope"}))
|
|
|
|
|
|
async def test_ensure_model_is_idempotent_without_download(
|
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
payload = b"already-cached-dummy-model"
|
|
asset = _dummy_asset(EMBEDDING_MODEL, payload, filename="embedding.onnx")
|
|
monkeypatch.setitem(MODEL_ASSETS, EMBEDDING_MODEL, asset)
|
|
target = model_path(EMBEDDING_MODEL, cache_dir=tmp_path)
|
|
target.parent.mkdir(parents=True)
|
|
target.write_bytes(payload)
|
|
|
|
def _no_http(*args: Any, **kwargs: Any) -> Any:
|
|
raise AssertionError("ensure_model must not open an HTTP client for a cached file")
|
|
|
|
monkeypatch.setattr(model_assets.httpx, "AsyncClient", _no_http)
|
|
|
|
first = await ensure_model(EMBEDDING_MODEL, cache_dir=tmp_path)
|
|
second = await ensure_model(EMBEDDING_MODEL, cache_dir=tmp_path)
|
|
|
|
assert first == second == target
|
|
assert target.read_bytes() == payload
|
|
|
|
|
|
async def test_ensure_model_rejects_unknown_name(tmp_path: Path) -> None:
|
|
with pytest.raises(ValueError, match="Available models"):
|
|
await ensure_model("not-a-model", cache_dir=tmp_path)
|
|
|
|
|
|
def _dummy_asset(name: str, payload: bytes, **kwargs: Any) -> ModelAsset:
|
|
return ModelAsset(
|
|
name=name,
|
|
url=f"https://example.invalid/{name}.bin",
|
|
filename=kwargs.pop("filename", f"{name}.onnx"),
|
|
size_bytes=len(payload),
|
|
sha256=hashlib.sha256(payload).hexdigest(),
|
|
**kwargs,
|
|
)
|
|
|
|
|
|
async def test_ensure_model_streams_download_and_replaces_empty_file(
|
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
payload = b"onnx-bytes" * 512
|
|
asset = _dummy_asset("unit-test-embedding", payload)
|
|
monkeypatch.setitem(MODEL_ASSETS, asset.name, asset)
|
|
target = model_path(asset.name, cache_dir=tmp_path)
|
|
target.parent.mkdir(parents=True)
|
|
target.write_bytes(b"") # truncated leftovers from an interrupted run
|
|
|
|
def handler(request: httpx.Request) -> httpx.Response:
|
|
assert str(request.url) == asset.url
|
|
return httpx.Response(200, content=payload)
|
|
|
|
transport = httpx.MockTransport(handler)
|
|
async with httpx.AsyncClient(transport=transport) as client:
|
|
resolved = await ensure_model(asset.name, cache_dir=tmp_path, client=client)
|
|
|
|
assert resolved == target
|
|
assert target.read_bytes() == payload
|
|
assert [entry.name for entry in target.parent.iterdir()] == [target.name]
|
|
|
|
|
|
async def test_ensure_model_extracts_archive_member(
|
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
payload = b"fake segmentation onnx payload"
|
|
buffer = io.BytesIO()
|
|
with tarfile.open(fileobj=buffer, mode="w:bz2") as tar:
|
|
info = tarfile.TarInfo(f"{SEGMENTATION_MODEL}/model.onnx")
|
|
info.size = len(payload)
|
|
tar.addfile(info, io.BytesIO(payload))
|
|
archive_bytes = buffer.getvalue()
|
|
|
|
asset = _dummy_asset(
|
|
"unit-test-segmentation",
|
|
payload,
|
|
filename="model.onnx",
|
|
archive_member=f"{SEGMENTATION_MODEL}/model.onnx",
|
|
)
|
|
asset = replace(asset, url="https://example.invalid/unit-test-segmentation.tar.bz2")
|
|
monkeypatch.setitem(MODEL_ASSETS, asset.name, asset)
|
|
|
|
transport = httpx.MockTransport(lambda request: httpx.Response(200, content=archive_bytes))
|
|
async with httpx.AsyncClient(transport=transport) as client:
|
|
resolved = await ensure_model(asset.name, cache_dir=tmp_path, client=client)
|
|
|
|
assert resolved == tmp_path / "models" / asset.name / "model.onnx"
|
|
assert resolved.read_bytes() == payload
|
|
assert [entry.name for entry in resolved.parent.iterdir()] == ["model.onnx"]
|
|
|
|
|
|
async def test_ensure_model_redownloads_a_corrupted_cached_file(
|
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
payload = b"correct-model-payload"
|
|
asset = _dummy_asset("unit-test-cached-corrupt", payload)
|
|
monkeypatch.setitem(MODEL_ASSETS, asset.name, asset)
|
|
target = model_path(asset.name, cache_dir=tmp_path)
|
|
target.parent.mkdir(parents=True)
|
|
target.write_bytes(b"x" * len(payload))
|
|
assert target.stat().st_size == len(payload)
|
|
|
|
transport = httpx.MockTransport(lambda request: httpx.Response(200, content=payload))
|
|
async with httpx.AsyncClient(transport=transport) as client:
|
|
resolved = await ensure_model(asset.name, cache_dir=tmp_path, client=client)
|
|
|
|
assert resolved == target
|
|
assert target.read_bytes() == payload
|
|
|
|
|
|
async def test_ensure_model_rejects_corrupt_download(
|
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
payload = b"corrupt bytes"
|
|
asset = replace(_dummy_asset("unit-test-corrupt", payload), sha256="0" * 64)
|
|
monkeypatch.setitem(MODEL_ASSETS, asset.name, asset)
|
|
|
|
transport = httpx.MockTransport(lambda request: httpx.Response(200, content=payload))
|
|
async with httpx.AsyncClient(transport=transport) as client:
|
|
with pytest.raises(RuntimeError, match="Integrity check failed"):
|
|
await ensure_model(asset.name, cache_dir=tmp_path, client=client)
|
|
|
|
target = model_path(asset.name, cache_dir=tmp_path)
|
|
assert not target.exists()
|
|
assert list(target.parent.iterdir()) == []
|
|
|
|
|
|
async def test_ensure_diarization_models_returns_both_cached_paths(
|
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
payloads = {
|
|
SEGMENTATION_MODEL: b"cached-segmentation-model",
|
|
EMBEDDING_MODEL: b"cached-embedding-model",
|
|
}
|
|
for name, payload in payloads.items():
|
|
asset = _dummy_asset(name, payload, filename=f"{name}.onnx")
|
|
monkeypatch.setitem(MODEL_ASSETS, name, asset)
|
|
path = model_path(name, cache_dir=tmp_path)
|
|
path.parent.mkdir(parents=True)
|
|
path.write_bytes(payload)
|
|
|
|
def _no_http(*args: Any, **kwargs: Any) -> Any:
|
|
raise AssertionError("both models are cached; no HTTP client should be created")
|
|
|
|
monkeypatch.setattr(model_assets.httpx, "AsyncClient", _no_http)
|
|
|
|
models = await ensure_diarization_models(cache_dir=tmp_path)
|
|
|
|
assert models.segmentation == model_path(SEGMENTATION_MODEL, cache_dir=tmp_path)
|
|
assert models.embedding == model_path(EMBEDDING_MODEL, cache_dir=tmp_path)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# diarize_audio entry point (no downloads, no inference)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
async def test_diarize_audio_missing_file_raises(tmp_path: Path) -> None:
|
|
options = _settings(tmp_path).options_for("diarize")
|
|
with pytest.raises(ValueError, match="not found"):
|
|
await diarize_audio(tmp_path / "missing.wav", options)
|
|
|
|
|
|
async def test_pyannote_backend_without_extra_reports_install_hint(tmp_path: Path) -> None:
|
|
try:
|
|
available = importlib.util.find_spec("pyannote.audio") is not None
|
|
except (ImportError, ValueError):
|
|
available = False
|
|
if available:
|
|
pytest.skip("pyannote.audio is installed; the missing-extra path cannot be tested")
|
|
|
|
wav = tmp_path / "audio.wav"
|
|
wav.write_bytes(b"RIFF-not-really-a-wav")
|
|
options = _settings(tmp_path, diarize_backend="pyannote").options_for("diarize")
|
|
|
|
with pytest.raises(ImportError, match=r"video-analyse\[pyannote\]") as excinfo:
|
|
await diarize_audio(wav, options)
|
|
assert "HF_TOKEN" in str(excinfo.value)
|
|
|
|
|
|
async def test_diarize_audio_sherpa_happy_path_uses_the_option_value(
|
|
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
"""The sherpa path is testable with a fake module and honours every option knob."""
|
|
|
|
class FakeConfig:
|
|
def __init__(self, **kwargs: Any) -> None:
|
|
self.__dict__.update(kwargs)
|
|
|
|
class FakeDiarizer:
|
|
instances: ClassVar[list[FakeDiarizer]] = []
|
|
|
|
def __init__(self, config: Any) -> None:
|
|
self.config = config
|
|
self.sample_rate = 16_000
|
|
self.samples: np.ndarray | None = None
|
|
FakeDiarizer.instances.append(self)
|
|
|
|
def process(self, samples: np.ndarray) -> Any:
|
|
self.samples = samples
|
|
return SimpleNamespace(
|
|
sort_by_start_time=lambda: [
|
|
SimpleNamespace(start=0.0, end=0.4, speaker=7),
|
|
SimpleNamespace(start=0.4, end=0.8, speaker=3),
|
|
]
|
|
)
|
|
|
|
fake_sherpa = SimpleNamespace(
|
|
OfflineSpeakerDiarizationConfig=FakeConfig,
|
|
OfflineSpeakerSegmentationModelConfig=FakeConfig,
|
|
OfflineSpeakerSegmentationPyannoteModelConfig=FakeConfig,
|
|
SpeakerEmbeddingExtractorConfig=FakeConfig,
|
|
FastClusteringConfig=FakeConfig,
|
|
OfflineSpeakerDiarization=FakeDiarizer,
|
|
)
|
|
monkeypatch.setitem(sys.modules, "sherpa_onnx", fake_sherpa)
|
|
|
|
models = DiarizationModels(
|
|
segmentation=tmp_path / "segmentation.onnx",
|
|
embedding=tmp_path / "embedding.onnx",
|
|
)
|
|
models.segmentation.write_bytes(b"segmentation")
|
|
models.embedding.write_bytes(b"embedding")
|
|
|
|
async def fake_ensure(*, cache_dir: Path) -> DiarizationModels:
|
|
assert cache_dir == tmp_path
|
|
return models
|
|
|
|
monkeypatch.setattr("video_analyse.diarize.ensure_diarization_models", fake_ensure)
|
|
|
|
samples = np.full(1600, 8192, dtype=np.int16)
|
|
wav = _write_wav(tmp_path / "audio.wav", samples, 16_000)
|
|
options = Settings(
|
|
cache_dir=tmp_path,
|
|
diarize_cluster_threshold=0.42,
|
|
diarize_min_duration_on=0.25,
|
|
diarize_min_duration_off=0.6,
|
|
).options_for("diarize")
|
|
|
|
turns = await diarize_audio(wav, options)
|
|
|
|
assert [turn.speaker for turn in turns] == ["S1", "S2"]
|
|
assert [(turn.start, turn.end) for turn in turns] == [(0.0, 0.4), (0.4, 0.8)]
|
|
(diarizer,) = FakeDiarizer.instances
|
|
assert diarizer.config.segmentation.pyannote.model == str(models.segmentation)
|
|
assert diarizer.config.embedding.model == str(models.embedding)
|
|
assert diarizer.config.clustering.threshold == pytest.approx(0.42)
|
|
assert diarizer.config.clustering.num_clusters == -1
|
|
assert diarizer.config.min_duration_on == pytest.approx(0.25)
|
|
assert diarizer.config.min_duration_off == pytest.approx(0.6)
|
|
assert diarizer.samples is not None
|
|
assert diarizer.samples.shape == (1600,)
|
|
assert float(diarizer.samples.max()) == pytest.approx(0.25, abs=1e-4)
|