| """Acceptable-reference expansion for WER scoring. |
| |
| Why this exists |
| ─────────────── |
| WER punishes the TTS model for every token the ASR writes differently from the |
| reference. But for Vietnamese benchmark text, *most* of those differences are |
| the ASR's formatting policy, not the model's pronunciation: |
| |
| text "Hạn cuối là ngày 31/12/2025." |
| whisper-v3 "Hạn cuối là ngày 31 tháng 12, 2025." ← perfect audio, 0.72 WER |
| PhoWhisper "hạn cuối là ngày ba mốt tháng mười hai hai ngàn ..." |
| |
| Both transcripts are *correct readings of correct audio*. A single written |
| reference plus a single hand-written spoken reference cannot cover them, |
| because the choices compose: an ASR may spell the acronym out while writing the |
| numbers as digits, giving a hybrid that matches neither. With k independent |
| format decisions there are 2^k acceptable transcripts, and the two-reference |
| scheme covers two of them. |
| |
| So instead of enumerating whole sentences, this module declares, per **surface |
| span**, every realization a correct reading may produce, and expands the |
| cross-product at scoring time. ``zerobench_eval/scorers.py`` then takes the minimum |
| WER over that set (see :func:`best_wer`). |
| |
| What is deliberately NOT admitted |
| ───────────────────────────────── |
| Only *legitimate* readings. Wrong Vietnamese stays wrong: |
| |
| * ``18/04`` → "mười tám tháng **tư**" ✓ / "tháng **không** tư" ✗ (voiced leading zero) |
| * ``92.000.000`` → "chín mươi hai **triệu**" ✓ / "chín mươi hai **nghìn nghìn**" ✗ |
| * ``AB-1234`` → "a bê một hai ba bốn" ✓ / "a bê một hai ba **bê** bốn" ✗ |
| |
| Those three are real ZeroTTS defects found in https://github.com/zeroweight-ai/ZeroTTS/blob/main/evaluation/HIGH_WER_ANALYSIS.md, |
| and the point of a faithful benchmark is that they keep costing WER. |
| |
| Phonetic renderings of English loanwords ("Slack" → "sờ lếch") are also NOT |
| listed. They are an artifact of PhoWhisper specifically, and the eval now runs |
| two ASRs and takes the better — ``openai/whisper-large-v3`` writes the Latin |
| spelling, so the artifact is handled by ASR agreement rather than by loosening |
| the reference set. The one exception is intra-word spacing (``ChatGPT`` vs |
| "chat GPT"), which *both* ASRs get "wrong" and which is pure orthography. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import re |
| from itertools import product |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| _DIGIT = ["không", "một", "hai", "ba", "bốn", "năm", "sáu", "bảy", "tám", "chín"] |
|
|
|
|
| def _under_100(n: int, *, after_tens_word: bool = True) -> list[str]: |
| """0-99. ``after_tens_word`` False renders 1-9 bare ("năm"), True allows the |
| post-"mươi" alternants.""" |
| if n < 10: |
| return [_DIGIT[n]] |
| if n < 20: |
| unit = n % 10 |
| if unit == 0: |
| return ["mười"] |
| if unit == 5: |
| return ["mười lăm"] |
| return [f"mười {_DIGIT[unit]}"] |
| tens, unit = divmod(n, 10) |
| head = f"{_DIGIT[tens]} mươi" |
| if unit == 0: |
| return [head] |
| if unit == 1: |
| tails = ["mốt", "một"] if after_tens_word else ["một"] |
| elif unit == 4: |
| tails = ["tư", "bốn"] |
| elif unit == 5: |
| tails = ["lăm"] |
| else: |
| tails = [_DIGIT[unit]] |
| |
| |
| return ([f"{head} {t}" for t in tails] |
| + [f"{_DIGIT[tens]} {t}" for t in tails]) |
|
|
|
|
| def _group3(n: int, *, pad_hundreds: bool) -> list[str]: |
| """0-999. ``pad_hundreds`` allows the "không trăm ..." form that Vietnamese |
| uses for a sub-100 group sitting under a larger scale ("hai nghìn KHÔNG TRĂM |
| hai mươi lăm").""" |
| if n == 0: |
| return [""] |
| if n < 100: |
| base = _under_100(n) |
| if pad_hundreds: |
| return base + [f"không trăm {b}" for b in base] |
| return base |
| hundreds, rest = divmod(n, 100) |
| head = f"{_DIGIT[hundreds]} trăm" |
| if rest == 0: |
| return [head] |
| if rest < 10: |
| return [f"{head} lẻ {_DIGIT[rest]}", f"{head} linh {_DIGIT[rest]}"] |
| return [f"{head} {r}" for r in _under_100(rest)] |
|
|
|
|
| _SCALES = ["", "nghìn", "triệu", "tỷ"] |
|
|
|
|
| def vi_int(n: int, *, cap: int = 12) -> list[str]: |
| """Every standard spoken reading of a non-negative integer.""" |
| if n == 0: |
| return ["không"] |
| groups: list[int] = [] |
| while n: |
| n, g = divmod(n, 1000) |
| groups.append(g) |
| groups.reverse() |
| n_groups = len(groups) |
|
|
| per_group: list[list[str]] = [] |
| for i, g in enumerate(groups): |
| scale = _SCALES[n_groups - 1 - i] |
| if g == 0: |
| per_group.append([""]) |
| continue |
| |
| readings = _group3(g, pad_hundreds=i > 0) |
| if scale == "nghìn": |
| per_group.append([f"{r} nghìn" for r in readings] + [f"{r} ngàn" for r in readings]) |
| elif scale: |
| per_group.append([f"{r} {scale}" for r in readings]) |
| else: |
| per_group.append(readings) |
|
|
| out: list[str] = [] |
| for combo in product(*per_group): |
| s = " ".join(p for p in combo if p).strip() |
| if s and s not in out: |
| out.append(s) |
| if len(out) >= cap: |
| break |
| return out |
|
|
|
|
| def vi_decimal(written: str) -> list[str]: |
| """"3,2" -> ["ba phẩy hai", ...]. Two-digit fractions get both the |
| read-as-a-number form ("hai phẩy hai mươi bảy") and the digit-by-digit form |
| ("hai phẩy hai bảy"); Vietnamese speakers use both.""" |
| whole, _, frac = written.replace(".", "").partition(",") |
| heads = vi_int(int(whole)) |
| if not frac: |
| return heads |
| tails = [] |
| if len(frac) == 1: |
| tails.append(_DIGIT[int(frac)]) |
| else: |
| tails.extend(vi_int(int(frac))) |
| tails.append(" ".join(_DIGIT[int(d)] for d in frac)) |
| return [f"{h} phẩy {t}" for h in heads for t in tails] |
|
|
|
|
| def _spoken(written: str) -> list[str]: |
| """Spoken readings of a bare numeric literal, decimal or integer.""" |
| return vi_decimal(written) if "," in written else vi_int(int(written.replace(".", ""))) |
|
|
|
|
| |
| |
| |
| |
|
|
| def num(written: str, *, suffix: str = "", extra: list[str] | None = None) -> list[str]: |
| """A number, optionally with a trailing unit that is part of the span.""" |
| tail = f" {suffix}" if suffix else "" |
| out = [f"{written}{tail}"] + [f"{s}{tail}" for s in _spoken(written)] |
| return _dedup(out + (extra or [])) |
|
|
|
|
| def pct(written: str) -> list[str]: |
| """"3,2%" -> written form, digits + "phần trăm", and the fully spoken form.""" |
| return _dedup([f"{written}%", f"{written} phần trăm"] |
| + [f"{s} phần trăm" for s in _spoken(written)]) |
|
|
|
|
| def _day(d: int) -> list[str]: |
| """Day-of-month. 1 and 2 take the "mùng/mồng" prefix Vietnamese uses for the |
| first ten days; 31 contracts to "ba mốt".""" |
| base = _under_100(d) |
| out = list(base) |
| if d <= 10: |
| out += [f"mùng {b}" for b in base] + [f"mồng {b}" for b in base] |
| return _dedup(out) |
|
|
|
|
| def _month(m: int) -> list[str]: |
| """Month name. April is "tư" (never "bốn" as a month), January "một"/"giêng".""" |
| if m == 1: |
| return ["một", "giêng"] |
| if m == 4: |
| return ["tư"] |
| return _under_100(m) |
|
|
|
|
| def date(written: str, d: int, m: int, y: int | None = None) -> list[str]: |
| """A ``dd/mm[/yyyy]`` span. Covers the written form, the half-spoken forms |
| both ASRs actually emit ("31 tháng 12, 2025"), and the fully spoken form |
| with and without the "năm" filler before the year. |
| |
| NOTE the leading zero in ``01/07`` / ``18/04`` is a *writing* convention |
| only — "tháng không bảy" is not admitted, so voicing it stays an error. |
| """ |
| |
| |
| |
| |
| |
| |
| parts = written.split("/") |
| d_num, m_num = [str(d)], [str(m)] |
| days = d_num + _day(d) |
| months = m_num + _month(m) |
|
|
| out = [written] |
| if y is None: |
| out += [f"{dd} tháng {mm}" for dd in days for mm in months] |
| out += [f"ngày {dd} tháng {mm}" for dd in d_num for mm in m_num] |
| return _dedup(out) |
| years = _dedup([parts[2]] + vi_int(y)) |
| out += [f"{dd} tháng {mm} {yy}" for dd in days for mm in months for yy in years] |
| out += [f"{dd} tháng {mm} năm {yy}" for dd in days for mm in months for yy in years] |
| return _dedup(out) |
|
|
|
|
| def time_(written: str, h: int, mi: int = 0) -> list[str]: |
| """A ``8h30`` / ``6h`` span, including the "rưỡi" (half past) reading.""" |
| out = [written, f"{h} giờ" if mi == 0 else f"{h} giờ {mi}", f"{h}:{mi:02d}"] |
| hours = _under_100(h) |
| if mi == 0: |
| out += [f"{hh} giờ" for hh in hours] |
| else: |
| mins = _under_100(mi) |
| out += [f"{hh} giờ {mm}" for hh in hours for mm in mins] |
| out += [f"{hh} giờ {mm} phút" for hh in hours for mm in mins] |
| if mi == 30: |
| out += [f"{hh} giờ rưỡi" for hh in hours] + [f"{hh} rưỡi" for hh in hours] |
| return _dedup(out) |
|
|
|
|
| def _dedup(items: list[str]) -> list[str]: |
| seen, out = set(), [] |
| for s in items: |
| s = re.sub(r"\s+", " ", s).strip() |
| if s and s not in seen: |
| seen.add(s) |
| out.append(s) |
| return out |
|
|
|
|
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| SPANS: dict[str, list[str]] = { |
|
|
| |
| |
| |
| |
| "ChatGPT": ["ChatGPT", "chat GPT", "Chát Ji Pi Ti", "chát gi pi ti", |
| "chat gi pi ti", "chát ji pi ti", "Chat GPT"], |
| "GDP": ["GDP", "gi đi pi", "giê đê pê", "tổng sản phẩm quốc nội"], |
| "WHO": ["WHO", "đắp liu hát ô", "vê hát ô", "vê kép hát ô", "đấp bờ liu ết chờ ô", |
| "Tổ chức Y tế Thế giới"], |
| "WTO": ["WTO", "đắp liu ti ô", "vê tê ô", "vê kép tê ô", "đấp bờ liu ti ô", |
| "Tổ chức Thương mại Thế giới"], |
| "UNICEF": ["UNICEF", "U-ni-xép", "u ni xép", "iu ni xép", |
| "Quỹ Nhi đồng Liên Hợp Quốc"], |
| "UNESCO": ["UNESCO", "U-nét-cô", "u nét cô", "iu nét cô"], |
| "ASEAN": ["ASEAN", "A-sê-an", "a sê an", "át xê an", "a si an"], |
| "HR": ["HR", "hát rờ", "ét chờ a rờ", "ây át rờ", "nhân sự"], |
| "IT": ["IT", "ai ti", "i ti"], |
| "QR": ["QR", "kiu a", "quy a", "cu rờ", "ku a"], |
| "Internet": ["Internet", "In-tơ-nét", "in tơ nét", "internet"], |
| "Gemini": ["Gemini", "Giê mi ni", "gờ mi ni", "gemini"], |
| "Copilot": ["Copilot", "Cô pi lốt", "co pi lot", "copilot"], |
| "Vientiane": ["Vientiane", "Viêng Chăn", "viêng chăn"], |
| "TP. HCM": ["TP. HCM", "TPHCM", "TP HCM", "Thành phố Hồ Chí Minh", |
| "thành phố Hồ Chí Minh", "tê pê hát xê em"], |
| "SE1": ["SE1", "SE 1", "ét ê một", "ét e một", "ét xê một", "es i một", "SE một"], |
|
|
| |
| |
| "VN-215": ["VN-215", "VN 215", "VN215", |
| "vê en 215", "vê en hai một năm", "vê en hai một lăm", |
| "vê en hai trăm mười lăm", "vê nờ hai một năm", "vi en hai một năm"], |
| "AB-1234": ["AB-1234", "AB 1234", "AB1234", |
| "a bê 1234", "a bê một hai ba bốn", "a bê một hai ba tư", |
| "ây bi một hai ba bốn", "a bê một nghìn hai trăm ba mươi bốn"], |
| "USD/VND": ["USD/VND", "USD VND", "USD trên VND", |
| "đô la Mỹ trên đồng Việt Nam", "đô la Mỹ đồng Việt Nam", |
| "u ét đê trên vê en đê", "đô la Mỹ VND", "u ét đê vê en đê"], |
|
|
| |
| "quý III": ["quý III", "quý 3", "quý ba"], |
| "quý II": ["quý II", "quý 2", "quý hai"], |
| "quý I": ["quý I", "quý 1", "quý một"], |
|
|
| |
| "38°C": ["38°C", "38 độ C", "ba mươi tám độ C", "ba mươi tám độ xê", |
| "ba mươi tám độ"], |
| "5 km": ["5 km", "năm km", "năm ki lô mét", "5 ki lô mét", "năm cây số"], |
| "đồng/tháng": ["đồng/tháng", "đồng một tháng", "đồng mỗi tháng", "đồng trên tháng"], |
|
|
| |
| "31/12/2025": date("31/12/2025", 31, 12, 2025), |
| "01/07/2024": date("01/07/2024", 1, 7, 2024), |
| "2/9/1945": date("2/9/1945", 2, 9, 1945), |
| "1/1/2026": date("1/1/2026", 1, 1, 2026), |
| "15/8": date("15/8", 15, 8), |
| "10/03": date("10/03", 10, 3), |
| "25/03": date("25/03", 25, 3), |
| "09/10": date("09/10", 9, 10), |
| "20/11": date("20/11", 20, 11), |
| "30/11": date("30/11", 30, 11), |
| "18/04": date("18/04", 18, 4), |
| "27/6": date("27/6", 27, 6), |
|
|
| |
| "23h59": time_("23h59", 23, 59), |
| "20h55": time_("20h55", 20, 55), |
| "12h30": time_("12h30", 12, 30), |
| "11h20": time_("11h20", 11, 20), |
| "8h30": time_("8h30", 8, 30), |
| "5h45": time_("5h45", 5, 45), |
| "4h50": time_("4h50", 4, 50), |
| "20h": time_("20h", 20), |
| "18h": time_("18h", 18), |
| "9h": time_("9h", 9), |
| "6h": time_("6h", 6), |
| "4h": time_("4h", 4), |
| "0h": time_("0h", 0) + ["không giờ", "12 giờ đêm"], |
|
|
| |
| "12,7%": pct("12,7"), "2,27%": pct("2,27"), "0,15%": pct("0,15"), |
| "99,4%": pct("99,4"), "0,3%": pct("0,3"), "1,7%": pct("1,7"), |
| "4,9%": pct("4,9"), "3,2%": pct("3,2"), "6,8%": pct("6,8"), |
| "100%": pct("100"), "90%": pct("90"), "75%": pct("75"), "60%": pct("60"), |
| "50%": pct("50"), "40%": pct("40"), "35%": pct("35"), "12%": pct("12"), |
| "10%": pct("10"), "6%": pct("6"), |
|
|
| |
| "92.000.000 đồng": num("92.000.000", suffix="đồng"), |
| "5.310.000 đồng": num("5.310.000", suffix="đồng"), |
| "1.100.000 thí sinh": num("1.100.000", suffix="thí sinh"), |
| "1.000.000 đồng": num("1.000.000", suffix="đồng"), |
| "350.000 giao dịch": num("350.000", suffix="giao dịch"), |
| "1.250 tỷ đồng": num("1.250", suffix="tỷ đồng"), |
| "9.000 ca": num("9.000", suffix="ca"), |
| "500 thí sinh": num("500", suffix="thí sinh"), |
| "5,2 triệu": num("5,2", suffix="triệu"), |
| "3,5 triệu": num("3,5", suffix="triệu"), |
| "7,5 triệu": num("7,5", suffix="triệu"), |
| "1,3 triệu": num("1,3", suffix="triệu"), |
| "lần thứ 44": ["lần thứ 44", "lần thứ bốn mươi bốn", "lần thứ bốn mươi tư"], |
| "10 nước": num("10", suffix="nước"), |
| "32 tiếng": num("32", suffix="tiếng"), |
| "gấp 3 lần": ["gấp 3 lần", "gấp ba lần"], |
| "26 và 27/6": ["26 và 27/6", "26 và 27 tháng 6", |
| "hai mươi sáu và hai mươi bảy tháng sáu", |
| "hai sáu và hai bảy tháng sáu"], |
| "2000 – 2019": ["2000 – 2019", "2000-2019", "2000 đến 2019", |
| "hai nghìn đến hai nghìn mười chín", |
| "hai nghìn đến hai nghìn không trăm mười chín", |
| "hai ngàn đến hai ngàn không trăm mười chín", |
| "hai nghìn hai nghìn mười chín"], |
|
|
| |
| |
| |
| |
| |
| |
| "thứ Hai": ["thứ Hai", "thứ 2"], |
| "thứ Tư": ["thứ Tư", "thứ 4"], |
| "thứ Sáu": ["thứ Sáu", "thứ 6"], |
| "thứ ba": ["thứ ba", "thứ 3"], |
| "chín giờ": ["chín giờ", "9 giờ", "9h"], |
| "sáu giờ": ["sáu giờ", "6 giờ", "6h"], |
| "mười lăm phút": ["mười lăm phút", "15 phút"], |
| "ba mươi phút": ["ba mươi phút", "30 phút"], |
| "mười tiếng": ["mười tiếng", "10 tiếng"], |
| "một tiếng": ["một tiếng", "1 tiếng"], |
| "ba năm": ["ba năm", "3 năm"], |
| "sáu tháng": ["sáu tháng", "6 tháng"], |
| "hai ngày": ["hai ngày", "2 ngày"], |
| "ba ngày": ["ba ngày", "3 ngày"], |
| "một tuần": ["một tuần", "1 tuần"], |
| "một ngày": ["một ngày", "1 ngày"], |
| "năm mươi nghìn": ["năm mươi nghìn", "50.000", "50000", "năm mươi ngàn"], |
|
|
| |
| |
| |
| |
| "Series": ["Series", "Serie"], |
| "series": ["series", "serie"], |
| "Team": ["Team", "Tim"], |
| |
| |
| |
| |
|
|
| |
| "năm 2020": ["năm 2020"] + [f"năm {s}" for s in vi_int(2020)], |
| "năm 2024": ["năm 2024"] + [f"năm {s}" for s in vi_int(2024)], |
| "năm 2025": ["năm 2025"] + [f"năm {s}" for s in vi_int(2025)], |
| "năm 2030": ["năm 2030"] + [f"năm {s}" for s in vi_int(2030)], |
| } |
|
|
| _SPAN_RE = re.compile("|".join(re.escape(k) for k in sorted(SPANS, key=len, reverse=True))) |
|
|
|
|
| |
|
|
| def segment(text: str) -> list[list[str]]: |
| """Split ``text`` into alternating fixed and variable segments. |
| |
| Returns a list where each element is the list of acceptable realizations of |
| that segment — length 1 for literal text between spans. Element 0 of every |
| variable segment is the verbatim source form, so taking index 0 everywhere |
| reconstructs ``text``. |
| """ |
| segs: list[list[str]] = [] |
| pos = 0 |
| for m in _SPAN_RE.finditer(text): |
| if m.start() > pos: |
| segs.append([text[pos:m.start()]]) |
| segs.append(SPANS[m.group(0)]) |
| pos = m.end() |
| if pos < len(text): |
| segs.append([text[pos:]]) |
| return segs or [[text]] |
|
|
|
|
| def n_variants(text: str) -> int: |
| n = 1 |
| for s in segment(text): |
| n *= len(s) |
| return n |
|
|
|
|
| def expand(text: str, limit: int = 4096) -> list[str]: |
| """Full cross-product of acceptable references, capped. Mostly for |
| inspection and tests — :func:`best_wer` avoids materializing it.""" |
| segs = segment(text) |
| out = [] |
| for combo in product(*segs): |
| out.append(re.sub(r"\s+", " ", "".join(combo)).strip()) |
| if len(out) >= limit: |
| break |
| return out |
|
|
|
|
| _EXHAUSTIVE_MAX = 512 |
|
|
|
|
| def best_wer(hyp: str, text: str, extra_refs: list[str] | None = None) -> tuple[float, str]: |
| """Minimum WER of ``hyp`` over every acceptable reading of ``text``. |
| |
| Returns ``(wer, winning_reference)``. |
| |
| Exhaustive when the cross-product is small. Above that it uses coordinate |
| descent: start from the verbatim text, then repeatedly pick the best |
| realization of one span holding the others fixed. The spans are disjoint, |
| contiguous, and non-interacting under edit distance, so this reaches the |
| same optimum as brute force in practice while doing O(spans x variants) |
| scorings instead of their product. |
| """ |
| from .scorers import normalize_for_cer, word_error_rate |
|
|
| h = normalize_for_cer(hyp) |
|
|
| def score(ref: str) -> float: |
| return word_error_rate(h, normalize_for_cer(ref)) |
|
|
| segs = segment(text) |
| total = 1 |
| for s in segs: |
| total *= len(s) |
|
|
| best_ref, best = None, 2.0 |
| if total <= _EXHAUSTIVE_MAX: |
| for combo in product(*segs): |
| ref = "".join(combo) |
| w = score(ref) |
| if w < best: |
| best, best_ref = w, ref |
| else: |
| idx = [0] * len(segs) |
| best_ref = "".join(s[0] for s in segs) |
| best = score(best_ref) |
| for _ in range(3): |
| improved = False |
| for i, seg in enumerate(segs): |
| if len(seg) == 1: |
| continue |
| for j in range(len(seg)): |
| if j == idx[i]: |
| continue |
| trial = idx.copy() |
| trial[i] = j |
| ref = "".join(segs[k][trial[k]] for k in range(len(segs))) |
| w = score(ref) |
| if w < best - 1e-12: |
| best, best_ref, idx, improved = w, ref, trial, True |
| if not improved: |
| break |
|
|
| for ref in extra_refs or []: |
| if not ref: |
| continue |
| w = score(ref) |
| if w < best: |
| best, best_ref = w, ref |
| return min(best, 1.0), (best_ref or text) |
|
|