cmvr-visual/inference/tests/test_native_two_person_turns.py

320 lines
10 KiB
Python

import pytest
from llm_services.dialogue import native_turns
def test_measured_turn_boundaries_do_not_borrow_neighbour_audio():
turns = [
{"utterance_id": "u1", "speaker_id": "a", "text": "好"},
{"utterance_id": "u2", "speaker_id": "b", "text": "好"},
]
words = [
{"text": "好", "start_sample": 4800, "end_sample": 28000},
{"text": "好", "start_sample": 56000, "end_sample": 76000},
]
assert native_turns.turn_windows(turns, words) == [(4800, 28000), (56000, 76000)]
with pytest.raises(ValueError):
native_turns.turn_windows(turns, [dict(words[0], text="好好")])
with pytest.raises(ValueError):
native_turns.turn_windows(turns, words + [words[-1]])
def test_voice_identification_measures_both_references_and_never_guesses():
refs = ["left", "right"]
assert (
native_turns.identify_voice(refs, [0.83, 0.02], 2)["observed_speaker_id"]
== "left"
)
assert (
native_turns.identify_voice(refs, [0.01, 0.83], 2)["observed_speaker_id"]
== "right"
)
assert (
native_turns.identify_voice(refs, [0.82, 0.80], 2)["observed_speaker_id"]
is None
)
assert (
native_turns.identify_voice(refs, [0.82, 0.02], 0.35)["observed_speaker_id"]
is None
)
def test_joint_mouth_rhythm_and_swapped_voice_fail_even_for_exact_transcript():
voice = {"observed_speaker_id": "a"}
sync = {"decision": "pass"}
resting = {"decision": "pass"}
assert native_turns.turn_decision("a", voice, sync, sync, resting) == "reject"
assert (
native_turns.turn_decision(
"b", voice, sync, {"decision": "indeterminate"}, resting
)
== "reject"
)
assert (
native_turns.turn_decision(
"a",
{"observed_speaker_id": None},
sync,
{"decision": "indeterminate"},
resting,
)
== "indeterminate"
)
assert (
native_turns.turn_decision(
"a", voice, sync, {"decision": "indeterminate"}, resting
)
== "pass"
)
def test_release_counts_all_24_and_rejects_replayed_cases():
from llm_services.dialogue.turn_certification import count_holdout
rows = [
(str(i), ["pass"] if i < 18 else ["reject", "pass"] if i < 22 else [])
for i in range(24)
]
assert count_holdout(rows) == (18, 22)
with pytest.raises(ValueError):
count_holdout(rows[:-1])
with pytest.raises(ValueError):
count_holdout(rows[:-1] + [rows[0]])
with pytest.raises(ValueError):
count_holdout(rows[:-1] + [("23", ["indeterminate"] * 3)])
def test_release_cannot_count_pass_label_without_independent_control_measurements():
from llm_services.dialogue.turn_certification import validate_screen
forged = {
"decision": "pass",
"controls": True,
"policy": native_turns.POLICY,
"turns": [
{
"decision": "pass",
"expected_speaker_id": s,
"voice": {"observed_speaker_id": s},
}
for s in ("a", "b")
],
}
with pytest.raises(ValueError):
validate_screen(forged, 158)
def test_operator_release_reads_frozen_queue_models_files_and_revokes_on_change(
tmp_path,
):
"""用隔离队列和小文件验证发布清单协议,不产生真实能力证书。"""
import hashlib
import json
import sqlite3
from types import SimpleNamespace
from llm_services.dialogue import turn_certification as release
from test_native_av_acceptance import good_controls, good_sync
def sha(data):
return hashlib.sha256(data).hexdigest()
config = tmp_path / "config" / "dialogue-validation" / "two-person-turns"
config.mkdir(parents=True)
outputs = tmp_path / "outputs"
outputs.mkdir()
def record(value):
data = json.dumps(value, sort_keys=True).encode()
key = sha(data)
(config / (key + ".json")).write_bytes(data)
return key
models = {}
for name in native_turns.MEASUREMENT_FILES:
path = tmp_path / "models" / "dialogue-v1" / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(name.encode())
models[name] = sha(name.encode())
n = 124
checks = {
k: {"decision": "pass"}
for k in ("tracking", "geometry", "audio_binding", "visual", "tail_a", "tail_b")
}
checks["geometry"].update(width=1344, height=768, fps=24, frames=n)
rows = [
{
"utterance_id": "u" + s,
"expected_speaker_id": s,
"listener_id": other,
"start_sample": i * 48000,
"end_sample": (i + 1) * 48000,
"speaker_sync": {
"decision": "pass",
"baseline": good_sync(),
"controls": good_controls(),
},
"listener_sync": {"decision": "indeterminate"},
"listener_rest": {"decision": "pass"},
"voice": {
"observed_speaker_id": s,
"similarities": {s: 0.8, other: 0.05},
"voiced_seconds": 1.1,
},
"decision": "pass",
}
for i, (s, other) in enumerate([("a", "b"), ("b", "a")])
]
proof = {
"policy": native_turns.POLICY,
"controls": True,
"measurement_sha256": models,
"decision": "pass",
"checks": checks,
"turns": rows,
"tracks": {"a": [0] * n, "b": [0] * n},
}
negatives = {}
for label in release.NEGATIVES:
faulty = [{**row, "decision": "indeterminate"} for row in rows]
screen = {
**proof,
"author_sha256": sha(label.encode()),
"turns": faulty,
"decision": "indeterminate",
"source_sha256": {"video": sha(label.encode())},
}
negatives[label] = record(
{
"label": label,
"verified_by": "fixture-operator",
"screen_sha256": record(screen),
}
)
film = b"test container bytes"
(config / (sha(film) + ".mp4")).write_bytes(film)
e2e = record(
{
"film_sha256": sha(film),
"decision": "pass",
"reviewer": "fixture-operator",
"checks": dict.fromkeys(
(
"mixed_story",
"caption_audio",
"bgm",
"pause_resume",
"repair",
"ownership",
"download",
"blind_listening",
),
True,
),
}
)
profile = release.H3_NATIVE_AV_TP2_PROFILE
plan = {
"profile": profile,
"revision": release.H3_REVISION,
"runtime_revision": release.H3_TP2_RUNTIME_COMMIT,
"width": 1344,
"height": 768,
"num_frames": n,
"fps": 24,
"language": "Chinese",
"measurement_sha256": models,
"frozen_at": 1,
"cases": [],
}
settings = SimpleNamespace(
workspace_root=tmp_path,
app_root=tmp_path,
outputs_dir=outputs,
db_path=tmp_path / "queue.sqlite",
native_dialogue_tp2_enabled=True,
)
assert not release.capability(settings)["available"]
db = sqlite3.connect(settings.db_path)
try:
db.execute(
"CREATE TABLE jobs(id TEXT,task_type TEXT,input_json TEXT,parameters_json TEXT,result_json TEXT,state TEXT,created_at REAL)"
)
attempts = {}
for i in range(24):
prompt = "p" + str(i)
first = outputs / (prompt + ".png")
first.write_bytes(prompt.encode())
author = sha(("actor" + str(i)).encode())
plan["cases"].append(
{
"case_id": prompt,
"prompt_sha256": sha(prompt.encode()),
"first_frame_sha256": sha(first.read_bytes()),
"author_sha256": author,
"seeds": [1, 2],
}
)
attempts[prompt] = []
if i >= 22:
continue
folder = outputs / prompt
folder.mkdir()
v, a = folder / "video_raw.mp4", folder / "audio_native.wav"
v.write_bytes(("video" + prompt).encode())
a.write_bytes(("audio" + prompt).encode())
digest_video = sha(v.read_bytes())
meta = {
"metadata": {
"revision": release.H3_REVISION,
"diffusers_source_revision": release.H3_TP2_RUNTIME_COMMIT,
},
"outputs": [{"path": str(v)}, {"path": str(a)}],
}
params = {
"profile": profile,
"width": 1344,
"height": 768,
"seed": 1,
"num_frames": n,
}
db.execute(
"INSERT INTO jobs VALUES(?,?,?,?,?,?,?)",
(
prompt,
"video.generate",
json.dumps({"prompt": prompt, "image_path": str(first)}),
json.dumps(params),
json.dumps(meta),
"succeeded",
2,
),
)
screen = {
**proof,
"author_sha256": author,
"source_sha256": {
"first_frame": sha(first.read_bytes()),
"video": digest_video,
"native_audio": sha(a.read_bytes()),
},
}
attempts[prompt] = [{"job_id": prompt, "screen_sha256": record(screen)}]
db.commit()
finally:
db.close()
cert = {
"policy": native_turns.POLICY,
"release_policy": release.RELEASE_POLICY,
"audited": True,
"auditor": "fixture-operator",
"preregistered_plan_sha256": record(plan),
"negative_controls": negatives,
"e2e_sha256": e2e,
"attempts": attempts,
}
(config / "release.json").write_text(json.dumps(cert))
accepted = release.capability(settings)
assert accepted["available"] and accepted["overall_pass"] == 22
(outputs / "p0" / "audio_native.wav").write_bytes(b"changed-sidecar")
assert not release.capability(settings)["available"]