1108 lines
39 KiB
Python
1108 lines
39 KiB
Python
"""逐词时间必须来自实际ASR,不可用字幕句长均分伪造。"""
|
||
|
||
import contextlib
|
||
import json
|
||
import sys
|
||
from types import SimpleNamespace
|
||
|
||
import numpy as np
|
||
import pytest
|
||
from llm_services.dialogue import SPEECH_INSPECT
|
||
|
||
|
||
def vad_evidence(start=0, end=96000, *, audio_sha256="a" * 64, speech=False):
|
||
count = (end - start + 2) // 3
|
||
probabilities = [0.9 if speech else 0.1] * ((count + 511) // 512)
|
||
return {
|
||
"policy": "silero-sensevoice-verified-silence-v1",
|
||
"source": "silero-vad-onnx-cpu",
|
||
"revision": "be95df9152c0d7618fa1edfeb296fc3dae32376f",
|
||
"model_sha256": "1a153a22f4509e292a94e67d6f9b85e8deb25b4988682b7e174c65279d8788e3",
|
||
"runtime": "onnxruntime-cpu",
|
||
"runtime_version": "1.31.1",
|
||
"status": "completed",
|
||
"decision": "speech" if speech else "no_speech",
|
||
"source_audio_sha256": audio_sha256,
|
||
"source_start_sample": start,
|
||
"source_end_sample": end,
|
||
"sample_rate": 16000,
|
||
"sample_count": count,
|
||
"window_size_samples": 512,
|
||
"window_count": len(probabilities),
|
||
"threshold": 0.5,
|
||
"negative_threshold": 0.35,
|
||
"max_speech_probability": max(probabilities),
|
||
"probabilities": probabilities,
|
||
"channel_policy": "all_channels_no_speech",
|
||
"channels": 2,
|
||
"channel_probabilities": [list(probabilities), list(probabilities)],
|
||
}
|
||
|
||
|
||
@pytest.fixture(autouse=True)
|
||
def independent_vad_boundary(monkeypatch):
|
||
from llm_services.dialogue import native_silence
|
||
|
||
monkeypatch.setattr(
|
||
native_silence,
|
||
"inspect_silence",
|
||
lambda source_path, root, *, audio_sha256, start_sample, end_sample: (
|
||
vad_evidence(start_sample, end_sample, audio_sha256=audio_sha256)
|
||
),
|
||
)
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"expected,secondary,vad_status,clipped,wanted",
|
||
[
|
||
("", "", "no_speech", 0.0, "pass"),
|
||
("", "", "speech", 0.0, "reject"),
|
||
("", "", "indeterminate", 0.0, "indeterminate"),
|
||
("", "", "unavailable", 0.0, "indeterminate"),
|
||
("", "。", "no_speech", 0.0, "reject"),
|
||
("。", "", "no_speech", 0.0, "reject"),
|
||
("", "", "no_speech", 0.001, "reject"),
|
||
("你好", "你好", "no_speech", 0.0, "pass"),
|
||
("你好", "你好", "unavailable", 0.0, "pass"),
|
||
],
|
||
)
|
||
def test_verified_silence_requires_empty_script_empty_secondary_and_complete_certain_vad(
|
||
tmp_path, monkeypatch, expected, secondary, vad_status, clipped, wanted
|
||
):
|
||
from llm_services.dialogue import audio_quality, native_silence
|
||
|
||
primary = expected if expected.strip() else "真实Whisper幻听"
|
||
monkeypatch.setattr(
|
||
audio_quality,
|
||
"selected_speech",
|
||
lambda *a: (np.zeros(16000), clipped, 0, 48000),
|
||
)
|
||
monkeypatch.setattr(audio_quality, "voiced_signal", lambda w: (w, 1.0))
|
||
monkeypatch.setattr(audio_quality, "digest", lambda _: "a" * 64)
|
||
monkeypatch.setattr(
|
||
module(),
|
||
"transcribe_words",
|
||
lambda _: {
|
||
"text": primary,
|
||
"chunks": [{"text": primary, "timestamp": (0.1, 0.3)}],
|
||
},
|
||
)
|
||
monkeypatch.setattr(
|
||
audio_quality, "sensevoice_transcribe", lambda *a, **kw: secondary
|
||
)
|
||
|
||
def actual_vad(wav, root, *, audio_sha256, start_sample, end_sample):
|
||
if vad_status == "unavailable":
|
||
raise OSError("independent VAD missing")
|
||
evidence = vad_evidence(
|
||
start_sample,
|
||
end_sample,
|
||
audio_sha256=audio_sha256,
|
||
speech=vad_status == "speech",
|
||
)
|
||
if vad_status == "indeterminate":
|
||
evidence.update(
|
||
decision="indeterminate",
|
||
max_speech_probability=0.4,
|
||
probabilities=[0.4] * evidence["window_count"],
|
||
channel_probabilities=[
|
||
[0.4] * evidence["window_count"],
|
||
[0.4] * evidence["window_count"],
|
||
],
|
||
)
|
||
return evidence
|
||
|
||
monkeypatch.setattr(native_silence, "inspect_silence", actual_vad)
|
||
_, report = module().inspect_native_speech(
|
||
{"audio_path": "native.wav", "expected_text": expected, "speaker_id": "1" * 32},
|
||
{},
|
||
tmp_path,
|
||
tmp_path,
|
||
)
|
||
assert report["decision"] == wanted
|
||
assert report["transcript"] == primary
|
||
if not expected.strip() and wanted == "pass":
|
||
assert (
|
||
report["content_verification_policy"]
|
||
== "silero-sensevoice-verified-silence-v1"
|
||
)
|
||
assert report["content_decision_source"] == "verified_silence"
|
||
assert report["content_error_rate"] == 1 and report["primary_reasons"]
|
||
assert report["words"][0]["text"] == primary
|
||
if expected == "你好":
|
||
assert (
|
||
report["content_verification_policy"] == "whisper-sensevoice-consensus-v1"
|
||
)
|
||
assert report["content_decision_source"] == "whisper_sensevoice_consensus"
|
||
|
||
|
||
def test_native_silence_vad_receives_original_path_when_asr_downmix_cancels(
|
||
tmp_path, monkeypatch
|
||
):
|
||
from llm_services.dialogue import audio_quality, native_silence
|
||
|
||
mono = np.zeros(16000, np.float32)
|
||
monkeypatch.setattr(
|
||
audio_quality, "selected_speech", lambda *a: (mono, 0.0, 0, 48000)
|
||
)
|
||
monkeypatch.setattr(audio_quality, "voiced_signal", lambda w: (w, 0.0))
|
||
monkeypatch.setattr(audio_quality, "digest", lambda _: "a" * 64)
|
||
|
||
def primary(wav):
|
||
assert wav is mono
|
||
return {"text": "", "chunks": []}
|
||
|
||
def secondary(wav, root, out, *, allow_empty):
|
||
assert wav is mono and allow_empty is True
|
||
return ""
|
||
|
||
def channel_vad(source_path, root, *, audio_sha256, start_sample, end_sample):
|
||
assert source_path == "original-stereo.wav"
|
||
return vad_evidence(
|
||
start_sample, end_sample, audio_sha256=audio_sha256, speech=True
|
||
)
|
||
|
||
monkeypatch.setattr(module(), "transcribe_words", primary)
|
||
monkeypatch.setattr(audio_quality, "sensevoice_transcribe", secondary)
|
||
monkeypatch.setattr(native_silence, "inspect_silence", channel_vad)
|
||
_, report = module().inspect_native_speech(
|
||
{
|
||
"audio_path": "original-stereo.wav",
|
||
"expected_text": "",
|
||
"speaker_id": "1" * 32,
|
||
},
|
||
{},
|
||
tmp_path,
|
||
tmp_path,
|
||
)
|
||
assert report["decision"] == "reject"
|
||
assert (
|
||
report["transcript"] == report["secondary_transcript"] == ""
|
||
and report["words"] == []
|
||
)
|
||
assert "independent_vad_detected_speech" in report["reasons"]
|
||
|
||
|
||
def test_native_invalid_real_timestamps_preserve_raw_decoder_evidence(
|
||
tmp_path, monkeypatch, capsys
|
||
):
|
||
from llm_services.dialogue import audio_quality
|
||
|
||
raw = {
|
||
"text": "请不吝点赞 订阅 转发 打赏支持明镜与点点栏目",
|
||
"chunks": [
|
||
{"text": "请不吝点赞", "timestamp": (0.0, 5.98)},
|
||
{"text": " 订阅", "timestamp": (5.98, 5.98)},
|
||
{"text": " 转发", "timestamp": (5.98, 5.98)},
|
||
{"text": " 打赏支持明镜与点点栏目", "timestamp": (5.98, 5.98)},
|
||
],
|
||
"whisper_decoding": {
|
||
"policy": "whisper-standard-no-speech-v1",
|
||
"no_speech_threshold": 0.6,
|
||
"logprob_threshold": -1.0,
|
||
"segments": [
|
||
{
|
||
"no_speech_probability": 0.95,
|
||
"average_log_probability": -0.2,
|
||
"no_speech_threshold": 0.6,
|
||
"logprob_threshold": -1.0,
|
||
"needs_fallback": False,
|
||
"should_skip": False,
|
||
}
|
||
],
|
||
"empty_segments_removed": False,
|
||
},
|
||
}
|
||
monkeypatch.setattr(
|
||
audio_quality, "selected_speech", lambda *a: (np.zeros(96000), 0.0, 0, 288000)
|
||
)
|
||
monkeypatch.setattr(audio_quality, "voiced_signal", lambda w: (w, 0.0))
|
||
monkeypatch.setattr(audio_quality, "digest", lambda _: "a" * 64)
|
||
monkeypatch.setattr(module(), "transcribe_words", lambda _: raw)
|
||
|
||
def independent(wav, root, out, *, allow_empty):
|
||
assert len(wav) == 96000 and allow_empty is True
|
||
return ""
|
||
|
||
monkeypatch.setattr(audio_quality, "sensevoice_transcribe", independent)
|
||
paths, report = module().inspect_native_speech(
|
||
{"audio_path": "silence.wav", "expected_text": "", "speaker_id": "1" * 32},
|
||
{},
|
||
tmp_path,
|
||
tmp_path,
|
||
)
|
||
assert report["decision"] == "pass"
|
||
assert report["transcript"] == raw["text"] and report["content_error_rate"] == 1
|
||
assert report["words"] is None and report["word_alignment_status"] == "invalid"
|
||
assert "word timestamps" in report["word_alignment_error"]
|
||
assert "invalid_word_timestamps" in report["primary_reasons"]
|
||
assert "independent_content_disagreement" in report["primary_reasons"]
|
||
assert report["reasons"] == []
|
||
assert (
|
||
report["content_verification_policy"] == "silero-sensevoice-verified-silence-v1"
|
||
)
|
||
assert report["content_decision_source"] == "verified_silence"
|
||
assert (
|
||
report["secondary_status"] == "completed"
|
||
and report["secondary_transcript"] == ""
|
||
)
|
||
assert json.loads(paths[0].read_text(encoding="utf-8")) == report
|
||
assert report["whisper_decoding"] == raw["whisper_decoding"]
|
||
assert json.loads(
|
||
(tmp_path / "native-whisper-raw.json").read_text(encoding="utf-8")
|
||
) == json.loads(json.dumps(raw))
|
||
assert "NATIVE_WHISPER_RAW=" in capsys.readouterr().err
|
||
|
||
|
||
@pytest.mark.parametrize("stamp", [(0.0, 0.0), (0.0, 3.0), (0.1, None)])
|
||
@pytest.mark.parametrize(
|
||
"secondary", ["你好", RuntimeError("independent decoder failed")]
|
||
)
|
||
def test_invalid_word_alignment_never_bypasses_independent_content_or_becomes_silence(
|
||
tmp_path, monkeypatch, stamp, secondary
|
||
):
|
||
from llm_services.dialogue import audio_quality
|
||
|
||
monkeypatch.setattr(
|
||
audio_quality,
|
||
"selected_speech",
|
||
lambda *a: (np.zeros(16000), 0.0, 48000, 96000),
|
||
)
|
||
monkeypatch.setattr(audio_quality, "voiced_signal", lambda w: (w, 1.0))
|
||
monkeypatch.setattr(audio_quality, "digest", lambda _: "a" * 64)
|
||
monkeypatch.setattr(
|
||
module(),
|
||
"transcribe_words",
|
||
lambda _: {"text": "你好", "chunks": [{"text": "你好", "timestamp": stamp}]},
|
||
)
|
||
|
||
def independent(wav, root, out, *, allow_empty):
|
||
if isinstance(secondary, Exception):
|
||
raise secondary
|
||
return secondary
|
||
|
||
monkeypatch.setattr(audio_quality, "sensevoice_transcribe", independent)
|
||
_, report = module().inspect_native_speech(
|
||
{"audio_path": "speech.wav", "expected_text": "你好", "speaker_id": "1" * 32},
|
||
{},
|
||
tmp_path,
|
||
tmp_path,
|
||
)
|
||
assert report["decision"] == "reject"
|
||
assert report["transcript"] == "你好" and report["content_error_rate"] == 0
|
||
assert "invalid_word_timestamps" in report["reasons"] and report["words"] is None
|
||
if isinstance(secondary, str):
|
||
assert report["secondary_status"] == "completed"
|
||
assert report["secondary_transcript"] == "你好"
|
||
assert report["secondary_content_error_rate"] == 0
|
||
else:
|
||
assert report["secondary_status"] == "unavailable"
|
||
assert "independent_content_unavailable" in report["reasons"]
|
||
|
||
|
||
def module():
|
||
from llm_services.dialogue import native_alignment
|
||
|
||
return native_alignment
|
||
|
||
|
||
def test_word_timestamps_preserve_actual_gaps_and_selected_audio_origin():
|
||
result = {
|
||
"text": "你好世界",
|
||
"chunks": [
|
||
{"text": "你好", "timestamp": (0.2, 0.6)},
|
||
{"text": "世界", "timestamp": (1.4, 1.9)},
|
||
],
|
||
}
|
||
words = module().word_timestamps(result, 48000, 144000)
|
||
assert words == [
|
||
{"text": "你好", "start_sample": 57600, "end_sample": 76800},
|
||
{"text": "世界", "start_sample": 115200, "end_sample": 139200},
|
||
]
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"chunks",
|
||
[
|
||
[],
|
||
[{"text": "你好", "timestamp": (0.2, None)}],
|
||
[{"text": "你好", "timestamp": (0, 3)}],
|
||
[
|
||
{"text": "你", "timestamp": (0.8, 1.2)},
|
||
{"text": "好", "timestamp": (1.1, 1.4)},
|
||
],
|
||
[{"text": "你", "timestamp": (0.1, 0.2)}],
|
||
],
|
||
)
|
||
def test_native_words_reject_missing_incomplete_outside_or_fabricated_alignment(chunks):
|
||
with pytest.raises(ValueError, match="word|timestamp|align"):
|
||
module().word_timestamps({"text": "你好", "chunks": chunks}, 0, 96000)
|
||
|
||
|
||
def test_native_transcription_requests_real_word_alignment_with_local_eager_model(
|
||
monkeypatch,
|
||
):
|
||
calls = {}
|
||
|
||
class Model:
|
||
@classmethod
|
||
def from_pretrained(cls, path, **kw):
|
||
calls["model"] = (path, kw)
|
||
return cls()
|
||
|
||
def eval(self):
|
||
return self
|
||
|
||
class Processor:
|
||
@classmethod
|
||
def from_pretrained(cls, *a, **kw):
|
||
assert kw["local_files_only"] is True
|
||
return SimpleNamespace(tokenizer="tokenizer", feature_extractor="features")
|
||
|
||
def make_pipeline(*a, **kw):
|
||
def run(audio, **kwargs):
|
||
calls["run"] = kwargs
|
||
assert audio["sampling_rate"] == 16000
|
||
return {
|
||
"text": "你好",
|
||
"chunks": [
|
||
{"text": "你", "timestamp": (0.1, 0.3)},
|
||
{"text": "好", "timestamp": (0.5, 0.7)},
|
||
],
|
||
}
|
||
|
||
return run
|
||
|
||
monkeypatch.setitem(
|
||
sys.modules,
|
||
"transformers",
|
||
SimpleNamespace(
|
||
WhisperForConditionalGeneration=Model,
|
||
WhisperProcessor=Processor,
|
||
pipeline=make_pipeline,
|
||
),
|
||
)
|
||
monkeypatch.setitem(
|
||
sys.modules,
|
||
"torch",
|
||
SimpleNamespace(float16="fp16", inference_mode=contextlib.nullcontext),
|
||
)
|
||
result = module().transcribe_words(np.zeros(16000, dtype=np.float32))
|
||
assert result["text"] == "你好" and len(result["chunks"]) == 2
|
||
assert result["chunks"] == [
|
||
{"text": "你", "timestamp": (0.1, 0.3)},
|
||
{"text": "好", "timestamp": (0.5, 0.7)},
|
||
]
|
||
assert result["whisper_decoding"]["policy"] == "whisper-standard-no-speech-v1"
|
||
assert calls["model"][1]["attn_implementation"] == "eager"
|
||
assert calls["model"][1]["local_files_only"] is True
|
||
assert calls["run"]["return_timestamps"] == "word"
|
||
assert calls["run"]["generate_kwargs"]["language"] == "zh"
|
||
assert calls["run"]["generate_kwargs"]["no_speech_threshold"] == 0.6
|
||
assert calls["run"]["generate_kwargs"]["logprob_threshold"] == -1.0
|
||
assert calls["run"]["generate_kwargs"]["temperature"] == 0.0
|
||
assert "prompt" not in calls["run"].get("generate_kwargs", {})
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"probability,logprob,skip",
|
||
[(0.95, -1.5, True), (0.95, -0.2, False), (0.1, -1.5, False)],
|
||
)
|
||
def test_native_whisper_records_actual_standard_no_speech_decision(
|
||
probability, logprob, skip
|
||
):
|
||
class Tensor:
|
||
shape = (1, 0 if skip else 2)
|
||
|
||
def numel(self):
|
||
return 0 if skip else 2
|
||
|
||
class Base:
|
||
def _retrieve_avg_logprobs(self, scores, sequence, temperature):
|
||
return logprob
|
||
|
||
def _need_fallback(
|
||
self, sequence, outputs, index, processors, config, vocab, temperature
|
||
):
|
||
assert (
|
||
config.no_speech_threshold == 0.6 and config.logprob_threshold == -1.0
|
||
)
|
||
return (logprob < -1.0 and not skip, skip)
|
||
|
||
def generate(self):
|
||
self._need_fallback(
|
||
[],
|
||
[{"scores": "actual scores"}],
|
||
0,
|
||
[SimpleNamespace(no_speech_prob=[probability])],
|
||
SimpleNamespace(no_speech_threshold=0.6, logprob_threshold=-1.0),
|
||
100,
|
||
None,
|
||
)
|
||
return {
|
||
"sequences": Tensor(),
|
||
"token_timestamps": Tensor(),
|
||
"segments": [[]] if skip else [[{"token_timestamps": [0.1, 0.3]}]],
|
||
}
|
||
|
||
model = module().measured_whisper_model(Base)()
|
||
decoded = model.generate()
|
||
assert ("segments" not in decoded) is skip
|
||
assert (
|
||
decoded["sequences"].numel()
|
||
== decoded["token_timestamps"].numel()
|
||
== (0 if skip else 2)
|
||
)
|
||
assert model.native_decode_evidence == [
|
||
{
|
||
"no_speech_probability": probability,
|
||
"average_log_probability": logprob,
|
||
"no_speech_threshold": 0.6,
|
||
"logprob_threshold": -1.0,
|
||
"needs_fallback": logprob < -1.0 and not skip,
|
||
"should_skip": skip,
|
||
}
|
||
]
|
||
|
||
|
||
def test_native_whisper_unmeasured_empty_segments_are_not_reported_as_silence():
|
||
class Base:
|
||
def generate(self):
|
||
return {"segments": [[]]}
|
||
|
||
with pytest.raises(ValueError, match="unmeasured|empty|Empty"):
|
||
module().measured_whisper_model(Base)().generate()
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"skips,token_count", [([False], 0), ([True, False], 0), ([True], 2)]
|
||
)
|
||
def test_native_whisper_never_clears_inconsistent_or_partially_skipped_empty_segments(
|
||
skips, token_count
|
||
):
|
||
class Tensor:
|
||
shape = (1, token_count)
|
||
|
||
def numel(self):
|
||
return token_count
|
||
|
||
raw = {"sequences": Tensor(), "token_timestamps": Tensor(), "segments": [[]]}
|
||
|
||
class Base:
|
||
def _retrieve_avg_logprobs(self, scores, sequence, temperature):
|
||
return scores
|
||
|
||
def _need_fallback(
|
||
self, sequence, outputs, index, processors, config, vocab, temperature
|
||
):
|
||
return False, outputs[0]["scores"] < -1.0
|
||
|
||
def generate(self):
|
||
for skip in skips:
|
||
self._need_fallback(
|
||
[],
|
||
[{"scores": -1.5 if skip else -0.2}],
|
||
0,
|
||
[SimpleNamespace(no_speech_prob=[0.95])],
|
||
SimpleNamespace(no_speech_threshold=0.6, logprob_threshold=-1.0),
|
||
100,
|
||
None,
|
||
)
|
||
return raw
|
||
|
||
with pytest.raises(ValueError, match="empty|Empty"):
|
||
module().measured_whisper_model(Base)().generate()
|
||
assert raw["segments"] == [[]]
|
||
|
||
|
||
def test_native_whisper_partial_skip_keeps_actual_nonempty_segments_untouched():
|
||
raw = {
|
||
"sequences": "actual text token tensor",
|
||
"token_timestamps": "actual timestamp tensor",
|
||
"segments": [[{"token_timestamps": [0.2, 0.6, 1.4, 1.9]}]],
|
||
}
|
||
|
||
class Base:
|
||
def _retrieve_avg_logprobs(self, scores, sequence, temperature):
|
||
return scores
|
||
|
||
def _need_fallback(
|
||
self, sequence, outputs, index, processors, config, vocab, temperature
|
||
):
|
||
return False, outputs[0]["scores"] < -1.0
|
||
|
||
def generate(self):
|
||
for logprob in (-1.5, -0.2):
|
||
self._need_fallback(
|
||
[],
|
||
[{"scores": logprob}],
|
||
0,
|
||
[SimpleNamespace(no_speech_prob=[0.95])],
|
||
SimpleNamespace(no_speech_threshold=0.6, logprob_threshold=-1.0),
|
||
100,
|
||
None,
|
||
)
|
||
return raw
|
||
|
||
model = module().measured_whisper_model(Base)()
|
||
assert model.generate() is raw
|
||
assert [sample["should_skip"] for sample in model.native_decode_evidence] == [
|
||
True,
|
||
False,
|
||
]
|
||
assert model.native_empty_segments_removed is False
|
||
|
||
|
||
def test_native_whisper_decoder_failures_propagate_without_empty_decode():
|
||
failure = RuntimeError("real decoder failed")
|
||
|
||
class Base:
|
||
def generate(self):
|
||
raise failure
|
||
|
||
with pytest.raises(RuntimeError) as caught:
|
||
module().measured_whisper_model(Base)().generate()
|
||
assert caught.value is failure
|
||
|
||
|
||
def test_native_whisper_beam_scores_use_the_same_actual_metric_as_standard_decoder():
|
||
class Output(dict):
|
||
@property
|
||
def sequences_scores(self):
|
||
return self["sequences_scores"]
|
||
|
||
class Base:
|
||
def _retrieve_avg_logprobs(self, *args):
|
||
raise AssertionError("beam-search already provided its sequence score")
|
||
|
||
def _need_fallback(self, *args):
|
||
return False, True
|
||
|
||
def generate(self):
|
||
self._need_fallback(
|
||
[],
|
||
[Output(sequences_scores=-1.25)],
|
||
0,
|
||
[SimpleNamespace(no_speech_prob=[0.85])],
|
||
SimpleNamespace(no_speech_threshold=0.6, logprob_threshold=-1.0),
|
||
100,
|
||
None,
|
||
)
|
||
return {"segments": [[{"token_timestamps": [0.1, 0.2]}]]}
|
||
|
||
model = module().measured_whisper_model(Base)()
|
||
model.generate()
|
||
assert model.native_decode_evidence[0]["average_log_probability"] == -1.25
|
||
assert model.native_decode_evidence[0]["no_speech_probability"] == 0.85
|
||
|
||
|
||
def test_native_inspection_accepts_exact_spoken_words_without_cloned_voice(
|
||
tmp_path, monkeypatch
|
||
):
|
||
from llm_services.dialogue import audio_quality
|
||
|
||
monkeypatch.setattr(
|
||
audio_quality,
|
||
"selected_speech",
|
||
lambda *a: (np.zeros(32000), 0.0, 48000, 144000),
|
||
)
|
||
monkeypatch.setattr(audio_quality, "voiced_signal", lambda w: (w, 1.5))
|
||
monkeypatch.setattr(audio_quality, "digest", lambda _: "a" * 64)
|
||
monkeypatch.setattr(
|
||
audio_quality,
|
||
"sensevoice_transcribe",
|
||
lambda wav, root, out, *, allow_empty: "你好",
|
||
)
|
||
monkeypatch.setattr(
|
||
module(),
|
||
"transcribe_words",
|
||
lambda _: {
|
||
"text": "你好",
|
||
"chunks": [
|
||
{"text": "你", "timestamp": (0.1, 0.3)},
|
||
{"text": "好", "timestamp": (0.5, 0.7)},
|
||
],
|
||
},
|
||
)
|
||
paths, report = audio_quality.inspect_speech(
|
||
{"audio_path": "native.wav", "expected_text": "你好", "speaker_id": "1" * 32},
|
||
{"native_av_policy": "native_av_v1"},
|
||
tmp_path,
|
||
tmp_path,
|
||
)
|
||
assert report["decision"] == "pass" and report["content_error_rate"] == 0
|
||
assert (
|
||
report["timestamp_source"] == "whisper-word-timestamps"
|
||
and report["timestamp_origin"] == "audio_asset"
|
||
)
|
||
assert report["sample_rate"] == 48000
|
||
assert report["content_verification_policy"] == "whisper-sensevoice-consensus-v1"
|
||
assert report["secondary_status"] == "completed"
|
||
assert (
|
||
report["secondary_transcript"]
|
||
== report["normalized_secondary_transcript"]
|
||
== "你好"
|
||
)
|
||
assert report["secondary_content_error_rate"] == 0
|
||
assert (
|
||
report["secondary_asr_revision"] == "90c1c61912018b70ada0fcc024ea24aca62f2e63"
|
||
)
|
||
assert (
|
||
report["secondary_runtime_revision"]
|
||
== "6991744856587fa44379e8b5dcc432debffeb1be"
|
||
)
|
||
assert report["words"][0] == {
|
||
"text": "你",
|
||
"start_sample": 52800,
|
||
"end_sample": 62400,
|
||
}
|
||
assert json.loads(paths[0].read_text(encoding="utf-8"))["words"] == report["words"]
|
||
|
||
|
||
def test_silent_speech_certificate_cannot_enable_native_word_alignment(
|
||
tmp_path, monkeypatch
|
||
):
|
||
from llm_services.dialogue import profiles
|
||
from llm_services.store import Settings
|
||
|
||
settings = Settings(tmp_path / "app", tmp_path)
|
||
monkeypatch.setattr(
|
||
profiles,
|
||
"_certificate",
|
||
lambda *a: {"available": True, "profile": "dialogue-audio-v1"},
|
||
)
|
||
cap = profiles.capabilities(settings)["speech_inspect"]["native_alignment"]
|
||
assert cap["available"] is False and cap["policy"] == "native_av_v1"
|
||
with pytest.raises(ValueError, match="native|alignment"):
|
||
profiles.admit(
|
||
settings,
|
||
SPEECH_INSPECT,
|
||
{"profile": "dialogue-audio-v1", "native_av_policy": "native_av_v1"},
|
||
)
|
||
|
||
|
||
def test_native_alignment_certificate_requires_native_measurement_and_complete_words(
|
||
tmp_path,
|
||
):
|
||
import sqlite3
|
||
|
||
from llm_services.store import Settings
|
||
|
||
settings = Settings(tmp_path / "app", tmp_path)
|
||
settings.state_dir.mkdir(parents=True)
|
||
report = {
|
||
"task_type": "audio.dialogue.inspect",
|
||
"profile": "dialogue-audio-v1",
|
||
"revision": "f0c48c298fd835726c27956a5d617bad7115627e",
|
||
"asr_revision": "41f01f3fe87f28c78e2fbf8b568835947dd65ed9",
|
||
"content_verification_policy": "whisper-sensevoice-consensus-v1",
|
||
"secondary_asr_revision": "90c1c61912018b70ada0fcc024ea24aca62f2e63",
|
||
"secondary_runtime_revision": "6991744856587fa44379e8b5dcc432debffeb1be",
|
||
"silence_verification_policy": "silero-sensevoice-verified-silence-v1",
|
||
"silence_vad_revision": "be95df9152c0d7618fa1edfeb296fc3dae32376f",
|
||
"silence_vad_sha256": "1a153a22f4509e292a94e67d6f9b85e8deb25b4988682b7e174c65279d8788e3",
|
||
"policy": "native_av_v1",
|
||
"timestamp_source": "whisper-word-timestamps",
|
||
"sample_rate": 48000,
|
||
"adapter_contract_version": "native-av-alignment-v1",
|
||
"decision": "pass",
|
||
"audited": True,
|
||
"validation_job_id": "a" * 32,
|
||
"silence_validation_job_id": "b" * 32,
|
||
}
|
||
path = (
|
||
settings.app_root
|
||
/ "config"
|
||
/ "dialogue-validation"
|
||
/ "speech_inspect-native_av_v1.json"
|
||
)
|
||
path.parent.mkdir(parents=True)
|
||
path.write_text(json.dumps(report), encoding="utf-8")
|
||
metadata = {
|
||
"native_av_policy": "native_av_v1",
|
||
"audio_sha256": "a" * 64,
|
||
"decision": "pass",
|
||
"content_error_rate": 0,
|
||
"normalized_expected_text": "你好",
|
||
"normalized_transcript": "你好",
|
||
"clipped_fraction": 0,
|
||
"expected_text": "你好",
|
||
"transcript": "你好",
|
||
"asr_revision": report["asr_revision"],
|
||
"content_verification_policy": "whisper-sensevoice-consensus-v1",
|
||
"content_decision_source": "whisper_sensevoice_consensus",
|
||
"silence_verification": vad_evidence(speech=True),
|
||
"secondary_status": "completed",
|
||
"secondary_transcript": "你好",
|
||
"normalized_secondary_transcript": "你好",
|
||
"secondary_content_error_rate": 0,
|
||
"secondary_asr_revision": report["secondary_asr_revision"],
|
||
"secondary_runtime_revision": report["secondary_runtime_revision"],
|
||
"timestamp_source": "whisper-word-timestamps",
|
||
"timestamp_origin": "audio_asset",
|
||
"sample_rate": 48000,
|
||
"source_start_sample": 0,
|
||
"source_end_sample": 96000,
|
||
"words": [
|
||
{"text": "你", "start_sample": 4800, "end_sample": 14400},
|
||
{"text": "好", "start_sample": 24000, "end_sample": 33600},
|
||
],
|
||
}
|
||
with sqlite3.connect(settings.db_path) as db:
|
||
db.execute(
|
||
"CREATE TABLE jobs(id TEXT,task_type TEXT,state TEXT,result_json TEXT,input_json TEXT,parameters_json TEXT)"
|
||
)
|
||
db.execute(
|
||
"INSERT INTO jobs VALUES(?,?,?,?,?,?)",
|
||
(
|
||
"a" * 32,
|
||
SPEECH_INSPECT,
|
||
"succeeded",
|
||
json.dumps(
|
||
{"outputs": [{"path": "speech-quality.json"}], "metadata": metadata}
|
||
),
|
||
"{}",
|
||
json.dumps(
|
||
{"profile": "dialogue-audio-v1", "native_av_policy": "native_av_v1"}
|
||
),
|
||
),
|
||
)
|
||
silence = {
|
||
**metadata,
|
||
"expected_text": "",
|
||
"transcript": "真实幻听",
|
||
"content_error_rate": 1,
|
||
"normalized_expected_text": "",
|
||
"normalized_transcript": "真实幻听",
|
||
"words": None,
|
||
"content_verification_policy": "silero-sensevoice-verified-silence-v1",
|
||
"content_decision_source": "verified_silence",
|
||
"silence_verification": vad_evidence(),
|
||
"secondary_transcript": "",
|
||
"normalized_secondary_transcript": "",
|
||
}
|
||
db.execute(
|
||
"INSERT INTO jobs VALUES(?,?,?,?,?,?)",
|
||
(
|
||
"b" * 32,
|
||
SPEECH_INSPECT,
|
||
"succeeded",
|
||
json.dumps(
|
||
{"outputs": [{"path": "speech-quality.json"}], "metadata": silence}
|
||
),
|
||
json.dumps({"expected_text": ""}),
|
||
json.dumps(
|
||
{"profile": "dialogue-audio-v1", "native_av_policy": "native_av_v1"}
|
||
),
|
||
),
|
||
)
|
||
cap = module().capability(settings)
|
||
assert cap["available"] is True and len(cap["report_sha256"]) == 64
|
||
assert cap["content_verification_policy"] == "whisper-sensevoice-consensus-v1"
|
||
assert cap["secondary_asr_revision"] == report["secondary_asr_revision"]
|
||
assert cap["secondary_runtime_revision"] == report["secondary_runtime_revision"]
|
||
for key in (
|
||
"content_verification_policy",
|
||
"secondary_asr_revision",
|
||
"secondary_runtime_revision",
|
||
"silence_verification_policy",
|
||
"silence_vad_revision",
|
||
"silence_vad_sha256",
|
||
):
|
||
old = report.pop(key)
|
||
path.write_text(json.dumps(report), encoding="utf-8")
|
||
assert module().capability(settings)["available"] is False, key
|
||
report[key] = old
|
||
path.write_text(json.dumps(report), encoding="utf-8")
|
||
for job_id, original in (("a" * 32, metadata), ("b" * 32, silence)):
|
||
for key, bad in (
|
||
("secondary_status", "unavailable"),
|
||
("secondary_transcript", None),
|
||
("secondary_transcript", "再见"),
|
||
("secondary_content_error_rate", 1),
|
||
("content_verification_policy", None),
|
||
("secondary_asr_revision", "a" * 40),
|
||
("secondary_runtime_revision", None),
|
||
("silence_verification", None),
|
||
("silence_verification", vad_evidence(speech=job_id == "b" * 32)),
|
||
(
|
||
"silence_verification",
|
||
{
|
||
**vad_evidence(speech=job_id == "a" * 32),
|
||
"channels": 1,
|
||
"channel_probabilities": [
|
||
vad_evidence(speech=job_id == "a" * 32)["probabilities"]
|
||
],
|
||
},
|
||
),
|
||
):
|
||
with sqlite3.connect(settings.db_path) as db:
|
||
db.execute(
|
||
"UPDATE jobs SET result_json=? WHERE id=?",
|
||
(
|
||
json.dumps(
|
||
{
|
||
"outputs": [{"path": "speech-quality.json"}],
|
||
"metadata": {**original, key: bad},
|
||
}
|
||
),
|
||
job_id,
|
||
),
|
||
)
|
||
assert module().capability(settings)["available"] is False, (job_id, key)
|
||
with sqlite3.connect(settings.db_path) as db:
|
||
db.execute(
|
||
"UPDATE jobs SET result_json=? WHERE id=?",
|
||
(
|
||
json.dumps(
|
||
{
|
||
"outputs": [{"path": "speech-quality.json"}],
|
||
"metadata": original,
|
||
}
|
||
),
|
||
job_id,
|
||
),
|
||
)
|
||
report.pop("silence_validation_job_id")
|
||
path.write_text(json.dumps(report), encoding="utf-8")
|
||
assert module().capability(settings)["available"] is False
|
||
report["silence_validation_job_id"] = "b" * 32
|
||
path.write_text(json.dumps(report), encoding="utf-8")
|
||
metadata["words"].pop()
|
||
with sqlite3.connect(settings.db_path) as db:
|
||
db.execute(
|
||
"UPDATE jobs SET result_json=?",
|
||
(
|
||
json.dumps(
|
||
{"outputs": [{"path": "speech-quality.json"}], "metadata": metadata}
|
||
),
|
||
),
|
||
)
|
||
assert module().capability(settings)["available"] is False
|
||
|
||
|
||
def test_native_protocol_accepts_only_explicit_policy(tmp_path):
|
||
from llm_services.dialogue.protocol import validate
|
||
|
||
source = tmp_path / "inputs" / "native.wav"
|
||
source.parent.mkdir()
|
||
source.touch()
|
||
inp = {"audio_path": str(source), "expected_text": "你好", "speaker_id": "1" * 32}
|
||
params = {
|
||
"profile": "dialogue-audio-v1",
|
||
"sample_rate": 48000,
|
||
"native_av_policy": "native_av_v1",
|
||
}
|
||
assert (
|
||
validate(SPEECH_INSPECT, inp, params, tmp_path)[1]["native_av_policy"]
|
||
== "native_av_v1"
|
||
)
|
||
params["native_av_policy"] = "guess"
|
||
with pytest.raises(ValueError, match="native|policy"):
|
||
validate(SPEECH_INSPECT, inp, params, tmp_path)
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"transcript,chunks,wanted",
|
||
[("", [], "pass"), ("你好", [{"text": "你好", "timestamp": (0.1, 0.5)}], "reject")],
|
||
)
|
||
def test_native_silent_shot_still_runs_actual_asr_and_rejects_extra_words(
|
||
tmp_path, monkeypatch, transcript, chunks, wanted
|
||
):
|
||
from llm_services.dialogue import audio_quality
|
||
|
||
monkeypatch.setattr(
|
||
audio_quality, "selected_speech", lambda *a: (np.zeros(32000), 0.0, 0, 96000)
|
||
)
|
||
monkeypatch.setattr(audio_quality, "voiced_signal", lambda w: (w, 0.0))
|
||
monkeypatch.setattr(audio_quality, "digest", lambda _: "a" * 64)
|
||
calls = []
|
||
|
||
def actual_asr(w):
|
||
calls.append(len(w))
|
||
return {"text": transcript, "chunks": chunks}
|
||
|
||
monkeypatch.setattr(module(), "transcribe_words", actual_asr)
|
||
|
||
def independent_asr(wav, root, out, *, allow_empty):
|
||
assert allow_empty is True
|
||
calls.append(len(wav))
|
||
return transcript
|
||
|
||
monkeypatch.setattr(audio_quality, "sensevoice_transcribe", independent_asr)
|
||
_, report = audio_quality.inspect_speech(
|
||
{"audio_path": "native.wav", "expected_text": "", "speaker_id": "1" * 32},
|
||
{"native_av_policy": "native_av_v1"},
|
||
tmp_path,
|
||
tmp_path,
|
||
)
|
||
assert calls == [32000, 32000]
|
||
assert report["decision"] == wanted
|
||
assert report["content_error_rate"] == (0 if wanted == "pass" else 1)
|
||
if wanted == "pass":
|
||
assert report["words"] == [] and report["transcript"] == ""
|
||
|
||
|
||
def test_only_native_protocol_accepts_empty_expected_text(tmp_path):
|
||
from llm_services.dialogue.protocol import validate
|
||
|
||
path = tmp_path / "inputs" / "silence.wav"
|
||
path.parent.mkdir()
|
||
path.touch()
|
||
inputs = {"audio_path": str(path), "expected_text": "", "speaker_id": "1" * 32}
|
||
params = {
|
||
"profile": "dialogue-audio-v1",
|
||
"sample_rate": 48000,
|
||
"native_av_policy": "native_av_v1",
|
||
}
|
||
assert validate(SPEECH_INSPECT, inputs, params, tmp_path)[0]["expected_text"] == ""
|
||
params.pop("native_av_policy")
|
||
with pytest.raises(ValueError, match="text"):
|
||
validate(SPEECH_INSPECT, inputs, params, tmp_path)
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"secondary,decision,reason",
|
||
[
|
||
("你 好!", "pass", None),
|
||
("您好", "reject", "independent_content_disagreement"),
|
||
("", "reject", "independent_content_disagreement"),
|
||
(None, "indeterminate", "independent_content_unavailable"),
|
||
(
|
||
RuntimeError("decoder failed"),
|
||
"indeterminate",
|
||
"independent_content_unavailable",
|
||
),
|
||
],
|
||
)
|
||
def test_native_exact_whisper_requires_blind_independent_content_consensus(
|
||
tmp_path, monkeypatch, secondary, decision, reason
|
||
):
|
||
from llm_services.dialogue import audio_quality
|
||
|
||
# 48k源音频的选段已下混/重采样;两路假模型必须接收同一个16k选段。
|
||
signal = (0.1 * np.sin(np.arange(16000) * (2 * np.pi * 240 / 16000))).astype(
|
||
np.float32
|
||
)
|
||
monkeypatch.setattr(
|
||
audio_quality, "selected_speech", lambda *a: (signal, 0.0, 48000, 96000)
|
||
)
|
||
monkeypatch.setattr(audio_quality, "digest", lambda _: "a" * 64)
|
||
observed = []
|
||
|
||
def primary(wav):
|
||
observed.append(wav)
|
||
return {
|
||
"text": "你好",
|
||
"chunks": [
|
||
{"text": "你", "timestamp": (0.1, 0.3)},
|
||
{"text": "好", "timestamp": (0.5, 0.7)},
|
||
],
|
||
}
|
||
|
||
def blind(wav, root, out, *, allow_empty):
|
||
assert root == out == tmp_path
|
||
assert allow_empty is True
|
||
observed.append(wav)
|
||
if isinstance(secondary, Exception):
|
||
raise secondary
|
||
return secondary
|
||
|
||
monkeypatch.setattr(module(), "transcribe_words", primary)
|
||
monkeypatch.setattr(audio_quality, "sensevoice_transcribe", blind)
|
||
_, report = module().inspect_native_speech(
|
||
{"audio_path": "native.wav", "expected_text": "你好", "speaker_id": "1" * 32},
|
||
{"source_start_sample": 48000, "source_end_sample": 96000},
|
||
tmp_path,
|
||
tmp_path,
|
||
)
|
||
assert report["decision"] == decision
|
||
assert (reason in report["reasons"]) if reason else report["reasons"] == []
|
||
assert report["transcript"] == "你好" and report["content_error_rate"] == 0
|
||
assert report["words"] == [
|
||
{"text": "你", "start_sample": 52800, "end_sample": 62400},
|
||
{"text": "好", "start_sample": 72000, "end_sample": 81600},
|
||
]
|
||
assert len(observed) == 2 and observed[0] is observed[1]
|
||
assert len(observed[0]) == 16000
|
||
assert np.isfinite(observed[0]).all()
|
||
|
||
|
||
def test_silent_native_cannot_pass_when_only_whisper_is_silent(tmp_path, monkeypatch):
|
||
from llm_services.dialogue import audio_quality
|
||
|
||
monkeypatch.setattr(
|
||
audio_quality, "selected_speech", lambda *a: (np.zeros(16000), 0.0, 0, 48000)
|
||
)
|
||
monkeypatch.setattr(audio_quality, "voiced_signal", lambda wav: (wav, 0.0))
|
||
monkeypatch.setattr(audio_quality, "digest", lambda _: "a" * 64)
|
||
monkeypatch.setattr(
|
||
module(), "transcribe_words", lambda wav: {"text": "", "chunks": []}
|
||
)
|
||
monkeypatch.setattr(
|
||
audio_quality,
|
||
"sensevoice_transcribe",
|
||
lambda wav, root, out, *, allow_empty: "额外对白",
|
||
)
|
||
_, report = module().inspect_native_speech(
|
||
{"audio_path": "native.wav", "expected_text": "", "speaker_id": "1" * 32},
|
||
{},
|
||
tmp_path,
|
||
tmp_path,
|
||
)
|
||
assert report["decision"] == "reject"
|
||
assert "independent_content_disagreement" in report["primary_reasons"]
|
||
assert "independent_spoken_content_mismatch" in report["reasons"]
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
"allow_empty,stderr,failure,wanted",
|
||
[
|
||
(True, "[sensevoice] done", False, ""),
|
||
(False, "[sensevoice] done", False, None),
|
||
(True, "", False, None),
|
||
(True, "[sensevoice] done\ncompute failed", False, None),
|
||
(True, "[sensevoice] done", True, None),
|
||
],
|
||
)
|
||
def test_sensevoice_silence_requires_successful_completed_decode(
|
||
tmp_path, monkeypatch, allow_empty, stderr, failure, wanted
|
||
):
|
||
import os
|
||
import subprocess
|
||
|
||
from llm_services.dialogue.audio_quality import sensevoice_transcribe
|
||
|
||
monkeypatch.setattr(os, "sched_getaffinity", lambda _: {0, 1}, raising=False)
|
||
selected = np.zeros(16000)
|
||
|
||
def write_segment(path, wav, rate, *, subtype):
|
||
assert wav is not None and np.array_equal(wav, selected)
|
||
assert rate == 16000 and subtype == "PCM_16"
|
||
assert path.name == "segment.wav" and path.parent.parent == tmp_path
|
||
|
||
monkeypatch.setitem(sys.modules, "soundfile", SimpleNamespace(write=write_segment))
|
||
|
||
def decode(command, **kw):
|
||
assert command[:3] == ["taskset", "-c", "0,1"]
|
||
assert command[3].endswith("/llama-funasr-sensevoice")
|
||
assert command[4:] == [
|
||
"-m",
|
||
str(tmp_path / "sensevoice" / "sensevoice-small-f16.gguf"),
|
||
"-a",
|
||
command[-1],
|
||
]
|
||
assert kw["check"] is True and kw["timeout"] == 90
|
||
if failure:
|
||
raise subprocess.CalledProcessError(1, command)
|
||
return SimpleNamespace(stdout="", stderr=stderr)
|
||
|
||
monkeypatch.setattr(subprocess, "run", decode)
|
||
kwargs = {"allow_empty": True} if allow_empty else {}
|
||
if wanted is None:
|
||
with pytest.raises((ValueError, subprocess.CalledProcessError)):
|
||
sensevoice_transcribe(selected, tmp_path, tmp_path, **kwargs)
|
||
else:
|
||
assert sensevoice_transcribe(selected, tmp_path, tmp_path, **kwargs) == wanted
|
||
assert list(tmp_path.iterdir()) == []
|