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

440 lines
15 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""双人轮读离线质检。每轮只对该轮的原片、原声计算指标。"""
import json
import math
import sys
import wave
from pathlib import Path
from .audio_quality import normalized_text
from .media import digest, frames
POLICY = "h3-two-person-turns-screen-v1"
MEASUREMENT_FILES = (
"auraface/scrfd_10g_bnkps.onnx",
"auraface/glintr100.onnx",
"wespeaker/voxceleb_resnet34_LM.onnx",
"face-parser/model.safetensors",
"face-parser/config.json",
"face-parser/preprocessor_config.json",
"syncnet/syncnet_v2.model",
"syncnet/SyncNetModel.py",
)
def turn_windows(turns, words):
if (
len(turns) != 2
or len({t["speaker_id"] for t in turns}) != 2
or len({t["utterance_id"] for t in turns}) != 2
):
raise ValueError("Expected two different speakers with one ordered line each")
windows = []
cursor = previous = 0
for turn in turns:
expected = normalized_text(turn["text"])
start = None
actual = ""
while expected and cursor < len(words) and actual != expected:
word = words[cursor]
cursor += 1
a, b = word["start_sample"], word["end_sample"]
if type(a) is not int or type(b) is not int or not 0 <= previous <= a < b:
raise ValueError("Word boundaries overlap or regress")
previous = b
content = normalized_text(word["text"])
if not content:
continue
start = a if start is None else start
actual += content
if not expected.startswith(actual):
raise ValueError(
"A word crosses turns or the recording differs from the script"
)
if start is None or actual != expected:
raise ValueError("Missing measured words for a turn")
windows.append((start, previous))
if any(normalized_text(w["text"]) for w in words[cursor:]):
raise ValueError("Unexpected extra speech after the second turn")
return windows
def identify_voice(ids, similarities, voiced_seconds):
result = {
"observed_speaker_id": None,
"similarities": dict(zip(ids, similarities, strict=True)),
"voiced_seconds": voiced_seconds,
}
if voiced_seconds >= 1 and all(
type(v) in (float, int) and math.isfinite(v) for v in similarities
):
best = int(similarities[1] > similarities[0])
if similarities[best] >= 0.50 and similarities[1 - best] < 0.25:
result["observed_speaker_id"] = ids[best]
return result
def turn_decision(expected, voice, sync, listener_sync, listener_rest):
observed = voice["observed_speaker_id"]
if (
observed is not None
and observed != expected
or sync["decision"] == "reject"
or listener_sync["decision"] == "pass"
):
return "reject"
if (
observed is None
or sync["decision"] != "pass"
or listener_rest["decision"] != "pass"
):
return "indeterminate"
return "pass"
def _voice_measurement(root, voices, audio, ids, windows):
import numpy as np
import onnxruntime as ort
from scipy.signal import resample_poly
from .audio_quality import embedding, load_audio, voiced_signal
session = ort.InferenceSession(
str(root / "wespeaker" / "voxceleb_resnet34_LM.onnx"),
providers=["CPUExecutionProvider"],
)
refs = []
for path in voices:
signal, _ = load_audio(path, 30)
voiced, seconds = voiced_signal(signal)
refs.append(embedding(session, voiced) if seconds >= 1 else None)
measured = []
for a, b in windows:
voiced, seconds = voiced_signal(
resample_poly(audio[a:b], 1, 3).astype(np.float32)
)
vector = embedding(session, voiced) if seconds >= 1 else None
scores = [
float(np.clip(vector @ ref, -1, 1))
if vector is not None and ref is not None
else None
for ref in refs
]
measured.append(identify_voice(ids, scores, seconds))
return measured
def _sync_model(root):
import torch
directory = root / "syncnet"
sys.path.insert(0, str(directory))
try:
from SyncNetModel import S
finally:
sys.path.pop(0)
model = S()
model.load_state_dict(
torch.load(
directory / "syncnet_v2.model", map_location="cpu", weights_only=True
)
)
return model.eval().to("cpu")
def _track_pair(root, video, n, faces, ids, first_frame):
import cv2
import numpy as np
from .analysis import FaceModels, iou
from .quality import syncnet_crop
from .rest import MouthParser
detector = FaceModels(root / "auraface")
parser = MouthParser(root, device="cpu")
refs = []
for path in faces:
image = cv2.imread(str(path))
found = detector.detect(image) if image is not None else []
if len(found) != 1:
raise ValueError(
"Each independent face reference must contain one clear face"
)
refs.append(detector.embed(image, found[0][1]))
tracks = {s: [] for s in ids}
crops = {s: [] for s in ids}
def match(image):
found = sorted(detector.detect(image), key=lambda f: f[0][0])
if len(found) != 2 or iou(found[0][0], found[1][0]) > 0.02:
return None
matches = []
for side, (box, points) in enumerate(found):
vector = detector.embed(image, points)
scores = [float(ref @ vector) for ref in refs]
if scores[side] < 0.4 or scores[side] - scores[1 - side] < 0.14:
return None
matches.append((box, points, scores))
return matches
image = cv2.imread(str(first_frame))
if image is None or not match(image):
return (
tracks,
crops,
{"decision": "indeterminate", "reason": "first_frame_identity_uncertain"},
)
prev = None
for i, frame in enumerate(frames(video, n)):
matched = match(frame)
if not matched:
return (
tracks,
crops,
{
"decision": "indeterminate",
"frame": i,
"reason": "identity_or_visibility_uncertain",
},
)
small = cv2.resize(frame, (64, 36)).astype(np.float32)
delta = float(np.mean(np.abs(small - prev))) if prev is not None else 0
if delta > 45:
return (
tracks,
crops,
{
"decision": "indeterminate",
"frame": i,
"reason": "possible_cut",
"frame_mae": delta,
},
)
prev = small
for sid, (box, points, scores) in zip(ids, matched, strict=True):
overlap = iou(tracks[sid][-1]["box"], box) if i else 1
if overlap < 0.35:
return (
tracks,
crops,
{
"decision": "indeterminate",
"frame": i,
"reason": "track_discontinuity",
"speaker_id": sid,
},
)
tracks[sid].append(
{
"frame": i,
"box": [int(v) for v in box],
"identity_similarities": scores,
"track_iou": overlap,
"aperture": parser.aperture(frame, box, points),
}
)
crops[sid].append(syncnet_crop(frame, box))
return tracks, crops, {"decision": "pass"}
def inspect_candidate(spec, root, *, controls=True):
"""输入角色按首帧从左到右排列,turns 只保存台词 ID、期望角色和发音稿。"""
from .native_acceptance import (
assess_geometry,
assess_sync,
audio_evidence,
embedded_audio,
probe_native,
shift_audio,
tail_window,
visual_review,
)
from .quality import syncnet_scores
from .rest import assess_rest
roles = spec["speakers"]
ids = [r["speaker_id"] for r in roles]
if (
len(ids) != 2
or len(set(ids)) != 2
or {t["speaker_id"] for t in spec["turns"]} != set(ids)
):
raise ValueError(
"Expected two unique references and turns with corresponding speaker IDs"
)
assets = {
k: Path(spec[k])
for k in (
"video",
"native_audio",
"speech_audio",
"speech_report",
"first_frame",
)
}
if spec.get("visual_review"):
assets["visual_review"] = Path(spec["visual_review"])
for i, role in enumerate(roles):
for kind in ("face", "voice"):
assets[f"{kind}_{i}"] = Path(role[kind])
hashes = {k: digest(p) for k, p in assets.items()}
if len(set(hashes.values())) != len(hashes):
raise ValueError(
"Expected distinct original assets and independent face and voice references"
)
if hashes["first_frame"] != spec.get("first_frame_sha256"):
raise ValueError("Confirmed first-frame hash does not match the supplied asset")
report = json.loads(assets["speech_report"].read_bytes())
metadata = probe_native(assets["video"])
n = metadata["frames"]
if [metadata["width"], metadata["height"]] != [1344, 768] or n not in range(
124, 346, 17
):
raise ValueError("Outside the horizontal, 24 fps H3 pilot scope")
playback = embedded_audio(assets["video"])
_, binding = audio_evidence(
assets["native_audio"], assets["speech_audio"], report, embedded=playback
)
with wave.open(str(assets["native_audio"]), "rb") as raw:
geometry = assess_geometry(
metadata,
samples=raw.getnframes(),
rate=raw.getframerate(),
channels=raw.getnchannels(),
width=raw.getsampwidth(),
)
windows = turn_windows(spec["turns"], report["words"])
if (
windows[-1][1] > min(n * 2000, len(playback))
or abs(metadata["audio_start"] - metadata["video_start"]) > 1 / 48000
):
raise ValueError("Unaligned sound and video origin or turn outside candidate")
audio = playback.mean(axis=1)
measured = _voice_measurement(
root, [assets["voice_0"], assets["voice_1"]], audio, ids, windows
)
tracks, crops, tracking = _track_pair(
root,
assets["video"],
n,
[assets["face_0"], assets["face_1"]],
ids,
assets["first_frame"],
)
summary = {
"geometry": geometry,
"audio_binding": binding,
"tracking": tracking,
"visual": visual_review(assets.get("visual_review"), hashes["video"], n),
}
rows = []
if tracking["decision"] == "pass":
model = _sync_model(root)
for turn, (a, b), voice in zip(spec["turns"], windows, measured, strict=True):
who = turn["speaker_id"]
other = next(s for s in ids if s != who)
row = {
"utterance_id": turn["utterance_id"],
"expected_speaker_id": who,
"listener_id": other,
"start_sample": a,
"end_sample": b,
"voice": voice,
"decision": "reject"
if voice["observed_speaker_id"] not in (None, who)
else "indeterminate",
}
if tracking["decision"] == "pass":
start, end = math.ceil(a / 2000), b // 2000
if end - start >= 24:
clip = audio[start * 2000 : end * 2000]
def score(role, sound, start=start, end=end):
return syncnet_scores(
model, crops[role][start:end], sound, device="cpu"
)
speaker = score(who, clip)
listener = score(other, clip)
if controls:
shifted = [
{
"shift_ms": ms,
"score": score(who, shift_audio(clip, ms * 48)),
}
for ms in (-400, 400)
]
speaker = assess_sync(speaker, shifted)
rest = assess_rest(
[(start, end)], {v["frame"]: v["aperture"] for v in tracks[other]}
)
row.update(
speaker_sync=speaker,
listener_sync=listener,
listener_rest=rest,
decision=turn_decision(who, voice, speaker, listener, rest),
)
else:
row["reason"] = "short_turn_no_borrowing"
rows.append(row)
gap_start = math.ceil(windows[0][1] / 2000)
gap_end = windows[1][0] // 2000
handoff = {
"start_sample": windows[0][1],
"end_sample": windows[1][0],
"full_frames": max(0, gap_end - gap_start),
}
if gap_end - gap_start >= 12 and tracking["decision"] == "pass":
handoff["faces"] = {
role: assess_rest(
[(gap_start, gap_end)],
{v["frame"]: v["aperture"] for v in tracks[role]},
)
for role in ids
}
# 交接时独立的表情动作留给逐轮复核。
if any(c["decision"] != "pass" for c in handoff["faces"].values()):
summary["handoff"] = {"decision": "indeterminate"}
tail = tail_window(report, frames=n)
for role in ids:
summary["tail_" + role] = (
assess_rest([tail], {v["frame"]: v["aperture"] for v in tracks[role]})
if tail and tracking["decision"] == "pass"
else {"decision": "indeterminate"}
)
decisions = [r["decision"] for r in rows] + [
v["decision"] for v in summary.values()
]
if hashes != {k: digest(p) for k, p in assets.items()}:
raise ValueError("Candidate assets changed during measurement")
import hashlib
author = {
"speaker_ids": ids,
"turns": spec["turns"],
"first_frame_sha256": hashes["first_frame"],
"references": [hashes[k] for k in ("face_0", "face_1", "voice_0", "voice_1")],
}
author_sha = hashlib.sha256(
json.dumps(
author, sort_keys=True, ensure_ascii=False, separators=(",", ":")
).encode()
).hexdigest()
measurement_sha256 = {name: digest(root / name) for name in MEASUREMENT_FILES}
return {
"policy": POLICY,
"author_sha256": author_sha,
"measurement_sha256": measurement_sha256,
"handoff": handoff,
"decision": "reject"
if "reject" in decisions
else "pass"
if all(d == "pass" for d in decisions)
else "indeterminate",
"controls": controls,
"source_sha256": hashes,
"turns": rows,
"tracks": tracks,
"checks": summary,
}