"""原生音画验收不能靠同长音轨或自报ASR通过;不加载真实模型。""" import contextlib import json import shutil import subprocess import sys from types import SimpleNamespace import numpy as np import pytest def module(): from llm_services.dialogue import native_acceptance return native_acceptance def good_sync(): return {"decision": "pass", "offset_ms": 0, "confidence": 4.0, "voiced_windows": 50} def good_controls(): return [ { "shift_ms": 400, "score": { "decision": "reject", "offset_ms": -400, "confidence": 4.0, "voiced_windows": 50, }, }, { "shift_ms": -400, "score": { "decision": "reject", "offset_ms": 400, "confidence": 4.0, "voiced_windows": 50, }, }, ] def test_negative_controls_must_track_both_real_audio_shifts(): assert module().assess_sync(good_sync(), good_controls())["decision"] == "pass" wrong = good_controls() wrong[0]["score"]["offset_ms"] = 400 assert module().assess_sync(good_sync(), wrong)["decision"] == "indeterminate" assert module().assess_sync(good_sync(), [])["decision"] == "indeterminate" rejected = {**good_sync(), "decision": "reject", "offset_ms": 200} assert module().assess_sync(rejected, good_controls())["decision"] == "reject" broken = good_controls() broken[0]["score"]["confidence"] = float("nan") assert module().assess_sync(good_sync(), broken)["decision"] == "indeterminate" def test_shift_is_only_a_padded_analysis_copy_and_never_mutates_original(): wave = np.arange(100, dtype=np.float32) shifted = module().shift_audio(wave, 20) assert np.array_equal(wave, np.arange(100)) assert np.array_equal(shifted[:20], np.zeros(20)) assert np.array_equal(shifted[20:], wave[:-20]) assert np.array_equal(module().shift_audio(wave, -20)[:-20], wave[20:]) def test_asr_tail_requires_sustained_closed_mouth_evidence(): report = {"words": [{"start_sample": 24000, "end_sample": 96000}]} assert module().tail_window(report, frames=158) == (54, 158) assert module().tail_window({"words": [{"end_sample": 310000}]}, frames=158) is None with pytest.raises(ValueError): module().tail_window({"words": []}, frames=158) def test_matching_duration_or_sync_score_cannot_override_missing_tail_or_visual_review(): checks = { "geometry": "pass", "audio_binding": "pass", "speech": "pass", "sync": "pass", "tracking": "pass", "rest": "pass", "visual": "pass", } assert module().overall(checks)["decision"] == "pass" assert ( module().overall({**checks, "rest": "indeterminate"})["decision"] == "indeterminate" ) assert ( module().overall({**checks, "visual": "indeterminate"})["decision"] == "indeterminate" ) assert module().overall({**checks, "sync": "reject"})["decision"] == "reject" def test_geometry_uses_actual_decoded_frame_clock_and_complete_wav(): metadata = { "frames": 158, "fps": 24, "width": 1344, "height": 768, "video_start": 0.0, "audio_start": 0.0, "video_duration": 158 / 24, "audio_duration": 6.60, } result = module().assess_geometry( metadata, samples=210400, rate=32000, channels=2, width=2 ) assert result["decision"] == "pass" assert result["native_audio_samples"] == 210400 assert ( module().assess_geometry( metadata, samples=200000, rate=32000, channels=2, width=2 )["decision"] == "reject" ) assert ( module().assess_geometry( {**metadata, "audio_start": 0.2}, samples=210400, rate=32000, channels=2, width=2, )["decision"] == "reject" ) def test_visual_review_requires_the_exact_video_and_complete_frame_range(tmp_path): path = tmp_path / "visual.json" value = { "decision": "pass", "video_sha256": "a" * 64, "source_start_frame": 0, "source_end_frame": 158, } path.write_text(json.dumps(value)) assert module().visual_review(path, "a" * 64, 158)["decision"] == "pass" assert module().visual_review(path, "b" * 64, 158)["decision"] == "indeterminate" assert module().visual_review(path, "a" * 64, 124)["decision"] == "indeterminate" assert module().visual_review(None, "a" * 64, 158)["decision"] == "indeterminate" @pytest.mark.skipif(not shutil.which("ffmpeg"), reason="ffmpeg not on PATH") def test_native_probe_counts_actual_frames_and_accepts_embedded_audio(tmp_path): path = tmp_path / "source.mp4" subprocess.run( [ "ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=blue:s=64x64:r=24:d=5.1666667", "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=32000:duration=5.175", "-map", "0:v:0", "-map", "1:a:0", "-frames:v", "124", "-c:v", "libx264", "-c:a", "aac", str(path), ], check=True, ) result = module().probe_native(path) assert result["frames"] == 124 assert result["fps"] == 24 assert result["audio_start"] == 0 assert module().embedded_audio(path).shape[1] == 2 def test_mouth_parser_cpu_retains_explicit_device(monkeypatch, tmp_path): from llm_services.dialogue.rest import MouthParser devices = [] class Model: config = SimpleNamespace( id2label={0: "mouth", 1: "u_lip", 2: "l_lip", 3: "skin"} ) @classmethod def from_pretrained(cls, *args, **kwargs): return cls() def to(self, device): devices.append(device) return self def eval(self): return self processor = SimpleNamespace(from_pretrained=lambda *a, **kw: "processor") monkeypatch.setitem( sys.modules, "transformers", SimpleNamespace( SegformerForSemanticSegmentation=Model, SegformerImageProcessor=processor ), ) assert MouthParser(tmp_path, device="cpu").device == "cpu" assert devices == ["cpu"] def test_evidence_graphics_preserve_inputs_and_make_both_artifacts( monkeypatch, tmp_path ): from PIL import Image from llm_services.dialogue.native_acceptance_visuals import evidence_images monkeypatch.setitem( sys.modules, "cv2", SimpleNamespace(COLOR_BGR2RGB=1, cvtColor=lambda image, _: image[:, :, ::-1]), ) original = np.full((80, 120, 3), 100, np.uint8) measurements = [ {"frame": i, "mouth_aperture": 0.02, "audio_rms": 0.01} for i in range(158) ] evidence_images( tmp_path, {0: (original, original), 157: (original, original)}, measurements, {"words": [{"start_sample": 24000, "end_sample": 96000}]}, (54, 158), ) assert np.all(original == 100) for name in ("native-av-evidence.png", "native-av-mouth-timeline.png"): with Image.open(tmp_path / name) as image: image.verify() def test_normalized_audio_cannot_borrow_a_matching_text_report_from_another_track( monkeypatch, tmp_path ): from llm_services.dialogue import native_alignment raw = np.linspace(-0.2, 0.2, 3200, dtype=np.float32)[:, None].repeat(2, axis=1) normalized = np.repeat(raw, 3, axis=0)[::2] source, selected = tmp_path / "native.wav", tmp_path / "selected.wav" source.write_bytes(b"native") selected.write_bytes(b"selected") monkeypatch.setitem( sys.modules, "soundfile", SimpleNamespace( read=lambda path, **kw: ( (raw, 32000) if path == source else (normalized, 48000) ) ), ) monkeypatch.setitem(sys.modules, "scipy", SimpleNamespace()) monkeypatch.setitem( sys.modules, "scipy.signal", SimpleNamespace( resample_poly=lambda array, *args, **kw: np.repeat(array, 3, axis=0)[::2] ), ) monkeypatch.setattr( native_alignment, "validate_content_verification", lambda report: None ) monkeypatch.setattr(native_alignment, "validate_words", lambda *a: None) report = { "decision": "pass", "native_av_policy": "native_av_v1", "asr_revision": "41f01f3fe87f28c78e2fbf8b568835947dd65ed9", "content_error_rate": 0, "audio_sha256": module().digest(selected), "sample_rate": 48000, "source_start_sample": 0, "source_end_sample": 4800, "reasons": [], "words": [], "transcript": "hello", "timestamp_source": "whisper-word-timestamps", "timestamp_origin": "audio_asset", } _, evidence = module().audio_evidence(source, selected, report) assert evidence["decision"] == "pass" _, evidence = module().audio_evidence( source, selected, report, embedded=normalized.copy() ) assert evidence["decision"] == "pass" _, evidence = module().audio_evidence( source, selected, report, embedded=normalized[:-4000] ) assert evidence["decision"] == "indeterminate" _, evidence = module().audio_evidence( source, selected, report, embedded=normalized[::-1].copy() ) assert evidence["decision"] == "indeterminate" with pytest.raises(ValueError, match="bound"): module().audio_evidence(source, selected, {**report, "audio_sha256": "f" * 64}) with pytest.raises(ValueError, match="bound"): module().audio_evidence( source, selected, {**report, "native_av_policy": "legacy"} ) normalized = normalized[::-1].copy() _, evidence = module().audio_evidence(source, selected, report) assert evidence["decision"] == "indeterminate" def test_syncnet_cpu_option_never_calls_cuda(monkeypatch): from llm_services.dialogue.quality import syncnet_scores devices = [] class Tensor: def __init__(self, value): self.value = np.asarray(value) def float(self): return self def to(self, device): devices.append(device) return self def cuda(self): raise AssertionError("CPU acceptance cannot request CUDA") def cpu(self): return self def __getitem__(self, indices): return Tensor(self.value[indices]) def __sub__(self, other): return Tensor(self.value - other.value) def norm(self, dim): return Tensor(np.linalg.norm(self.value, axis=dim)) def mean(self): return Tensor(self.value.mean()) def item(self): return self.value.item() torch = SimpleNamespace( from_numpy=Tensor, cat=lambda tensors: Tensor(np.concatenate([t.value for t in tensors])), inference_mode=contextlib.nullcontext, ) monkeypatch.setitem(sys.modules, "torch", torch) monkeypatch.setitem(sys.modules, "scipy", SimpleNamespace()) monkeypatch.setitem( sys.modules, "scipy.signal", SimpleNamespace(resample_poly=lambda wave, *a: wave[::3]), ) monkeypatch.setitem( sys.modules, "python_speech_features", SimpleNamespace(mfcc=lambda *a: np.zeros((400, 13), np.float32)), ) model = SimpleNamespace( forward_lip=lambda value: Tensor(np.zeros((len(value.value), 8))), forward_aud=lambda value: Tensor(np.zeros((len(value.value), 8))), ) result = syncnet_scores( model, [np.zeros((2, 2, 3), np.uint8)] * 96, np.ones(192000, np.float32) * 0.1, device="cpu", ) assert result["decision"] == "indeterminate" assert devices and set(devices) == {"cpu"}