cmvr-visual/inference/tests/test_dialogue_runtime.py

1239 lines
41 KiB
Python

import pytest
from llm_services.runner import validate_request
from llm_services.store import TASK_TYPES
def test_reference_style_and_continuation_use_official_voxcpm_modes():
from llm_services.dialogue.runtime import synthesis_controls
inp = {"reference_path": "fixed.wav", "prompt": "剧院见。"}
p = {"voice": "speaker-a", "style": "镇静", "reference_text": "你好。"}
assert synthesis_controls(inp, p) == (
"(镇静)剧院见。",
{"reference_wav_path": "fixed.wav"},
"controlled_clone",
)
assert synthesis_controls(inp, {**p, "style": ""}) == (
"剧院见。",
{
"reference_wav_path": "fixed.wav",
"prompt_wav_path": "fixed.wav",
"prompt_text": "你好。",
},
"continuation_clone",
)
def test_dialogue_queue_contract(tmp_path):
assert "video.lipsync" in TASK_TYPES
inputs = tmp_path / "inputs" / "llm-services"
inputs.mkdir(parents=True)
paths = {}
for field, suffix in (
("video_path", "mp4"),
("face_tracks_path", "json"),
("audio_path", "wav"),
):
path = inputs / ("a" * 64 + "." + suffix)
path.write_bytes(b"test")
paths[field] = str(path)
p = {
"profile": "musetalk-v15-v1",
"fps": 24,
"num_frames": 24,
"speaker_id": "c" * 32,
"target_track_id": "c" * 32,
}
job = {
"task_type": "video.lipsync",
"input": paths,
"parameters": p,
"output_dir": str(tmp_path / "outputs" / "new"),
}
assert validate_request(job, workspace=tmp_path)["parameters"] == p
for task in ("video.lipsync", "video.dialogue.inspect"):
fields = dict(paths)
if task.endswith("inspect"):
fields["base_video_path"] = paths["video_path"]
for policy in ("source-rest-v2", "neutral-rest-v1"):
params = {**p, "speech_silence_policy": policy}
request = {**job, "task_type": task, "input": fields, "parameters": params}
assert validate_request(request, workspace=tmp_path)["parameters"] == params
with pytest.raises(ValueError):
validate_request(
{**request, "parameters": {**params, "speech_silence_policy": "open"}},
workspace=tmp_path,
)
for delta in (-6, 0, 6):
params = {**p, "audio_context_shift_frames": delta}
assert (
validate_request({**job, "parameters": params}, workspace=tmp_path)[
"parameters"
]
== params
)
for invalid in (-7, 7, True, 1.5):
with pytest.raises(ValueError):
validate_request(
{**job, "parameters": {**p, "audio_context_shift_frames": invalid}},
workspace=tmp_path,
)
with pytest.raises(ValueError):
validate_request({**job, "parameters": {**p, "fps": 25}}, workspace=tmp_path)
with pytest.raises(ValueError):
validate_request({**job, "input": {**paths, "loop": True}}, workspace=tmp_path)
def test_analysis_binding_rejects_stale_source_or_missing_frames():
from llm_services.dialogue.media import target_boxes
track = {"track_id": "a", "speaker_id": "a", "boxes": [[10, 10, 80, 80]] * 24}
record = {
"source_sha256": "1" * 64,
"fps": 24,
"num_frames": 24,
"tracks": [track],
"decision": "pass",
}
params = {"num_frames": 24, "speaker_id": "a", "target_track_id": "a"}
assert len(target_boxes(record, params, "1" * 64, 100, 100)) == 24
with pytest.raises(ValueError):
target_boxes(record, params, "2" * 64, 100, 100)
track["boxes"].pop()
with pytest.raises(ValueError):
target_boxes(record, params, "1" * 64, 100, 100)
@pytest.mark.parametrize("count,limit", [(1, 1), (2, 1), (2, 2)])
def test_admission_counts_visible_faces_including_silent_listeners(
tmp_path, monkeypatch, count, limit
):
import json
from types import SimpleNamespace
from llm_services.dialogue import profiles
data = {
"decision": "pass",
"tracks": [{"speaker_id": str(i)} for i in range(count)],
}
path = tmp_path / "tracks.json"
path.write_text(json.dumps(data))
monkeypatch.setattr(
profiles,
"capabilities",
lambda _: {
"silence_policies": {
"source-rest-v2": {
"lipsync": {
"available": True,
"max_people": limit,
"speech_silence_policy": "source-rest-v2",
}
}
}
},
)
inputs = {"face_tracks_path": str(path), "speech_tracks": [{"speaker_id": "0"}]}
if count > limit:
with pytest.raises(ValueError, match="multi-person"):
profiles.admit(
SimpleNamespace(),
"video.lipsync",
{"speech_silence_policy": "source-rest-v2"},
inputs,
)
else:
profiles.admit(
SimpleNamespace(),
"video.lipsync",
{"speech_silence_policy": "source-rest-v2"},
inputs,
)
@pytest.mark.parametrize(
"shift, expected",
[
(0, [10, 11, 3, 13]),
(1, [11, 12, 3, 1]),
(-1, [1, 10, 3, 12]),
(6, [1, 1, 3, 1]),
(-6, [1, 1, 3, 1]),
],
)
def test_audio_context_shift_keeps_source_frames_and_vad(shift, expected):
from types import SimpleNamespace
import numpy as np
from llm_services.dialogue.lipsync import render_frame
wave = np.repeat([1.0, 1.0, 0.0, 1.0], 2000)
original = wave.copy()
boxes = [[0, 0, 1, 1]] * 4
model = SimpleNamespace(
patch=lambda frame, box, points, context, ref: context + (ref or 0)
)
for i, want in enumerate(expected):
base = np.full((1, 2, 3), i, dtype=np.uint8)
got = render_frame(
model,
base,
[(None, boxes, [None] * 4, wave)],
[[10, 11, 12, 13]],
[1] * 4,
i,
[2],
shift,
)
assert got[0, 0, 0] == want and got[0, 1, 0] == i
assert (base == i).all()
assert np.array_equal(wave, original)
def test_silent_frames_of_a_speaking_track_are_synthesized_but_unassigned_faces_are_untouched():
from types import SimpleNamespace
import numpy as np
from llm_services.dialogue.lipsync import render_frame
base = np.zeros((8, 16, 3), dtype=np.uint8)
wave = np.zeros(4000)
wave[:2000] = 0.2
row = ({}, [[0, 0, 8, 8]] * 2, [None] * 2, wave)
m = SimpleNamespace(
patch=lambda image, box, landmarks, audio, reference: np.full(
(8, 8, 3), audio + (reference or 0)
)
)
for i, expected in enumerate([9, 5]):
frame = render_frame(m, base, [row], [[9, 9]], [3, 3], i, [2])
assert np.all(frame[:, :8] == expected) and np.all(frame[:, 8:] == 0)
assert not base.any()
def test_rest_quality_measures_sustained_silence_and_fails_closed_without_lip_evidence():
import numpy as np
from llm_services.dialogue.rest import assess_rest, quiet_windows
wave = np.zeros(2000 * 36)
wave[:20000] = 0.15
windows = quiet_windows(wave)
assert windows == [(12, 36)]
assert assess_rest(windows, {i: 0.01 for i in range(12, 36)})["decision"] == "pass"
assert (
assess_rest(windows, {i: (0.18 if i % 6 < 3 else 0.01) for i in range(12, 36)})[
"decision"
]
== "reject"
)
assert assess_rest(windows, {})["decision"] == "indeterminate"
def test_brief_speaking_cannot_hide_inside_long_silence():
import math
from llm_services.dialogue.rest import assess_rest
quiet = dict.fromkeys(range(120), 0.01)
open_mouth = {**quiet, **dict.fromkeys(range(100, 110), 0.4)}
result = assess_rest([(0, 120)], open_mouth)
assert result["decision"] == "reject"
window = result["windows"][0]
assert window["aperture_p90"] == 0.01
assert window["aperture_range_p90_p10"] == 0
assert window["short_window_frames"] == 12
assert window["max_short_window_p90"] == 0.4
assert 88 < window["first_rejected_short_window_start"] <= 100
assert assess_rest([(0, 120)], {**quiet, 103: 0.4})["decision"] == "pass"
for missing in (None, math.nan):
assert (
assess_rest([(0, 120)], {**open_mouth, 104: missing})["decision"]
== "indeterminate"
)
def test_source_mouth_blocks_distinguish_mouth_damage_from_eye_damage_and_codec_noise():
import numpy as np
from llm_services.dialogue.profiles import verify_mouth_preservation
from llm_services.dialogue.quality import (
mouth_blocks,
mouth_source_check,
visual_verdict,
)
diff = np.full((128, 128), 2.0)
roi = (slice(70, 112), slice(33, 94))
diff[10:42, 35:67] = 255
noise = mouth_blocks(diff, roi)
check = mouth_source_check("actor", [noise])
assert check["decision"] == "pass" and check["max_block_mae"] == 2
source = [{"speaker_id": "actor", "silent_frames": 1, "decision": "pass"}]
evidence = {"source_rest_checks": source, "silent_mouth_source_checks": [check]}
with pytest.raises(ValueError):
verify_mouth_preservation(evidence, "reject")
diff[roi] = 50
check = mouth_source_check("actor", [mouth_blocks(diff, roi)])
assert check["decision"] == "reject" and check["block_count"] > 0
evidence["silent_mouth_source_checks"] = [check]
verify_mouth_preservation(evidence, "reject")
assert visual_verdict(
[{"decision": "pass"}], [], [], 1, 0, 0, 0, 0, mouth_source_checks=[check]
) == ("reject", ["silent_mouth_source_changed"])
assert mouth_source_check("actor", [])["decision"] == "not_applicable"
assert (
mouth_source_check("actor", [mouth_blocks(diff, (slice(1, 3), slice(2, 4)))])[
"decision"
]
== "indeterminate"
)
def test_protected_blocks_reveal_localized_damage_and_ignore_only_the_target_mask():
import numpy as np
from llm_services.dialogue.quality import protected_blocks
diff = np.full((768, 1344), 2.0)
protected = np.ones(diff.shape, bool)
diff[20:70, 20:70] = 255
assert diff.mean() < 6
error, fraction = protected_blocks(diff, protected)
assert error > 18 and fraction > 0.15
protected[20:70, 20:70] = False
assert protected_blocks(diff, protected) == (2.0, 0.0)
def test_voice_enrollment_needs_every_measured_mismatched_pair():
from llm_services.dialogue.profiles import verify_voice_set
own = [
{"reference_sha256": r, "audio_sha256": a, "decision": "pass", "speaker_id": r}
for r, a in zip("abc", "xyz")
]
cross = [
{
"reference_sha256": other["reference_sha256"],
"audio_sha256": src["audio_sha256"],
"decision": "reject",
"reasons": ["different_voice"],
"content_error_rate": 0,
}
for src in own
for other in own
if src is not other
]
verify_voice_set(own, cross)
with pytest.raises(ValueError):
verify_voice_set(own, cross[:-1])
with pytest.raises(ValueError):
verify_voice_set(own, [{**cross[0], "decision": "pass"}, *cross[1:]])
with pytest.raises(ValueError):
verify_voice_set(
own, [{**cross[0], "reasons": ["spoken_content_mismatch"]}, *cross[1:]]
)
def test_no_self_declared_readiness(tmp_path):
from types import SimpleNamespace
from llm_services.dialogue.profiles import capabilities
conf = tmp_path / "config"
conf.mkdir()
(conf / "dialogue-certificates.json").write_text('{"lipsync":{"available":true}}')
assert (
capabilities(SimpleNamespace(app_root=tmp_path, workspace_root=tmp_path))[
"lipsync"
]["available"]
is False
)
def test_real_frame_count_and_audio_isolation(tmp_path):
import shutil
import subprocess
from llm_services.dialogue.media import probe
if not shutil.which("ffmpeg") or not shutil.which("ffprobe"):
pytest.skip("ffmpeg/ffprobe required")
source = tmp_path / "selected.mp4"
subprocess.run(
[
"ffmpeg",
"-hide_banner",
"-loglevel",
"error",
"-f",
"lavfi",
"-i",
"testsrc2=size=64x48:rate=24",
"-frames:v",
"24",
"-an",
"-c:v",
"libx264",
"-threads",
"1",
str(source),
],
check=True,
)
assert probe(source, 24) == (64, 48)
with pytest.raises(ValueError):
probe(source, 25)
mixed = tmp_path / "with-source-audio.mp4"
subprocess.run(
[
"ffmpeg",
"-loglevel",
"error",
"-i",
str(source),
"-f",
"lavfi",
"-i",
"sine=duration=1",
"-c:v",
"copy",
"-c:a",
"aac",
str(mixed),
],
check=True,
)
with pytest.raises(ValueError):
probe(mixed, 24)
def test_calibration_is_one_owner_one_idempotent_job(tmp_path):
import json
import time
from types import SimpleNamespace
from llm_services.dialogue.profiles import admit, calibration_digest
settings = SimpleNamespace(app_root=tmp_path, workspace_root=tmp_path)
task = "audio.dialogue.speech"
inputs = {"prompt": "test"}
p = {"profile": "voxcpm2-v1", "seed": 2, "voice": "A"}
sha = calibration_digest(task, inputs, p)
folder = tmp_path / "config" / "dialogue-validation" / "calibration"
folder.mkdir(parents=True)
path = folder / (sha + ".json")
receipt = {"sha256": sha, "owner_id": "a" * 32, "expires_at": time.time() + 60}
path.write_text(json.dumps(receipt))
key = "cmvr-visual:" + "b" * 32
with pytest.raises(ValueError):
admit(settings, task, p, inputs, principal="c" * 32, idempotency_key=key)
with pytest.raises(ValueError):
admit(
settings,
task,
{**p, "seed": 3},
inputs,
principal="a" * 32,
idempotency_key=key,
)
admit(settings, task, p, inputs, principal="a" * 32, idempotency_key=key)
admit(settings, task, p, inputs, principal="a" * 32, idempotency_key=key)
with pytest.raises(ValueError):
admit(
settings,
task,
p,
inputs,
principal="a" * 32,
idempotency_key="cmvr-visual:" + "c" * 32,
)
path.write_text(json.dumps({**receipt, "expires_at": time.time() - 1}))
with pytest.raises(ValueError):
admit(settings, task, p, inputs, principal="a" * 32, idempotency_key=key)
def test_certificate_requires_exact_blind_control_and_two_nonmatching_scripts():
from llm_services.dialogue.audio_quality import (
CONTENT_REVIEW_POLICY,
SENSEVOICE_REVISION,
SENSEVOICE_RUNTIME,
)
from llm_services.dialogue.profiles import verify_crosscheck
positive = {
"content_review_policy": CONTENT_REVIEW_POLICY,
"secondary_status": "completed",
"secondary_asr_revision": SENSEVOICE_REVISION,
"secondary_runtime_revision": SENSEVOICE_RUNTIME,
"primary_content_error_rate": 0.1,
"secondary_transcript": "以前装过新门",
"expected_text": "以前装过新门",
"transcript": "以前转过新门",
"decision": "pass",
"content_decision_source": "sensevoice",
"secondary_content_error_rate": 0,
"resource_metrics": {"peak_gpu_mib": 1786, "peak_host_mib": 2100},
"audio_sha256": "a" * 64,
"reference_sha256": "b" * 64,
"speaker_id": "lin",
"source_start_sample": 0,
"source_end_sample": 99999,
}
neg = {
**positive,
"decision": "indeterminate",
"content_decision_source": "unconfirmed",
"secondary_content_error_rate": 0.15,
"reasons": ["uncertain_transcript"],
}
near, missing = (
{**neg, "expected_text": "以前撞过新门"},
{**neg, "expected_text": "以前装新门"},
)
verify_crosscheck(positive, [near, missing])
for bad in (
{**near, "audio_sha256": "c" * 64},
{**near, "secondary_content_error_rate": 0},
missing,
):
with pytest.raises(ValueError):
verify_crosscheck(positive, [bad, missing])
with pytest.raises(ValueError):
verify_crosscheck({**positive, "content_review_policy": "old"}, [near, missing])
def test_crosscheck_exact_blind_transcript_and_unavailable_evidence():
from llm_services.dialogue.audio_quality import review_content
script = "以前装过新门,大家更喜欢现在这一扇。"
first = script.replace("装", "转")
for second, outcome, source in (
(script, "pass", "sensevoice"),
(first, "indeterminate", "unconfirmed"),
(script.replace("大家", "大伙"), "indeterminate", "unconfirmed"),
(script.replace("过", ""), "indeterminate", "unconfirmed"),
):
calls = []
def blind(calls=calls, second=second):
calls.append(True)
return second
decision, reasons, rate, evidence = review_content(
script, first, 2, 0, 2, 0.8, blind, lambda s: s
)
assert calls == [True]
assert (decision, evidence["content_decision_source"]) == (outcome, source)
assert evidence["secondary_transcript"] == second
assert evidence["primary_content_error_rate"] > 0
assert (rate == 0) == (outcome == "pass")
def offline():
raise OSError("unavailable")
decision, reasons, rate, evidence = review_content(
script, first, 2, 0, 2, 0.8, offline, lambda s: s
)
assert reasons == ["uncertain_transcript"] and rate > 0
assert decision == "indeterminate" and evidence["secondary_status"] == "unavailable"
assert evidence["secondary_transcript"] is None
def test_crosscheck_never_overrides_primary_reject_or_noncontent_gate():
from llm_services.dialogue.audio_quality import review_content
def forbidden():
raise AssertionError("second recognizer invoked")
for candidate, voice, clipped, ref, similarity, expected in (
("长句测正确", 2, 0, 2, 0.8, "pass"),
("短片", 2, 0, 2, 0.8, "reject"),
("长句测正", 2, 0, 2, 0.8, "reject"), # CER exactly 0.20
("长句测式正确吗", 0.9, 0, 2, 0.8, "indeterminate"),
("长句测式正确吗", 2, 0.02, 2, 0.8, "reject"),
("长句测式正确吗", 2, 0, 0.8, None, "indeterminate"),
("长句测式正确吗", 2, 0, 2, 0.3, "indeterminate"),
("长句测式正确吗", 2, 0, 2, 0.2, "reject"),
):
script = "长句测试正确吗" if candidate.endswith("吗") else "长句测正确"
decision, _, _, ev = review_content(
script, candidate, voice, clipped, ref, similarity, forbidden, lambda s: s
)
assert decision == expected and ev["secondary_status"] == "not_requested"
def test_spoken_mandarin_third_person_pronouns_share_one_reading():
from llm_services.dialogue.audio_quality import error_rate, verdict
for expected in "他她它":
for observed in "他她它":
assert error_rate(f"叫{expected}灰楼", f"叫{observed}灰楼") == 0
expected, transcript = "五号楼。小时候叫它灰楼。", "5号楼小时候叫他灰楼"
assert verdict(expected, transcript, 2, 0, 2, 0.543) == ("pass", [], 0)
assert verdict(expected, transcript, 2, 0, 2, 0.24)[0] == "reject"
assert verdict(expected, transcript, 0.9, 0, 2, 0.543)[0] == "indeterminate"
assert verdict(expected, transcript, 2, 0.016, 2, 0.543)[0] == "reject"
def test_spoken_pronoun_rule_preserves_missing_extra_and_different_words():
from llm_services.dialogue.audio_quality import error_rate
for expected, observed in (
("叫它灰楼", "叫灰楼"),
("叫它灰楼", "叫他他灰楼"),
("叫它灰楼", "叫他回楼"),
("是她吗", "是塔吗"),
("师父", "师傅"),
("she", "he"),
):
assert error_rate(expected, observed) > 0
def test_transcript_accepts_equivalent_single_digits_but_preserves_number_changes():
from llm_services.dialogue.audio_quality import error_rate
assert error_rate("五号楼", "5号楼") == 0
assert error_rate("五号楼", "6号楼") > 0
assert error_rate("五十", "五") > 0
assert error_rate("鞋能走", "邪能走") > 0
def test_audio_quality_requires_content_and_independent_voice():
from llm_services.dialogue.audio_quality import verdict
assert verdict("您好。", "您好", 3, 0, 3, 0.80)[0] == "pass"
assert verdict("您好。", "您好", 3, 0, 0, None)[0] == "indeterminate"
assert verdict("您好。", "再见", 3, 0, 3, 0.80)[0] == "reject"
assert verdict("您好。", "您好", 3, 0, 3, 0.05)[0] == "reject"
assert verdict("您好。", "您好", 0.15, 0, 3, 0.80)[0] != "pass"
def test_visual_verdict_returns_each_triggered_reason_without_hiding_uncertainty():
from llm_services.dialogue.quality import visual_verdict
passing = [{"decision": "pass"}]
assert visual_verdict(passing, passing, [], 0.65, 6, 18, 0.15, 8) == ("pass", [])
d, r = visual_verdict(
[{"decision": "indeterminate", "confidence": 1.4}],
passing,
[],
0.64,
0,
0,
0,
0,
)
assert d == "reject" and set(r) == {"identity_changed", "low_sync_confidence"}
d, r = visual_verdict(
[{"decision": "reject"}], [{"decision": "reject"}], passing, 0.9, 0, 19, 0, 9
)
assert d == "reject" and set(r) == {
"sync_offset",
"silence_mouth_motion",
"listener_changed",
"listener_sync",
"protected_region_changed",
}
assert visual_verdict(
[{"decision": "indeterminate", "reason": "short_sample"}],
passing,
[],
0.8,
0,
0,
0,
0,
) == ("indeterminate", ["short_sample"])
@pytest.mark.parametrize("policy", ["neutral-rest-v1", "source-rest-v2"])
def test_feature_shift_cert_only_accepts_exact_matched_pair(monkeypatch, policy):
from llm_services.dialogue import AUDIO_CONTEXT_SHIFT_POLICY, profiles
task = "video.lipsync"
qa = "video.dialogue.inspect"
params = {"seed": 42}
src = {
"video_path": "same",
"speech_tracks": [{"speaker_id": "xu", "audio_path": "original"}],
}
old_src, new_src = {**src, "video_path": "old"}, {**src, "video_path": "new"}
def evidence(sha, decision, offset, reasons):
return {
"synced_sha256": sha,
"decision": decision,
"reasons": reasons,
"scores": [{"speaker_id": "xu", "offset_ms": offset, "confidence": 6.42}],
}
report = {
"speech_silence_policy": policy,
"audio_context_shift_policy": AUDIO_CONTEXT_SHIFT_POLICY,
**{
name: name
for name in [
"shift_baseline_render",
"shift_render",
"shift_baseline_quality",
"shift_quality",
"shift_negative_quality",
]
},
}
jobs = {
"shift_baseline_render": (task, {"synced_sha256": "old"}, src, params),
"shift_render": (
task,
{
"synced_sha256": "new",
"audio_context_shift_policy": AUDIO_CONTEXT_SHIFT_POLICY,
"audio_context_shift_frames": 3,
},
src,
{**params, "audio_context_shift_frames": 3},
),
"shift_baseline_quality": (
qa,
evidence("old", "reject", 120, ["sync_offset"]),
old_src,
{},
),
"shift_quality": (qa, evidence("new", "pass", 0, []), new_src, {}),
"shift_negative_quality": (
qa,
evidence("new", "reject", -400, ["sync_offset"]),
{**new_src, "speech_tracks": [{"speaker_id": "xu", "audio_path": "400ms"}]},
{},
),
}
for key in ("shift_zero_render", "shift_opposite_render", "shift_opposite_quality"):
report[key] = key
jobs["shift_zero_render"] = (
task,
{
"audio_context_shift_policy": AUDIO_CONTEXT_SHIFT_POLICY,
"audio_context_shift_frames": 0,
"synced_sha256": "old",
},
src,
{**params, "audio_context_shift_frames": 0},
)
jobs["shift_opposite_render"] = (
task,
{
"audio_context_shift_policy": AUDIO_CONTEXT_SHIFT_POLICY,
"audio_context_shift_frames": -3,
"synced_sha256": "opposite",
},
src,
{**params, "audio_context_shift_frames": -3},
)
jobs["shift_opposite_quality"] = (
qa,
evidence("opposite", "reject", 240, ["sync_offset"]),
{**new_src, "video_path": "opposite"},
{},
)
def measured(_, job, expected):
kind, *row = jobs[job]
assert kind == expected
return row
for _, meta, _, params in jobs.values():
meta["speech_silence_policy"] = policy
meta["mouth_blend_policy"] = "semantic-skin-ellipse-v1"
if policy == "source-rest-v2":
params["speech_silence_policy"] = policy
monkeypatch.setattr(profiles, "measured_job", measured)
profiles.verify_shift_evidence(None, report)
jobs["shift_negative_quality"][1]["speech_silence_policy"] = (
"source-rest-v2" if policy == "neutral-rest-v1" else "neutral-rest-v1"
)
with pytest.raises(ValueError):
profiles.verify_shift_evidence(None, report)
jobs["shift_negative_quality"][1]["speech_silence_policy"] = policy
jobs["shift_render"][-1]["seed"] = 43
with pytest.raises(ValueError):
profiles.verify_shift_evidence(None, report)
def test_source_rest_renders_only_the_currently_speaking_actor():
from types import SimpleNamespace
import numpy as np
from llm_services.dialogue.lipsync import render_frame
base = np.arange(12, dtype=np.uint8).reshape(1, 4, 3)
left = [[0, 0, 2, 1]] * 2
right = [[2, 0, 4, 1]] * 2
first = np.zeros(4000)
first[:2000] = 1
second = np.zeros(4000)
calls = []
def patch(src, box, landmarks, context, reference):
calls.append((box, context, reference))
return 42
rows = [({}, left, [None] * 2, first), ({}, right, [None] * 2, second)]
for i in (0, 1):
got = render_frame(
SimpleNamespace(patch=patch),
base,
rows,
[[8, 7], [6, 5]],
[3, 3],
i,
[None, None],
1,
speech_silence_policy="source-rest-v2",
)
expected = base.copy()
if i == 0:
expected[:, :2] = 42
assert np.array_equal(got, expected)
assert calls == [(left[0], 7, None)]
def test_source_rest_distinguishes_speaking_source_from_missing_evidence():
from llm_services.dialogue.quality import visual_verdict
from llm_services.dialogue.rest import assess_rest
spans = [(0, 24)]
closed = assess_rest(spans, dict.fromkeys(range(24), 0.0))
speaking = assess_rest(spans, dict.fromkeys(range(24), 0.2))
ambiguous = assess_rest(spans, {})
assert closed["decision"] == "pass"
assert assess_rest(spans, {})["decision"] == "indeterminate"
kwargs = {
"scores": [{"decision": "pass"}],
"rest_checks": [closed],
"cross_checks": [],
"min_identity": 1,
"outside_peak": 0,
"block_mae": 0,
"block_severe": 0,
"listener_peak": 0,
}
assert visual_verdict(**kwargs, source_rest_checks=[speaking]) == (
"reject",
["source_speaking_during_silence"],
)
assert visual_verdict(**kwargs, source_rest_checks=[ambiguous]) == (
"indeterminate",
["insufficient_source_rest_evidence"],
)
def test_current_cert_does_not_admit_frozen_neutral_requests(monkeypatch):
from llm_services.dialogue import profiles
monkeypatch.setattr(
profiles,
"capabilities",
lambda _: {
"silence_policies": {
"neutral-rest-v1": {
"lipsync": {
"available": True,
"max_people": 1,
"speech_silence_policy": "source-rest-v2",
}
}
}
},
)
for params in ({}, {"speech_silence_policy": "neutral-rest-v1"}):
with pytest.raises(ValueError, match="silence policy"):
profiles.admit(None, "video.lipsync", params, {})
def test_source_rest_calibration_requires_three_distinct_linked_measured_clips(
monkeypatch,
):
from llm_services.dialogue import INSPECT, SYNC, profiles
groups = []
records = {}
params = {"speech_silence_policy": "source-rest-v2", "num_frames": 24}
for i in range(3):
src, out, actor = f"src{i}", f"out{i}", f"actor{i}"
window = {"start_frame": 12, "end_frame": 24, "decision": "pass"}
checks = [
{
"speaker_id": actor,
"decision": "pass",
"silent_frames": 12,
"rest_quality_policy": "aperture-window12-v1",
"windows": [window],
}
]
inputs = {
"video_path": src,
"speech_tracks": [{"speaker_id": actor}],
"face_tracks_path": f"faces{i}",
}
metadata = {
"speech_silence_policy": "source-rest-v2",
"mouth_blend_policy": "semantic-skin-ellipse-v1",
"synced_sha256": out,
"base_sha256": src,
}
records[src] = (
SYNC,
{
**metadata,
"source_rest_frames": [{"speaker_id": actor, "silent_frames": 12}],
},
inputs,
)
records[out] = (
INSPECT,
{
**metadata,
"num_frames": 24,
"decision": "pass",
"source_rest_checks": checks,
"silent_mouth_source_checks": [
{
"speaker_id": actor,
"decision": "pass",
"silent_frames": 12,
"measured_frames": 12,
"block_count": 55,
"max_block_mae": 3.0,
"max_block_severe_fraction": 0.0,
}
],
"rest_checks": checks,
},
{**inputs, "base_video_path": src, "video_path": out},
)
groups.append({"render_job_id": src, "quality_job_id": out})
def measured(_, key, task):
real_task, meta, inputs = records[key]
assert real_task == task
return meta, inputs, params
monkeypatch.setattr(profiles, "measured_job", measured)
profiles.verify_source_rest_samples(None, groups)
missing = records["out2"][1].pop("silent_mouth_source_checks")
with pytest.raises(ValueError):
profiles.verify_source_rest_samples(None, groups)
records["out2"][1]["silent_mouth_source_checks"] = missing
with pytest.raises(ValueError):
profiles.verify_source_rest_samples(None, [groups[0]] * 3)
records["out1"][1]["source_rest_checks"] = []
with pytest.raises(ValueError):
profiles.verify_source_rest_samples(None, groups)
def test_speaking_source_controls_require_distinct_untouched_sources(monkeypatch):
from llm_services.dialogue import profiles
def measured(_, job, task):
return (
{
"speech_silence_policy": "source-rest-v2",
"mouth_blend_policy": "semantic-skin-ellipse-v1",
"base_sha256": job,
"synced_sha256": job,
"decision": "reject",
"reasons": ["source_speaking_during_silence"],
"num_frames": 48,
"source_rest_checks": [
{
"decision": "reject",
"windows": [
{
"decision": "reject",
"start_frame": 0,
"end_frame": 24 if job == "intro" else 48,
}
],
}
],
},
{},
{"speech_silence_policy": "source-rest-v2"},
)
monkeypatch.setattr(profiles, "measured_job", measured)
profiles.verify_speaking_sources(None, ["first", "second"])
with pytest.raises(ValueError):
profiles.verify_speaking_sources(None, ["first", "first"])
with pytest.raises(ValueError):
profiles.verify_speaking_sources(None, ["first", "intro"])
def test_both_reviewed_policy_files_publish_and_admit_independently(
tmp_path, monkeypatch
):
import json
from types import SimpleNamespace
from llm_services.dialogue import (
INSPECT,
KEYS,
REVISIONS,
SILENCE_POLICY,
SOURCE_REST_POLICY,
SYNC,
profiles,
)
settings = SimpleNamespace(app_root=tmp_path)
root = tmp_path / "config" / "dialogue-validation"
root.mkdir(parents=True)
tracks = tmp_path / "tracks.json"
tracks.write_text(json.dumps({"decision": "pass", "tracks": [{"speaker_id": "x"}]}))
inputs = {"face_tracks_path": str(tracks)}
reviewed = {
(task, policy)
for task in (SYNC, INSPECT)
for policy in (SILENCE_POLICY, SOURCE_REST_POLICY)
}
def check(settings, task, report):
if (task, report["speech_silence_policy"]) not in reviewed:
raise ValueError("Revoked measurement")
monkeypatch.setattr(profiles, "check_evidence", check)
for task, policy in reviewed:
key = KEYS[task]
path = root / (
f"{key}.json" if policy == SILENCE_POLICY else f"{key}-{policy}.json"
)
path.write_text(
json.dumps(
{
"profile": profiles.profile(task),
"task_type": task,
"decision": "pass",
"audited": True,
"adapter_contract_version": "dialogue-v1",
"revision": REVISIONS[task],
"peak_gpu_mib": 10,
"peak_host_mib": 10,
"validation_job_id": "0" * 32,
"max_people": 1,
"speech_silence_policy": policy,
}
)
)
for task in (SYNC, INSPECT):
caps = profiles.capabilities(settings)
assert caps[KEYS[task]] == caps["silence_policies"][SILENCE_POLICY][KEYS[task]]
for policy in (SILENCE_POLICY, SOURCE_REST_POLICY):
params = {"speech_silence_policy": policy}
profiles.admit(settings, task, params, inputs)
reviewed.remove((task, policy))
with pytest.raises(ValueError):
profiles.admit(settings, task, params, inputs)
other = SOURCE_REST_POLICY if policy == SILENCE_POLICY else SILENCE_POLICY
profiles.admit(settings, task, {"speech_silence_policy": other}, inputs)
reviewed.add((task, policy))
def test_legacy_certificates_use_measured_queue_evidence_and_admit_only_v1(tmp_path):
import json
import sqlite3
from types import SimpleNamespace
from llm_services.dialogue import INSPECT, REVISIONS, SYNC, profiles
settings = SimpleNamespace(app_root=tmp_path, db_path=tmp_path / "queue.db")
conf = tmp_path / "config" / "dialogue-validation"
conf.mkdir(parents=True)
actor = "e" * 32
inp = {
"speech_tracks": [{"speaker_id": actor}],
"base_video_path": "base",
"video_path": "synced",
}
policy = {
"mouth_blend_policy": "semantic-skin-ellipse-v1",
"speech_silence_policy": "neutral-rest-v1",
}
resource = {"peak_gpu_mib": 6000, "peak_host_mib": 3000}
window = {
"start_frame": 10,
"end_frame": 36,
"short_window_frames": 12,
"max_short_window_p90": 0.02,
"max_short_window_range": 0.01,
"first_rejected_short_window_start": None,
}
rest = {
"decision": "pass",
"rest_quality_policy": "aperture-window12-v1",
"silent_frames": 26,
"windows": [window],
}
qa = {
**policy,
"base_sha256": "base",
"synced_sha256": "synced",
"decision": "pass",
"rest_checks": [rest],
"protected_block_size": 32,
"resource_metrics": resource,
}
render = {
**policy,
"synced_sha256": "synced",
"rest_reference_frames": [0],
"resource_metrics": resource,
}
jobs = [
(SYNC, render, {}),
(INSPECT, qa, inp),
(
INSPECT,
{
**qa,
"decision": "reject",
"synced_sha256": "open",
"rest_checks": [
{
**rest,
"decision": "reject",
"windows": [
{**window, "first_rejected_short_window_start": 18}
],
}
],
},
{**inp, "video_path": "open"},
),
(
INSPECT,
{
**qa,
"decision": "reject",
"synced_sha256": "damaged",
"max_protected_block_mae": 25,
},
inp,
),
(
INSPECT,
{
**qa,
"decision": "reject",
"scores": [{"decision": "reject", "offset_ms": 240}],
},
inp,
),
]
db = sqlite3.connect(settings.db_path)
db.execute(
"CREATE TABLE jobs (id,task_type,state,result_json,input_json,parameters_json)"
)
def key(i):
return f"{i:032x}"
for i, (task, meta, inputs) in enumerate(jobs):
db.execute(
"INSERT INTO jobs VALUES (?,?,?,?,?,?)",
(
key(i),
task,
"succeeded",
json.dumps({"metadata": meta, "outputs": [{}]}),
json.dumps(inputs),
json.dumps({"profile": "musetalk-v15-v1"}),
),
)
db.commit()
cert = {
**policy,
**resource,
"max_people": 1,
"profile": "musetalk-v15-v1",
"decision": "pass",
"adapter_contract_version": "dialogue-v1",
"audited": True,
}
for idx, (name, kind, extra) in enumerate(
(
("lipsync", SYNC, {"quality_job_id": key(1)}),
(
"inspect",
INSPECT,
{
"render_job_id": key(0),
"negative_rest_job_id": key(2),
"negative_damage_job_id": key(3),
"negative_control_job_id": key(4),
},
),
)
):
(conf / f"{name}.json").write_text(
json.dumps(
{
**cert,
**extra,
"revision": REVISIONS[kind],
"task_type": kind,
"validation_job_id": key(idx),
}
)
)
caps = profiles.capabilities(settings)
for name in ("lipsync", "inspect"):
assert caps["silence_policies"]["neutral-rest-v1"][name] == caps[name]
assert not caps["silence_policies"]["source-rest-v2"][name]["available"]
legacy = (conf / f"{name}.json").read_bytes()
new = conf / f"{name}-source-rest-v2.json"
new.write_bytes(legacy)
assert not profiles.capabilities(settings)["silence_policies"][
"source-rest-v2"
][name]["available"]
new.write_text(
json.dumps(
{**json.loads(legacy), "speech_silence_policy": "source-rest-v2"}
)
)
assert not profiles.capabilities(settings)["silence_policies"][
"source-rest-v2"
][name]["available"]
assert (
caps[name]["available"]
and caps[name]["speech_silence_policy"] == "neutral-rest-v1"
)
path = tmp_path / "tracks.json"
path.write_text(json.dumps({"decision": "pass", "tracks": [{"speaker_id": actor}]}))
for p in ({}, {"speech_silence_policy": "neutral-rest-v1"}):
profiles.admit(settings, SYNC, p, {"face_tracks_path": str(path)})
with pytest.raises(ValueError):
profiles.admit(
settings,
SYNC,
{"speech_silence_policy": "source-rest-v2"},
{"face_tracks_path": str(path)},
)
db.execute("UPDATE jobs SET state='failed' WHERE id=?", (key(4),))
db.commit()
assert not profiles.capabilities(settings)["inspect"]["available"]
db.execute(
"UPDATE jobs SET parameters_json=? WHERE id=?",
(
json.dumps(
{
"profile": "musetalk-v15-v1",
"speech_silence_policy": "source-rest-v2",
}
),
key(0),
),
)
db.commit()
assert not profiles.capabilities(settings)["lipsync"]["available"]
db.close()