lsgr / az_numbers.py
cillegio's picture
Upload folder using huggingface_hub
b8a600a verified
Raw History Blame Contribute Delete
6.7 kB
"""Canonicalise numbers in Azerbaijani text, for scoring only.
The corpora disagree about how to write a number, and so does any single one of
them: our own call corpus writes digits on 14.3% of lines and number words on
15.5%. Soniox writes "108" for an identifier and "iki min üçüncü" for a date,
which is correct on both counts and unscoreable against a model that chose the
other form. Edit distance sees unrelated tokens and charges a full substitution
for a number the model got right.
So this runs on the reference *and* the hypothesis before scoring, never on
training targets. Two rules make it safe:
digits -> words, never the reverse. "2003" -> "iki min üç" is deterministic.
"bir" -> "1" is wrong most of the time, because bir is also the indefinite
article: "bir az" is "a little", not "1 az". Rewriting words to digits would
corrupt ordinary prose across every corpus we have.
ordinals collapse to cardinals on both sides. "2003-cü" and "iki min üçüncü"
both become "iki min üç". That is not a correct transcription of either, and
it does not need to be -- it is a comparison key, and its only job is that two
spellings of the same spoken number produce the same tokens.
Roman numerals are folded in too: the corpora write "XIX əsr" where a model
emits "19-cu əsr", which is the same disagreement wearing a different alphabet.
"""
from __future__ import annotations
import re
ONES = ["", "bir", "iki", "üç", "dörd", "beş", "altı", "yeddi", "səkkiz", "doqquz"]
TENS = ["", "on", "iyirmi", "otuz", "qırx", "əlli", "altmış", "yetmiş",
"səksən", "doxsan"]
SCALES = [(10 ** 9, "milyard"), (10 ** 6, "milyon"), (1000, "min"), (100, "yüz")]
# Ordinal word -> the cardinal it is built from. Listed rather than derived
# because the suffix follows vowel harmony and the stems are not all regular
# (doqquz -> doqquzuncu, altı -> altıncı, qırx -> qırxıncı).
ORDINALS = {
"birinci": "bir", "ikinci": "iki", "üçüncü": "üç", "dördüncü": "dörd",
"beşinci": "beş", "altıncı": "altı", "yeddinci": "yeddi",
"səkkizinci": "səkkiz", "doqquzuncu": "doqquz", "onuncu": "on",
"iyirminci": "iyirmi", "otuzuncu": "otuz", "qırxıncı": "qırx",
"əllinci": "əlli", "altmışıncı": "altmış", "yetmişinci": "yetmiş",
"səksəninci": "səksən", "doxsanıncı": "doxsan", "yüzüncü": "yüz",
"mininci": "min", "milyonuncu": "milyon",
}
ROMAN_VALUES = {"i": 1, "v": 5, "x": 10, "l": 50, "c": 100, "d": 500, "m": 1000}
# Roman numerals up to 99, which covers what actually appears here: centuries
# and volume numbers. Written as the standard subtractive grammar rather than a
# flat alternation, because a flat one cannot backtrack into "XIX" -- it commits
# to the leading X and then finds an I it has no rule for.
ROMAN_RX = re.compile(
r"(?<![\w])((?=[IVXL])(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3}))(?![\w])")
# A digit run, optionally carrying an Azerbaijani ordinal suffix: 19-cu, 2003-cü,
# 1-ci. The suffix is dropped, matching what happens to the ordinal words.
DIGIT_RX = re.compile(r"(?<!\w)(\d+)\s*-?\s*(?:[cç][ıiuü]|[ıiuü]nc[ıiuü])?(?!\w)",
re.IGNORECASE)
def int_to_az_words(n: int) -> str:
"""Cardinal form. 0 -> sıfır, 100 -> yüz (not "bir yüz"), 1000 -> min."""
if n == 0:
return "sıfır"
if n < 0:
return "mənfi " + int_to_az_words(-n)
out: list[str] = []
for value, name in SCALES:
if n >= value:
count = n // value
# "yüz" and "min" stand alone at a count of one; "milyon" and
# "milyard" take an explicit "bir".
if count > 1 or value >= 10 ** 6:
out.append(int_to_az_words(count))
out.append(name)
n %= value
if n >= 10:
out.append(TENS[n // 10])
n %= 10
if n > 0:
out.append(ONES[n])
return " ".join(out)
def roman_to_int(s: str) -> int | None:
s = s.lower()
total = prev = 0
for ch in reversed(s):
v = ROMAN_VALUES.get(ch)
if v is None:
return None
total += -v if v < prev else v
prev = max(prev, v)
return total or None
def _expand_digits(m: re.Match) -> str:
raw = m.group(1)
# A long run is an identifier -- a phone number, an account -- and is read
# out rather than said as one quantity. Grouping it in pairs matches how
# these are spoken and, more to the point, matches whatever the other side
# did with the same digits.
if len(raw) > 6:
return " ".join(int_to_az_words(int(raw[i:i + 2]))
for i in range(0, len(raw), 2))
try:
return int_to_az_words(int(raw))
except ValueError:
return raw
def _expand_roman(m: re.Match) -> str:
s = m.group(1)
# A single character is left alone. In Azerbaijani "I" is the capital
# dotless i and "V" and "L" start ordinary words, so a one-letter match is
# far more often a letter than a numeral.
if len(s) < 2:
return s
v = roman_to_int(s)
return int_to_az_words(v) if v else s
def normalise_numbers(text: str, romans: bool = True) -> str:
"""Canonical number form, for comparison only -- never for training text."""
if not text:
return text
if romans:
text = ROMAN_RX.sub(_expand_roman, text)
text = DIGIT_RX.sub(_expand_digits, text)
# ordinal words down to their cardinals, so "üçüncü" meets the "üç" that
# "2003-cü" just became
return " ".join(ORDINALS.get(w.lower(), w) for w in text.split())
if __name__ == "__main__":
CASES = [
("2003-cü ildə", "iki min üç ildə"),
("İki min üçüncü ildə", "İki min üç ildə"),
("XIX əsrin əvvəllərində", "on doqquz əsrin əvvəllərində"),
("19-cu əsrin əvvəllərində", "on doqquz əsrin əvvəllərində"),
("27 manat", "iyirmi yeddi manat"),
("108, düzdürmü?", "yüz səkkiz, düzdürmü?"),
("3 dəqiqədən sonra", "üç dəqiqədən sonra"),
("bir az gözlə", "bir az gözlə"), # the article must survive
("Birinci yaşayış yeri", "bir yaşayış yeri"),
("1000 nəfər", "min nəfər"),
("2500", "iki min beş yüz"),
("0", "sıfır"),
]
bad = 0
for src, want in CASES:
got = normalise_numbers(src)
ok = got == want
bad += not ok
print(f"{'ok ' if ok else 'FAIL'} {src!r}\n -> {got!r}"
+ ("" if ok else f"\n want {want!r}"))
print(f"\n{len(CASES)-bad}/{len(CASES)} passed")
raise SystemExit(1 if bad else 0)