File size: 1,738 Bytes
434a66e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
"""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)