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

532 lines
18 KiB
Python
Raw Permalink Normal View History

"""运维只读原生音画验收;输出证据,不渲染、不修嘴、不改变源音视频。"""
import json
import math
import subprocess
import sys
import wave
from fractions import Fraction
from pathlib import Path
from .media import digest, frames
POLICY = "native-av-independent-acceptance-v1"
def shift_audio(source, samples):
"""只移动质检副本,正数表示声音延后;绝不写回源波形。"""
import numpy as np
result = np.zeros_like(source)
if abs(samples) < len(source):
if samples > 0:
result[samples:] = source[:-samples]
elif samples < 0:
result[:samples] = source[-samples:]
else:
result[:] = source
return result
def assess_sync(baseline, controls):
def valid(score):
return (
all(
type(score.get(k)) in (int, float) and math.isfinite(score[k])
for k in ("offset_ms", "confidence")
)
and score["confidence"] >= 2
and type(score.get("voiced_windows")) is int
and score["voiced_windows"] >= 15
)
if not valid(baseline):
return {
"decision": "indeterminate",
"reason": "insufficient_sync_evidence",
"baseline": baseline,
"controls": controls,
}
if baseline.get("decision") != "pass":
return {
"decision": baseline.get("decision", "indeterminate"),
"reason": "baseline_sync",
"baseline": baseline,
"controls": controls,
}
shifts = set()
for item in controls:
shift, score = item["shift_ms"], item["score"]
shifts.add(shift)
if (
score.get("decision") != "reject"
or not valid(score)
or abs(score.get("offset_ms", 9999) - baseline["offset_ms"] + shift) > 80
):
return {
"decision": "indeterminate",
"reason": "negative_control_unproven",
"baseline": baseline,
"controls": controls,
}
return {
"decision": "pass" if shifts == {-400, 400} else "indeterminate",
"baseline": baseline,
"controls": controls,
}
def tail_window(report, *, frames):
words = report.get("words")
if not isinstance(words, list) or not words:
raise ValueError("Speaking acceptance requires actual word timestamps")
end = max(word["end_sample"] for word in words)
if type(end) is not int or end <= 0:
raise ValueError("Invalid final spoken-word boundary")
start = math.ceil(end / 2000) + 6
return (start, frames) if frames - start >= 12 else None
def overall(checks):
names = (
"geometry",
"audio_binding",
"speech",
"sync",
"tracking",
"rest",
"visual",
)
rejected = [name for name in names if checks.get(name) == "reject"]
unknown = [name for name in names if checks.get(name) != "pass"]
return {
"decision": "reject" if rejected else "indeterminate" if unknown else "pass",
"reasons": rejected or unknown,
}
def assess_geometry(metadata, *, samples, rate, channels, width):
n = metadata["frames"]
duration = n / 24
difference = samples / rate - duration
valid = (
type(n) is int
and n in range(124, 346, 17)
and metadata["fps"] == 24
and 0 < metadata["width"] * metadata["height"] <= 1920 * 1080
and (rate, channels, width) == (32000, 2, 2)
and abs(difference) <= 1 / 80 + 1 / 32000
and abs(metadata["audio_start"] - metadata["video_start"]) <= 1 / 24
)
return dict(
decision="pass" if valid else "reject",
**metadata,
native_audio_samples=samples,
native_audio_rate=rate,
native_audio_channels=channels,
native_audio_duration=samples / rate,
av_duration_delta=difference,
audio_trimmed=False,
)
def probe_native(video):
data = json.loads(
subprocess.check_output(
["ffprobe", "-v", "error", "-show_streams", "-of", "json", str(video)],
timeout=60,
)
)
videos = [s for s in data["streams"] if s["codec_type"] == "video"]
audios = [s for s in data["streams"] if s["codec_type"] == "audio"]
if len(videos) != 1 or len(audios) != 1:
raise ValueError("Expected exactly one native video and embedded audio stream")
visual, audio = videos[0], audios[0]
info = json.loads(
subprocess.check_output(
[
"ffprobe",
"-v",
"error",
"-select_streams",
"v:0",
"-show_frames",
"-show_entries",
"frame=best_effort_timestamp_time",
"-of",
"json",
str(video),
],
timeout=60,
)
)
stamps = [Fraction(f["best_effort_timestamp_time"]) for f in info["frames"]]
origin = Fraction(visual.get("start_time", "0"))
if not 1 <= len(stamps) <= 345 or any(
abs(t - origin - Fraction(i, 24)) > Fraction(1, 100000)
for i, t in enumerate(stamps)
):
raise ValueError(
"Missing, duplicated, shifted or unbounded actual video frames"
)
return {
"frames": len(stamps),
"fps": float(Fraction(visual["avg_frame_rate"])),
"width": visual["width"],
"height": visual["height"],
"video_start": float(origin),
"audio_start": float(audio.get("start_time", "0")),
"video_duration": len(stamps) / 24,
"audio_duration": float(audio.get("duration", len(stamps) / 24)),
"embedded_audio_rate": int(audio["sample_rate"]),
}
def embedded_audio(video):
import numpy as np
raw = subprocess.check_output(
[
"ffmpeg",
"-nostdin",
"-v",
"error",
"-threads",
"2",
"-i",
str(video),
"-map",
"0:a:0",
"-vn",
"-ar",
"48000",
"-ac",
"2",
"-f",
"f32le",
"pipe:1",
],
timeout=90,
)
audio = np.frombuffer(raw, dtype="<f4")
if (
len(audio) % 2
or not len(audio)
or not np.isfinite(audio).all()
or len(audio) > 48000 * 2 * 16
):
raise ValueError("Invalid or unbounded decoded MP4 audio")
return audio.reshape(-1, 2)
def audio_evidence(native_audio, speech_audio, report, *, embedded=None):
import numpy as np
import soundfile as sf
from scipy.signal import resample_poly
from .native_alignment import (
ASR_REVISION,
validate_content_verification,
validate_words,
)
from .native_alignment import POLICY as ALIGNMENT_POLICY
raw, rate = sf.read(native_audio, dtype="float32", always_2d=True)
normalized, target_rate = sf.read(speech_audio, dtype="float32", always_2d=True)
if not np.isfinite(raw).all() or not np.isfinite(normalized).all():
raise ValueError("Audio contains non-finite samples")
expected = resample_poly(raw, 3, 2, axis=0)
count = min(len(normalized), len(expected))
if (
rate != 32000
or target_rate != 48000
or raw.shape[1] != 2
or normalized.shape[1] != 2
or count < 1
):
raise ValueError("Expected complete stereo native32k and inspection48k WAV")
a, b = expected[:count].ravel(), normalized[:count].ravel()
correlation = float(
a @ b / max(float(np.linalg.norm(a) * np.linalg.norm(b)), 1e-12)
)
error = float(np.sqrt(np.mean((a - b) ** 2)))
binding = {
"decision": "pass"
if abs(len(normalized) - len(expected)) <= 1
and correlation >= 0.995
and error <= 0.03
else "indeterminate",
"waveform_cosine": correlation,
"waveform_rmse": error,
"native_samples": len(raw),
"inspection_samples": len(normalized),
}
if embedded is not None:
count = min(len(embedded), len(normalized))
left, right = embedded[:count].ravel(), normalized[:count].ravel()
cosine = float(
left
@ right
/ max(float(np.linalg.norm(left) * np.linalg.norm(right)), 1e-12)
)
rmse = float(np.sqrt(np.mean((left - right) ** 2)))
extra = len(embedded) - len(normalized)
matches = -0.001 * 48000 <= extra <= 3072 and cosine >= 0.98 and rmse <= 0.03
binding.update(
embedded_audio_samples=len(embedded),
embedded_waveform_cosine=cosine,
embedded_waveform_rmse=rmse,
embedded_codec_padding_samples=extra,
embedded_matches_native=matches,
)
if not matches:
binding["decision"] = "indeterminate"
validate_content_verification(report)
if (
report.get("decision") != "pass"
or report.get("native_av_policy") != ALIGNMENT_POLICY
or report.get("asr_revision") != ASR_REVISION
or type(report.get("content_error_rate")) not in (int, float)
or report["content_error_rate"] != 0
or report.get("audio_sha256") != digest(speech_audio)
or report.get("sample_rate") != 48000
or report.get("source_start_sample") != 0
or report.get("source_end_sample") != len(normalized)
or report.get("reasons")
or report.get("timestamp_source") != "whisper-word-timestamps"
or report.get("timestamp_origin") != "audio_asset"
):
raise ValueError("ASR report is not bound to this complete inspection audio")
validate_words(report["words"], 0, len(normalized), report["transcript"])
return normalized.mean(axis=1), binding
def visual_review(path, video_sha, count):
if path is None:
return {
"decision": "indeterminate",
"reason": "independent_visual_review_required",
}
report = json.loads(Path(path).read_text(encoding="utf-8"))
source = report.get("video_sha256", report.get("source_sha256"))
bound = (
source == video_sha
and report.get("source_start_frame") == 0
and report.get("source_end_frame") == count
)
return {
"decision": report.get("decision", "indeterminate")
if bound
else "indeterminate",
"review_sha256": digest(path),
"source_matched": source == video_sha,
"whole_clip_matched": bound,
}
def inspect(
video,
native_audio,
speech_audio,
speech_report,
reference,
model_root,
output,
*,
review=None,
):
"""所有真实模型都在CPU;不能调用本函数作为生成/修脸或认证免检入口。"""
import cv2
import numpy as np
import torch
from .analysis import FaceModels, iou
from .quality import syncnet_crop, syncnet_scores
from .rest import MouthParser, assess_rest
video, native_audio, speech_audio, speech_report, reference = map(
Path, (video, native_audio, speech_audio, speech_report, reference)
)
model_root, output = Path(model_root), Path(output)
output.mkdir(parents=True, exist_ok=True)
sources = {
str(path.resolve()): digest(path)
for path in (video, native_audio, speech_audio, speech_report, reference)
}
if any(
(output / name).resolve() in [Path(p) for p in sources]
for name in (
"native-av-acceptance.json",
"native-av-evidence.png",
"native-av-mouth-timeline.png",
)
):
raise ValueError("Acceptance output would overwrite a source")
metadata = probe_native(video)
with wave.open(str(native_audio), "rb") as wav:
geometry = assess_geometry(
metadata,
samples=wav.getnframes(),
rate=wav.getframerate(),
channels=wav.getnchannels(),
width=wav.getsampwidth(),
)
report = json.loads(speech_report.read_text(encoding="utf-8"))
playback = embedded_audio(video)
_, binding = audio_evidence(native_audio, speech_audio, report, embedded=playback)
# 口型评分采用用户实际听到的MP4解码音轨;完整WAV与识别音轨先独立核对来源。
audio = playback.mean(axis=1)
n = metadata["frames"]
tail = tail_window(report, frames=n)
detector = FaceModels(model_root / "auraface")
initial = cv2.imread(str(reference))
if initial is None:
raise ValueError("Reference is not a decodable image")
faces = detector.detect(initial)
if len(faces) != 1:
raise ValueError("Reference must have one unambiguous visible face")
identity = detector.embed(initial, faces[0][1])
parser = MouthParser(model_root, device="cpu")
sys.path.insert(0, str(model_root / "syncnet"))
from SyncNetModel import S
model = S()
model.load_state_dict(
torch.load(
model_root / "syncnet" / "syncnet_v2.model",
map_location="cpu",
weights_only=True,
)
)
model = model.eval().to("cpu")
torch.set_num_threads(2)
crops, observations, images, aperture, errors = [], [], {}, {}, []
previous_box = previous_small = None
static_run = max_static = 0
sampled = set(np.linspace(0, n - 1, min(16, n), dtype=int).tolist())
if tail:
sampled.update([tail[0], n - 1])
for index, frame in enumerate(frames(video, n)):
detected = detector.detect(frame)
if len(detected) != 1:
errors.append(
{
"frame": index,
"reason": "missing_or_multiple_faces",
"count": len(detected),
}
)
break
box, points = detected[0]
vector = detector.embed(frame, points)
similarity = float(identity @ vector)
overlap = iou(box, previous_box) if previous_box else 1.0
if similarity < 0.4 or overlap < 0.35:
errors.append(
{
"frame": index,
"reason": "identity_or_track_uncertain",
"similarity": similarity,
"overlap": overlap,
}
)
crop = syncnet_crop(frame, box)
crops.append(crop)
gray = cv2.cvtColor(crop, cv2.COLOR_BGR2GRAY)
sharpness = float(cv2.Laplacian(gray, cv2.CV_64F).var())
small = cv2.resize(gray, (64, 64)).astype(np.float32)
delta = (
float(np.abs(small - previous_small).mean())
if previous_small is not None
else None
)
static_run = static_run + 1 if delta is not None and delta <= 0.05 else 0
max_static = max(max_static, static_run)
aperture[index] = parser.aperture(frame, box, points)
frame_audio = audio[index * 2000 : (index + 1) * 2000]
rms = float(np.sqrt(np.mean(frame_audio**2))) if len(frame_audio) else None
observations.append(
{
"frame": index,
"time_seconds": index / 24,
"identity_similarity": similarity,
"track_iou": overlap,
"sharpness_laplacian": sharpness,
"face_motion_mae": delta,
"mouth_aperture": aperture[index],
"audio_rms": rms,
}
)
if index in sampled:
images[index] = frame.copy(), crop.copy()
previous_box, previous_small = box, small
track = {
"decision": "indeterminate" if errors or len(crops) != n else "pass",
"errors": errors,
"frames_measured": len(crops),
"minimum_identity_similarity": min(
(row["identity_similarity"] for row in observations), default=None
),
"maximum_nearly_static_frames": max_static,
"minimum_sharpness": min(
(row["sharpness_laplacian"] for row in observations), default=None
),
}
if len(crops) == n:
original = syncnet_scores(model, crops, audio, device="cpu")
controls = [
{
"shift_ms": ms,
"score": syncnet_scores(
model, crops, shift_audio(audio, ms * 48), device="cpu"
),
}
for ms in (400, -400)
]
sync = assess_sync(original, controls)
else:
sync = {"decision": "indeterminate", "reason": "incomplete_face_track"}
rest = (
assess_rest([tail], aperture)
if tail
else {"decision": "indeterminate", "reason": "no_sustained_post_speech_tail"}
)
review_evidence = visual_review(review, sources[str(video.resolve())], n)
checks = {
"geometry": geometry["decision"],
"audio_binding": binding["decision"],
"speech": "pass",
"sync": sync["decision"],
"tracking": track["decision"],
"rest": rest["decision"],
"visual": review_evidence["decision"],
}
if any(digest(Path(path)) != sha for path, sha in sources.items()):
raise ValueError("Source changed during read-only acceptance")
result = dict(
policy=POLICY,
**overall(checks),
checks=checks,
source_sha256=sources,
geometry=geometry,
audio_binding=binding,
speech_report_sha256=digest(speech_report),
sync=sync,
tracking=track,
rest=rest,
visual_review=review_evidence,
observations=observations,
cpu_only=True,
sync_audio_source="actual-mp4-decoded-audio",
modifies_source=False,
note="SyncNet is an independent screening metric, not proof of every phoneme; inspect evidence images and the source movie.",
)
from .native_acceptance_visuals import evidence_images
evidence_images(output, images, observations, report, tail)
(output / "native-av-acceptance.json").write_text(
json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False),
encoding="utf-8",
)
return result