cmvr-visual/inference/llm_services/dialogue/turn_certification.py

417 lines
15 KiB
Python
Raw Normal View History

"""同框发布清单仅由运维安装,按冻结输入、队列原产物和独立筛查报告复核。"""
import hashlib
import json
import os
import re
import sqlite3
from contextlib import closing
from functools import lru_cache
from pathlib import Path
from ..video_profiles import (
H3_NATIVE_AV_PROFILE,
H3_NATIVE_AV_TP2_PROFILE,
H3_REVISION,
H3_RUNTIME_COMMIT,
H3_TP2_RUNTIME_COMMIT,
)
from .native_turns import MEASUREMENT_FILES, POLICY
RELEASE_POLICY = "h3-two-person-turns-release-v1"
NEGATIVES = {
"speaker_swap",
"both_lips",
"shift_400",
"shift_minus_400",
"hard_cut",
"shared_voice",
"occlusion",
"short_reply",
}
def count_holdout(rows):
if len(rows) != 24 or len({case for case, _ in rows}) != 24:
raise ValueError("Release requires 24 distinct preregistered tasks")
first = total = 0
for _, attempts in rows:
if len(attempts) > 2 or any(
a not in {"pass", "reject", "indeterminate"} for a in attempts
):
raise ValueError("Unknown outcome or too many attempts")
first += bool(attempts and attempts[0] == "pass")
total += "pass" in attempts
return first, total
def _require(condition):
if not condition:
raise ValueError("Incomplete or inconsistent two-person release evidence")
def _sha(value):
return isinstance(value, str) and re.fullmatch("[0-9a-f]{64}", value) is not None
def _read(path, settings, limit):
from ..store import open_confined_file
with open_confined_file(path, settings.workspace_root) as stream:
data = stream.read(limit + 1)
_require(len(data) <= limit)
return data
@lru_cache(maxsize=256)
def _artifact_hash(path, workspace, fingerprint):
from ..store import open_confined_file
with open_confined_file(path, workspace) as stream:
info = os.fstat(stream.fileno())
# Windows 的路径状态和文件描述符使用不同的 ctime 语义;ctime 只签入缓存键。
if (info.st_ino, info.st_size, info.st_mtime_ns) != fingerprint[:3]:
raise ValueError("Certification artifact changed while reading")
value = hashlib.file_digest(stream, "sha256").hexdigest()
final = os.fstat(stream.fileno())
if (final.st_ino, final.st_size, final.st_mtime_ns) != (
info.st_ino,
info.st_size,
info.st_mtime_ns,
):
raise ValueError("Certification artifact changed while hashing")
return value
def artifact_hash(path, workspace):
st = path.stat()
return _artifact_hash(
path, workspace, (st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns)
)
def validate_screen(screen, n):
"""复算全部通过项,防止单人报告或缺失负控的汇总进入通过计数。"""
from .native_acceptance import assess_sync
from .native_turns import identify_voice
_require(
isinstance(screen, dict)
and screen.get("controls") is True
and screen.get("policy") == POLICY
and screen.get("decision") in {"pass", "reject", "indeterminate"}
and _sha(screen.get("author_sha256"))
)
rows = screen.get("turns")
_require(
isinstance(rows, list)
and len(rows) == 2
and all(isinstance(t, dict) for t in rows)
)
ids = [t.get("expected_speaker_id") for t in rows]
_require(
all(isinstance(s, str) and s for s in ids)
and len(set(ids)) == 2
and len({t.get("utterance_id") for t in rows}) == 2
)
checks = screen.get("checks", {})
_require(
all(
isinstance(checks.get(k), dict)
for k in (
"geometry",
"audio_binding",
"visual",
"tracking",
*["tail_" + s for s in ids],
)
)
)
g = checks["geometry"]
_require(
[g.get("width"), g.get("height"), g.get("fps"), g.get("frames")]
== [1344, 768, 24, n]
)
end = 0
states = [c.get("decision") for c in checks.values()]
for i, t in enumerate(rows):
start, stop = t.get("start_sample"), t.get("end_sample")
_require(
type(start) is int
and type(stop) is int
and end <= start < stop <= n * 2000
and t.get("listener_id") == ids[1 - i]
and t.get("decision") in {"pass", "reject", "indeterminate"}
)
end = stop
states.append(t["decision"])
if t["decision"] == "pass":
sync = t.get("speaker_sync", {})
_require(
isinstance(sync.get("baseline"), dict)
and isinstance(sync.get("controls"), list)
and assess_sync(sync["baseline"], sync["controls"])["decision"]
== "pass"
)
v = t.get("voice", {})
sims = v.get("similarities", {})
_require(
set(sims) == set(ids)
and identify_voice(
ids, [sims[k] for k in ids], v.get("voiced_seconds", 0)
)["observed_speaker_id"]
== ids[i]
)
_require(
t.get("listener_sync", {}).get("decision")
in {"reject", "indeterminate"}
and t.get("listener_rest", {}).get("decision") == "pass"
)
_require(all(s in {"pass", "reject", "indeterminate"} for s in states))
_require(
screen["decision"]
== (
"reject"
if "reject" in states
else "pass"
if set(states) == {"pass"}
else "indeterminate"
)
)
if screen["decision"] == "pass":
_require(all(len(screen.get("tracks", {}).get(s, [])) == n for s in ids))
def capability(settings):
cap = {
"available": False,
"audited": False,
"policy": POLICY,
"release_policy": RELEASE_POLICY,
}
try:
folder = (
settings.app_root / "config" / "dialogue-validation" / "two-person-turns"
)
raw = _read(folder / "release.json", settings, 65536)
release = json.loads(raw)
_require(
release["release_policy"] == RELEASE_POLICY
and release["policy"] == POLICY
and release["audited"] is True
and release["auditor"].strip()
)
def record(key):
_require(_sha(key))
data = _read(folder / (key + ".json"), settings, 2 * 1024 * 1024)
_require(hashlib.sha256(data).hexdigest() == key)
return json.loads(data)
plan = record(release["preregistered_plan_sha256"])
profile = plan["profile"]
pair = profile == H3_NATIVE_AV_TP2_PROFILE
revision = H3_TP2_RUNTIME_COMMIT if pair else H3_RUNTIME_COMMIT
n = plan["num_frames"]
models = plan["measurement_sha256"]
_require(
set(models) == set(MEASUREMENT_FILES)
and all(_sha(h) for h in models.values())
)
for name, sha in models.items():
_require(
artifact_hash(
settings.workspace_root / "models" / "dialogue-v1" / name,
settings.workspace_root,
)
== sha
)
_require(
getattr(
settings,
"native_dialogue_tp2_enabled" if pair else "native_dialogue_enabled",
False,
)
is True
)
_require(
profile in {H3_NATIVE_AV_PROFILE, H3_NATIVE_AV_TP2_PROFILE}
and n in range(124, 159 if pair else 346, 17)
and plan["revision"] == H3_REVISION
and plan["runtime_revision"] == revision
and plan["language"] == "Chinese"
and [plan["width"], plan["height"], plan["fps"]] == [1344, 768, 24]
)
_require(
set(release["negative_controls"]) == NEGATIVES
and len(set(release["negative_controls"].values())) == len(NEGATIVES)
)
screens = set()
for label, key in release["negative_controls"].items():
witness = record(key)
_require(witness["label"] == label and witness["verified_by"].strip())
_require(witness["screen_sha256"] not in screens)
screens.add(witness["screen_sha256"])
evidence = record(witness["screen_sha256"])
validate_screen(evidence, n)
_require(
evidence["measurement_sha256"] == models
and evidence["policy"] == POLICY
and evidence["decision"] in {"reject", "indeterminate"}
and evidence["controls"] is True
and _sha(evidence["source_sha256"]["video"])
and len(evidence["turns"]) == 2
)
e2e = record(release["e2e_sha256"])
_require(
e2e["decision"] == "pass"
and e2e["reviewer"].strip()
and _sha(e2e["film_sha256"])
and all(
e2e["checks"].get(k) is True
for k in (
"mixed_story",
"caption_audio",
"bgm",
"pause_resume",
"repair",
"ownership",
"download",
"blind_listening",
)
)
)
film = folder / (e2e["film_sha256"] + ".mp4")
_require(artifact_hash(film, settings.workspace_root) == e2e["film_sha256"])
cases = plan["cases"]
_require(
len(cases) == 24
and len(
{
(
c["prompt_sha256"],
c["first_frame_sha256"],
c["author_sha256"],
tuple(c["seeds"]),
)
for c in cases
}
)
== 24
and set(release["attempts"]) == {c["case_id"] for c in cases}
)
seen, video_hashes, rows = set(), set(), []
with closing(
sqlite3.connect(settings.db_path.as_uri() + "?mode=ro", uri=True, timeout=1)
) as db:
for case in cases:
attempts = release["attempts"][case["case_id"]]
_require(
len(attempts) <= 2
and len(case["seeds"]) == 2
and case["seeds"][0] != case["seeds"][1]
)
decisions = []
for idx, attempt in enumerate(attempts):
job = attempt["job_id"]
_require(job not in seen)
seen.add(job)
item = db.execute(
"SELECT input_json,parameters_json,result_json,state,created_at FROM jobs WHERE id=? AND task_type='video.generate'",
(job,),
).fetchone()
_require(item is not None and 0 < plan["frozen_at"] <= item[4])
inp, params = json.loads(item[0]), json.loads(item[1])
_require(
params["profile"] == profile
and params["seed"] == case["seeds"][idx]
and params["num_frames"] == n
and [params["width"], params["height"]] == [1344, 768]
and params.get("conditioning_mode", "first_frame")
== "first_frame"
and hashlib.sha256(inp["prompt"].encode()).hexdigest()
== case["prompt_sha256"]
)
_require(
artifact_hash(Path(inp["image_path"]), settings.workspace_root)
== case["first_frame_sha256"]
)
if item[3] != "succeeded":
_require(
item[3] in {"failed", "cancelled"}
and not attempt.get("screen_sha256")
)
decisions.append("indeterminate")
continue
evidence = record(attempt["screen_sha256"])
validate_screen(evidence, n)
result = json.loads(item[2])
_require(
result["metadata"]["revision"] == H3_REVISION
and result["metadata"]["diffusers_source_revision"] == revision
and evidence["measurement_sha256"] == models
and evidence["policy"] == POLICY
and evidence["controls"] is True
and evidence["author_sha256"] == case["author_sha256"]
and evidence["source_sha256"]["first_frame"]
== case["first_frame_sha256"]
)
outputs = {
Path(o["path"]).name: Path(o["path"]) for o in result["outputs"]
}
for key, filename in (
("video", "video_raw.mp4"),
("native_audio", "audio_native.wav"),
):
path = outputs[filename]
_require(path.resolve().is_relative_to(settings.outputs_dir))
_require(
artifact_hash(path, settings.workspace_root)
== evidence["source_sha256"][key]
)
_require(evidence["source_sha256"]["video"] not in video_hashes)
video_hashes.add(evidence["source_sha256"]["video"])
if evidence["decision"] == "pass":
_require(
len(evidence["turns"]) == 2
and all(
t["decision"] == "pass"
and t["expected_speaker_id"]
== t["voice"]["observed_speaker_id"]
for t in evidence["turns"]
)
)
decisions.append(evidence["decision"])
rows.append((case["case_id"], decisions))
first, total = count_holdout(rows)
_require(first >= 18 and total >= 22)
cap.update(
available=True,
audited=True,
decision="pass",
profile=profile,
revision=H3_REVISION,
runtime_revision=revision,
width=1344,
height=768,
num_frames=n,
fps=24,
language="Chinese",
tasks=24,
first_pass=first,
overall_pass=total,
measurement_sha256=models,
report_sha256=hashlib.sha256(raw).hexdigest(),
)
except (
AttributeError,
ValueError,
KeyError,
TypeError,
IndexError,
OSError,
sqlite3.Error,
):
pass
return cap