378 lines
13 KiB
Python
378 lines
13 KiB
Python
"""SyncNet's native evaluation clock is 25 fps with 16kHz audio."""
|
||
|
||
import json
|
||
import sys
|
||
|
||
from . import MOUTH_BLEND_POLICY, SILENCE_POLICY, SOURCE_REST_POLICY
|
||
from .media import digest, frames, probe
|
||
from .rest import MouthParser, assess_rest, quiet_windows
|
||
|
||
|
||
def syncnet_scores(model, crops, wave, *, device="cuda"):
|
||
import numpy as np
|
||
import torch
|
||
from python_speech_features import mfcc
|
||
from scipy.signal import resample_poly
|
||
|
||
# 只在质检副本上按时间戳采样;成片/原始对白的帧和声音不做变速。
|
||
count = len(crops) * 25 // 24
|
||
video = [crops[min(len(crops) - 1, (i * 24 + 12) // 25)] for i in range(count)]
|
||
pcm = np.clip(resample_poly(wave, 1, 3) * 32767, -32768, 32767).astype(np.int16)
|
||
cep = mfcc(pcm, 16000).T.astype(np.float32)
|
||
count = min(len(video) - 4, (cep.shape[1] - 20) // 4 + 1)
|
||
if count < 20:
|
||
return {"decision": "indeterminate", "reason": "short_sample"}
|
||
vf = []
|
||
af = []
|
||
with torch.inference_mode():
|
||
for start in range(0, count, 8):
|
||
idx = range(start, min(start + 8, count))
|
||
visual = np.stack([video[i : i + 5] for i in idx]).transpose(0, 4, 1, 2, 3)
|
||
audio = np.stack([cep[:, 4 * i : 4 * i + 20] for i in idx])[:, None]
|
||
vf.append(
|
||
model.forward_lip(torch.from_numpy(visual).float().to(device)).cpu()
|
||
)
|
||
af.append(model.forward_aud(torch.from_numpy(audio).to(device)).cpu())
|
||
vis, aud = torch.cat(vf), torch.cat(af)
|
||
# 同一组有语音的窗口用于所有偏移,避免以大片静音或两端填零取得虚高置信度。
|
||
# SyncNet official vshift=15 at 25 Hz spans both directions out to 600 ms.
|
||
shift = 15
|
||
idx = [
|
||
i
|
||
for i in range(shift, count - shift)
|
||
if np.sqrt(np.mean((pcm[i * 640 : i * 640 + 3200].astype(float) / 32768) ** 2))
|
||
>= 0.009
|
||
]
|
||
if len(idx) < 15:
|
||
return {
|
||
"decision": "indeterminate",
|
||
"reason": "insufficient_voiced_evidence",
|
||
"voiced_windows": len(idx),
|
||
}
|
||
costs = np.array(
|
||
[
|
||
(vis[idx] - aud[[i + k for i in idx]]).norm(dim=1).mean().item()
|
||
for k in range(-shift, shift + 1)
|
||
]
|
||
)
|
||
best = int(costs.argmin())
|
||
offset = (shift - best) * 40
|
||
confidence = float(np.median(costs) - costs[best])
|
||
decision = (
|
||
"indeterminate"
|
||
if confidence < 2.0
|
||
else "reject"
|
||
if abs(offset) > 80
|
||
else "pass"
|
||
)
|
||
return {
|
||
"decision": decision,
|
||
"offset_ms": offset,
|
||
"confidence": round(confidence, 4),
|
||
"working_fps": 25,
|
||
"search_radius_ms": shift * 40,
|
||
"voiced_windows": len(idx),
|
||
}
|
||
|
||
|
||
def syncnet_crop(image, box):
|
||
import cv2
|
||
import numpy as np
|
||
|
||
x, y, r, b = box
|
||
half = max(r - x, b - y) / 2
|
||
size = max(1, round(2.8 * half))
|
||
left, top = round((r + x) / 2 - size / 2), round((y + b) / 2 - half)
|
||
square = np.full((size, size, 3), 110, np.uint8)
|
||
x0, y0 = max(0, left), max(0, top)
|
||
x1, y1 = min(image.shape[1], left + size), min(image.shape[0], top + size)
|
||
square[y0 - top : y1 - top, x0 - left : x1 - left] = image[y0:y1, x0:x1]
|
||
return cv2.resize(square, (224, 224))
|
||
|
||
|
||
def _block_stats(diff, protected):
|
||
import numpy as np
|
||
|
||
size = 32
|
||
h, w = diff.shape
|
||
padding = ((0, (-h) % size), (0, (-w) % size))
|
||
|
||
# 分块统计让手、道具和背景边缘的小面积损伤不会被整帧均值稀释。
|
||
def sums(values):
|
||
values = np.pad(values, padding)
|
||
return values.reshape(
|
||
values.shape[0] // size, size, values.shape[1] // size, size
|
||
).sum(axis=(1, 3))
|
||
|
||
counts = sums(protected)
|
||
valid = counts >= 128
|
||
if not valid.any():
|
||
return 0.0, 0.0, 0
|
||
mae = sums(diff * protected)[valid] / counts[valid]
|
||
severe = sums((diff >= 32) & protected)[valid] / counts[valid]
|
||
return float(mae.max()), float(severe.max()), int(valid.sum())
|
||
|
||
|
||
def protected_blocks(diff, protected):
|
||
mae, severe, count = _block_stats(diff, protected)
|
||
return (mae, severe) if count else (255.0, 1.0)
|
||
|
||
|
||
def mouth_blocks(diff, region):
|
||
import numpy as np
|
||
|
||
y, x = region
|
||
# 从原图的32像素块边界开始,单独统计嘴区内的像素。
|
||
top, left = y.start // 32 * 32, x.start // 32 * 32
|
||
crop = diff[top : y.stop, left : x.stop]
|
||
mask = np.zeros(crop.shape, bool)
|
||
mask[y.start - top :, x.start - left :] = True
|
||
return _block_stats(crop, mask)
|
||
|
||
|
||
def blocks_changed(mae, severe):
|
||
return mae > 18 or severe > 0.15
|
||
|
||
|
||
def mouth_source_check(actor, frames):
|
||
measured = [row for row in frames if row[2]]
|
||
mae = max((row[0] for row in measured), default=0.0)
|
||
severe = max((row[1] for row in measured), default=0.0)
|
||
decision = "pass"
|
||
if not frames:
|
||
decision = "not_applicable"
|
||
elif blocks_changed(mae, severe):
|
||
decision = "reject"
|
||
elif len(measured) != len(frames):
|
||
decision = "indeterminate"
|
||
return {
|
||
"speaker_id": actor,
|
||
"silent_frames": len(frames),
|
||
"measured_frames": len(measured),
|
||
"block_count": sum(row[2] for row in measured),
|
||
"max_block_mae": mae,
|
||
"max_block_severe_fraction": severe,
|
||
"decision": decision,
|
||
}
|
||
|
||
|
||
def visual_verdict(
|
||
scores,
|
||
rest_checks,
|
||
cross_checks,
|
||
min_identity,
|
||
outside_peak,
|
||
block_mae,
|
||
block_severe,
|
||
listener_peak,
|
||
source_rest_checks=(),
|
||
mouth_source_checks=(),
|
||
):
|
||
failures = []
|
||
unknown = []
|
||
if outside_peak > 6 or blocks_changed(block_mae, block_severe):
|
||
failures.append("protected_region_changed")
|
||
if listener_peak > 8:
|
||
failures.append("listener_changed")
|
||
if min_identity < 0.65:
|
||
failures.append("identity_changed")
|
||
if any(c["decision"] == "pass" for c in cross_checks):
|
||
failures.append("listener_sync")
|
||
for row in scores:
|
||
if row["decision"] == "reject":
|
||
failures.append("sync_offset")
|
||
elif row["decision"] != "pass":
|
||
unknown.append(row.get("reason", "low_sync_confidence"))
|
||
for row in rest_checks:
|
||
if row["decision"] == "reject":
|
||
failures.append("silence_mouth_motion")
|
||
elif row["decision"] != "pass":
|
||
unknown.append(row.get("reason", "insufficient_silence_evidence"))
|
||
for row in source_rest_checks:
|
||
if row["decision"] == "reject":
|
||
failures.append("source_speaking_during_silence")
|
||
elif row["decision"] != "pass":
|
||
unknown.append("insufficient_source_rest_evidence")
|
||
for check in mouth_source_checks:
|
||
if check["decision"] == "reject":
|
||
failures.append("silent_mouth_source_changed")
|
||
elif check["decision"] == "indeterminate":
|
||
unknown.append("insufficient_silent_mouth_source_evidence")
|
||
if not scores and not rest_checks:
|
||
unknown.append("insufficient_sync_evidence")
|
||
decision = "reject" if failures else "indeterminate" if unknown else "pass"
|
||
return decision, list(dict.fromkeys(failures + unknown))
|
||
|
||
|
||
def inspect(base, synced, rows, p, root, out, listeners=()):
|
||
import numpy as np
|
||
import torch
|
||
|
||
from .analysis import FaceModels
|
||
|
||
if probe(synced, p["num_frames"]) != probe(base, p["num_frames"]):
|
||
raise ValueError("Quality inputs differ in size")
|
||
sys.path.insert(0, str(root / "syncnet"))
|
||
from SyncNetModel import S
|
||
|
||
detector = FaceModels(root / "auraface")
|
||
model = S()
|
||
state = torch.load(
|
||
root / "syncnet" / "syncnet_v2.model", map_location="cpu", weights_only=True
|
||
)
|
||
model.load_state_dict(state)
|
||
model = model.eval().cuda()
|
||
crops = [[] for _ in rows]
|
||
listener_crops = {tr["speaker_id"]: [] for tr in listeners}
|
||
identity = []
|
||
outside_delta = []
|
||
listener_delta = []
|
||
windows = [quiet_windows(wave) for _, _, _, wave in rows]
|
||
quiet_indices = [
|
||
{i for start, end in ranges for i in range(start, end)} for ranges in windows
|
||
]
|
||
parser = MouthParser(root) if any(quiet_indices) else None
|
||
policy = p.get("speech_silence_policy", SILENCE_POLICY)
|
||
source_rest = policy == SOURCE_REST_POLICY
|
||
mouth_measurements = [{} for _ in rows]
|
||
source_measurements = [{} for _ in rows]
|
||
mouth_block_measurements = [[] for _ in rows]
|
||
max_block_error = 0.0
|
||
max_block_severe_fraction = 0.0
|
||
for i, (src, dst) in enumerate(
|
||
zip(frames(base, p["num_frames"]), frames(synced, p["num_frames"]), strict=True)
|
||
):
|
||
diff = np.abs(src.astype(np.int16) - dst.astype(np.int16)).mean(axis=2)
|
||
protected = np.ones(src.shape[:2], bool)
|
||
for j, (_, boxes, points, wave) in enumerate(rows):
|
||
x, y, r, b = boxes[i]
|
||
crops[j].append(syncnet_crop(dst, boxes[i]))
|
||
centre = np.array(points[i][3:5]).mean(axis=0).astype(int)
|
||
radius = max(
|
||
3, int(np.linalg.norm(np.subtract(points[i][3], points[i][4])))
|
||
)
|
||
cx, cy = centre
|
||
region = (
|
||
slice(max(y, cy - radius), min(b, cy + radius)),
|
||
slice(max(x, cx - radius), min(r, cx + radius)),
|
||
)
|
||
if (
|
||
not source_rest
|
||
or np.max(np.abs(wave[2000 * i : 2000 * (i + 1)])) > 0.003
|
||
):
|
||
protected[region] = False
|
||
if i in quiet_indices[j]:
|
||
if source_rest:
|
||
mouth_block_measurements[j].append(mouth_blocks(diff, region))
|
||
source_measurements[j][i] = parser.aperture(
|
||
src, boxes[i], points[i]
|
||
)
|
||
mouth_measurements[j][i] = parser.aperture(dst, boxes[i], points[i])
|
||
if i % 6 == 0:
|
||
a = detector.embed(src, np.asarray(points[i]))
|
||
b_id = detector.embed(dst, np.asarray(points[i]))
|
||
identity.append(
|
||
{
|
||
"frame": i,
|
||
"speaker_id": rows[j][0]["speaker_id"],
|
||
"similarity": float(a @ b_id),
|
||
}
|
||
)
|
||
for tr in listeners:
|
||
listener_crops[tr["speaker_id"]].append(syncnet_crop(dst, tr["boxes"][i]))
|
||
x, y, r, b = tr["boxes"][i]
|
||
listener_delta.append(float(diff[y:b, x:r].mean()))
|
||
block_mae, block_severe = protected_blocks(diff, protected)
|
||
max_block_error = max(max_block_error, block_mae)
|
||
max_block_severe_fraction = max(max_block_severe_fraction, block_severe)
|
||
outside_delta.append(
|
||
float(diff[protected].mean()) if protected.any() else 255.0
|
||
)
|
||
scores = [
|
||
{**syncnet_scores(model, clips, wave), "speaker_id": stem["speaker_id"]}
|
||
for clips, (stem, _, _, wave) in zip(crops, rows)
|
||
]
|
||
visible = {
|
||
**listener_crops,
|
||
**{stem["speaker_id"]: clips for clips, (stem, _, _, _) in zip(crops, rows)},
|
||
}
|
||
cross_checks = []
|
||
for stem, _, _, wave in rows:
|
||
for speaker_id, clips in visible.items():
|
||
if speaker_id != stem["speaker_id"]:
|
||
cross_checks.append(
|
||
{
|
||
**syncnet_scores(model, clips, wave),
|
||
"audio_speaker_id": stem["speaker_id"],
|
||
"face_speaker_id": speaker_id,
|
||
}
|
||
)
|
||
outside_peak = max(outside_delta)
|
||
listener_peak = max(listener_delta, default=0.0)
|
||
source_checks = (
|
||
[
|
||
{**assess_rest(spans, values), "speaker_id": stem["speaker_id"]}
|
||
for spans, values, (stem, _, _, _) in zip(
|
||
windows, source_measurements, rows
|
||
)
|
||
]
|
||
if source_rest
|
||
else []
|
||
)
|
||
rest_checks = [
|
||
{**assess_rest(spans, values), "speaker_id": stem["speaker_id"]}
|
||
for spans, values, (stem, _, _, _) in zip(windows, mouth_measurements, rows)
|
||
]
|
||
mouth_source_checks = (
|
||
[
|
||
mouth_source_check(stem["speaker_id"], values)
|
||
for (stem, _, _, _), values in zip(rows, mouth_block_measurements)
|
||
]
|
||
if source_rest
|
||
else []
|
||
)
|
||
min_identity = min(row["similarity"] for row in identity)
|
||
decision, reasons = visual_verdict(
|
||
scores,
|
||
rest_checks,
|
||
cross_checks,
|
||
min_identity,
|
||
outside_peak,
|
||
max_block_error,
|
||
max_block_severe_fraction,
|
||
listener_peak,
|
||
source_checks,
|
||
mouth_source_checks,
|
||
)
|
||
report = {
|
||
"decision": decision,
|
||
"reasons": reasons,
|
||
"scores": scores,
|
||
"rest_checks": rest_checks,
|
||
"speech_silence_policy": policy,
|
||
**(
|
||
{
|
||
"source_rest_checks": source_checks,
|
||
"silent_mouth_source_checks": mouth_source_checks,
|
||
}
|
||
if source_rest
|
||
else {}
|
||
),
|
||
"mouth_blend_policy": MOUTH_BLEND_POLICY,
|
||
"listener_sync_checks": cross_checks,
|
||
"base_sha256": digest(base),
|
||
"synced_sha256": digest(synced),
|
||
"min_identity_similarity": min_identity,
|
||
"identity_samples": identity,
|
||
"max_protected_pixel_error": outside_peak,
|
||
"max_protected_block_mae": max_block_error,
|
||
"max_protected_block_severe_fraction": max_block_severe_fraction,
|
||
"protected_block_size": 32,
|
||
"max_silent_speaker_error": listener_peak,
|
||
"fps": 24,
|
||
"num_frames": p["num_frames"],
|
||
}
|
||
path = out / "sync-quality.json"
|
||
path.write_text(json.dumps(report, allow_nan=False), encoding="utf-8")
|
||
return [path], report
|