Datasets:
File size: 24,969 Bytes
b982e77 448b7f5 b982e77 448b7f5 b982e77 448b7f5 b982e77 | 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 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 | """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
# ── Vietnamese number reading ─────────────────────────────────────────────────
# Each helper returns EVERY standard reading, because the dialect/register
# switches below are all genuinely used by Vietnamese speakers and all emitted
# by ASR:
# 5 in the units slot after a tens word → "lăm" | "năm"
# 4 in the units slot after "mươi" → "tư" | "bốn"
# 1 in the units slot after "mươi" → "mốt" | "một"
# 10^3 → "nghìn" | "ngàn"
# a <100 group under a larger scale → with or without "không trăm"
# a <10 remainder after "trăm" → "lẻ" | "linh"
_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]]
# Speakers routinely contract away "mươi": "ba mươi mốt" -> "ba mốt",
# "hai mươi lăm" -> "hai lăm". Both ASRs emit the contracted form.
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() # most significant first
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
# A group is "padded" only when something more significant precedes it.
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(".", "")))
# ── span builders ─────────────────────────────────────────────────────────────
# Each returns the acceptable realizations of one surface span, written forms
# FIRST (index 0 is always the verbatim source text, so `text` itself is always
# among the references and coordinate descent starts from it).
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.
"""
# The zero-padded numeral is deliberately NOT offered in the half-spoken
# forms. "18 tháng 04" is ambiguous — whisper-large-v3 writes it both for
# audio that says "tháng tư" and for audio that says "tháng KHÔNG tư" — and
# admitting it silently excuses the voiced-leading-zero defect that
# PhoWhisper transcribes explicitly. The verbatim ``written`` span stays a
# reference (it is the source text); only the expansion is unpadded.
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
# ── the span table ────────────────────────────────────────────────────────────
# Keyed by the LITERAL substring as it appears in evaluation/text_pools.py.
# Matching is longest-key-first and non-overlapping, so "20h" wins over "0h"
# and "12,7%" over "12%".
#
# Curated by hand against the two ASRs' actual output (see
# https://github.com/zeroweight-ai/ZeroTTS/blob/main/evaluation/HIGH_WER_ANALYSIS.md); every entry is a reading a correct
# Vietnamese speaker could produce for that span.
SPANS: dict[str, list[str]] = {
# ── acronyms & brands ─────────────────────────────────────────────────────
# Vietnamese reads Latin acronyms three ways: keep the letters, spell them
# with Vietnamese letter names, or substitute the translated full name. All
# three are correct; which one comes out is the model's choice, not an error.
"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"],
# Codes: the letters may stay Latin or be spelled with Vietnamese letter
# names, and the digits may stay digits or be read out — independently.
"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 đê"],
# ── quarters (roman numerals) ─────────────────────────────────────────────
"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"],
# ── units & symbols ───────────────────────────────────────────────────────
"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"],
# ── dates ─────────────────────────────────────────────────────────────────
"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),
# ── times ─────────────────────────────────────────────────────────────────
"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"],
# ── percentages ───────────────────────────────────────────────────────────
"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"),
# ── quantities (span includes the unit so bare digits stay unambiguous) ───
"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"],
# ── spelled-out numbers in the SOURCE text ────────────────────────────────
# The mirror image of the cases above: where text_pools already writes the
# number as words, whisper-large-v3 transcribes it back as a digit ("thứ
# Sáu" -> "thứ 6", "chín giờ" -> "9 giờ"). Same audio either way, so
# admitting both spellings cannot excuse a mispronunciation — it only stops
# charging WER for the ASR's choice of numerals.
"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"],
# ── English loanwords whose Vietnamese pronunciation both ASRs re-spell ───
# Kept deliberately short: two-ASR agreement already covers PhoWhisper's
# phonetic renderings. These are the ones BOTH ASRs write differently from
# the source, i.e. genuinely ambiguous orthography rather than ASR weakness.
"Series": ["Series", "Serie"],
"series": ["series", "serie"],
"Team": ["Team", "Tim"],
# NOTE deliberately absent: "khuyến mãi" / "khuyến mại". That pair differs
# by TONE (ngã vs nặng), so it is a mispronunciation, not a spelling
# variant — the model really did say the wrong tone and must be charged.
# Same rule for every other tone-only pair: never admit one.
# ── bare years (always preceded by "năm" in the source text) ──────────────
"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)))
# ── expansion & scoring ───────────────────────────────────────────────────────
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)
|