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

171 lines
5.7 KiB
Python

"""Reference-bound SCRFD + ArcFace. Ambiguous or missing identities require review."""
import json
from .media import digest, frames, probe
class FaceModels:
def __init__(self, root):
import onnxruntime as ort
options = ort.SessionOptions()
options.intra_op_num_threads = 2
options.inter_op_num_threads = 1
self.det = ort.InferenceSession(
str(root / "scrfd_10g_bnkps.onnx"),
options,
providers=["CPUExecutionProvider"],
)
self.rec = ort.InferenceSession(
str(root / "glintr100.onnx"), options, providers=["CPUExecutionProvider"]
)
def detect(self, frame):
import cv2
import numpy as np
h, w = frame.shape[:2]
scale = min(640 / h, 640 / w)
rw, rh = round(w * scale), round(h * scale)
canvas = np.zeros((640, 640, 3), np.uint8)
canvas[:rh, :rw] = cv2.resize(frame, (rw, rh))
blob = cv2.dnn.blobFromImage(
canvas, 1 / 128, (640, 640), (127.5,) * 3, swapRB=True
)
outs = self.det.run(None, {self.det.get_inputs()[0].name: blob})
candidates = []
for level, stride in enumerate((8, 16, 32)):
scores = outs[level].reshape(-1)
boxes = outs[level + 3].reshape(-1, 4) * stride
keys = outs[level + 6].reshape(-1, 5, 2) * stride
n = 640 // stride
for index in np.flatnonzero(scores >= 0.65):
anchor = index // 2
cx, cy = anchor % n * stride, anchor // n * stride
l, t, r, b = boxes[index]
box = [
max(0, int((cx - l) / scale)),
max(0, int((cy - t) / scale)),
min(w, int((cx + r) / scale)),
min(h, int((cy + b) / scale)),
]
if min(box[2] - box[0], box[3] - box[1]) < 40:
continue
candidates.append(
(float(scores[index]), box, (keys[index] + [cx, cy]) / scale)
)
kept = []
for score, box, kps in sorted(candidates, key=lambda row: -row[0]):
if any(iou(box, b) > 0.4 for b, _ in kept):
continue
kept.append((box, kps))
return kept
def embed(self, frame, kps):
import cv2
import numpy as np
target = np.float32(
[
[38.2946, 51.6963],
[73.5318, 51.5014],
[56.0252, 71.7366],
[41.5493, 92.3655],
[70.7299, 92.2041],
]
)
matrix, _ = cv2.estimateAffinePartial2D(
kps.astype(np.float32), target, method=cv2.LMEDS
)
if matrix is None:
raise ValueError("Face could not be aligned")
face = cv2.warpAffine(frame, matrix, (112, 112))
blob = cv2.dnn.blobFromImage(
face, 1 / 127.5, (112, 112), (127.5,) * 3, swapRB=True
)
features = self.rec.run(None, {self.rec.get_inputs()[0].name: blob})[0].ravel()
return features / max(np.linalg.norm(features), 1e-10)
def iou(a, b):
overlap = max(0, min(a[2], b[2]) - max(a[0], b[0])) * max(
0, min(a[3], b[3]) - max(a[1], b[1])
)
return overlap / max(
1, (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - overlap
)
def analyze(inputs, p, root, out):
import cv2
import numpy as np
model = FaceModels(root / "auraface")
n = p["num_frames"]
probe(inputs["video_path"], n)
refs = []
for path in inputs["reference_paths"]:
image = cv2.imread(path)
if image is None:
raise ValueError("Unable to decode reference")
found = model.detect(image)
if len(found) != 1:
raise ValueError("Each reference must contain exactly one face")
refs.append(model.embed(image, found[0][1]))
tracks = [
{"speaker_id": s, "track_id": s, "boxes": [], "landmarks": []}
for s in p["speaker_ids"]
]
reason = None
for i, frame in enumerate(frames(inputs["video_path"], n)):
found = model.detect(frame)
if len(found) != len(tracks) or (
len(found) == 2 and iou(found[0][0], found[1][0]) > 0.02
):
reason = "missing_face_or_overlap"
break
scores = np.array(
[
[float(r @ v) for r in refs]
for v in [model.embed(frame, k) for _, k in found]
]
)
winners = scores.argmax(axis=1)
if len(set(winners)) != len(tracks):
reason = "identity_conflict"
break
for j, idx in enumerate(winners):
if scores[j, idx] < 0.4 or (
len(refs) == 2 and abs(scores[j, 0] - scores[j, 1]) < 0.14
):
reason = "identity_uncertain"
break
box, kps = found[j]
tr = tracks[idx]
if i and iou(box, tr["boxes"][-1]) < 0.35:
reason = "track_discontinuity"
break
tr["boxes"].append(box)
tr["landmarks"].append(kps.tolist())
if reason:
break
summary = {
"decision": "indeterminate" if reason else "pass",
"reason": reason,
"fps": 24,
"num_frames": n,
"source_sha256": digest(inputs["video_path"]),
"tracks": [
{"speaker_id": t["speaker_id"], "track_id": t["track_id"]} for t in tracks
]
if not reason
else [],
}
path = out / "face-tracks.json"
path.write_text(
json.dumps({**summary, "tracks": tracks if not reason else []}),
encoding="utf-8",
)
return [path], summary