Spaces:
Running

File size: 3,494 Bytes
ca681c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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"(?<![\u0600-\u06FF\u200c])(ن?می) (?=[\u0600-\u06FF])")
_HA = re.compile(r"(?<=[\u0600-\u06FF]) (ها|های|هایی|هایم|هایت|هایش|هایمان|هایتان|هایشان)(?![\u0600-\u06FF\u200c])")


def normalize(text):
    # ezafe written on a final he (خانهٔ, خانۀ) -> 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()