"""Persian text normalization shared by the corpus builder and the front end. normalize(text): Arabic letter forms -> Persian (ي ك ى -> ی ک ی), Persian/Arabic digits -> ASCII, tatweel and short-vowel marks removed (tanwin ً and kasra ـِ kept: they change the reading, kasra forces an ezafe), spaces squeezed, and every number written out in words (cardinals, decimals with ممیز, percent with درصد, thousands separators dropped). """ import re _ONES = ["صفر", "یک", "دو", "سه", "چهار", "پنج", "شش", "هفت", "هشت", "نه", "ده", "یازده", "دوازده", "سیزده", "چهارده", "پانزده", "شانزده", "هفده", "هجده", "نوزده"] _TENS = ["", "", "بیست", "سی", "چهل", "پنجاه", "شصت", "هفتاد", "هشتاد", "نود"] _HUNDREDS = ["", "صد", "دویست", "سیصد", "چهارصد", "پانصد", "ششصد", "هفتصد", "هشتصد", "نهصد"] _SCALES = [(10 ** 12, "تریلیون"), (10 ** 9, "میلیارد"), (10 ** 6, "میلیون"), (1000, "هزار")] def _below_1000(n): parts = [] if n >= 100: parts.append(_HUNDREDS[n // 100]); n %= 100 if n >= 20: parts.append(_TENS[n // 10]); n %= 10 if n: parts.append(_ONES[n]) return " و ".join(parts) def number_words(n): """Cardinal in words: 1250 -> یک هزار و دویست و پنجاه (هزار alone for 1000-1999).""" if n == 0: return _ONES[0] parts = [] for value, name in _SCALES: if n >= value: q = n // value; n %= value parts.append(name if (value == 1000 and q == 1) else f"{number_words(q)} {name}") if n: parts.append(_below_1000(n)) return " و ".join(parts) _DIGITS = str.maketrans("۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩", "01234567890123456789") _LETTERS = str.maketrans({"ي": "ی", "ى": "ی", "ك": "ک", "ۀ": "ه‌ی", "ة": "ه", "ـ": None, "‏": None, "‎": None, "َ": None, "ُ": None, "ْ": None, "ّ": None, "ٰ": None, "ٔ": None}) _THOUSANDS = re.compile(r"(?<=\d)[,٬](?=\d{3}\b)") _DECIMAL = re.compile(r"(\d+)[.٫/](\d+)") _PERCENT = re.compile(r"(\d+(?:[.٫]\d+)?)\s*[%٪]") _NUMBER = re.compile(r"\d+") def _decimal(m): return f"{number_words(int(m.group(1)))} ممیز {number_words(int(m.group(2)))}" def numbers_to_words(text): text = _THOUSANDS.sub("", text) text = _PERCENT.sub(lambda m: m.group(1) + " درصد", text) text = _DECIMAL.sub(_decimal, text) return _NUMBER.sub(lambda m: f" {number_words(int(m.group()))} ", text) _MI = re.compile(r"(? kasra, which the G2P reads as a forced ezafe text = text.replace("ه\u0654", "ه\u0650").replace("ۀ", "ه\u0650") text = text.translate(_DIGITS).translate(_LETTERS) text = numbers_to_words(text) text = re.sub(r"[ \t ]+", " ", text) text = re.sub(r" ?‌ ?", "‌", text) text = re.sub(r" ([،؛:.!؟?])", r"\1", text) # verb prefix and plural suffix written with a space instead of ZWNJ (می توان, دوره های) -> one word text = _MI.sub("\\1\u200c", text) text = _HA.sub("\u200c\\1", text) return text.strip()