cmvr-visual/inference/tests/test_native_av_silence.py

332 lines
12 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""静默必须由同一原音轨完整选段的独立CPU VAD实测确认。"""
import hashlib
import sys
import wave
from copy import deepcopy
from types import SimpleNamespace
import numpy as np
import pytest
def module():
from llm_services.dialogue import native_silence
return native_silence
@pytest.fixture(autouse=True)
def audio_library_boundary(monkeypatch):
# 只替代本机未安装的文件库/重采样库;真正写入和读取PCM WAV,不替代VAD待测逻辑。
class SoundFile:
def __init__(self, stream):
self.reader = wave.open(stream, "rb") # noqa: SIM115 -- 此测试文件接口由__exit__关闭。
self.samplerate = self.reader.getframerate()
self.channels = self.reader.getnchannels()
self.frames = self.reader.getnframes()
assert self.reader.getsampwidth() == 2
def __enter__(self):
return self
def __exit__(self, *args):
self.reader.close()
def seek(self, position):
self.reader.setpos(position)
def read(self, frames, *, dtype, always_2d):
assert dtype == "float32" and always_2d is True
return (
np.frombuffer(self.reader.readframes(frames), dtype="<i2")
.astype(np.float32)
.reshape(-1, self.channels)
/ 32768
)
def resample_poly(values, up, down, *, axis):
assert values.ndim == 1 and up == 1 and down == 3 and axis == 0
return values[::3]
monkeypatch.setitem(sys.modules, "soundfile", SimpleNamespace(SoundFile=SoundFile))
monkeypatch.setitem(sys.modules, "scipy", SimpleNamespace())
monkeypatch.setitem(
sys.modules, "scipy.signal", SimpleNamespace(resample_poly=resample_poly)
)
def source_audio(tmp_path, wav, *, start_sample=0, end_sample=None):
values = wav.reshape(-1, 1) if wav.ndim == 1 else wav
source_count = len(wav) * 3 if end_sample is None else end_sample - start_sample
source = np.concatenate(
(
np.zeros((start_sample, values.shape[1]), np.float32),
np.repeat(values, 3, axis=0)[:source_count],
)
)
path = tmp_path / "source.wav"
with wave.open(str(path), "wb") as output:
output.setparams((values.shape[1], 2, 48000, 0, "NONE", "not compressed"))
output.writeframes(np.rint(source * 32768).astype("<i2").tobytes())
return (
path,
hashlib.sha256(path.read_bytes()).hexdigest(),
start_sample + source_count,
)
def inspect_vad(tmp_path, wav, *, start_sample=0, end_sample=None):
path, sha, end = source_audio(
tmp_path, wav, start_sample=start_sample, end_sample=end_sample
)
return module().inspect_silence(
path, tmp_path, audio_sha256=sha, start_sample=start_sample, end_sample=end
)
def fake_runtime(tmp_path, monkeypatch, probabilities, *, windows_per_channel=None):
mod = module()
weights = b"CPU fake ONNX boundary"
path = tmp_path / "silero-vad" / "silero_vad.onnx"
path.parent.mkdir()
path.write_bytes(weights)
monkeypatch.setattr(mod, "MODEL_SHA256", hashlib.sha256(weights).hexdigest())
monkeypatch.setattr(mod, "MODEL_BYTES", len(weights))
calls = []
windows_per_channel = windows_per_channel or len(probabilities)
class Session:
def __init__(self, path, *, providers, sess_options):
assert providers == ["CPUExecutionProvider"]
assert (
sess_options.inter_op_num_threads
== sess_options.intra_op_num_threads
== 1
)
def get_providers(self):
return ["CPUExecutionProvider"]
def run(self, outputs, feed):
assert set(feed) == {"input", "state", "sr"}
assert feed["input"].shape == (1, 576) and feed["input"].dtype == np.float32
assert feed["state"].shape == (2, 1, 128)
assert np.all(feed["state"] == len(calls) % windows_per_channel)
assert feed["sr"].dtype == np.int64 and feed["sr"].item() == 16000
calls.append(feed["input"].copy())
probability = (
probabilities(feed["input"])
if callable(probabilities)
else probabilities[len(calls) - 1]
)
return np.array([[probability]], np.float64), np.ones(
(2, 1, 128), np.float32
) * ((len(calls) - 1) % windows_per_channel + 1)
monkeypatch.setitem(
sys.modules,
"onnxruntime",
SimpleNamespace(
__version__="1.31.1",
SessionOptions=SimpleNamespace,
InferenceSession=Session,
),
)
return calls
def test_vad_covers_entire_original_selection_with_state_context_and_padded_tail(
tmp_path, monkeypatch
):
calls = fake_runtime(tmp_path, monkeypatch, [0.01, 0.02, 0.03])
wav = np.arange(1025, dtype=np.float32) / 2048
result = inspect_vad(tmp_path, wav, start_sample=48000, end_sample=51073)
assert result["decision"] == "no_speech" and result["status"] == "completed"
assert result["sample_count"] == 1025 and result["window_count"] == 3
sha = hashlib.sha256((tmp_path / "source.wav").read_bytes()).hexdigest()
assert result["source_audio_sha256"] == sha
assert (
result["channel_policy"] == "all_channels_no_speech" and result["channels"] == 1
)
assert result["channel_probabilities"] == [[0.01, 0.02, 0.03]]
assert (
result["source_start_sample"] == 48000 and result["source_end_sample"] == 51073
)
assert len(calls) == 3
np.testing.assert_array_equal(calls[0][0, :64], np.zeros(64))
np.testing.assert_array_equal(calls[1][0, :64], wav[448:512])
np.testing.assert_array_equal(calls[2][0, :64], wav[960:1024])
assert calls[2][0, 64] == wav[1024] and not calls[2][0, 65:].any()
module().validate_evidence(result, sha, 48000, 51073)
@pytest.mark.parametrize(
"probability,decision",
[
(0.1, "no_speech"),
(0.35, "indeterminate"),
(0.49, "indeterminate"),
(0.5, "speech"),
(0.9, "speech"),
],
)
def test_vad_does_not_discard_short_speech_or_uncertain_windows(
tmp_path, monkeypatch, probability, decision
):
fake_runtime(tmp_path, monkeypatch, [probability])
result = inspect_vad(tmp_path, np.zeros(512, np.float32))
assert result["decision"] == decision
@pytest.mark.parametrize("bad", [float("nan"), float("inf"), -0.1, 1.1])
def test_vad_invalid_model_probabilities_fail_closed(tmp_path, monkeypatch, bad):
fake_runtime(tmp_path, monkeypatch, [bad])
with pytest.raises(ValueError):
inspect_vad(tmp_path, np.zeros(512, np.float32))
@pytest.mark.parametrize(
"change",
[
"range",
"audiohash",
"hash",
"revision",
"runtime",
"count",
"windows",
"max",
"threshold",
"missing_probability",
"speech_claimed_silent",
],
)
def test_vad_evidence_is_bound_to_source_model_runtime_and_every_window(
tmp_path, monkeypatch, change
):
fake_runtime(tmp_path, monkeypatch, [0.1, 0.2])
result = inspect_vad(tmp_path, np.zeros(1024, np.float32))
bad = deepcopy(result)
key, value = {
"range": ("source_end_sample", 1536),
"audiohash": ("source_audio_sha256", "b" * 64),
"hash": ("model_sha256", "b" * 64),
"revision": ("revision", "b" * 40),
"runtime": ("runtime_version", "unknown"),
"count": ("sample_count", 512),
"windows": ("window_count", 1),
"max": ("max_speech_probability", 0.0),
"threshold": ("negative_threshold", 0.6),
"missing_probability": ("probabilities", [0.1]),
"speech_claimed_silent": ("probabilities", [0.1, 0.9]),
}[change]
bad[key] = value
with pytest.raises(ValueError):
module().validate_evidence(
bad,
hashlib.sha256((tmp_path / "source.wav").read_bytes()).hexdigest(),
0,
3072,
)
def test_vad_missing_or_modified_weights_are_never_used(tmp_path, monkeypatch):
with pytest.raises(OSError):
inspect_vad(tmp_path, np.zeros(512, np.float32))
path = tmp_path / "silero-vad" / "silero_vad.onnx"
path.parent.mkdir()
path.write_bytes(b"not the official pinned model")
with pytest.raises(ValueError, match="model|weight|hash"):
inspect_vad(tmp_path, np.zeros(512, np.float32))
@pytest.mark.parametrize("mode", ["opposite_phase", "right_only", "left_only"])
def test_vad_checks_each_original_channel_even_when_mono_speech_cancels(
tmp_path, monkeypatch, mode
):
signal = (0.1 * np.sin(np.arange(1024) * 2 * np.pi * 240 / 16000)).astype(
np.float32
)
channels = np.column_stack(
(
signal if mode != "right_only" else np.zeros_like(signal),
-signal
if mode == "opposite_phase"
else signal
if mode == "right_only"
else np.zeros_like(signal),
)
)
if mode == "opposite_phase":
assert not channels.mean(axis=1).any()
calls = fake_runtime(
tmp_path,
monkeypatch,
lambda value: 0.9 if value.any() else 0.1,
windows_per_channel=2,
)
result = inspect_vad(tmp_path, channels)
assert result["decision"] == "speech"
assert result["channels"] == 2 and len(result["channel_probabilities"]) == 2
assert len(calls) == 4
assert result["probabilities"] == [0.9, 0.9]
assert not calls[0][0, :64].any() and not calls[2][0, :64].any()
def test_vad_quiet_channels_have_independent_state_and_context_and_window_max(
tmp_path, monkeypatch
):
calls = fake_runtime(
tmp_path, monkeypatch, [0.1, 0.2, 0.3, 0.05], windows_per_channel=2
)
result = inspect_vad(tmp_path, np.zeros((1024, 2), np.float32))
assert result["decision"] == "no_speech" and result["channels"] == 2
assert result["channel_probabilities"] == [[0.1, 0.2], [0.3, 0.05]]
assert (
result["probabilities"] == [0.3, 0.2]
and result["max_speech_probability"] == 0.3
)
assert not calls[0].any() and not calls[2].any()
def test_vad_one_uncertain_channel_prevents_silence(tmp_path, monkeypatch):
fake_runtime(tmp_path, monkeypatch, [0.1, 0.35], windows_per_channel=1)
result = inspect_vad(tmp_path, np.zeros((512, 2), np.float32))
assert result["decision"] == "indeterminate"
assert result["probabilities"] == [0.35]
def test_vad_rejects_source_path_with_another_audio_hash(tmp_path, monkeypatch):
fake_runtime(tmp_path, monkeypatch, [0.1])
source, _, end = source_audio(tmp_path, np.zeros(512, np.float32))
with pytest.raises(ValueError, match="source audio hash"):
module().inspect_silence(
source, tmp_path, audio_sha256="b" * 64, start_sample=0, end_sample=end
)
@pytest.mark.parametrize(
"key,value",
[
("channel_policy", None),
("channels", True),
("channels", 3),
("channel_probabilities", None),
("channel_probabilities", [[0.1, 0.2]]),
("channel_probabilities", [[0.1, 0.2], [0.3]]),
("channel_probabilities", [[0.1, 0.2], [0.3, float("nan")]]),
("channel_probabilities", [[0.1, 0.2], [0.3, True]]),
("probabilities", [0.1, 0.2]),
],
)
def test_vad_certificate_rejects_missing_channels_or_false_window_aggregation(
tmp_path, monkeypatch, key, value
):
fake_runtime(tmp_path, monkeypatch, [0.1, 0.2, 0.3, 0.05], windows_per_channel=2)
result = inspect_vad(tmp_path, np.zeros((1024, 2), np.float32))
result[key] = value
sha = hashlib.sha256((tmp_path / "source.wav").read_bytes()).hexdigest()
with pytest.raises(ValueError):
module().validate_evidence(result, sha, 0, 3072)