139 lines
4.9 KiB
Python
139 lines
4.9 KiB
Python
"""Semantic mouth aperture evidence for sustained silent intervals on a speaker track."""
|
|
|
|
from itertools import groupby
|
|
|
|
SHORT_WINDOW_FRAMES = 12
|
|
REST_QUALITY_POLICY = "aperture-window12-v1"
|
|
|
|
|
|
class MouthParser:
|
|
def __init__(self, root, *, device="cuda"):
|
|
from transformers import (
|
|
SegformerForSemanticSegmentation,
|
|
SegformerImageProcessor,
|
|
)
|
|
|
|
self.device = device
|
|
self.processor = SegformerImageProcessor.from_pretrained(
|
|
root / "face-parser", local_files_only=True
|
|
)
|
|
self.model = (
|
|
SegformerForSemanticSegmentation.from_pretrained(
|
|
root / "face-parser", local_files_only=True
|
|
)
|
|
.to(device)
|
|
.eval()
|
|
)
|
|
names = {name: idx for idx, name in self.model.config.id2label.items()}
|
|
self.inner = names["mouth"]
|
|
self.lips = [names["u_lip"], names["l_lip"]]
|
|
self.writable = [self.inner, *self.lips, names["skin"]]
|
|
|
|
def labels(self, rgb, shape):
|
|
import torch
|
|
from PIL import Image
|
|
|
|
inputs = self.processor(images=Image.fromarray(rgb), return_tensors="pt").to(
|
|
self.device
|
|
)
|
|
with torch.inference_mode():
|
|
logits = self.model(**inputs).logits
|
|
return (
|
|
torch.nn.functional.interpolate(
|
|
logits, size=shape, mode="bilinear", align_corners=False
|
|
)
|
|
.argmax(1)[0]
|
|
.cpu()
|
|
.numpy()
|
|
)
|
|
|
|
def aperture(self, image, box, points):
|
|
import cv2
|
|
import numpy as np
|
|
|
|
x, y, r, b = box
|
|
rgb = cv2.cvtColor(cv2.resize(image[y:b, x:r], (256, 256)), cv2.COLOR_BGR2RGB)
|
|
labels = self.labels(rgb, (b - y, r - x))
|
|
corners = np.asarray(points, dtype=float)[3:5] - [x, y]
|
|
span = float(np.linalg.norm(corners[0] - corners[1]))
|
|
cx, cy = corners.mean(0)
|
|
if span < 6:
|
|
return None
|
|
region = labels[
|
|
max(0, int(cy - span * 0.6)) : min(b - y, int(cy + span * 0.6) + 1),
|
|
max(0, int(cx - span)) : min(r - x, int(cx + span) + 1),
|
|
]
|
|
lips = np.isin(region, self.lips)
|
|
if int(lips.sum()) < max(8, span * 0.35):
|
|
return None
|
|
return float(np.sum(region == self.inner) / (span * span))
|
|
|
|
|
|
def quiet_windows(wave):
|
|
import numpy as np
|
|
|
|
quiet = np.max(np.abs(wave.reshape(-1, 2000)), axis=1) <= 0.003
|
|
windows = []
|
|
for silent, group in groupby(enumerate(quiet), key=lambda pair: pair[1]):
|
|
indices = [i for i, _ in group]
|
|
if silent:
|
|
start = indices[0] + (2 if indices[0] else 0)
|
|
end = indices[-1] + 1 - (2 if indices[-1] + 1 < len(quiet) else 0)
|
|
if end - start >= 4:
|
|
windows.append((start, end))
|
|
return windows
|
|
|
|
|
|
def speaking_aperture(peak, variation):
|
|
return (peak > 0.14) | ((peak > 0.055) & (variation > 0.045))
|
|
|
|
|
|
def assess_rest(windows, apertures):
|
|
import numpy as np
|
|
|
|
evidence = []
|
|
decision = "pass"
|
|
for start, end in windows:
|
|
values = [apertures.get(i) for i in range(start, end)]
|
|
if any(v is None or not np.isfinite(v) for v in values):
|
|
evidence.append(
|
|
{"start_frame": start, "end_frame": end, "decision": "indeterminate"}
|
|
)
|
|
if decision != "reject":
|
|
decision = "indeterminate"
|
|
continue
|
|
ratios = np.asarray(values)
|
|
peak = float(np.percentile(ratios, 90))
|
|
variation = float(np.percentile(ratios, 90) - np.percentile(ratios, 10))
|
|
# Aperture is the inner-mouth area divided by squared landmark span.
|
|
width = min(SHORT_WINDOW_FRAMES, len(ratios))
|
|
rolling = np.lib.stride_tricks.sliding_window_view(ratios, width)
|
|
lower, upper = np.percentile(rolling, (10, 90), axis=1)
|
|
drift = upper - lower
|
|
rejected = np.flatnonzero(speaking_aperture(upper, drift))
|
|
failed = speaking_aperture(peak, variation) or bool(rejected.size)
|
|
if failed:
|
|
decision = "reject"
|
|
evidence.append(
|
|
{
|
|
"start_frame": start,
|
|
"end_frame": end,
|
|
"decision": "reject" if failed else "pass",
|
|
"aperture_p90": peak,
|
|
"short_window_frames": width,
|
|
"max_short_window_p90": float(upper.max()),
|
|
"max_short_window_range": float(drift.max()),
|
|
"first_rejected_short_window_start": start + int(rejected[0])
|
|
if rejected.size
|
|
else None,
|
|
"aperture_range_p90_p10": variation,
|
|
"aperture_series": [round(float(v), 4) for v in ratios],
|
|
}
|
|
)
|
|
return {
|
|
"decision": decision,
|
|
"rest_quality_policy": REST_QUALITY_POLICY,
|
|
"silent_frames": sum(b - a for a, b in windows),
|
|
"windows": evidence,
|
|
}
|