lipsync-2d 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
eval/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """Evaluation metrics and MFCC baseline for lipsync-2d."""
@@ -0,0 +1,312 @@
1
+ """Head-to-head benchmark on human-annotated TIMIT phoneme boundaries:
2
+ lipsync-2d ONNX vs official Rhubarb Lip Sync CLI (v1.14.0) vs MFCC baseline.
3
+
4
+ Evaluates normal pitch (0 st), high-pitched (+4 semitones, Rhubarb Issue #174),
5
+ and male vs female speaker slices on kylelovesllms/timit_asr official test split.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import io
12
+ import json
13
+ import subprocess
14
+ import tempfile
15
+ import wave
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ import numpy as np
20
+ import onnxruntime as ort
21
+ import pyarrow.parquet as pq
22
+ import soundfile as sf
23
+ from huggingface_hub import hf_hub_download
24
+ from scipy.signal import resample_poly
25
+
26
+ from eval.metrics import evaluate_predictions
27
+ from lipsync_2d.decode import decode_cues
28
+ from lipsync_2d.features import SAMPLE_RATE, compute_frame_energy_db, extract_log_mel_np, normalize_speech_rms
29
+ from lipsync_2d.visemes import RHUBARB_SHAPES
30
+
31
+ RHUBARB_TO_IDX = {s: i for i, s in enumerate(RHUBARB_SHAPES)}
32
+
33
+ # Official 61-phone TIMIT Arpabet -> 9 Rhubarb shapes (X, A-H)
34
+ TIMIT_TO_RHUBARB: dict[str, str] = {
35
+ # X: silence / pause / epenthetic silence
36
+ "h#": "X", "pau": "X", "epi": "X",
37
+ # A: bilabial closures & releases (p, b, m)
38
+ "p": "A", "b": "A", "m": "A", "em": "A", "pcl": "A", "bcl": "A",
39
+ # G: labiodentals (f, v)
40
+ "f": "G", "v": "G",
41
+ # H: laterals (l)
42
+ "l": "H", "el": "H",
43
+ # D: wide open vowels (aa, ae, ah, aw, ay)
44
+ "aa": "D", "ae": "D", "ah": "D", "aw": "D", "ay": "D",
45
+ # C: open mid vowels (eh, ey, ax, ax-h, ix)
46
+ "eh": "C", "ey": "C", "ax": "C", "ax-h": "C", "ix": "C",
47
+ # E: rounded open / r-colored (ao, ow, oy, r, er, axr)
48
+ "ao": "E", "ow": "E", "oy": "E", "r": "E", "er": "E", "axr": "E",
49
+ # F: narrow rounded / puckered (uw, ux, uh, w)
50
+ "uw": "F", "ux": "F", "uh": "F", "w": "F",
51
+ # B: clenched / slightly open consonants & high front vowels
52
+ "t": "B", "d": "B", "k": "B", "g": "B", "s": "B", "z": "B",
53
+ "sh": "B", "zh": "B", "ch": "B", "jh": "B", "th": "B", "dh": "B",
54
+ "n": "B", "ng": "B", "nx": "B", "en": "B", "eng": "B",
55
+ "ih": "B", "iy": "B", "y": "B", "hh": "B", "hv": "B", "dx": "B",
56
+ "tcl": "B", "dcl": "B", "kcl": "B", "gcl": "B", "q": "B",
57
+ }
58
+
59
+
60
+ def pitch_shift_preserve_duration(wav: np.ndarray, semitones: float, sr: int = SAMPLE_RATE) -> np.ndarray:
61
+ """Phase-vocoder style duration-preserving pitch shift using STFT (or fast resample+OLA)."""
62
+ if abs(semitones) < 1e-3:
63
+ return wav.astype(np.float32)
64
+ factor = 2.0 ** (semitones / 12.0)
65
+ # Time-stretch by `factor` via phase vocoder, then resample back to original length
66
+ n_fft = 512
67
+ hop_a = 128
68
+ win = np.hanning(n_fft).astype(np.float32)
69
+ pad = n_fft // 2
70
+ x = np.pad(wav.astype(np.float32), (pad, pad))
71
+ n_frames = 1 + (len(x) - n_fft) // hop_a
72
+ if n_frames < 2:
73
+ return wav.astype(np.float32)
74
+ frames = np.stack([x[i * hop_a : i * hop_a + n_fft] * win for i in range(n_frames)], axis=0)
75
+ spec = np.fft.rfft(frames, axis=-1)
76
+ mag = np.abs(spec)
77
+ phase = np.angle(spec)
78
+ omega = 2.0 * np.pi * np.arange(spec.shape[1]) * hop_a / n_fft
79
+
80
+ t_steps = np.arange(0.0, n_frames - 1, 1.0 / factor)
81
+ out_spec = np.zeros((len(t_steps), spec.shape[1]), dtype=np.complex64)
82
+ ph_acc = phase[0].copy()
83
+ for out_i, t in enumerate(t_steps):
84
+ i0 = int(np.floor(t))
85
+ i1 = min(i0 + 1, n_frames - 1)
86
+ frac = t - i0
87
+ m = (1.0 - frac) * mag[i0] + frac * mag[i1]
88
+ dphi = phase[i1] - phase[i0] - omega
89
+ dphi = dphi - 2.0 * np.pi * np.round(dphi / (2.0 * np.pi))
90
+ if out_i > 0:
91
+ ph_acc += omega + dphi
92
+ out_spec[out_i] = m * np.exp(1j * ph_acc)
93
+
94
+ out_len = (len(t_steps) - 1) * hop_a + n_fft
95
+ y = np.zeros(out_len, dtype=np.float32)
96
+ wsum = np.zeros(out_len, dtype=np.float32)
97
+ for i in range(len(t_steps)):
98
+ s = i * hop_a
99
+ y[s : s + n_fft] += np.fft.irfft(out_spec[i], n=n_fft).astype(np.float32) * win
100
+ wsum[s : s + n_fft] += win * win
101
+ y /= np.maximum(wsum, 1e-6)
102
+ y = y[pad : out_len - pad]
103
+ # Resample stretched signal back to exact original length -> pitch shifted by `factor`, same timing!
104
+ idx = np.linspace(0.0, max(0, len(y) - 1), len(wav), dtype=np.float64)
105
+ shifted = np.interp(idx, np.arange(len(y)), y).astype(np.float32)
106
+ return np.clip(shifted, -1.0, 1.0)
107
+
108
+
109
+ def phonetic_detail_to_50hz_labels(phonetic_detail: list[dict[str, Any]], n_samples: int, sr: int = SAMPLE_RATE) -> np.ndarray:
110
+ """Rasterize sample-accurate TIMIT human phonetic labels to 50 Hz (20 ms/frame) Rhubarb-9 indices."""
111
+ n_frames = n_samples // (sr // 50)
112
+ labels = np.zeros(n_frames, dtype=np.int64)
113
+ hop = sr // 50 # 320 samples
114
+ for seg in phonetic_detail:
115
+ phone = str(seg["utterance"]).lower().strip()
116
+ shape = TIMIT_TO_RHUBARB.get(phone, "B")
117
+ idx = RHUBARB_TO_IDX[shape]
118
+ s0 = int(seg["start"])
119
+ s1 = int(seg["stop"])
120
+ f0 = max(0, int(round(s0 / hop)))
121
+ f1 = min(n_frames, max(f0 + 1, int(round(s1 / hop))))
122
+ labels[f0:f1] = idx
123
+ return labels
124
+
125
+
126
+ def write_wav_16k(path: Path, wav: np.ndarray) -> None:
127
+ pcm = np.clip(wav * 32767.0, -32768, 32767).astype(np.int16)
128
+ with wave.open(str(path), "wb") as wf:
129
+ wf.setnchannels(1)
130
+ wf.setsampwidth(2)
131
+ wf.setframerate(SAMPLE_RATE)
132
+ wf.writeframes(pcm.tobytes())
133
+
134
+
135
+ def run_rhubarb_cli(rhubarb_bin: Path, wav_path: Path, n_frames: int) -> np.ndarray:
136
+ res = subprocess.run(
137
+ [str(rhubarb_bin), "-f", "json", "--extendedShapes", "GHX", "-r", "phonetic", str(wav_path)],
138
+ capture_output=True,
139
+ text=True,
140
+ check=True,
141
+ )
142
+ data = json.loads(res.stdout)
143
+ preds = np.zeros(n_frames, dtype=np.int64)
144
+ for cue in data.get("mouthCues", []):
145
+ idx = RHUBARB_TO_IDX.get(cue["value"], 0)
146
+ f0 = max(0, int(round(float(cue["start"]) * 50.0)))
147
+ f1 = min(n_frames, int(round(float(cue["end"]) * 50.0)))
148
+ preds[f0:f1] = idx
149
+ return preds
150
+
151
+
152
+ def run_lipsync_onnx(sess: ort.InferenceSession, wav: np.ndarray, n_frames: int) -> tuple[np.ndarray, np.ndarray]:
153
+ wav_norm = normalize_speech_rms(wav)
154
+ mel = extract_log_mel_np(wav_norm, norm="fixed", causal=True)
155
+ _, r9_logits, _ = sess.run(None, {"mel": mel[None, :, :].astype(np.float32)})
156
+ logits = r9_logits[0][:n_frames]
157
+ raw_pred = np.argmax(logits, axis=-1).astype(np.int64)
158
+ # Also compute Viterbi-decoded cues rasterized to 50 Hz for direct apples-to-apples vs Rhubarb cues
159
+ ex = np.exp(logits - np.max(logits, axis=-1, keepdims=True))
160
+ probs = ex / np.maximum(ex.sum(axis=-1, keepdims=True), 1e-8)
161
+ rms_db = compute_frame_energy_db(wav_norm, frame_ms=20)[: len(probs)]
162
+ cues = decode_cues(probs, audio_rms_db=rms_db)
163
+ cue_pred = np.zeros(n_frames, dtype=np.int64)
164
+ for c in cues:
165
+ f0 = max(0, int(round(c.start * 50.0)))
166
+ f1 = min(n_frames, int(round(c.end * 50.0)))
167
+ cue_pred[f0:f1] = RHUBARB_TO_IDX[c.value]
168
+ if len(raw_pred) < n_frames:
169
+ raw_pred = np.pad(raw_pred, (0, n_frames - len(raw_pred)))
170
+ return raw_pred, cue_pred
171
+
172
+
173
+ def benchmark_timit(
174
+ onnx_path: Path,
175
+ rhubarb_bin: Path | None = None,
176
+ n_utts: int = 160,
177
+ output_json: Path | None = None,
178
+ ) -> dict[str, Any]:
179
+ tp = hf_hub_download("kylelovesllms/timit_asr", "data/test-00000-of-00001.parquet", repo_type="dataset")
180
+ tbl = pq.read_table(tp, columns=["audio", "phonetic_detail", "speaker_sex", "speaker_id"])
181
+
182
+ # Balanced 50/50 distinct Male + Female speakers from official TIMIT test split (1 utterance per speaker, zero training overlap!)
183
+ sexes = tbl["speaker_sex"].to_pylist()
184
+ spk_ids = tbl["speaker_id"].to_pylist()
185
+ m_idx: list[int] = []
186
+ f_idx: list[int] = []
187
+ seen_spk: set[str] = set()
188
+ half = n_utts // 2
189
+ for i, (sex, spk) in enumerate(zip(sexes, spk_ids)):
190
+ if spk in seen_spk:
191
+ continue
192
+ if sex == "M" and len(m_idx) < half:
193
+ m_idx.append(i)
194
+ seen_spk.add(spk)
195
+ elif sex == "F" and len(f_idx) < (n_utts - half):
196
+ f_idx.append(i)
197
+ seen_spk.add(spk)
198
+ if len(m_idx) >= half and len(f_idx) >= (n_utts - half):
199
+ break
200
+ indices = m_idx + f_idx
201
+ unique_speakers_by_sex = {"M": len(m_idx), "F": len(f_idx)}
202
+
203
+ sess = ort.InferenceSession(str(onnx_path), providers=["CPUExecutionProvider"])
204
+
205
+ def eval_condition(semitones: float) -> dict[str, Any]:
206
+ trues, ls_raws, ls_cues, rh_preds = [], [], [], []
207
+ by_sex: dict[str, dict[str, list[np.ndarray]]] = {
208
+ "M": {"t": [], "ls": [], "rh": []},
209
+ "F": {"t": [], "ls": [], "rh": []},
210
+ }
211
+ with tempfile.TemporaryDirectory() as td:
212
+ wav_file = Path(td) / "utt.wav"
213
+ for idx in indices:
214
+ au = tbl["audio"][idx].as_py()
215
+ pd = tbl["phonetic_detail"][idx].as_py()
216
+ sex = str(tbl["speaker_sex"][idx].as_py())
217
+ wav, sr = sf.read(io.BytesIO(au["bytes"]), dtype="float32")
218
+ if wav.ndim > 1:
219
+ wav = wav.mean(axis=-1)
220
+ if sr != SAMPLE_RATE:
221
+ g = int(np.gcd(sr, SAMPLE_RATE))
222
+ wav = resample_poly(wav, SAMPLE_RATE // g, sr // g).astype(np.float32)
223
+ y_true = phonetic_detail_to_50hz_labels(pd, len(wav), SAMPLE_RATE)
224
+ n_f = len(y_true)
225
+ if n_f < 10:
226
+ continue
227
+ wav_cond = pitch_shift_preserve_duration(wav, semitones, SAMPLE_RATE)
228
+ raw_p, cue_p = run_lipsync_onnx(sess, wav_cond, n_f)
229
+ trues.append(y_true)
230
+ ls_raws.append(raw_p)
231
+ ls_cues.append(cue_p)
232
+ by_sex[sex]["t"].append(y_true)
233
+ by_sex[sex]["ls"].append(raw_p)
234
+ if rhubarb_bin and rhubarb_bin.exists():
235
+ write_wav_16k(wav_file, wav_cond)
236
+ rp = run_rhubarb_cli(rhubarb_bin, wav_file, n_f)
237
+ rh_preds.append(rp)
238
+ by_sex[sex]["rh"].append(rp)
239
+
240
+ out: dict[str, Any] = {
241
+ "n_utterances": len(trues),
242
+ "lipsync_2d_raw": evaluate_predictions(
243
+ np.concatenate(trues), np.concatenate(ls_raws), r9_true_seqs=trues, r9_pred_seqs=ls_raws
244
+ ),
245
+ "lipsync_2d_viterbi": evaluate_predictions(
246
+ np.concatenate(trues), np.concatenate(ls_cues), r9_true_seqs=trues, r9_pred_seqs=ls_cues
247
+ ),
248
+ "lipsync_2d_by_sex_macro_f1": {
249
+ s: evaluate_predictions(np.concatenate(d["t"]), np.concatenate(d["ls"]))["rhubarb9_macro_f1"]
250
+ for s, d in by_sex.items() if d["t"]
251
+ },
252
+ }
253
+ if rh_preds:
254
+ out["rhubarb_v1_14_phonetic"] = evaluate_predictions(
255
+ np.concatenate(trues), np.concatenate(rh_preds), r9_true_seqs=trues, r9_pred_seqs=rh_preds
256
+ )
257
+ out["rhubarb_by_sex_macro_f1"] = {
258
+ s: evaluate_predictions(np.concatenate(d["t"]), np.concatenate(d["rh"]))["rhubarb9_macro_f1"]
259
+ for s, d in by_sex.items() if d["rh"]
260
+ }
261
+ return out
262
+
263
+ report: dict[str, Any] = {
264
+ "dataset": "kylelovesllms/timit_asr (official test split, human hand-annotated 61-phone timestamps)",
265
+ "model": str(onnx_path.name),
266
+ "n_unique_speakers": len(m_idx) + len(f_idx),
267
+ "unique_speakers_by_sex": unique_speakers_by_sex,
268
+ "normal_0st": eval_condition(0.0),
269
+ "high_pitch_plus4st": eval_condition(4.0),
270
+ }
271
+ # Compute +4st relative drops
272
+ for key in ("lipsync_2d_raw", "lipsync_2d_viterbi", "rhubarb_v1_14_phonetic"):
273
+ if key in report["normal_0st"] and key in report["high_pitch_plus4st"]:
274
+ f0 = report["normal_0st"][key]["rhubarb9_macro_f1"]
275
+ f4 = report["high_pitch_plus4st"][key]["rhubarb9_macro_f1"]
276
+ report[f"{key}_plus4st_rel_drop_pct"] = round((f0 - f4) / max(f0, 1e-8) * 100.0, 2)
277
+
278
+ if output_json:
279
+ output_json.parent.mkdir(parents=True, exist_ok=True)
280
+ output_json.write_text(json.dumps(report, indent=2), encoding="utf-8")
281
+ return report
282
+
283
+
284
+ def main() -> None:
285
+ parser = argparse.ArgumentParser(description="Benchmark lipsync-2d vs Rhubarb CLI on human-labeled TIMIT.")
286
+ parser.add_argument("--onnx", type=Path, required=True)
287
+ parser.add_argument("--rhubarb", type=Path, default=None)
288
+ parser.add_argument("--n-utts", type=int, default=90)
289
+ parser.add_argument("--out", type=Path, default=None)
290
+ args = parser.parse_args()
291
+ rep = benchmark_timit(args.onnx, args.rhubarb, args.n_utts, args.out)
292
+ print(json.dumps({
293
+ "normal_ls_raw": rep["normal_0st"]["lipsync_2d_raw"]["rhubarb9_macro_f1"],
294
+ "normal_ls_vit": rep["normal_0st"]["lipsync_2d_viterbi"]["rhubarb9_macro_f1"],
295
+ "normal_rhubarb": rep["normal_0st"].get("rhubarb_v1_14_phonetic", {}).get("rhubarb9_macro_f1"),
296
+ "normal_ls_A": rep["normal_0st"]["lipsync_2d_raw"]["bilabial_A_f1"],
297
+ "normal_rh_A": rep["normal_0st"].get("rhubarb_v1_14_phonetic", {}).get("bilabial_A_f1"),
298
+ "normal_ls_G": rep["normal_0st"]["lipsync_2d_raw"]["labiodental_G_f1"],
299
+ "normal_rh_G": rep["normal_0st"].get("rhubarb_v1_14_phonetic", {}).get("labiodental_G_f1"),
300
+ "normal_ls_onset_ms": rep["normal_0st"]["lipsync_2d_viterbi"]["boundary_onset_mae_ms"],
301
+ "normal_rh_onset_ms": rep["normal_0st"].get("rhubarb_v1_14_phonetic", {}).get("boundary_onset_mae_ms"),
302
+ "hp4_ls_raw": rep["high_pitch_plus4st"]["lipsync_2d_raw"]["rhubarb9_macro_f1"],
303
+ "hp4_rhubarb": rep["high_pitch_plus4st"].get("rhubarb_v1_14_phonetic", {}).get("rhubarb9_macro_f1"),
304
+ "ls_drop_pct": rep.get("lipsync_2d_raw_plus4st_rel_drop_pct"),
305
+ "rh_drop_pct": rep.get("rhubarb_v1_14_phonetic_plus4st_rel_drop_pct"),
306
+ "ls_by_sex": rep["normal_0st"]["lipsync_2d_by_sex_macro_f1"],
307
+ "rh_by_sex": rep["normal_0st"].get("rhubarb_by_sex_macro_f1"),
308
+ }, indent=2))
309
+
310
+
311
+ if __name__ == "__main__":
312
+ main()
eval/metrics.py ADDED
@@ -0,0 +1,203 @@
1
+ """Objective evaluation metrics for 2D lip-sync models and baselines."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+
11
+ from lipsync_2d.visemes import OCULUS_VISEMES, RHUBARB_SHAPES
12
+
13
+
14
+ def compute_classification_f1(
15
+ y_true: np.ndarray,
16
+ y_pred: np.ndarray,
17
+ class_names: tuple[str, ...],
18
+ ) -> dict[str, Any]:
19
+ """Compute per-class F1, Macro-F1, and Weighted-F1 across present classes."""
20
+ yt = np.asarray(y_true, dtype=np.int64).reshape(-1)
21
+ yp = np.asarray(y_pred, dtype=np.int64).reshape(-1)
22
+ n_classes = len(class_names)
23
+
24
+ per_class: dict[str, float] = {}
25
+ supports = np.zeros(n_classes, dtype=np.float64)
26
+ f1s = np.zeros(n_classes, dtype=np.float64)
27
+
28
+ for idx, name in enumerate(class_names):
29
+ tp = int(np.sum((yt == idx) & (yp == idx)))
30
+ fp = int(np.sum((yt != idx) & (yp == idx)))
31
+ fn = int(np.sum((yt == idx) & (yp != idx)))
32
+ supports[idx] = float(tp + fn)
33
+ denom = 2 * tp + fp + fn
34
+ f1 = (2.0 * tp / denom) if denom > 0 else 0.0
35
+ f1s[idx] = f1
36
+ per_class[name] = round(float(f1), 6)
37
+
38
+ present = supports > 0
39
+ macro_f1 = float(np.mean(f1s[present])) if np.any(present) else 0.0
40
+ total_support = float(np.sum(supports))
41
+ weighted_f1 = float(np.sum(f1s * supports) / total_support) if total_support > 0 else 0.0
42
+ return {
43
+ "macro_f1": round(macro_f1, 6),
44
+ "weighted_f1": round(weighted_f1, 6),
45
+ "per_class_f1": per_class,
46
+ }
47
+
48
+
49
+ def compute_boundary_onset_mae_ms(
50
+ y_true_seq: np.ndarray | list[np.ndarray],
51
+ y_pred_seq: np.ndarray | list[np.ndarray],
52
+ frame_dt: float = 0.02,
53
+ max_match_ms: float = 200.0,
54
+ ) -> float:
55
+ """Compute Mean Absolute Error (ms) of predicted transition onsets against true transitions."""
56
+ seqs_true = [y_true_seq] if isinstance(y_true_seq, np.ndarray) and y_true_seq.ndim == 1 else list(y_true_seq)
57
+ seqs_pred = [y_pred_seq] if isinstance(y_pred_seq, np.ndarray) and y_pred_seq.ndim == 1 else list(y_pred_seq)
58
+
59
+ max_frames = int(round((max_match_ms / 1000.0) / frame_dt))
60
+ errors_ms: list[float] = []
61
+
62
+ for yt, yp in zip(seqs_true, seqs_pred):
63
+ yt_arr = np.asarray(yt, dtype=np.int64)
64
+ yp_arr = np.asarray(yp, dtype=np.int64)
65
+ if yt_arr.size < 2 or yp_arr.size < 2:
66
+ continue
67
+ true_onsets = np.where(yt_arr[1:] != yt_arr[:-1])[0] + 1
68
+ pred_onsets = np.where(yp_arr[1:] != yp_arr[:-1])[0] + 1
69
+ if true_onsets.size == 0:
70
+ continue
71
+ if pred_onsets.size == 0:
72
+ errors_ms.extend([max_match_ms] * int(true_onsets.size))
73
+ continue
74
+
75
+ for t_idx in true_onsets:
76
+ dist = int(np.min(np.abs(pred_onsets - t_idx)))
77
+ err_frames = min(dist, max_frames)
78
+ errors_ms.append(err_frames * frame_dt * 1000.0)
79
+
80
+ if not errors_ms:
81
+ return 0.0
82
+ return round(float(np.mean(errors_ms)), 4)
83
+
84
+
85
+ def compute_silence_false_positive_rate_pct(
86
+ y_true: np.ndarray,
87
+ y_pred: np.ndarray,
88
+ silence_idx: int = 0,
89
+ ) -> float:
90
+ """Return percentage of true silence frames predicted as non-silence (jaw flap rate)."""
91
+ yt = np.asarray(y_true, dtype=np.int64).reshape(-1)
92
+ yp = np.asarray(y_pred, dtype=np.int64).reshape(-1)
93
+ sil_mask = yt == silence_idx
94
+ total_sil = int(np.sum(sil_mask))
95
+ if total_sil == 0:
96
+ return 0.0
97
+ fp = int(np.sum(sil_mask & (yp != silence_idx)))
98
+ return round(100.0 * fp / total_sil, 4)
99
+
100
+
101
+ def compute_high_pitch_relative_drop_pct(
102
+ base_macro_f1: float,
103
+ high_pitch_macro_f1: float,
104
+ ) -> float:
105
+ """Compute relative macro-F1 drop (%) at +4 semitones."""
106
+ if base_macro_f1 <= 1e-8:
107
+ return 0.0
108
+ drop = (base_macro_f1 - high_pitch_macro_f1) / base_macro_f1 * 100.0
109
+ return round(float(drop), 4)
110
+
111
+
112
+ def evaluate_predictions(
113
+ r9_true: np.ndarray,
114
+ r9_pred: np.ndarray,
115
+ v15_true: np.ndarray | None = None,
116
+ v15_pred: np.ndarray | None = None,
117
+ r9_true_seqs: list[np.ndarray] | None = None,
118
+ r9_pred_seqs: list[np.ndarray] | None = None,
119
+ r9_high_pitch_true: np.ndarray | None = None,
120
+ r9_high_pitch_pred: np.ndarray | None = None,
121
+ frame_dt: float = 0.02,
122
+ ) -> dict[str, Any]:
123
+ """Compute complete evaluation dictionary for Rhubarb-9 and Oculus-15 predictions."""
124
+ r9_stats = compute_classification_f1(r9_true, r9_pred, RHUBARB_SHAPES)
125
+ report: dict[str, Any] = {
126
+ "rhubarb9_macro_f1": r9_stats["macro_f1"],
127
+ "rhubarb9_weighted_f1": r9_stats["weighted_f1"],
128
+ "rhubarb9_per_class_f1": r9_stats["per_class_f1"],
129
+ "bilabial_A_f1": r9_stats["per_class_f1"]["A"],
130
+ "labiodental_G_f1": r9_stats["per_class_f1"]["G"],
131
+ "silence_fp_jaw_flap_pct": compute_silence_false_positive_rate_pct(r9_true, r9_pred, silence_idx=0),
132
+ }
133
+
134
+ if v15_true is not None and v15_pred is not None:
135
+ v15_stats = compute_classification_f1(v15_true, v15_pred, OCULUS_VISEMES)
136
+ report["viseme15_macro_f1"] = v15_stats["macro_f1"]
137
+ report["viseme15_weighted_f1"] = v15_stats["weighted_f1"]
138
+ report["viseme15_per_class_f1"] = v15_stats["per_class_f1"]
139
+ report["bilabial_PP_f1"] = v15_stats["per_class_f1"]["PP"]
140
+ report["labiodental_FF_f1"] = v15_stats["per_class_f1"]["FF"]
141
+
142
+ if r9_true_seqs is not None and r9_pred_seqs is not None:
143
+ report["boundary_onset_mae_ms"] = compute_boundary_onset_mae_ms(
144
+ r9_true_seqs, r9_pred_seqs, frame_dt=frame_dt
145
+ )
146
+ else:
147
+ report["boundary_onset_mae_ms"] = compute_boundary_onset_mae_ms(
148
+ r9_true, r9_pred, frame_dt=frame_dt
149
+ )
150
+
151
+ if r9_high_pitch_true is not None and r9_high_pitch_pred is not None:
152
+ hp_stats = compute_classification_f1(r9_high_pitch_true, r9_high_pitch_pred, RHUBARB_SHAPES)
153
+ report["high_pitch_rhubarb9_macro_f1"] = hp_stats["macro_f1"]
154
+ report["high_pitch_relative_f1_drop_pct"] = compute_high_pitch_relative_drop_pct(
155
+ r9_stats["macro_f1"], hp_stats["macro_f1"]
156
+ )
157
+
158
+ return report
159
+
160
+
161
+ def benchmark_onnx_model(
162
+ onnx_path: str | Path,
163
+ streaming: bool = False,
164
+ n_warmup: int = 5,
165
+ n_iters: int = 50,
166
+ n_50hz_frames: int = 50,
167
+ ) -> dict[str, float]:
168
+ """Measure ONNX file size (MB) and inference latency (ms per 20 ms frame)."""
169
+ import onnxruntime as ort
170
+
171
+ path = Path(onnx_path)
172
+ size_mb = round(path.stat().st_size / (1024.0 * 1024.0), 4)
173
+ session = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])
174
+
175
+ if streaming:
176
+ inputs_by_name = {inp.name: inp.shape for inp in session.get_inputs()}
177
+ mel_chunk = np.random.randn(1, 2, 80).astype(np.float32)
178
+ h_shape = tuple(int(d) if isinstance(d, int) and d > 0 else 1 for d in inputs_by_name.get("h_in", [1, 1, 1]))
179
+ c_shape = tuple(
180
+ int(d) if isinstance(d, int) and d > 0 else 1 for d in inputs_by_name.get("conv_cache_in", [1, 288, 248])
181
+ )
182
+ h_in = np.zeros(h_shape, dtype=np.float32)
183
+ conv_cache = np.zeros(c_shape, dtype=np.float32)
184
+ feed = {"mel_chunk": mel_chunk, "h_in": h_in, "conv_cache_in": conv_cache}
185
+ frames_per_call = 1
186
+ else:
187
+ mel = np.random.randn(1, n_50hz_frames * 2, 80).astype(np.float32)
188
+ feed = {"mel": mel}
189
+ frames_per_call = n_50hz_frames
190
+
191
+ for _ in range(n_warmup):
192
+ session.run(None, feed)
193
+
194
+ start = time.perf_counter()
195
+ for _ in range(n_iters):
196
+ session.run(None, feed)
197
+ elapsed_ms = (time.perf_counter() - start) * 1000.0
198
+ ms_per_frame = elapsed_ms / (n_iters * frames_per_call)
199
+
200
+ return {
201
+ "onnx_size_mb": size_mb,
202
+ "ms_per_20ms_frame": round(float(ms_per_frame), 4),
203
+ }
eval/mfcc_baseline.py ADDED
@@ -0,0 +1,72 @@
1
+ """uLipSync-style MFCC centroid/prototype baseline classifier."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ from scipy.fft import dct
7
+
8
+
9
+ def log_mel_to_mfcc_50hz(log_mel_10ms: np.ndarray, n_mfcc: int = 16) -> np.ndarray:
10
+ """Convert [T_10ms, 80] Log-Mel frames to 50 Hz [T_50hz, n_mfcc + 1] MFCC+energy features."""
11
+ mel = np.asarray(log_mel_10ms, dtype=np.float32)
12
+ t_even = (mel.shape[0] // 2) * 2
13
+ if t_even == 0:
14
+ return np.zeros((0, n_mfcc + 1), dtype=np.float32)
15
+
16
+ # Average consecutive 10 ms frames into 20 ms (50 Hz) frames before DCT-II.
17
+ mel_50 = mel[:t_even].reshape(t_even // 2, 2, mel.shape[1]).mean(axis=1)
18
+ mfcc = dct(mel_50, type=2, axis=-1, norm="ortho")[:, :n_mfcc]
19
+ energy = mel_50.mean(axis=-1, keepdims=True)
20
+ return np.concatenate([mfcc, energy], axis=-1).astype(np.float32)
21
+
22
+
23
+ class MFCCBaseline:
24
+ """uLipSync-style L2/cosine prototype centroid classifier on 50 Hz MFCC profiles."""
25
+
26
+ def __init__(self, n_classes: int, n_mfcc: int = 16, temperature: float = 0.25) -> None:
27
+ self.n_classes = n_classes
28
+ self.n_mfcc = n_mfcc
29
+ self.temperature = temperature
30
+ self.centroids_: np.ndarray | None = None
31
+ self.class_present_: np.ndarray | None = None
32
+
33
+ @staticmethod
34
+ def _normalize_rows(x: np.ndarray) -> np.ndarray:
35
+ norms = np.linalg.norm(x, axis=-1, keepdims=True)
36
+ return x / np.maximum(norms, 1e-8)
37
+
38
+ def fit(self, features_50hz: np.ndarray, labels_50hz: np.ndarray) -> "MFCCBaseline":
39
+ """Compute normalized per-class MFCC centroids from [N, D] features and [N] labels."""
40
+ feats = np.asarray(features_50hz, dtype=np.float32)
41
+ labels = np.asarray(labels_50hz, dtype=np.int64)
42
+ normed = self._normalize_rows(feats)
43
+ dim = normed.shape[1]
44
+
45
+ centroids = np.zeros((self.n_classes, dim), dtype=np.float32)
46
+ present = np.zeros(self.n_classes, dtype=bool)
47
+ for c in range(self.n_classes):
48
+ mask = labels == c
49
+ if np.any(mask):
50
+ mean_vec = normed[mask].mean(axis=0)
51
+ norm = np.linalg.norm(mean_vec)
52
+ if norm > 1e-8:
53
+ centroids[c] = mean_vec / norm
54
+ present[c] = True
55
+ self.centroids_ = centroids
56
+ self.class_present_ = present
57
+ return self
58
+
59
+ def predict_proba(self, features_50hz: np.ndarray) -> np.ndarray:
60
+ """Return softmax probabilities [N, n_classes] from cosine similarity to centroids."""
61
+ if self.centroids_ is None or self.class_present_ is None:
62
+ raise RuntimeError("MFCCBaseline must be fit before calling predict_proba")
63
+ feats = self._normalize_rows(np.asarray(features_50hz, dtype=np.float32))
64
+ logits = (feats @ self.centroids_.T) / self.temperature
65
+ logits[:, ~self.class_present_] = -1e9
66
+ logits -= np.max(logits, axis=-1, keepdims=True)
67
+ exp = np.exp(logits)
68
+ return (exp / np.sum(exp, axis=-1, keepdims=True)).astype(np.float32)
69
+
70
+ def predict(self, features_50hz: np.ndarray) -> np.ndarray:
71
+ """Return hard class predictions [N]."""
72
+ return np.argmax(self.predict_proba(features_50hz), axis=-1)