"""tr_norm v1 entry points (DESIGN.md ยง4). Hypotheses (STT output) are verbalized with `trttsbench.verbalize` into a lattice of spoken alternatives and then normalized with `textnorm.normalize_basic`; references are built from `text_spoken` + `alt_spans`. Both sides end in the same token space, so `trttsbench.score.align(ref, hyp)` compares like with like. """ from __future__ import annotations from .textnorm import TR_NORM_VERSION, Lattice, build_lattice, tokens from .verbalize import verbalize_lattice __all__ = ["TR_NORM_VERSION", "normalize_hyp", "normalize_hyp_str", "normalize_ref"] def normalize_hyp(text: str) -> Lattice: """Lattice of normalized token sequences for a written (e.g. STT) string; first option = canonical.""" out: Lattice = [] for group in verbalize_lattice(text or ""): opts: list[list[str]] = [] for o in group: t = tokens(" ".join(o) if isinstance(o, (list, tuple)) else str(o)) if t not in opts: opts.append(t) if any(opts): out.append([o for o in opts if o] if all(opts) else opts) merged: Lattice = [] for g in out: if len(g) == 1 and merged and len(merged[-1]) == 1: merged[-1] = [merged[-1][0] + g[0]] else: merged.append(g) return merged def normalize_hyp_str(text: str) -> str: """Canonical normalized string of a hypothesis (first option of every group).""" return " ".join(t for g in normalize_hyp(text) for t in g[0]) def normalize_ref(text_spoken: str, alt_spans: list[dict] | None = None) -> Lattice: """Reference lattice from the canonical spoken text and its span alternatives.""" return build_lattice(text_spoken, alt_spans)