import hashlib import json import re from functools import partial from . import ( ANALYZE, AUDIO_CONTEXT_SHIFT_POLICY, INSPECT, KEYS, LATENTSYNC_PREVIEW, MOUTH_BLEND_POLICY, REVISIONS, SILENCE_POLICY, SOURCE_REST_POLICY, SPEECH, SPEECH_INSPECT, SYNC, profile, ) def measured_job(settings, job_id, task): import sqlite3 from contextlib import closing # 认证必须回查本机队列的真实成功结果,客户端或独立手写JSON不足以开放能力。 with closing( sqlite3.connect(settings.db_path.as_uri() + "?mode=ro", uri=True, timeout=1) ) as db: row = db.execute( "SELECT result_json,input_json,parameters_json FROM jobs WHERE id=? AND task_type=? AND state='succeeded'", (job_id, task), ).fetchone() if row is None: raise ValueError("Missing successful calibration job") result, inputs, params = (json.loads(x) for x in row) if not result.get("outputs") or params.get("profile") != profile(task): raise ValueError("Unexpected calibration output") return result["metadata"], inputs, params def verify_voice_set(own, cross): # 仅产生三份不同文件无法证明三人可区分。每个克隆必须独立匹配自己, # 并在同一段音频/同一句内容下明确排除其余两个角色的固定声线。 if ( len(own) != 3 or any(m.get("decision") != "pass" for m in own) or any( len({m[k] for m in own}) != 3 for k in ("reference_sha256", "audio_sha256", "speaker_id") ) ): raise ValueError("Three independently verified voices are required") expected = { (src["audio_sha256"], other["reference_sha256"]) for src in own for other in own if src is not other } measured = { (m["audio_sha256"], m["reference_sha256"]) for m in cross if m.get("decision") == "reject" and "different_voice" in m.get("reasons", []) and m.get("content_error_rate") == 0 } if expected != measured: raise ValueError("Confusable or unmeasured pair of character voices") def verify_crosscheck(positive, negatives): from .audio_quality import ( CONTENT_REVIEW_POLICY, SENSEVOICE_REVISION, SENSEVOICE_RUNTIME, normalized_text, ) for sample in [positive, *negatives]: if not ( sample.get("content_review_policy") == CONTENT_REVIEW_POLICY and sample.get("secondary_status") == "completed" and sample.get("secondary_asr_revision") == SENSEVOICE_REVISION and sample.get("secondary_runtime_revision") == SENSEVOICE_RUNTIME and 0 < sample["primary_content_error_rate"] < 0.20 and sample.get("secondary_transcript") and sample["resource_metrics"]["peak_host_mib"] <= 16 * 1024 and sample["resource_metrics"]["peak_gpu_mib"] <= 8 * 1024 ): raise ValueError("Missing bounded independent content measurement") if ( positive["decision"] != "pass" or positive["content_decision_source"] != "sensevoice" or positive["secondary_content_error_rate"] != 0 or len(negatives) != 2 ): raise ValueError("Missing independent exact-match control") expected = normalized_text(positive["expected_text"]) deltas = [] for negative in negatives: if ( negative["decision"] != "indeterminate" or negative["content_decision_source"] != "unconfirmed" or negative["secondary_content_error_rate"] <= 0 or negative["reasons"] != ["uncertain_transcript"] or any( negative[k] != positive[k] for k in ( "audio_sha256", "reference_sha256", "source_start_sample", "source_end_sample", "transcript", "secondary_transcript", "speaker_id", ) ) ): raise ValueError("Missing blind comparison on the same recording") text = normalized_text(negative["expected_text"]) delta = len(text) - len(expected) if delta == 0 and sum(a != b for a, b in zip(text, expected)) != 1: raise ValueError("Expected a single near-word substitution") if delta == -1 and not any( text == expected[:i] + expected[i + 1 :] for i in range(len(expected)) ): raise ValueError("Expected a single omitted character") deltas.append(delta) if sorted(deltas) != [-1, 0]: raise ValueError("Require both missing-word and near-word controls") def measured_visual_job(settings, job_id, task, *, policy=SOURCE_REST_POLICY): meta, inputs, params = measured_job(settings, job_id, task) if ( meta.get("speech_silence_policy") != policy or params.get("speech_silence_policy", SILENCE_POLICY) != policy or meta.get("mouth_blend_policy") != MOUTH_BLEND_POLICY ): raise ValueError(f"Missing measured {policy} job") return meta, inputs, params def verify_mouth_preservation(meta, expected="pass"): from .quality import blocks_changed source = meta.get("source_rest_checks", []) checks = meta.get("silent_mouth_source_checks", []) if not source or len(checks) != len(source): raise ValueError("Missing independent silent mouth measurements") for rest, row in zip(source, checks): count = rest.get("silent_frames") mae, severe = row.get("max_block_mae"), row.get("max_block_severe_fraction") if not ( rest.get("decision") == "pass" and row.get("speaker_id") == rest["speaker_id"] and row.get("decision") == expected and type(count) is int and count > 0 and type(row.get("measured_frames")) is int and type(row.get("silent_frames")) is int and row["measured_frames"] == row["silent_frames"] == count and type(row.get("block_count")) is int and row["block_count"] >= count and type(mae) in (int, float) and 0 <= mae <= 255 and type(severe) in (int, float) and 0 <= severe <= 1 and blocks_changed(mae, severe) == (expected == "reject") ): raise ValueError("Unproven quiet source mouth preservation") def verify_source_rest_samples(settings, pairs): from .rest import REST_QUALITY_POLICY, SHORT_WINDOW_FRAMES if not isinstance(pairs, list) or len(pairs) != 3: raise ValueError("Three measured source-rest render/inspect pairs are required") actors = set() sources = set() for pair in pairs: render, source, rp = measured_visual_job(settings, pair["render_job_id"], SYNC) quality, inputs, qp = measured_visual_job( settings, pair["quality_job_id"], INSPECT ) if ( quality["decision"] != "pass" or render["base_sha256"] != quality["base_sha256"] or render["synced_sha256"] != quality["synced_sha256"] or inputs["base_video_path"] != source["video_path"] or { k: v for k, v in inputs.items() if k not in ("video_path", "base_video_path") } != {k: v for k, v in source.items() if k != "video_path"} or any( rp.get(k) != qp.get(k) for k in ("num_frames", "speaker_id", "target_track_id") ) ): raise ValueError("Unlinked source-rest quality measurement") skips = render["source_rest_frames"] if len(skips) != 1: raise ValueError("Each calibration clip must isolate one actor") actor = skips[0]["speaker_id"] verify_mouth_preservation(quality) for field in ("source_rest_checks", "rest_checks"): checks = quality[field] if ( len(checks) != 1 or checks[0]["decision"] != "pass" or checks[0]["speaker_id"] != actor or checks[0]["rest_quality_policy"] != REST_QUALITY_POLICY or not any( w["decision"] == "pass" and w["end_frame"] == quality["num_frames"] and w["end_frame"] - w["start_frame"] >= SHORT_WINDOW_FRAMES for w in checks[0]["windows"] ) or skips[0]["silent_frames"] < checks[0]["silent_frames"] ): raise ValueError( "Missing sustained source or rendered rest measurement" ) actors.add(actor) sources.add(quality["base_sha256"]) if len(actors) != 3 or len(sources) != 3: raise ValueError("Distinct measured actors and source clips are required") def verify_speaking_sources(settings, job_ids): if not isinstance(job_ids, list) or len(job_ids) != 2: raise ValueError("Two speaking source controls are required") sources = set() for job_id in job_ids: negative, _, _ = measured_visual_job(settings, job_id, INSPECT) if ( negative.get("decision") != "reject" or "source_speaking_during_silence" not in negative.get("reasons", []) or negative["base_sha256"] != negative["synced_sha256"] or not any( window["decision"] == "reject" and window["end_frame"] == negative["num_frames"] for check in negative["source_rest_checks"] for window in check["windows"] ) ): raise ValueError( "Unchanged speaking source must fail independent inspection" ) sources.add(negative["base_sha256"]) if len(sources) != 2: raise ValueError("Distinct speaking sources are required") def check_evidence(settings, task, report): meta, inputs, p = measured_job(settings, report["validation_job_id"], task) metrics = meta["resource_metrics"] if any(report[k] != metrics[k] for k in ("peak_gpu_mib", "peak_host_mib")): raise ValueError("Unmeasured resource claims") if task in (ANALYZE, INSPECT, SPEECH_INSPECT) and meta.get("decision") != "pass": raise ValueError("The validation run did not pass") if task == SPEECH and ( meta.get("sample_rate") != 48000 or meta.get("sample_count", 0) <= 0 ): raise ValueError("No measured synthesized speech") if task == SPEECH: proofs = [ measured_job(settings, j, SPEECH_INSPECT)[0] for j in report["voice_validation_job_ids"] ] compared = [ measured_job(settings, j, SPEECH_INSPECT)[0] for j in report["cross_voice_validation_job_ids"] ] verify_voice_set(proofs, compared) if task == SPEECH_INSPECT: verify_crosscheck( meta, [ measured_job(settings, report[k], task)[0] for k in ("secondary_near_word_job_id", "secondary_missing_word_job_id") ], ) for field, reason in ( ("negative_voice_job_id", "different_voice"), ("negative_content_job_id", "spoken_content_mismatch"), ): negative, _, _ = measured_job(settings, report[field], task) if negative.get("decision") != "reject" or reason not in negative.get( "reasons", [] ): raise ValueError("Missing negative control") if task in (INSPECT, SYNC): policy = report.get("speech_silence_policy") if ( policy not in (SILENCE_POLICY, SOURCE_REST_POLICY) or meta.get("speech_silence_policy") != policy or p.get("speech_silence_policy", SILENCE_POLICY) != policy or report.get("mouth_blend_policy") != MOUTH_BLEND_POLICY or meta.get("mouth_blend_policy") != MOUTH_BLEND_POLICY ): raise ValueError("A matching measured silence policy is required") read_proof = partial(measured_visual_job, settings, policy=policy) if policy == SOURCE_REST_POLICY: verify_source_rest_samples(settings, report["source_rest_validation_pairs"]) verify_speaking_sources(settings, report["negative_source_rest_job_ids"]) if task == INSPECT: from .rest import REST_QUALITY_POLICY, SHORT_WINDOW_FRAMES render, _, _ = read_proof(report["render_job_id"], SYNC) if ( render.get("mouth_blend_policy") != MOUTH_BLEND_POLICY or render["synced_sha256"] != meta["synced_sha256"] or ( policy == SOURCE_REST_POLICY and render["base_sha256"] != meta["base_sha256"] ) ): raise ValueError("Missing linked render for the certified mouth policy") source_checks = meta.get("source_rest_checks", []) output_checks = meta.get("rest_checks", []) if not output_checks or (policy == SOURCE_REST_POLICY and not source_checks): raise ValueError("Missing independent source or output silence measurement") checks = [*source_checks, *output_checks] if not checks or any( c.get("decision") != "pass" or c.get("silent_frames", 0) < 12 or c.get("rest_quality_policy") != REST_QUALITY_POLICY or not c.get("windows") or any( w.get("short_window_frames") != min(SHORT_WINDOW_FRAMES, w["end_frame"] - w["start_frame"]) or not isinstance(w.get("max_short_window_p90"), (int, float)) or not isinstance(w.get("max_short_window_range"), (int, float)) or w.get("first_rejected_short_window_start", -1) is not None for w in c["windows"] ) for c in checks ): raise ValueError("Missing measured silent-tail evidence") unrest, unrest_inputs, _ = read_proof(report["negative_rest_job_id"], task) if policy == SOURCE_REST_POLICY: verify_mouth_preservation(meta) verify_mouth_preservation(unrest, "reject") has_rest_negative = ( "silent_mouth_source_changed" in unrest.get("reasons", []) and unrest.get("base_sha256") == meta["base_sha256"] and [ (c["speaker_id"], c["silent_frames"]) for c in unrest["source_rest_checks"] ] == [ (c["speaker_id"], c["silent_frames"]) for c in meta["source_rest_checks"] ] ) else: has_rest_negative = any( c["decision"] == "reject" and c.get("rest_quality_policy") == REST_QUALITY_POLICY and any( type(w.get("first_rejected_short_window_start")) is int for w in c.get("windows", []) ) for c in unrest.get("rest_checks", []) ) if ( unrest.get("decision") != "reject" or unrest.get("speech_silence_policy") != policy or not has_rest_negative or {k: v for k, v in unrest_inputs.items() if k != "video_path"} != {k: v for k, v in inputs.items() if k != "video_path"} or unrest.get("synced_sha256") == meta.get("synced_sha256") ): raise ValueError("Missing rejected speaking-during-silence control") if meta.get("protected_block_size") != 32: raise ValueError("Missing local visual protection evidence") damage, _, _ = read_proof(report["negative_damage_job_id"], task) if not ( damage.get("decision") == "reject" and damage.get("base_sha256") == meta.get("base_sha256") and damage.get("synced_sha256") != meta.get("synced_sha256") and damage.get("protected_block_size") == 32 and ( damage["max_protected_block_mae"] > 18 or damage["max_protected_block_severe_fraction"] > 0.15 ) ): raise ValueError("Missing rejected local damage control") negative, _, _ = read_proof(report["negative_control_job_id"], task) if ( negative.get("decision") != "reject" or negative["synced_sha256"] != meta["synced_sha256"] or not any( s.get("decision") == "reject" and abs(s.get("offset_ms", 0)) > 80 for s in negative.get("scores", []) ) ): raise ValueError("Missing rejected sync control") if task == SYNC: if policy == SILENCE_POLICY and not any( type(frame) is int for frame in meta.get("rest_reference_frames", []) ): raise ValueError("Missing identity-bound neutral reference evidence") if policy == SOURCE_REST_POLICY and not any( row["silent_frames"] >= 12 for row in meta.get("source_rest_frames", []) ): raise ValueError("Missing untouched silent frames") check, _, _ = read_proof(report["quality_job_id"], INSPECT) if policy == SOURCE_REST_POLICY: verify_mouth_preservation(check) if ( check.get("decision") != "pass" or check.get("speech_silence_policy") != policy or check.get("mouth_blend_policy") != MOUTH_BLEND_POLICY or check.get("protected_block_size") != 32 or check.get("synced_sha256") != meta.get("synced_sha256") or ( policy == SOURCE_REST_POLICY and check["base_sha256"] != meta["base_sha256"] ) ): raise ValueError("Synced output has no linked passing SyncNet measurement") people = ( len(p["speaker_ids"]) if task == ANALYZE else len(inputs.get("speech_tracks", [None])) ) if report.get("max_people", 1) > people: raise ValueError("Unmeasured multi-person capability") def verify_shift_evidence(settings, report): read_proof = partial( measured_visual_job, settings, policy=report["speech_silence_policy"] ) before, before_inputs, before_params = read_proof( report["shift_baseline_render"], SYNC ) after, after_inputs, after_params = read_proof(report["shift_render"], SYNC) old, old_inputs, old_p = read_proof(report["shift_baseline_quality"], INSPECT) check, check_inputs, check_p = read_proof(report["shift_quality"], INSPECT) bad, bad_inputs, bad_p = read_proof(report["shift_negative_quality"], INSPECT) zero, zero_inputs, zero_params = read_proof(report["shift_zero_render"], SYNC) opposite, opp_inputs, opp_params = read_proof(report["shift_opposite_render"], SYNC) opposite_qa, opp_check_inputs, opp_check_params = read_proof( report["shift_opposite_quality"], INSPECT ) original = old["scores"][0] if not ( report["audio_context_shift_policy"] == after.get("audio_context_shift_policy") == AUDIO_CONTEXT_SHIFT_POLICY and before_inputs == after_inputs == zero_inputs == opp_inputs and zero["synced_sha256"] == before["synced_sha256"] and zero.get("audio_context_shift_policy") == opposite.get("audio_context_shift_policy") == AUDIO_CONTEXT_SHIFT_POLICY and zero.get("audio_context_shift_frames") == 0 and opposite.get("audio_context_shift_frames") == -3 and zero_params == {**after_params, "audio_context_shift_frames": 0} and opp_params == {**after_params, "audio_context_shift_frames": -3} and opposite_qa["synced_sha256"] == opposite["synced_sha256"] and {k: v for k, v in opp_check_inputs.items() if k != "video_path"} == {k: v for k, v in check_inputs.items() if k != "video_path"} and opp_check_params == check_p and opposite_qa["decision"] == "reject" and "sync_offset" in opposite_qa["reasons"] and opposite_qa["scores"][0]["offset_ms"] > original["offset_ms"] and before_params.get("audio_context_shift_frames", 0) == 0 and after_params.get("audio_context_shift_frames") == after.get("audio_context_shift_frames") == 3 and { k: v for k, v in before_params.items() if k != "audio_context_shift_frames" } == {k: v for k, v in after_params.items() if k != "audio_context_shift_frames"} and old_p == check_p == bad_p and len(old["scores"]) == len(check["scores"]) == len(bad["scores"]) == 1 and old["scores"][0]["speaker_id"] == check["scores"][0]["speaker_id"] == bad["scores"][0]["speaker_id"] and {k: v for k, v in bad_inputs.items() if k != "speech_tracks"} == {k: v for k, v in check_inputs.items() if k != "speech_tracks"} and len(bad_inputs["speech_tracks"]) == len(check_inputs["speech_tracks"]) == 1 and bad_inputs["speech_tracks"][0]["audio_path"] != check_inputs["speech_tracks"][0]["audio_path"] and { k: v for k, v in bad_inputs["speech_tracks"][0].items() if k != "audio_path" } == { k: v for k, v in check_inputs["speech_tracks"][0].items() if k != "audio_path" } and {k: v for k, v in old_inputs.items() if k != "video_path"} == {k: v for k, v in check_inputs.items() if k != "video_path"} and old["synced_sha256"] == before["synced_sha256"] and check["synced_sha256"] == after["synced_sha256"] != old["synced_sha256"] and old["reasons"] == ["sync_offset"] and original["offset_ms"] == 120 and original["confidence"] >= 4 and check["decision"] == "pass" and abs(check["scores"][0]["offset_ms"]) < 120 and bad["decision"] == "reject" and "sync_offset" in bad["reasons"] and bad["synced_sha256"] == check["synced_sha256"] and abs(bad["scores"][0]["offset_ms"]) >= 320 ): raise ValueError( "Missing same-seed, unshifted-stem feature compensation measurements" ) def _certificate(settings, task, path, policy=None): import sqlite3 cert = {"task_type": task, "profile": profile(task), "available": False} try: raw = path.read_bytes() if len(raw) > 65536: raise ValueError("Oversized validation") report = json.loads(raw) if policy is not None and report.get("speech_silence_policy") != policy: raise ValueError("Silence policy does not match the certificate file") if not ( report["decision"] == "pass" and report["profile"] == profile(task) and report["task_type"] == task and report["adapter_contract_version"] == "dialogue-v1" and re.fullmatch("[0-9a-f]{40}", report["revision"]) and report["revision"] == REVISIONS[task] and all( type(report[k]) in (int, float) and ( report[k] > 0 or k == "peak_gpu_mib" and task == ANALYZE and report[k] == 0 ) for k in ("peak_gpu_mib", "peak_host_mib") ) and re.fullmatch("[0-9a-f]{32}", report["validation_job_id"]) and report.get("audited") is True ): raise ValueError("Invalid evidence") if task != SPEECH and ( type(report.get("max_people")) is not int or report["max_people"] not in (1, 2) ): raise ValueError("Invalid people limit") check_evidence(settings, task, report) if task == SYNC and "audio_context_shift_policy" in report: verify_shift_evidence(settings, report) cert["audio_context_shift_policy"] = AUDIO_CONTEXT_SHIFT_POLICY if task == SPEECH_INSPECT: from .audio_quality import CONTENT_REVIEW_POLICY cert["content_review_policy"] = CONTENT_REVIEW_POLICY if task in (SYNC, INSPECT): cert["speech_silence_policy"] = report["speech_silence_policy"] cert["mouth_blend_policy"] = MOUTH_BLEND_POLICY cert.update( available=True, decision="pass", adapter_contract_version="dialogue-v1", revision=report["revision"], report_sha256=hashlib.sha256(raw).hexdigest(), max_people=report.get("max_people", 1), ) except ( OSError, ValueError, KeyError, TypeError, AttributeError, sqlite3.Error, ): pass return cert def capabilities(settings): root = settings.app_root / "config" / "dialogue-validation" policies = {SILENCE_POLICY: {}, SOURCE_REST_POLICY: {}} result = {} for task, key in KEYS.items(): legacy_path = root / (key + ".json") if task in (SYNC, INSPECT): result[key] = _certificate(settings, task, legacy_path, SILENCE_POLICY) policies[SILENCE_POLICY][key] = result[key] source_path = root / f"{key}-{SOURCE_REST_POLICY}.json" policies[SOURCE_REST_POLICY][key] = _certificate( settings, task, source_path, SOURCE_REST_POLICY ) else: result[key] = _certificate(settings, task, legacy_path) if task == SPEECH_INSPECT: from .native_alignment import capability as native_alignment_capability result[key]['native_alignment'] = native_alignment_capability(settings) from .turn_certification import capability as turn_capability result["two_person_turns"] = turn_capability(settings) result["silence_policies"] = policies return result def calibration_digest(task, inputs, p): return hashlib.sha256( json.dumps( [task, inputs, p], sort_keys=True, separators=(",", ":"), ensure_ascii=False ).encode() ).hexdigest() def admit(settings, task, p, inputs=None, *, principal=None, idempotency_key=None, job_id=None): # 一次性操作员小样须精确绑定源素材、模型、目标及长度;普通请求不可传认证开关。 import time if task == SPEECH_INSPECT and "turn_policy" in p: from .turn_certification import capability as turn_capability ev = turn_capability(settings) if ev.get("available") and ev.get("report_sha256") == p.get( "certificate_sha256" ): return raise ValueError("Dedicated two-person certificate missing or changed") if task == SPEECH_INSPECT and p.get('native_av_policy') == 'native_av_v1': from .native_alignment import capability as native_alignment_capability if native_alignment_capability(settings).get('available'): return from ..native_av_calibration import admit as admit_native_calibration if admit_native_calibration(settings, task, inputs, p, principal, idempotency_key, job_id=job_id): return raise ValueError('Native word alignment requires independent operator-reviewed evidence') if ( inputs is not None and isinstance(principal, str) and re.fullmatch("[0-9a-f]{32}", principal) and isinstance(idempotency_key, str) and re.fullmatch("cmvr-visual:[0-9a-f]{32}", idempotency_key) and p.get("num_frames", 1) <= 144 and len(inputs.get("prompt", "")) <= 240 ): key = calibration_digest(task, inputs, p) plan = ( settings.app_root / "config" / "dialogue-validation" / "calibration" / (key + ".json") ) try: receipt = json.loads(plan.read_bytes()) if ( receipt.get("sha256") == key and receipt.get("owner_id") == principal and time.time() < receipt["expires_at"] <= time.time() + 86400 ): import os import tempfile with tempfile.NamedTemporaryFile( dir=plan.parent, delete=False ) as stream: stream.write(idempotency_key.encode()) try: claim = plan.with_suffix(".used") try: os.link(stream.name, claim) except FileExistsError: pass if claim.read_text() == idempotency_key: return finally: os.unlink(stream.name) except (OSError, ValueError, KeyError, TypeError): pass if p.get("profile") == LATENTSYNC_PREVIEW: raise ValueError( "LatentSync preview requires an exact operator calibration ticket" ) caps = capabilities(settings) if task in (SYNC, INSPECT): policy = p.get("speech_silence_policy", SILENCE_POLICY) cert = caps["silence_policies"].get(policy, {}).get(KEYS[task], {}) else: cert = caps[KEYS[task]] if ( task == SYNC and p.get("audio_context_shift_frames", 0) and cert.get("audio_context_shift_policy") != AUDIO_CONTEXT_SHIFT_POLICY ): raise ValueError("Uncertified audio context shift") if not cert.get("available"): raise ValueError("Dialogue model requires operator-reviewed real sample") people = max( len(p.get("speaker_ids", [])), len((inputs or {}).get("speech_tracks", [])) ) if task in ("video.lipsync", "video.dialogue.inspect"): if p.get("speech_silence_policy", SILENCE_POLICY) != cert.get( "speech_silence_policy" ): raise ValueError("Uncertified speech silence policy") from .media import read_tracks record = read_tracks(inputs["face_tracks_path"]) people = max(people, len(record["tracks"])) if people > cert["max_people"]: raise ValueError("Uncertified multi-person dialogue")