FilSwitch / eval_script.py
qwerttyuiiop's picture
Create eval_script.py
0e8589b verified
Raw
History Blame Contribute Delete
7.19 kB
"""Dataset-normalized word error rate (WER)."""
import re
import jiwer
from word2number import w2n
def convert_text(text: str) -> str:
"""Convert the dataset's spoken English number forms to digits."""
text = re.sub(
r"\bcovid-nineteen\b",
"COVID-19",
text,
flags=re.IGNORECASE,
)
decade_map = {
"hundreds": 0,
"tens": 10,
"twenties": 20,
"thirties": 30,
"forties": 40,
"fifties": 50,
"sixties": 60,
"seventies": 70,
"eighties": 80,
"nineties": 90,
}
def decade_to_number(match):
prefix = match.group(1).lower()
suffix = match.group(2).lower()
base = 1900 if prefix == "nineteen" else 2000
return f"{base + decade_map[suffix]}s"
text = re.sub(
r"\b(nineteen|twenty)\s+"
r"(hundreds|tens|twenties|thirties|forties|fifties|"
r"sixties|seventies|eighties|nineties)\b",
decade_to_number,
text,
flags=re.IGNORECASE,
)
def spoken_year_to_number(match):
prefix = match.group(1).lower()
remainder = match.group(2)
try:
value = w2n.word_to_num(remainder)
if 0 <= value <= 99:
base = 1900 if prefix == "nineteen" else 2000
return str(base + value)
except Exception:
pass
return match.group(0)
text = re.sub(
r"\b(nineteen|twenty)\s+"
r"(ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|"
r"eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|"
r"eighty|ninety)"
r"(?:[\s-](?:zero|one|two|three|four|five|six|seven|eight|nine))?\b",
spoken_year_to_number,
text,
flags=re.IGNORECASE,
)
text = re.sub(
r"\b(one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve)"
r"\s+(am|pm)\b",
lambda match: (
f"{w2n.word_to_num(match.group(1))} {match.group(2).upper()}"
),
text,
flags=re.IGNORECASE,
)
def spoken_time_to_number(match):
try:
hour = w2n.word_to_num(match.group(1))
minute = w2n.word_to_num(match.group(2))
return f"{hour}:{minute:02d}"
except Exception:
return match.group(0)
text = re.sub(
r"\b(one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve)\s+"
r"(ten|twenty|thirty|forty|fifty)"
r"(?:[\s-](?:one|two|three|four|five|six|seven|eight|nine))?\b",
spoken_time_to_number,
text,
flags=re.IGNORECASE,
)
def filipino_time_to_number(match):
hour_map = {
"una": 1,
"dos": 2,
"tres": 3,
"kwatro": 4,
"singko": 5,
"sais": 6,
"syete": 7,
"otso": 8,
"nwebe": 9,
"dyis": 10,
"onse": 11,
"dose": 12,
}
hour = hour_map.get(match.group(2).lower())
if hour is None:
return match.group(0)
return f"{hour}:30" if match.group(3) else f"{hour}:00"
text = re.sub(
r"\b(ala|alas)-"
r"(una|dos|tres|kwatro|singko|sais|syete|otso|nwebe|dyis|onse|dose)"
r"(\s+y\s+medya)?\b",
filipino_time_to_number,
text,
flags=re.IGNORECASE,
)
def ordinal_to_number(match):
try:
number = w2n.word_to_num(match.group(0).replace("-", " "))
if 10 <= number % 100 <= 20:
suffix = "th"
else:
suffix = {1: "st", 2: "nd", 3: "rd"}.get(
number % 10,
"th",
)
return f"{number}{suffix}"
except Exception:
return match.group(0)
ordinal_pattern = (
r"\b(?:(?:one|two|three|four|five|six|seven|eight|nine|ten|"
r"eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|"
r"eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|"
r"eighty|ninety)[\s-])*"
r"(?:first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|"
r"tenth|eleventh|twelfth|thirteenth|fourteenth|fifteenth|"
r"sixteenth|seventeenth|eighteenth|nineteenth|twentieth|"
r"thirtieth|fortieth|fiftieth|sixtieth|seventieth|eightieth|"
r"ninetieth)\b"
)
text = re.sub(
ordinal_pattern,
ordinal_to_number,
text,
flags=re.IGNORECASE,
)
def legal_reference_to_number(match):
digit_words = {
"zero": "0",
"one": "1",
"two": "2",
"three": "3",
"four": "4",
"five": "5",
"six": "6",
"seven": "7",
"eight": "8",
"nine": "9",
}
digits = match.group(2).lower().split()
if not all(digit in digit_words for digit in digits):
return match.group(0)
return f"{match.group(1)} {''.join(digit_words[d] for d in digits)}"
text = re.sub(
r"\b(RA|Article|Barangay|Pavilion)\s+"
r"((?:zero|one|two|three|four|five|six|seven|eight|nine)"
r"(?:\s+(?:zero|one|two|three|four|five|six|seven|eight|nine))*)\b",
legal_reference_to_number,
text,
flags=re.IGNORECASE,
)
number_words = (
r"zero|one|two|three|four|five|six|seven|eight|nine|ten|"
r"eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|"
r"eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|"
r"eighty|ninety|hundred|thousand|million|billion"
)
def peso_amount_to_number(match):
try:
amount = w2n.word_to_num(match.group(1).replace("-", " "))
return f"{amount} pesos"
except Exception:
return match.group(0)
text = re.sub(
rf"\b(({number_words})(?:[\s-]+(?:{number_words}))*)\s+pesos\b",
peso_amount_to_number,
text,
flags=re.IGNORECASE,
)
def regular_number_to_number(match):
try:
words = re.sub(
r"\band\b",
"",
match.group(0),
flags=re.IGNORECASE,
).replace("-", " ")
return str(w2n.word_to_num(words))
except Exception:
return match.group(0)
text = re.sub(
rf"\b(({number_words})"
rf"(?:[\s-]+(?:and\s+)?(?:{number_words}))*)\b",
regular_number_to_number,
text,
flags=re.IGNORECASE,
)
return text
def normalize_for_wer(text: object) -> str:
"""Apply the dataset's casing, punctuation, and whitespace cleanup."""
text = str(text).casefold()
text = re.sub(r"[^\w\s']", " ", text, flags=re.UNICODE)
text = text.replace("_", " ")
return " ".join(text.split())
def wer(reference, hypothesis):
"""Compute the same digit-aware corpus WER with a JiWER-like API.
For each pair, the normalized reference and its spoken-number-to-digit
variant are compared with the hypothesis. The variant with fewer word edits
is used in the final corpus score, matching the dataset evaluator.
"""
references = [reference] if isinstance(reference, str) else list(reference)
hypotheses = (
[hypothesis] if isinstance(hypothesis, str) else list(hypothesis)
)
if len(references) != len(hypotheses):
raise ValueError(
"reference and hypothesis must contain the same number of sentences"
)
normalized_references = []
normalized_hypotheses = []
for reference_text, hypothesis_text in zip(references, hypotheses):
reference_raw = normalize_for_wer(reference_text)
reference_with_digits = normalize_for_wer(
convert_text(str(reference_text))
)
hypothesis_normalized = normalize_for_wer(hypothesis_text)
raw_result = jiwer.process_words(
reference_raw,
hypothesis_normalized,
)
digit_result = jiwer.process_words(
reference_with_digits,
hypothesis_normalized,
)
raw_errors = (
raw_result.substitutions
+ raw_result.deletions
+ raw_result.insertions
)
digit_errors = (
digit_result.substitutions
+ digit_result.deletions
+ digit_result.insertions
)
normalized_references.append(
reference_raw
if raw_errors < digit_errors
else reference_with_digits
)
normalized_hypotheses.append(hypothesis_normalized)
return jiwer.wer(normalized_references, normalized_hypotheses)