File size: 3,896 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env python3
"""Score STT transcripts of your TTS outputs against TR-TTS-Bench (stdlib only; no GPU needed).

  python score_transcripts.py --segments data/public/segments.jsonl --hyps my_system_R.jsonl --track R

`--hyps` is JSON Lines with {"id": "trtb-00001", "hyp": "<STT transcript of your audio for that segment>"}.
Segments without a transcript count as failures (all deletions). Track R = your TTS was given `text`; track S = it
was given `text_spoken` (scored strictly against the canonical reading). Prints headline WER/CER/SER, entity
accuracy and per-group WER; `--out` writes per-segment scores.
"""
from __future__ import annotations

import argparse
import json
import sys
from collections import defaultdict
from pathlib import Path

HERE = Path(__file__).resolve().parent
for p in (HERE, HERE.parent):  # works from the repo (scripts/) and from the HF snapshot (code/)
    if (p / "trttsbench").is_dir():
        sys.path.insert(0, str(p))

from trttsbench.normalize import normalize_hyp  # noqa: E402
from trttsbench.score import score_segment  # noqa: E402
from trttsbench.textnorm import parse_lattice  # noqa: E402


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--segments", required=True)
    ap.add_argument("--hyps", required=True)
    ap.add_argument("--track", choices=["R", "S"], default="R")
    ap.add_argument("--out", help="write per-segment scores (JSON Lines)")
    a = ap.parse_args()
    rows = [json.loads(x) for x in Path(a.segments).read_text(encoding="utf-8").splitlines() if x.strip()]
    hyps = {}
    for x in Path(a.hyps).read_text(encoding="utf-8").splitlines():
        if x.strip():
            d = json.loads(x)
            hyps[d["id"]] = d.get("hyp", "")
    strict = a.track == "S"
    tot = defaultdict(lambda: defaultdict(float))
    per = []
    for r in rows:
        failed = r["id"] not in hyps
        s = score_segment(parse_lattice(r["ref_lattice"]), normalize_hyp(hyps.get(r["id"], "")), failed=failed,
                          strict=strict)
        s.update(id=r["id"], group=r["group"], headline=r["headline"], long_form=r.get("long_form", False))
        per.append(s)
        scopes = ["headline" if r["headline"] else ("long_form" if r.get("long_form") else "diagnostic")]
        if r["headline"]:
            scopes.append(f"group:{r['group']} {r['group_name']}")
        for sc in scopes:
            t = tot[sc]
            t["n"] += 1
            t["err"] += s["errors"]
            t["ref"] += s["ref_words"]
            t["cerr"] += s["char_errors"]
            t["cref"] += s["ref_chars"]
            t["sent"] += bool(s["sentence_error"])
            t["ent"] += s["n_entities"]
            t["entok"] += s["n_entities_correct"]
            t["fail"] += failed
    def line(name: str, t: dict) -> str:
        wer = 100 * t["err"] / max(1, t["ref"])
        cer = 100 * t["cerr"] / max(1, t["cref"])
        ser = 100 * t["sent"] / max(1, t["n"])
        ent = f"{100 * t['entok'] / t['ent']:.1f}" if t["ent"] else "–"
        return f"| {name} | {int(t['n'])} | {wer:.2f} | {cer:.2f} | {ser:.1f} | {ent} | {int(t['fail'])} |"
    print(f"Track {a.track} ({'strict canonical' if strict else 'lattice: min over accepted readings'}), "
          f"{len(hyps)} transcripts for {len(rows)} segments\n")
    print("| scope | n | WER % | CER % | SER % | entity acc % | missing |\n|---|---:|---:|---:|---:|---:|---:|")
    for k in ["headline", "long_form", "diagnostic"] + sorted(k for k in tot if k.startswith("group:")):
        if k in tot:
            print(line(k, tot[k]))
    if a.out:
        with open(a.out, "w", encoding="utf-8") as f:
            for s in per:
                f.write(json.dumps(s, ensure_ascii=False) + "\n")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())