#!/usr/bin/env python3 """aligner_bench — which forced aligner should score Thai TTS pauses? A SELF-CONTAINED benchmark (one file + one asset bundle, no other project code) that answers two questions about a candidate forced aligner on Thai TTS audio: 1. DELAY / TIMING — how far off are its boundaries? Measured against the TTS model's OWN duration predictor (`pred_dur`), which is ground truth by construction: the vocoder rendered exactly those frame counts, so the token boundaries in the audio ARE the pred_dur boundaries. Reported as onset error percentiles, signed bias, jitter (bias-removed spread) and duration error. 2. PAUSE ACCURACY — does the downstream pause metric still work through it? Silences are detected in the audio, attributed to a text juncture via the aligner's char timings, and classified ok / bad_juncture / intra_word / unaligned. The same clips scored through `pred_dur` give the reference, so every arm is also reported as AGREEMENT with ground truth (per-clip count correlation, clip-verdict agreement, per-speaker precision correlation, bad-juncture overlap). Three aligners ship, all behind `--aligner`: ctc airesearch/wav2vec2-large-xlsr-53-th Thai char CTC, 50 fps (default) mms torchaudio.pipelines.MMS_FA multilingual phone aligner qwen Qwen/Qwen3-ASR-1.7B-hf + a Thai char timestamp head, 26 fps (`--ctc-head-repo`; the head architecture is inferred from its weights, so a new head loads without code changes — this is the slot to try your own aligner in) Adding a fourth: write a `_char_spans(wav, sr, item, bundle) -> [(char_idx, t0_ms, t1_ms)]` and register it in ALIGNERS. Everything downstream is shared. -------------------------------------------------------------------------------- QUICK START (the bundle ships wavs + frozen ground truth; no Thai NLP needed) pip install numpy soundfile torch torchaudio transformers python aligner_bench.py run --bundle bundle --aligner ctc --out out/ctc python aligner_bench.py run --bundle bundle --aligner mms --out out/mms python aligner_bench.py report out/ctc out/mms `run` = `align` (GPU, writes char spans) + `score` (CPU, writes metrics.json). Run them separately if you want to re-score without re-aligning. The `qwen` arm needs transformers>=5.13 and an HF token for the head repo: pip install --no-deps --target=/tmp/tf514 transformers==5.14.1 PYTHONPATH=/tmp/tf514 HF_TOKEN=... python aligner_bench.py run \ --bundle bundle --aligner qwen --ctc-head-repo Warit/ctc-head-v2 --out out/qwen -------------------------------------------------------------------------------- BUNDLE FORMAT (built by `export`, which is the only subcommand that needs the original project — a recipient never runs it) bundle/ items.jsonl one JSON per clip, see `export_bundle` for the schema audio/.flac 24 kHz mono, lossless (the source wavs were PCM_16) README.md Each item carries the frozen ground truth so the benchmark needs no Thai tokenizer, G2P or TTS model at run time: text the normalized text that was actually spoken (all char indices, gold marks and word spans live in THIS coordinate space) gold pause mask, '|' = a break here is allowed (hand-calibrated) pred_dur per-token frame counts from the TTS duration predictor (25 ms/frame) align phonemes + syllable units + words + index maps (ground-truth path) word_spans {"tltk": …, "newmm": …} — two segmentations, `--word-seg` picks one -------------------------------------------------------------------------------- READING THE OUTPUT * Precision is precision-side ONLY: the masks carry no "a break is required here" marks, so never pausing scores 1.000. Always read `pause_precision` next to `pauses_per_clip`. * `per_speaker_precision_r` is the metric that matters most for a benchmark instrument — it is whether the aligner RANKS voices the way ground truth does. An aligner can hold aggregate precision and still be useless here. * Onset error is measured on synthetic (vocoder) audio, which is out of domain for aligners trained on natural speech. That is the point — it is the audio the metric has to work on — but it is not a claim about natural speech. """ from __future__ import annotations import argparse import bisect import json import os import sys import time import unicodedata from dataclasses import dataclass, field from pathlib import Path from types import SimpleNamespace import numpy as np # --------------------------------------------------------------------------- # §1 Constants: frame grids, silence thresholds, break rules # --------------------------------------------------------------------------- SR = 24000 # The DURATION grid. One pred_dur unit = one acoustic frame = 600 samples @ 24 kHz # = 25 ms. `sum(pred_dur) * 600 == len(audio)` exactly, so this grid fully # determines output length — which is why it is usable as timing ground truth. SAMPLES_PER_DUR_FRAME = 600 DUR_FRAME_MS = 1000.0 * SAMPLES_PER_DUR_FRAME / SR # 25.0 # The ANALYSIS grid used by detect_silences hops by 300 samples = 12.5 ms, i.e. # two analysis frames per duration frame, so a measured silence lands on duration # frame boundaries and can be attributed to a token span without interpolation. # -35 dBFS floor and an 80 ms minimum, calibrated on human clean/bad judgements. # A silence whose neighbouring phone is an ORAL stop (p t k c b d / ก ต ป ท …) is # usually that stop's closure rather than a pause, so those need stop_min_pause_ms. # Glottal ʔ is deliberately NOT guarded: Thai vowel-initial words get ʔ-epenthesis # and a silence there (และ-อาหาร) is prosodic, not articulatory. THRESHOLDS = dict(silence_db=-35.0, min_pause_ms=80.0, stop_min_pause_ms=120.0) # oral-stop onsets in the two alphabets the two paths work in (IPA / Thai script) _STOP_IPA = set("ptkcbd") _STOP_THAI = set("กขคฆจฉชฌฎฏฐฑฒดตถทธบปผพภ") # a within-unit silence reaching this close to the unit's edge is attributed to # the adjacent juncture (phrase-final silence booked into the last token) TAIL_TOL_MS = 60.0 # one char span this long that fully swallows a detected silence marks a local # alignment failure (real Thai chars run far shorter) -> UNALIGNED LONG_CHAR_SPAN_MS = 500.0 # Stop-closure context width for the char path, in Thai chars either side of the # juncture. The ground-truth path asks whether an oral stop sits within ±1 PHONE # of the silence; one phone spells as 1-3 chars (preposed vowels เแโใไ, tone # marks, clusters), so 3 is the orthographic equivalent. STOP_CTX_CHARS = 3 # Words a pause may occur BEFORE (they attach rightward, so a pause AFTER them is # an error — the flagship …และ-อาหารอร่อย failure). Frozen list. BREAK_BEFORE_WORDS = [ "และ", "หรือ", "แต่", "ที่", "ซึ่ง", "เพราะ", "เมื่อ", "ถ้า", "หาก", "โดย", "จึง", "เพื่อ", "แล้ว", "ก็", "แล้วก็", "ส่วน", "รวมทั้ง", "ตลอดจน", ] PAUSE_OK, BAD_JUNCTURE, INTRA_WORD, INTRA_SYL, UNALIGNED = ( "ok", "bad_juncture", "intra_word", "intra_syl", "unaligned") BAD_CLASSES = {BAD_JUNCTURE, INTRA_WORD, INTRA_SYL} MARK_ALLOWED, MARK_EXPECTED = "|", "‖" def parse_gold(mask: str) -> tuple[str, set, set]: """'ประเทศไทย|มี…' -> (text, allowed_offsets, expected_offsets).""" text, allowed, expected = [], set(), set() for ch in mask: if ch == MARK_ALLOWED: allowed.add(len(text)) elif ch == MARK_EXPECTED: allowed.add(len(text)) expected.add(len(text)) else: text.append(ch) return "".join(text), allowed, expected # --------------------------------------------------------------------------- # §2 Silence detection (audio side — shared by every arm, including the reference) # --------------------------------------------------------------------------- @dataclass class Silence: f0: int # frame span [f0, f1) on the analysis hop grid f1: int t0_ms: float t1_ms: float dur_ms: float mean_db: float def frame_db(wav: np.ndarray, sr: int = SR, *, hop: int | None = None, win: int | None = None): """Per-frame dBFS on the analysis hop grid, plus the frame step in ms.""" wav = np.asarray(wav, dtype=np.float32) if wav.ndim > 1: wav = wav.mean(1) hop = hop or max(1, round(sr * 0.0125)) win = win or 4 * hop n = len(wav) // hop if n < 3: return np.zeros(0), 1000.0 * hop / sr pad = (win - hop) // 2 x = np.pad(wav, (pad, pad), mode="reflect") cs = np.concatenate([[0.0], np.cumsum(x.astype(np.float64) ** 2)]) starts = np.arange(n) * hop rms = np.sqrt((cs[starts + win] - cs[starts]) / win) return 20.0 * np.log10(rms + 1e-9), 1000.0 * hop / sr def detect_silences(wav: np.ndarray, sr: int = SR, *, silence_db: float = THRESHOLDS["silence_db"], min_ms: float = THRESHOLDS["min_pause_ms"]) -> list: """Internal silences >= min_ms below silence_db. Leading/trailing silence is dropped (a clip's onset lag and final fade are not pauses).""" db, frame_ms = frame_db(wav, sr) n = len(db) if n < 3: return [] silent = db < silence_db min_frames = max(1, int(round(min_ms / frame_ms))) out, i = [], 0 while i < n: if not silent[i]: i += 1 continue j = i while j < n and silent[j]: j += 1 if (j - i) >= min_frames and i > 0 and j < n: # drop edge runs out.append(Silence(f0=i, f1=j, t0_ms=i * frame_ms, t1_ms=j * frame_ms, dur_ms=(j - i) * frame_ms, mean_db=float(db[i:j].mean()))) i = j return out # --------------------------------------------------------------------------- # §3 Ground-truth alignment structures (frozen in the bundle, no G2P needed) # --------------------------------------------------------------------------- @dataclass class Unit: """Smallest aligned span: one syllable chunk / English word / punct char.""" ph_a: int = -1 # [ph_a, ph_b) in the phoneme string (-1 = emitted nothing) ph_b: int = -1 ch_a: int = -1 # [ch_a, ch_b) in text ch_b: int = -1 kind: str = "syl" # 'syl' | 'en' | 'punct' word: int = -1 # index into words; -1 for punct @dataclass class Word: ch_a: int ch_b: int surface: str units: list = field(default_factory=list) @dataclass class Align: text_norm: str phonemes: str units: list # list[Unit] words: list # list[Word] ph2unit: list # per phoneme char: unit index or -1 (spaces) tok2ph: list # model-token index (unpadded) -> phoneme char index @property def n_tokens(self) -> int: return len(self.tok2ph) @staticmethod def from_dict(d: dict) -> "Align": return Align(text_norm=d["text_norm"], phonemes=d["phonemes"], units=[Unit(**u) for u in d["units"]], words=[Word(**w) for w in d["words"]], ph2unit=d["ph2unit"], tok2ph=d["tok2ph"]) def load_bundle(bundle: Path, limit: int = 0, speakers: str = "") -> list[dict]: """Read items.jsonl and resolve each item's audio path.""" bundle = Path(bundle) items = [json.loads(l) for l in open(bundle / "items.jsonl", encoding="utf-8") if l.strip()] if speakers: keep = {s.strip() for s in speakers.split(",") if s.strip()} items = [it for it in items if it["speaker"] in keep or it["speaker"].split("_")[0] in keep] if limit: items = items[:limit] for it in items: it["audio_path"] = str(bundle / it["audio"]) return items def read_audio(path: str): import soundfile as sf wav, sr = sf.read(path) wav = np.asarray(wav, dtype=np.float32) if wav.ndim > 1: wav = wav.mean(1) return wav, sr # --------------------------------------------------------------------------- # §4 Aligners. Contract: (wav, sr, item, bundle) -> [(char_idx, t0_ms, t1_ms)] # over item["text"], time-monotonic. Add yours here. # --------------------------------------------------------------------------- CTC_MODEL = "airesearch/wav2vec2-large-xlsr-53-th" # --- ctc: Thai char CTC (the default, and the incumbent to beat) --------------- def ctc_bundle(device: str, **_): import torch from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor proc = Wav2Vec2Processor.from_pretrained(CTC_MODEL) model = Wav2Vec2ForCTC.from_pretrained(CTC_MODEL).to(device).eval() return SimpleNamespace(proc=proc, model=model, device=device, torch=torch, tag="ctc:" + CTC_MODEL.split("/")[-1], batched=True) def _ctc_targets(text: str, tokenizer): vocab = tokenizer.get_vocab() delim = getattr(tokenizer, "word_delimiter_token", "|") ids, char_idx = [], [] for i, ch in enumerate(text): key = delim if ch == " " else ch if key in vocab: ids.append(vocab[key]) char_idx.append(i) return ids, char_idx def _merge_ctc_groups(labels: list, blank: int, n_targets: int) -> list: """Frame labels from forced_align -> one [f0, f1) group per target.""" groups, prev = [], blank for f, lab in enumerate(labels): if lab != blank and (prev == blank or lab != prev): groups.append([f, f + 1]) elif lab != blank: groups[-1][1] = f + 1 prev = lab if len(groups) != n_targets: raise RuntimeError(f"CTC merge produced {len(groups)} spans " f"for {n_targets} targets") return groups def _ctc_spans(emissions, ids, char_idx, dur_s, blank, torch): """Forced alignment over precomputed emissions (T, C) -> char spans.""" import torchaudio.functional as AF labels, _ = AF.forced_align(emissions.unsqueeze(0), torch.tensor([ids], dtype=torch.int32), blank=blank) groups = _merge_ctc_groups(labels[0].tolist(), blank, len(ids)) ms = dur_s / emissions.shape[0] * 1000.0 return [(char_idx[k], g[0] * ms, g[1] * ms) for k, g in enumerate(groups)] def ctc_char_spans(wav, sr, item, b): """Single-clip path. `align` uses the batched path below for speed; both produce identical spans because both pass an explicit length mask.""" torch = b.torch import torchaudio.functional as AF x = torch.from_numpy(np.asarray(wav, dtype=np.float32)) if sr != 16000: x = AF.resample(x, sr, 16000) ids, char_idx = _ctc_targets(item["text"], b.proc.tokenizer) if not ids: return [] with torch.no_grad(): feats = b.proc(x.numpy(), sampling_rate=16000, return_tensors="pt").input_values.to(b.device) logits = b.model(feats).logits.cpu() em = torch.log_softmax(logits.float(), dim=-1)[0] return _ctc_spans(em, ids, char_idx, len(x) / 16000.0, b.proc.tokenizer.pad_token_id or 0, torch) def ctc_batch_spans(batch: list, b) -> list: """Batched CTC — the fast path. THE PADDING MASK IS LOAD-BEARING: this checkpoint ships `return_attention_mask: false`, but it is feat_extract_norm='layer' (trained WITH masking). Without a mask every clip in a padded batch gets its whole char timeline scaled by len/batch_max — a drift that reached −1670 ms by the end of a 7.5 s clip when it was live, and silently destroyed every downstream number. Build the mask from raw lengths. Any new batched aligner needs the same care.""" import torchaudio.functional as AF torch = b.torch arrays, metas = [], [] for it, wav, sr in batch: x = torch.from_numpy(np.asarray(wav, dtype=np.float32)) if sr != 16000: x = AF.resample(x, sr, 16000) ids, char_idx = _ctc_targets(it["text"], b.proc.tokenizer) if ids: arrays.append(x.numpy()) metas.append((it, ids, char_idx, len(x) / 16000.0)) if not arrays: return [] with torch.no_grad(): feats = b.proc(arrays, sampling_rate=16000, return_tensors="pt", padding=True) mask = feats.get("attention_mask") if mask is None: in_lens = torch.tensor([len(a) for a in arrays]) mask = (torch.arange(feats.input_values.shape[1])[None, :] < in_lens[:, None]).long() logits = b.model(feats.input_values.to(b.device), attention_mask=mask.to(b.device)).logits.cpu().float() lens = b.model._get_feat_extract_output_lengths(mask.sum(-1)).tolist() blank = b.proc.tokenizer.pad_token_id or 0 out = [] for k, (it, ids, char_idx, dur_s) in enumerate(metas): em = torch.log_softmax(logits[k, :int(lens[k])], dim=-1) out.append((it, _ctc_spans(em, ids, char_idx, dur_s, blank, torch))) return out # --- mms: generic multilingual phone aligner ---------------------------------- # MMS labels are ROMANIZED latin, so the bundle's IPA is mapped onto them rather # than pulling in `uroman`. Lossy by construction: vowel length and tone are # dropped and ɛ/e, ɔ/o, ɯ/ɤ/u collapse — which is most of why it loses on Thai. IPA_TO_MMS_ROMAN = {"ʰ": "h", "ŋ": "ng", "ɛ": "e", "ɔ": "o", "ɯ": "u", "ɤ": "e", "ʔ": "'", "j": "y", "c": "ch"} _IPA_TONES = set("˩˨˧˦˥→↓↗↘↑") def _romanize_ipa(phonemes: str) -> tuple[str, list]: """IPA -> MMS roman labels. Returns (roman, roman_idx -> phoneme_idx).""" out, back, i = [], [], 0 while i < len(phonemes): ch = phonemes[i] if ch.isdigit() or ch in _IPA_TONES or ch in ".+ː": i += 1 continue r = IPA_TO_MMS_ROMAN.get(ch, ch if (ch.isalpha() and ch.isascii()) else "") if ch == "c" and i + 1 < len(phonemes) and phonemes[i + 1] == "ʰ": i += 1 # cʰ is a single 'ch', not 'ch'+'h' for c in r: out.append(c) back.append(i) i += 1 return "".join(out), back def mms_bundle(device: str, **_): import torch from torchaudio.pipelines import MMS_FA return SimpleNamespace(model=MMS_FA.get_model().to(device).eval(), lex=MMS_FA.get_dict(), device=device, torch=torch, tag="mms:MMS_FA", batched=False) def mms_char_spans(wav, sr, item, b): """Phone-level alignment returned in the SAME char-span contract, so the whole scoring path is shared. Phone spans map back to text chars through the bundle's `units`; each unit is spread evenly over its own chars (the unit, not the char, is the aligned atom — spreading only keeps granularity comparable with the char-CTC path).""" import torchaudio.functional as AF torch = b.torch align = item["_align"] roman, back = _romanize_ipa(align.phonemes) ids = [b.lex[c] for c in roman if c in b.lex] keep = [k for c, k in zip(roman, back) if c in b.lex] if not ids: return [] x = torch.from_numpy(np.asarray(wav, dtype=np.float32)) if sr != 16000: x = AF.resample(x, sr, 16000) with torch.no_grad(): em, _ = b.model(x.unsqueeze(0).to(b.device)) em = torch.log_softmax(em, dim=-1).cpu() labels, _ = AF.forced_align(em, torch.tensor([ids], dtype=torch.int32), blank=0) groups = _merge_ctc_groups(labels[0].tolist(), 0, len(ids)) ms = (len(x) / 16000.0) / em.shape[1] * 1000.0 on, off = {}, {} for k, (s, e) in enumerate(groups): pi = keep[k] on.setdefault(pi, s * ms) off[pi] = e * ms spans = [] for u in align.units: if u.ph_a < 0: continue a = next((on[i] for i in range(u.ph_a, u.ph_b) if i in on), None) c = next((off[i] for i in range(u.ph_b - 1, u.ph_a - 1, -1) if i in off), None) if a is None or c is None: continue n = max(1, u.ch_b - u.ch_a) for k, ci in enumerate(range(u.ch_a, u.ch_b)): spans.append((ci, a + (c - a) * k / n, a + (c - a) * (k + 1) / n)) spans.sort(key=lambda s: s[1]) return spans # --- qwen: frozen Qwen3-ASR encoder + a swappable Thai char timestamp head ----- # The head is a small CTC head riding the frozen encoder (tap: ln_post, 1024-d, # 13 fps; the head upsamples to the output frame rate). This is the arm to clone # if you want to benchmark your own head: the architecture is INFERRED from the # weights, so only `--ctc-head-repo` changes. # # Needs transformers >= 5.13 for `qwen3_asr`. If your environment is older, # side-load rather than upgrade in place: # pip install --no-deps --target=/tmp/tf514 transformers==5.14.1 # PYTHONPATH=/tmp/tf514 python aligner_bench.py run --aligner qwen … QWEN_ASR_MODEL = "Qwen/Qwen3-ASR-1.7B-hf" # the -hf (converted) repo. The raw # `Qwen/Qwen3-ASR-1.7B` repo loads with dozens of MISSING keys under this loader # — a randomly initialised encoder that still runs and produces plausible junk. CTC_HEAD_REPO = os.environ.get("CTC_HEAD_REPO", "Warit/ctc-head-v2") class ThaiCTCHead: """Builds an nn.Module to match a head's state_dict. Width, depth, ffn and vocab are read off the weights, so a head that differs from the reference loads unchanged. The two parameters the weights cannot carry — the ConvTranspose stride (the upsample factor, hence the output frame rate) and the attention head count — come from an optional config.json in the repo. A head whose config implies a shape the weights do not match raises a key/shape diff rather than running silently wrong. """ @staticmethod def from_state_dict(sd, cfg: dict | None = None): import torch.nn as nn cfg = cfg or {} w_up = sd["up.weight"] # ConvTranspose1d (d_in, d, k) d_in, d, kernel = w_up.shape vocab = sd["out.weight"].shape[0] ffn = sd["layers.layers.0.linear1.weight"].shape[0] n_layers = 1 + max(int(k.split(".")[2]) for k in sd if k.startswith("layers.layers.")) n_heads = int(cfg.get("n_heads", 12)) stride = int(cfg.get("up_stride", cfg.get("upsample", 2))) padding = int(cfg.get("up_padding", max(0, (kernel - stride) // 2))) if d % n_heads: raise ValueError(f"head dim {d} not divisible by n_heads {n_heads} — " f"the head repo needs a config.json with the right n_heads") class Head(nn.Module): def __init__(self): super().__init__() self.up = nn.ConvTranspose1d(d_in, d, kernel_size=kernel, stride=stride, padding=padding) layer = nn.TransformerEncoderLayer(d, n_heads, ffn, dropout=0.1, batch_first=True, norm_first=True) self.layers = nn.TransformerEncoder(layer, n_layers) self.ln = nn.LayerNorm(d) self.out = nn.Linear(d, vocab) self.up_factor = stride def forward(self, h): # (B, T, d_in) -> (B, sT, vocab) x = self.up(h.transpose(1, 2)).transpose(1, 2) return self.out(self.ln(self.layers(x))) m = Head() missing, unexpected = m.load_state_dict(sd, strict=False) if missing or unexpected: raise RuntimeError( f"head state_dict does not match the inferred architecture " f"(d_in={d_in} d={d} layers={n_layers} ffn={ffn} vocab={vocab}); " f"missing={list(missing)[:6]} unexpected={list(unexpected)[:6]}. " f"If the repo ships a config.json, its stride/n_heads may differ.") return m def qwen_bundle(device: str, head_repo: str | None = None, **_): import torch from huggingface_hub import hf_hub_download from safetensors.torch import load_file try: from transformers import AutoProcessor, Qwen3ASRForConditionalGeneration except ImportError as e: # < 5.13 has no qwen3_asr raise SystemExit(f"the qwen arm needs transformers>=5.13; side-load it " f"(see the note above QWEN_ASR_MODEL). Original error: {e}") repo = head_repo or CTC_HEAD_REPO token = os.environ.get("HF_TOKEN") proc = AutoProcessor.from_pretrained(QWEN_ASR_MODEL) full = Qwen3ASRForConditionalGeneration.from_pretrained( QWEN_ASR_MODEL, dtype=torch.bfloat16).eval() encoder = full.model.audio_tower.to(device) sd = load_file(hf_hub_download(repo, "head.safetensors", token=token)) cfg = {} try: # optional; some heads ship none cfg = json.loads(Path(hf_hub_download(repo, "config.json", token=token)).read_text()) except Exception: # noqa: BLE001 — no config is fine pass head = ThaiCTCHead.from_state_dict(sd, cfg) symbols = json.loads(Path(hf_hub_download( repo, "ctc_vocab.json", token=token)).read_text())["symbols"] print(f" head {repo}: up_factor={head.up_factor} vocab={len(symbols)}", file=sys.stderr) return SimpleNamespace(proc=proc, encoder=encoder, head=head.eval().to(device), sym2id={s: i for i, s in enumerate(symbols)}, device=device, torch=torch, tag="qwen+" + repo.split("/")[-1], batched=False, sr=proc.feature_extractor.sampling_rate) def qwen_char_spans(wav, sr, item, b): import torchaudio.functional as AF torch = b.torch x = torch.from_numpy(np.asarray(wav, dtype=np.float32)) if sr != b.sr: x = AF.resample(x, sr, b.sr) a = x.numpy() dur_s = len(a) / b.sr ids, char_idx = [], [] for i, ch in enumerate(item["text"]): key = " " if ch.isspace() else ch if key in b.sym2id: ids.append(b.sym2id[key]) char_idx.append(i) if not ids: return [] feats = b.proc.feature_extractor(a, sampling_rate=b.sr, return_tensors="pt", padding="max_length") xf = feats["input_features"].to(b.device).to(torch.bfloat16) # features are padded to 30 s; without a length mask every clip's timeline is # scaled by dur/30 — the same trap as the batched CTC arm above. mask = torch.zeros(1, xf.shape[-1], dtype=torch.bool) mask[0, :int(np.ceil(len(a) / 160))] = True # 10 ms mel hop cap = {} hk = b.encoder.ln_post.register_forward_hook( lambda mo, i, o: cap.__setitem__("h", o)) try: with torch.no_grad(): b.encoder(input_features=xf, input_features_mask=mask.to(b.device)) h = cap["h"] h = h[0] if isinstance(h, tuple) else h if h.dim() == 2: h = h.unsqueeze(0) logits = b.head(h.float()) finally: hk.remove() em = torch.log_softmax(logits, dim=-1).cpu() labels, _ = AF.forced_align(em, torch.tensor([ids], dtype=torch.int32), blank=0) groups = _merge_ctc_groups(labels[0].tolist(), 0, len(ids)) ms = dur_s / em.shape[1] * 1000.0 return [(char_idx[k], g[0] * ms, g[1] * ms) for k, g in enumerate(groups)] ALIGNERS = { "ctc": (ctc_bundle, ctc_char_spans, ctc_batch_spans), "mms": (mms_bundle, mms_char_spans, None), "qwen": (qwen_bundle, qwen_char_spans, None), } # --------------------------------------------------------------------------- # §5 Attribution + classification # --------------------------------------------------------------------------- @dataclass class Pause: t0_ms: float t1_ms: float dur_ms: float ch_offset: int # juncture position in the text (-1 for intra/unaligned) cls: str before: str after: str def allowed_offsets(align: Align, gold_mask: str | None, break_before=None) -> tuple[set, set]: """(allowed, expected) juncture char-offsets for the GROUND-TRUTH path. allowed = rule whitelist (punct positions, post-space word starts, word starts in BREAK_BEFORE_WORDS) ∪ gold-mask marks.""" gold_allowed, expected = set(), set() if gold_mask: text, gold_allowed, expected = parse_gold(gold_mask) if text != align.text_norm: raise ValueError(f"gold mask does not match text: {text[:40]!r}") break_before = set(break_before if break_before is not None else BREAK_BEFORE_WORDS) elems = [(w.ch_a, w.ch_b, w.surface, "word") for w in align.words] elems += [(u.ch_a, u.ch_b, align.text_norm[u.ch_a:u.ch_b], "punct") for u in align.units if u.kind == "punct"] elems.sort() allowed = set() for i, (a, _b, surf, kind) in enumerate(elems): if kind == "punct": allowed.add(a) if i + 1 < len(elems): allowed.add(elems[i + 1][0]) continue if i > 0 and " " in align.text_norm[elems[i - 1][1]:a]: allowed.add(a) if surf in break_before: allowed.add(a) return allowed | gold_allowed, expected def cue_offsets(align: Align) -> set: """Text offsets of the junctures the TTS model could actually see: a space or a punctuation token in the PHONEME string. Strict subset of allowed_offsets. Gives the recall-ish `space_realization` axis the masks cannot.""" ph, p2u, U = align.phonemes, align.ph2unit, align.units n = len(ph) nxt = [-1] * (n + 1) for j in range(n - 1, -1, -1): nxt[j] = U[p2u[j]].ch_a if p2u[j] >= 0 else nxt[j + 1] out = set() for i, c in enumerate(ph): if c == " " and p2u[i] < 0 and nxt[i + 1] >= 0: out.add(nxt[i + 1]) for u in U: if u.kind == "punct": out.add(u.ch_a) if u.ph_b >= 0 and nxt[u.ph_b] >= 0: out.add(nxt[u.ph_b]) return out def _allowed_from_word_spans(text: str, word_spans: list, break_before=None) -> set: """The char path's rule whitelist — the word-span mirror of allowed_offsets.""" break_before = set(break_before if break_before is not None else BREAK_BEFORE_WORDS) allowed = set() for i, (a, _b, surf) in enumerate(word_spans): if not any("฀" <= c <= "๿" or c.isalnum() for c in surf): allowed.add(a) # punctuation token if i + 1 < len(word_spans): allowed.add(word_spans[i + 1][0]) continue if i > 0 and " " in text[word_spans[i - 1][1]:a]: allowed.add(a) if surf in break_before: allowed.add(a) return allowed def _classify_junction(align: Align, ph_b: int, ph_a: int, allowed: set) -> tuple[str, int, str, str]: """Classify the juncture between phoneme chars ph_b (before the silence) and ph_a (after) -> (cls, ch_offset, before_surface, after_surface).""" p2u = align.ph2unit while ph_b >= 0 and p2u[ph_b] < 0: ph_b -= 1 while ph_a < len(p2u) and p2u[ph_a] < 0: ph_a += 1 if ph_b < 0 or ph_a >= len(p2u): return UNALIGNED, -1, "", "" ub, ua = p2u[ph_b], p2u[ph_a] U, W, T = align.units, align.words, align.text_norm def surf(u): return T[U[u].ch_a:U[u].ch_b] if ub == ua: if U[ub].kind == "en": return PAUSE_OK, -1, surf(ub), surf(ub) # letter-spelling gaps return INTRA_SYL, -1, surf(ub), surf(ub) wb, wa = U[ub].word, U[ua].word if wb == wa and wb >= 0: return INTRA_WORD, -1, W[wb].surface, W[wa].surface off = U[ua].ch_a before = W[wb].surface if wb >= 0 else surf(ub) after = W[wa].surface if wa >= 0 else surf(ua) return (PAUSE_OK if off in allowed else BAD_JUNCTURE), off, before, after def attribute_pauses(silences: list, pred_dur, align: Align, allowed: set, stop_min_ms: float = THRESHOLDS["stop_min_pause_ms"]) -> list: """GROUND-TRUTH path: silence times -> token indices via cumsum(pred_dur)*25 ms -> phoneme chars -> juncture. Exact by construction; this is the reference every aligner arm is compared against.""" pred_dur = np.asarray(pred_dur).ravel() bounds_ms = np.cumsum(pred_dur) * DUR_FRAME_MS # len = n_tokens + 2 (pads) n_tok = len(align.tok2ph) def padded_of_time(t_ms: float) -> int: return min(max(int(np.searchsorted(bounds_ms, t_ms, side="right")), 1), n_tok) def ph_of_time(t_ms: float) -> int: return align.tok2ph[padded_of_time(t_ms) - 1] def unit_span_ms(u: int) -> tuple[float, float]: t0 = int(np.searchsorted(align.tok2ph, align.units[u].ph_a, side="left")) t1 = int(np.searchsorted(align.tok2ph, align.units[u].ph_b, side="left")) return float(bounds_ms[t0]), float(bounds_ms[t1]) out = [] for s in silences: ph_b = ph_of_time(s.t0_ms - 1e-3) ph_a = ph_of_time(s.t1_ms + 1e-3) # A short silence next to an oral-stop token is that stop's closure (an # onset closure like ไทย's tʰ, or an unreleased final like กลับ's p̚), not # a prosodic pause. if s.dur_ms < stop_min_ms: lo = max(padded_of_time(s.t0_ms - 1e-3) - 1, 1) hi = min(padded_of_time(s.t1_ms + 1e-3) + 1, n_tok) ctx = {align.phonemes[align.tok2ph[p - 1]] for p in range(lo, hi + 1)} if ctx & _STOP_IPA: continue # Phrase-final pauses are booked into the LAST token of the preceding # phrase (the model stretches its frames into the silence). At utterance # edges the same shape is just final fade — not a pause at all. u_b, u_a = align.ph2unit[ph_b], align.ph2unit[ph_a] if u_b == u_a and u_a >= 0: ua, ub = unit_span_ms(u_a) if ub - s.t1_ms <= TAIL_TOL_MS: nxt = align.units[u_a].ph_b if nxt >= len(align.phonemes): continue ph_a = nxt elif s.t0_ms - ua <= TAIL_TOL_MS: prv = align.units[u_a].ph_a - 1 if prv < 0: continue ph_b = prv cls, off, before, after = _classify_junction(align, ph_b, ph_a, allowed) out.append(Pause(s.t0_ms, s.t1_ms, s.dur_ms, off, cls, before, after)) return out def attribute_pauses_chars(silences: list, char_spans: list, text: str, word_spans: list, allowed: set, stop_min_ms: float = THRESHOLDS["stop_min_pause_ms"]) -> list: """EXTERNAL path: an aligner's char timings instead of pred_dur. char_spans = [(char_idx, t0_ms, t1_ms)]; word_spans = [(a, b, surface)]. Attribution is NEAREST-BOUNDARY, not containment: forced-alignment emissions are peaky and their char spans routinely overlap real silences, so requiring a silence to fall cleanly between two spans marks most pauses unattributable (it once produced 64% UNALIGNED). Split the time-monotonic spans at the silence midpoint, then snap to a word boundary within the jitter tolerance. UNALIGNED is reserved for a silence swallowed whole by one implausibly long char span — the aligner lost lock locally.""" out = [] if not char_spans or not word_spans: return [Pause(s.t0_ms, s.t1_ms, s.dur_ms, -1, UNALIGNED, "", "") for s in silences] spans = char_spans mids = [(c[1] + c[2]) / 2.0 for c in spans] starts = [a for a, _, _ in word_spans] ends = [b for _, b, _ in word_spans] word_starts = set(starts) for s in silences: # juncture j sits between spans[j-1] and spans[j]; valid j in [1, n-1] k0 = bisect.bisect_right(mids, (s.t0_ms + s.t1_ms) / 2.0) if k0 <= 0 or k0 >= len(spans): continue # edge silence: onset lag / final fade, not a pause if any(c[1] <= s.t0_ms and c[2] >= s.t1_ms and (c[2] - c[1]) > LONG_CHAR_SPAN_MS for c in (spans[k0 - 1], spans[k0])): out.append(Pause(s.t0_ms, s.t1_ms, s.dur_ms, -1, UNALIGNED, "", "")) continue # jitter-ambiguous juncture range around k0: a char whose emission lies # inside (or within TAIL_TOL_MS of) the silence could sit on either side lo = k0 while lo - 1 >= 1 and spans[lo - 1][1] >= s.t0_ms - TAIL_TOL_MS: lo -= 1 hi = k0 while hi + 1 <= len(spans) - 1 and spans[hi][2] <= s.t1_ms + TAIL_TOL_MS: hi += 1 j = min((jj for jj in range(lo, hi + 1) if spans[jj][0] in word_starts), key=lambda jj: abs(jj - k0), default=k0) cb, ca = spans[j - 1][0], spans[j][0] # a pause can never precede a combining mark (tone / above-below vowel); # such a split is pure timing noise — fold the mark into the before side while ca < len(text) and unicodedata.category(text[ca]) == "Mn": ca += 1 if ca >= len(text): continue if s.dur_ms < stop_min_ms: # STOP_CTX_CHARS either side, not just the two juncture chars: Thai # orthography hides onsets behind preposed vowels (ไทย starts with ไ, # its stop is ท) and codas behind tone marks. ctx = set(text[max(0, cb - STOP_CTX_CHARS + 1):cb + 1]) \ | set(text[ca:ca + STOP_CTX_CHARS]) if ctx & _STOP_THAI: continue # stop closure, not a pause wb = bisect.bisect_right(starts, cb) - 1 wa = bisect.bisect_right(ends, ca) if wb < 0 or wa >= len(word_spans): continue # pause beyond the first/last word: edge, not a pause if wb == wa: cls, off = INTRA_WORD, -1 sb = sa = word_spans[wb][2] else: off = word_spans[wa][0] cls = PAUSE_OK if off in allowed else BAD_JUNCTURE sb, sa = word_spans[wb][2], word_spans[wa][2] out.append(Pause(s.t0_ms, s.t1_ms, s.dur_ms, off, cls, sb, sa)) return out @dataclass class ClipReport: clip_id: str speaker: str text_id: str audio_s: float pauses: list n_ok: int = 0 n_bad_junc: int = 0 n_intra: int = 0 n_unaligned: int = 0 verdict: str = "clean" expected_hit: int = 0 expected_total: int = 0 n_cue: int = 0 n_cue_hit: int = 0 def finalize(self): self.n_ok = sum(1 for p in self.pauses if p.cls == PAUSE_OK) self.n_bad_junc = sum(1 for p in self.pauses if p.cls == BAD_JUNCTURE) self.n_intra = sum(1 for p in self.pauses if p.cls in (INTRA_WORD, INTRA_SYL)) self.n_unaligned = sum(1 for p in self.pauses if p.cls == UNALIGNED) self.verdict = "bad" if any(p.cls in BAD_CLASSES for p in self.pauses) \ else "clean" return self @property def bad_junctures(self) -> set: return {p.ch_offset for p in self.pauses if p.cls == BAD_JUNCTURE and p.ch_offset >= 0} def score_reference_clip(item: dict, wav, sr, thr: dict) -> ClipReport: """The pred_dur ground-truth arm.""" align = item["_align"] allowed, expected = allowed_offsets(align, item.get("gold")) sils = detect_silences(wav, sr, silence_db=thr["silence_db"], min_ms=thr["min_pause_ms"]) pauses = attribute_pauses(sils, np.array(item["pred_dur"]), align, allowed, thr["stop_min_pause_ms"]) realized = {p.ch_offset for p in pauses if p.cls == PAUSE_OK} cues = cue_offsets(align) return ClipReport(clip_id=item["id"], speaker=item["speaker"], text_id=item["text_id"], audio_s=len(wav) / sr, pauses=pauses, expected_hit=len(expected & realized), expected_total=len(expected), n_cue=len(cues), n_cue_hit=len(cues & realized)).finalize() def score_aligner_clip(item: dict, char_spans: list, wav, sr, thr: dict, word_seg: str) -> ClipReport: """One aligner arm, scored through the char path.""" text = item["text"] word_spans = [tuple(w) for w in item["word_spans"][word_seg]] _, gold_allowed, expected = parse_gold(item["gold"]) if item.get("gold") \ else ("", set(), set()) cues = _allowed_from_word_spans(text, word_spans, break_before=[]) allowed = _allowed_from_word_spans(text, word_spans) | gold_allowed sils = detect_silences(wav, sr, silence_db=thr["silence_db"], min_ms=thr["min_pause_ms"]) pauses = attribute_pauses_chars(sils, char_spans, text, word_spans, allowed, thr["stop_min_pause_ms"]) realized = {p.ch_offset for p in pauses if p.cls == PAUSE_OK} return ClipReport(clip_id=item["id"], speaker=item["speaker"], text_id=item["text_id"], audio_s=len(wav) / sr, pauses=pauses, expected_hit=len(expected & realized), expected_total=len(expected), n_cue=len(cues), n_cue_hit=len(cues & realized)).finalize() # --------------------------------------------------------------------------- # §6 Timing metrics: aligner boundaries vs the pred_dur ground truth # --------------------------------------------------------------------------- def gold_unit_onsets(item: dict) -> dict: """unit index -> onset ms, from the duration predictor. bounds_ms[t] is the END of padded token t, and pred_dur carries one leading pad, so bounds_ms[t] is the ONSET of unpadded token t. A unit's onset is the onset of its first token.""" align = item["_align"] bounds_ms = np.cumsum(np.asarray(item["pred_dur"]).ravel()) * DUR_FRAME_MS tok2ph = align.tok2ph out = {} for i, u in enumerate(align.units): if u.ph_a < 0 or u.ch_a < 0: continue t = int(np.searchsorted(tok2ph, u.ph_a, side="left")) if t < len(bounds_ms): out[i] = float(bounds_ms[t]) return out def pred_unit_onsets(item: dict, char_spans: list, quant_ms: float = 0.0) -> dict: """unit index -> onset ms, from an aligner's char spans: the start of the first span whose char falls in the unit. `quant_ms` rounds onto a coarser frame grid — use it to test whether an aligner's deficit is just frame rate.""" align = item["_align"] by_char = {} for ci, t0, _t1 in char_spans: if ci not in by_char or t0 < by_char[ci]: by_char[ci] = t0 out = {} for i, u in enumerate(align.units): if u.ch_a < 0: continue v = next((by_char[c] for c in range(u.ch_a, u.ch_b) if c in by_char), None) if v is not None: out[i] = round(v / quant_ms) * quant_ms if quant_ms > 0 else v return out def timing_errors(item: dict, char_spans: list, audio_ms: float, quant_ms: float = 0.0) -> dict: """Per-clip onset / duration errors and span coverage against pred_dur. DURATION is onset[i+1] − onset[i] — the boundary-to-boundary interval, the same "every frame is allocated" convention pred_dur uses. Do NOT measure it as a span's own width: aligners allocate CTC blank frames differently (span coverage below ranges from 40% to 74% of the clip), so span widths are not comparable across aligners and produce the opposite ranking. """ gold, pred = gold_unit_onsets(item), pred_unit_onsets(item, char_spans, quant_ms) keys = sorted(set(gold) & set(pred)) onset_err = [pred[k] - gold[k] for k in keys] ks = set(keys) dur_err = [(pred[k + 1] - pred[k]) - (gold[k + 1] - gold[k]) for k in keys if k + 1 in ks] span_ms = sum(t1 - t0 for _c, t0, t1 in char_spans) widths = [t1 - t0 for _c, t0, t1 in char_spans if t1 > t0] return {"onset_err": onset_err, "dur_err": dur_err, "coverage": span_ms / audio_ms if audio_ms else 0.0, "min_width": min(widths) if widths else 0.0} def _pct(v, q): return float(np.percentile(v, q)) if len(v) else float("nan") def summarize_timing(per_clip: list) -> dict: """Aggregate onset/duration error over clips. bias = median SIGNED onset error. Aligners report the LEFT edge of a frame, so each carries a systematic ~half-frame early bias; a bias is correctable by a constant shift, jitter is not. jitter = median |onset error − bias|, i.e. the spread once bias is removed. This is the number that decides whether an aligner is usable.""" on = np.array([e for c in per_clip for e in c["onset_err"]], dtype=float) du = np.array([e for c in per_clip for e in c["dur_err"]], dtype=float) bias = float(np.median(on)) if len(on) else float("nan") a_on = np.abs(on) return { "onsets": int(len(on)), "onset_p50": round(_pct(a_on, 50), 2), "onset_p75": round(_pct(a_on, 75), 2), "onset_p90": round(_pct(a_on, 90), 2), "onset_p95": round(_pct(a_on, 95), 2), "onset_gt_100ms": round(float((a_on > 100).mean()), 4) if len(on) else None, "onset_bias": round(bias, 2), "onset_jitter": round(float(np.median(np.abs(on - bias))), 2) if len(on) else None, "dur_p50": round(_pct(np.abs(du), 50), 2), "dur_p90": round(_pct(np.abs(du), 90), 2), "span_coverage": round(float(np.mean([c["coverage"] for c in per_clip])), 3), "frame_step_ms": round(float(np.median([c["min_width"] for c in per_clip if c["min_width"] > 0])), 2), } # --------------------------------------------------------------------------- # §7 Aggregation + agreement with the reference # --------------------------------------------------------------------------- def aggregate(reps: list) -> dict: n = len(reps) if not n: return {} minutes = sum(r.audio_s for r in reps) / 60.0 n_pauses = sum(len(r.pauses) for r in reps) d = { "clips": n, "pauses_per_clip": round(n_pauses / n, 3), "pper": round(sum(1 for r in reps if r.verdict == "bad") / n, 4), "intra_word_rate": round(sum(1 for r in reps if any( p.cls in (INTRA_WORD, INTRA_SYL) for p in r.pauses)) / n, 4), "bad_pauses_per_min": round( sum(r.n_bad_junc + r.n_intra for r in reps) / minutes, 3) if minutes else 0.0, } if n_pauses: d["pause_precision"] = round(sum(r.n_ok for r in reps) / n_pauses, 4) d["unaligned_rate"] = round(sum(r.n_unaligned for r in reps) / n_pauses, 4) n_cue = sum(r.n_cue for r in reps) if n_cue: # P(pause | the input marked a juncture): the recall-side axis the masks # cannot give. A precision gain that arrives with THIS falling is the # system pausing less, not phrasing better. d["space_realization"] = round(sum(r.n_cue_hit for r in reps) / n_cue, 4) return d def _pearson(a, b) -> float: a, b = np.asarray(a, float), np.asarray(b, float) if len(a) < 2 or a.std() == 0 or b.std() == 0: return float("nan") return round(float(np.corrcoef(a, b)[0, 1]), 4) def _spearman(a, b) -> float: def rank(v): order = np.argsort(np.asarray(v, float), kind="mergesort") r = np.empty(len(v), float) r[order] = np.arange(len(v), dtype=float) return r return _pearson(rank(a), rank(b)) def agreement(ref: dict, arm: dict) -> dict: """How closely an aligner arm reproduces the ground-truth path. per_speaker_precision_r is the headline: an instrument that cannot RANK speakers the way ground truth does cannot be used to compare systems, even if its aggregate precision looks right.""" ids = sorted(set(ref) & set(arm)) if not ids: return {} ca = [len(ref[i].pauses) for i in ids] cb = [len(arm[i].pauses) for i in ids] spk = sorted({ref[i].speaker for i in ids}) pa, pb = [], [] for s in spk: sub = [i for i in ids if ref[i].speaker == s] for src, dst in ((ref, pa), (arm, pb)): tot = sum(len(src[i].pauses) for i in sub) dst.append(sum(src[i].n_ok for i in sub) / tot if tot else 0.0) ja = {(i, o) for i in ids for o in ref[i].bad_junctures} jb = {(i, o) for i in ids for o in arm[i].bad_junctures} union = len(ja | jb) return { "clips_compared": len(ids), "count_pearson_r": _pearson(ca, cb), "count_spearman_rho": _spearman(ca, cb), "verdict_agreement": round( sum(1 for i in ids if ref[i].verdict == arm[i].verdict) / len(ids), 4), "per_speaker_precision_r": _pearson(pa, pb) if len(spk) > 2 else None, "bad_juncture_hit": f"{len(ja & jb)}/{len(ja)}", "bad_juncture_jaccard": round(len(ja & jb) / union, 4) if union else None, } # --------------------------------------------------------------------------- # §8 Commands # --------------------------------------------------------------------------- def cmd_align(args): """Stage A (GPU): run one aligner over the bundle -> spans.jsonl.""" items = load_bundle(Path(args.bundle), args.limit, args.speakers) if args.aligner not in ALIGNERS: raise SystemExit(f"unknown aligner {args.aligner!r}; " f"known: {', '.join(ALIGNERS)}") make_bundle, span_fn, batch_fn = ALIGNERS[args.aligner] for it in items: it["_align"] = Align.from_dict(it["align"]) out_dir = Path(args.out) out_dir.mkdir(parents=True, exist_ok=True) print(f"loading {args.aligner} on {args.device} …", file=sys.stderr) b = make_bundle(args.device, head_repo=args.ctc_head_repo) t0 = time.time() n_fail = 0 with open(out_dir / "spans.jsonl", "w", encoding="utf-8") as fh: def emit(it, spans): fh.write(json.dumps({"id": it["id"], "char_spans": [[int(c), float(a), float(z)] for c, a, z in spans]}) + "\n") if batch_fn and args.batch_size > 1: for k in range(0, len(items), args.batch_size): chunk = [] for it in items[k:k + args.batch_size]: wav, sr = read_audio(it["audio_path"]) chunk.append((it, wav, sr)) try: for it, spans in batch_fn(chunk, b): emit(it, spans) except Exception as e: # noqa: BLE001 print(f" !! batch at {k}: {e}", file=sys.stderr) n_fail += len(chunk) if (k + args.batch_size) % 200 < args.batch_size: print(f" aligned {min(k + args.batch_size, len(items))}" f"/{len(items)}", file=sys.stderr) else: for k, it in enumerate(items): wav, sr = read_audio(it["audio_path"]) try: emit(it, span_fn(wav, sr, it, b)) except Exception as e: # noqa: BLE001 — one bad clip print(f" !! {it['id']}: {e}", file=sys.stderr) n_fail += 1 if (k + 1) % 200 == 0: print(f" aligned {k + 1}/{len(items)}", file=sys.stderr) elapsed = time.time() - t0 (out_dir / "align_meta.json").write_text(json.dumps({ "aligner": args.aligner, "tag": b.tag, "clips": len(items), "failed": n_fail, "device": args.device, "wall_clock_s": round(elapsed, 1), "s_per_clip": round(elapsed / max(1, len(items)), 4), }, indent=2)) print(f"aligned {len(items) - n_fail}/{len(items)} clips in {elapsed:.0f}s " f"({elapsed / max(1, len(items)):.3f} s/clip) -> {out_dir}") def cmd_score(args): """Stage B (CPU): spans.jsonl + bundle -> metrics.json.""" items = load_bundle(Path(args.bundle), args.limit, args.speakers) by_id = {it["id"]: it for it in items} for it in items: it["_align"] = Align.from_dict(it["align"]) out_dir = Path(args.out) spans = {} for line in open(out_dir / "spans.jsonl", encoding="utf-8"): d = json.loads(line) spans[d["id"]] = [tuple(s) for s in d["char_spans"]] thr = dict(silence_db=args.silence_db, min_pause_ms=args.min_pause_ms, stop_min_pause_ms=args.stop_min_pause_ms) ref, arm, timing = {}, {}, [] for cid, cs in spans.items(): it = by_id.get(cid) if it is None: continue wav, sr = read_audio(it["audio_path"]) ref[cid] = score_reference_clip(it, wav, sr, thr) arm[cid] = score_aligner_clip(it, cs, wav, sr, thr, args.word_seg) if cs: timing.append(timing_errors(it, cs, len(wav) / sr * 1000.0, args.quantize_ms)) meta = json.loads((out_dir / "align_meta.json").read_text()) \ if (out_dir / "align_meta.json").exists() else {} out = { "arm": f"{meta.get('tag', args.out)} × {args.word_seg}", "align_meta": meta, "word_seg": args.word_seg, "thresholds": thr, "quantize_ms": args.quantize_ms, "timing_vs_pred_dur": summarize_timing(timing), "pause_metrics": aggregate(list(arm.values())), "reference_pred_dur": aggregate(list(ref.values())), "agreement_with_reference": agreement(ref, arm), } (out_dir / "metrics.json").write_text(json.dumps(out, ensure_ascii=False, indent=2)) print(json.dumps(out, ensure_ascii=False, indent=2)) def cmd_run(args): cmd_align(args) cmd_score(args) def _table(rows: list, cols: list) -> str: head = [c[0] for c in cols] body = [[f"{r.get(c[1], '')}" for c in cols] for r in rows] w = [max(len(head[i]), *(len(b[i]) for b in body)) if body else len(head[i]) for i in range(len(cols))] line = lambda cells: "| " + " | ".join( # noqa: E731 c.ljust(w[i]) for i, c in enumerate(cells)) + " |" return "\n".join([line(head), "|" + "|".join("-" * (x + 2) for x in w) + "|", *(line(b) for b in body)]) def cmd_report(args): runs = [] for p in args.runs: f = Path(p) / "metrics.json" if Path(p).is_dir() else Path(p) runs.append(json.loads(f.read_text())) t_rows, p_rows = [], [] for r in runs: t, a, g = (r["timing_vs_pred_dur"], r["pause_metrics"], r["agreement_with_reference"]) t_rows.append({"arm": r["arm"], **t, "s/clip": r.get("align_meta", {}).get("s_per_clip", "")}) p_rows.append({"arm": r["arm"], **a, **g}) ref = runs[0]["reference_pred_dur"] p_rows.insert(0, {"arm": "pred_dur (ground truth)", **ref}) print("\n## Timing vs pred_dur ground truth (ms; lower is better)\n") print(_table(t_rows, [("arm", "arm"), ("onsets", "onsets"), ("p50", "onset_p50"), ("p75", "onset_p75"), ("p90", "onset_p90"), ("p95", "onset_p95"), (">100ms", "onset_gt_100ms"), ("bias", "onset_bias"), ("jitter", "onset_jitter"), ("dur p50", "dur_p50"), ("coverage", "span_coverage"), ("frame", "frame_step_ms"), ("s/clip", "s/clip")])) print("\n## Pause metrics + agreement with ground truth\n") print(_table(p_rows, [("arm", "arm"), ("/clip", "pauses_per_clip"), ("precision", "pause_precision"), ("intra_word", "intra_word_rate"), ("PPER", "pper"), ("bad/min", "bad_pauses_per_min"), ("unaligned", "unaligned_rate"), ("r(count)", "count_pearson_r"), ("verdict", "verdict_agreement"), ("per-spk r", "per_speaker_precision_r"), ("bad-junc", "bad_juncture_hit"), ("Jaccard", "bad_juncture_jaccard")])) print("\nRead precision NEXT TO pauses/clip: the masks have no " "\"a break is required here\" marks, so never pausing scores 1.000.\n" "per-spk r is the instrument test — can it rank voices the way ground " "truth does?\n") # --------------------------------------------------------------------------- # §9 Bundle export (project-side; a recipient of the bundle never runs this) # --------------------------------------------------------------------------- def cmd_export(args): """Freeze wavs + ground truth into a portable bundle. Needs the original project: own-path sidecars (pred_dur + alignment), the calibrated masks, and — only here — pythainlp/tltk to precompute the two word segmentations. Everything the benchmark needs at run time is written out, so the bundle has no Thai-NLP dependency at all. """ sys.path.insert(0, str(Path(__file__).resolve().parents[1])) import soundfile as sf from kokoro_thai.pause_eval import (_build_mask, _newmm_word_spans, _remap_mask_offsets, parse_gold as pg, sanitize_gold, word_spans_tltk) out = Path(args.out) (out / "audio").mkdir(parents=True, exist_ok=True) masks = {str(d["id"]): (d["text"], d["gold"]) for d in (json.loads(l) for l in open(args.masks, encoding="utf-8"))} if args.masks else {} keep = {s.strip() for s in args.speakers.split(",")} if args.speakers else None n, skipped = 0, 0 with open(out / "items.jsonl", "w", encoding="utf-8") as fh: for p in sorted(Path(args.sidecars).glob("*.json")): d = json.loads(p.read_text()) if d.get("source") != "pred_dur": continue if keep and not (d["speaker"] in keep or d["speaker"].split("_")[0] in keep): continue text = d["align"]["text_norm"] # The calibrated masks live in RAW-text coordinates; the audio was # rendered from text_norm (numbers verbalized, ๆ expanded). Re-express # the mask onto text_norm so BOTH paths score in one coordinate space # — the aligner arms then differ only in timing, not in what counts as # an allowed break. gold = d.get("gold") tid = str(d["text_id"]) if tid in masks: raw, g = masks[tid] g = sanitize_gold(raw, g) if g: _, allowed, expected = pg(g) gold = _build_mask(text, _remap_mask_offsets(raw, text, allowed), _remap_mask_offsets(raw, text, expected)) if gold and pg(gold)[0] != text: skipped += 1 continue src = Path(d["wav_path"]) if not src.exists(): src = Path(args.wav_dir or "") / f"{p.stem}.wav" if not src.exists(): skipped += 1 continue wav, sr = sf.read(str(src), dtype="int16") sf.write(str(out / "audio" / f"{p.stem}.flac"), wav, sr, format="FLAC", subtype="PCM_16") fh.write(json.dumps({ "id": p.stem, "speaker": d["speaker"], "text_id": tid, "epoch": d.get("epoch", -1), "text": text, "gold": gold, "audio": f"audio/{p.stem}.flac", "sr": sr, "pred_dur": d["pred_dur"], "align": {k: d["align"][k] for k in ("text_norm", "phonemes", "units", "words", "ph2unit", "tok2ph")}, "word_spans": {"tltk": [list(w) for w in word_spans_tltk(text)], "newmm": [list(w) for w in _newmm_word_spans(text)]}, }, ensure_ascii=False) + "\n") n += 1 if n % 100 == 0: print(f" exported {n}", file=sys.stderr) if args.limit and n >= args.limit: break (out / "README.md").write_text(BUNDLE_README) print(f"exported {n} clips ({skipped} skipped) -> {out}") BUNDLE_README = """# aligner_bench asset bundle Thai TTS audio with frozen ground-truth alignment, for benchmarking forced aligners. Produced from a Kokoro/StyleTTS2 Thai student (12 synthetic speakers x long-sentence eval texts). items.jsonl one JSON per clip audio/.flac 24 kHz mono, lossless Per item: | field | meaning | |---|---| | `id` / `speaker` / `text_id` | clip key; `speaker` groups the same text across voices | | `text` | the NORMALIZED text that was actually spoken — every char index below is in this space | | `gold` | pause mask; `\\|` marks a juncture where a break is allowed (hand-calibrated, precision-side only) | | `pred_dur` | the TTS duration predictor's per-token frame counts, 25 ms/frame, with one pad token at each end. `sum(pred_dur) * 600 == len(audio)` at 24 kHz, so these boundaries ARE the audio's boundaries — this is the timing ground truth | | `align.phonemes` | IPA, byte-identical to what the model was fed | | `align.units` | syllable/word/punct atoms: `[ph_a, ph_b)` in phonemes, `[ch_a, ch_b)` in text | | `align.words` | word spans with surfaces | | `align.ph2unit` | phoneme char -> unit index (-1 for spaces) | | `align.tok2ph` | model token index -> phoneme char index | | `word_spans` | two independent word segmentations (`tltk`, `newmm`) so tokenizer choice can be varied without a Thai tokenizer installed | The audio is vocoder output, not natural speech: out of domain for aligners trained on read speech, which is deliberate — it is the audio the metric has to work on. """ # --------------------------------------------------------------------------- def main(argv=None): ap = argparse.ArgumentParser( prog="aligner_bench", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) sub = ap.add_subparsers(dest="cmd", required=True) def common(p, scoring=True): p.add_argument("--bundle", default="bundle", help="asset bundle dir") p.add_argument("--out", required=True, help="output dir for this arm") p.add_argument("--limit", type=int, default=0) p.add_argument("--speakers", default="", help="comma-separated speaker filter, e.g. spk00,spk03") if scoring: p.add_argument("--word-seg", choices=("tltk", "newmm"), default="tltk", help="which frozen word segmentation to attribute with") p.add_argument("--silence-db", type=float, default=THRESHOLDS["silence_db"]) p.add_argument("--min-pause-ms", type=float, default=THRESHOLDS["min_pause_ms"]) p.add_argument("--stop-min-pause-ms", type=float, default=THRESHOLDS["stop_min_pause_ms"]) p.add_argument("--quantize-ms", type=float, default=0.0, help="round predicted onsets onto this grid before " "scoring — tests whether a deficit is just frame rate") def aligning(p): p.add_argument("--aligner", default="ctc", choices=sorted(ALIGNERS)) p.add_argument("--device", default="cuda:0") p.add_argument("--batch-size", type=int, default=8) p.add_argument("--ctc-head-repo", default=None, help="qwen arm: HF repo of the timestamp head") p = sub.add_parser("align", help="stage A: run an aligner (GPU)") common(p, scoring=False) aligning(p) p.set_defaults(func=cmd_align) p = sub.add_parser("score", help="stage B: score existing spans (CPU)") common(p) p.set_defaults(func=cmd_score) p = sub.add_parser("run", help="align + score") common(p) aligning(p) p.set_defaults(func=cmd_run) p = sub.add_parser("report", help="compare finished runs") p.add_argument("runs", nargs="+", help="run dirs or metrics.json paths") p.set_defaults(func=cmd_report) p = sub.add_parser("export", help="build the asset bundle (project-side)") p.add_argument("--sidecars", required=True, help="dir of own-path (source=pred_dur) sidecar JSONs") p.add_argument("--masks", default=None, help="calibrated masks JSONL") p.add_argument("--wav-dir", default=None, help="fallback wav dir") p.add_argument("--speakers", default="") p.add_argument("--limit", type=int, default=0) p.add_argument("--out", required=True) p.set_defaults(func=cmd_export) args = ap.parse_args(argv) args.func(args) if __name__ == "__main__": main()