multilingual-num2text 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. multilingual_num2text/__init__.py +57 -0
  2. multilingual_num2text/core/__init__.py +16 -0
  3. multilingual_num2text/core/currencies.py +215 -0
  4. multilingual_num2text/core/digits.py +44 -0
  5. multilingual_num2text/core/language.py +186 -0
  6. multilingual_num2text/core/lexicon.py +74 -0
  7. multilingual_num2text/core/number_rules.py +415 -0
  8. multilingual_num2text/core/patterns.py +22 -0
  9. multilingual_num2text/core/registry.py +19 -0
  10. multilingual_num2text/core/text_rules.py +128 -0
  11. multilingual_num2text/core/words.py +29 -0
  12. multilingual_num2text/languages/__init__.py +4 -0
  13. multilingual_num2text/languages/bangla/__init__.py +3 -0
  14. multilingual_num2text/languages/bangla/currencies.py +191 -0
  15. multilingual_num2text/languages/bangla/language.py +110 -0
  16. multilingual_num2text/languages/bangla/lexicon.py +60 -0
  17. multilingual_num2text/languages/bangla/rules.py +75 -0
  18. multilingual_num2text/languages/bangla/vocabulary.py +86 -0
  19. multilingual_num2text/languages/english/__init__.py +3 -0
  20. multilingual_num2text/languages/english/currencies.py +208 -0
  21. multilingual_num2text/languages/english/language.py +113 -0
  22. multilingual_num2text/languages/english/lexicon.py +27 -0
  23. multilingual_num2text/languages/english/rules.py +71 -0
  24. multilingual_num2text/languages/english/vocabulary.py +71 -0
  25. multilingual_num2text-0.1.0.dist-info/METADATA +197 -0
  26. multilingual_num2text-0.1.0.dist-info/RECORD +29 -0
  27. multilingual_num2text-0.1.0.dist-info/WHEEL +5 -0
  28. multilingual_num2text-0.1.0.dist-info/licenses/LICENSE +202 -0
  29. multilingual_num2text-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,57 @@
1
+ """Convert numbers to words in several languages.
2
+
3
+ from multilingual_num2text import convert_text, number_to_text, NumberStyle
4
+
5
+ number_to_text(2712, "bn") # দুই হাজার সাতশত বারো
6
+ number_to_text(2712, "en", "digitwise") # two seven one two
7
+ convert_text("Send ৳1,250.50 to 01711-123456", "en")
8
+ """
9
+
10
+ import re
11
+
12
+ from .core import (
13
+ Currency,
14
+ Language,
15
+ Lexicon,
16
+ NumberStyle,
17
+ Rule,
18
+ Words,
19
+ available_languages,
20
+ get_language,
21
+ register_language,
22
+ )
23
+ from .languages import BanglaLanguage, EnglishLanguage
24
+ from .languages.bangla.lexicon import LEXICON as BANGLA_LEXICON
25
+ from .languages.english.lexicon import LEXICON as ENGLISH_LEXICON
26
+
27
+ register_language(BanglaLanguage())
28
+ register_language(EnglishLanguage())
29
+
30
+
31
+ def convert_text(text: str, lang: str, keep: re.Pattern | None = None) -> str:
32
+ """Write out every number in the text as words, in the given language."""
33
+ return get_language(lang).convert_text(text, keep)
34
+
35
+
36
+ def number_to_text(value: int | float | str, lang: str, style: NumberStyle | str = NumberStyle.CARDINAL) -> str:
37
+ """Speak one number. style: 'cardinal' (default), 'digitwise' or 'auto'."""
38
+ return get_language(lang).number_to_text(value, style)
39
+
40
+
41
+ __all__ = [
42
+ "BANGLA_LEXICON",
43
+ "ENGLISH_LEXICON",
44
+ "BanglaLanguage",
45
+ "Currency",
46
+ "EnglishLanguage",
47
+ "Language",
48
+ "Lexicon",
49
+ "NumberStyle",
50
+ "Rule",
51
+ "Words",
52
+ "available_languages",
53
+ "convert_text",
54
+ "get_language",
55
+ "number_to_text",
56
+ "register_language",
57
+ ]
@@ -0,0 +1,16 @@
1
+ from .language import Language, NumberStyle, Rule
2
+ from .lexicon import Currency, Lexicon
3
+ from .registry import available_languages, get_language, register_language
4
+ from .words import Words
5
+
6
+ __all__ = [
7
+ "Currency",
8
+ "Language",
9
+ "Lexicon",
10
+ "NumberStyle",
11
+ "Rule",
12
+ "Words",
13
+ "available_languages",
14
+ "get_language",
15
+ "register_language",
16
+ ]
@@ -0,0 +1,215 @@
1
+ """Every circulating ISO 4217 currency: code, written symbols and digits after the decimal point.
2
+
3
+ Names live in each language (languages/<lang>/currencies.py) and are joined with this table by
4
+ build_currencies(). The ISO code itself is always recognised, so symbols list only extra forms.
5
+ Ambiguous signs shared by many currencies (kr, R, P, Fr) are left out on purpose.
6
+ """
7
+
8
+ from dataclasses import dataclass
9
+
10
+ from .lexicon import Currency
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class CurrencyCode:
15
+ code: str
16
+ symbols: tuple[str, ...] = ()
17
+ minor_digits: int = 2
18
+
19
+
20
+ CURRENCY_CODES = (
21
+ CurrencyCode("AED", ("د.إ",)),
22
+ CurrencyCode("AFN", ("؋",)),
23
+ CurrencyCode("ALL"),
24
+ CurrencyCode("AMD", ("֏",)),
25
+ CurrencyCode("AOA", ("Kz",)),
26
+ CurrencyCode("ARS"),
27
+ CurrencyCode("AUD", ("A$", "AU$")),
28
+ CurrencyCode("AWG", ("Afl.",)),
29
+ CurrencyCode("AZN", ("₼",)),
30
+ CurrencyCode("BAM", ("KM",)),
31
+ CurrencyCode("BBD", ("Bds$",)),
32
+ CurrencyCode("BDT", ("৳", "Tk.", "Tk", "TK")),
33
+ CurrencyCode("BHD", ("BD",), 3),
34
+ CurrencyCode("BIF", (), 0),
35
+ CurrencyCode("BMD"),
36
+ CurrencyCode("BND", ("B$",)),
37
+ CurrencyCode("BOB", ("Bs.",)),
38
+ CurrencyCode("BRL", ("R$",)),
39
+ CurrencyCode("BSD"),
40
+ CurrencyCode("BTN", ("Nu.",)),
41
+ CurrencyCode("BWP"),
42
+ CurrencyCode("BYN"),
43
+ CurrencyCode("BZD", ("BZ$",)),
44
+ CurrencyCode("CAD", ("C$", "CA$")),
45
+ CurrencyCode("CDF", ("FC",)),
46
+ CurrencyCode("CHF"),
47
+ CurrencyCode("CLP", (), 0),
48
+ CurrencyCode("CNY", ("CN¥", "元", "RMB")),
49
+ CurrencyCode("COP", ("COL$",)),
50
+ CurrencyCode("CRC", ("₡",)),
51
+ CurrencyCode("CUP"),
52
+ CurrencyCode("CVE"),
53
+ CurrencyCode("CZK", ("Kč",)),
54
+ CurrencyCode("DJF", ("Fdj",), 0),
55
+ CurrencyCode("DKK"),
56
+ CurrencyCode("DOP", ("RD$",)),
57
+ CurrencyCode("DZD"),
58
+ CurrencyCode("EGP", ("E£",)),
59
+ CurrencyCode("ERN", ("Nfk",)),
60
+ CurrencyCode("ETB"),
61
+ CurrencyCode("EUR", ("€",)),
62
+ CurrencyCode("FJD", ("FJ$",)),
63
+ CurrencyCode("FKP"),
64
+ CurrencyCode("GBP", ("£",)),
65
+ CurrencyCode("GEL", ("₾",)),
66
+ CurrencyCode("GHS", ("GH₵", "₵")),
67
+ CurrencyCode("GIP"),
68
+ CurrencyCode("GMD"),
69
+ CurrencyCode("GNF", ("FG",), 0),
70
+ CurrencyCode("GTQ"),
71
+ CurrencyCode("GYD", ("G$",)),
72
+ CurrencyCode("HKD", ("HK$",)),
73
+ CurrencyCode("HNL"),
74
+ CurrencyCode("HTG"),
75
+ CurrencyCode("HUF", ("Ft",)),
76
+ CurrencyCode("IDR", ("Rp",)),
77
+ CurrencyCode("ILS", ("₪",)),
78
+ CurrencyCode("INR", ("₹", "Rs.", "Rs")),
79
+ CurrencyCode("IQD", (), 3),
80
+ CurrencyCode("IRR", (), 0),
81
+ CurrencyCode("ISK", (), 0),
82
+ CurrencyCode("JMD", ("J$",)),
83
+ CurrencyCode("JOD", ("JD",), 3),
84
+ CurrencyCode("JPY", ("¥", "円"), 0),
85
+ CurrencyCode("KES", ("KSh",)),
86
+ CurrencyCode("KGS"),
87
+ CurrencyCode("KHR", ("៛",)),
88
+ CurrencyCode("KMF", (), 0),
89
+ CurrencyCode("KPW"),
90
+ CurrencyCode("KRW", ("₩",), 0),
91
+ CurrencyCode("KWD", ("KD",), 3),
92
+ CurrencyCode("KYD", ("CI$",)),
93
+ CurrencyCode("KZT", ("₸",)),
94
+ CurrencyCode("LAK", ("₭",)),
95
+ CurrencyCode("LBP"),
96
+ CurrencyCode("LKR"),
97
+ CurrencyCode("LRD", ("L$",)),
98
+ CurrencyCode("LSL"),
99
+ CurrencyCode("LYD", ("LD",), 3),
100
+ CurrencyCode("MAD"),
101
+ CurrencyCode("MDL"),
102
+ CurrencyCode("MGA", (), 0),
103
+ CurrencyCode("MKD"),
104
+ CurrencyCode("MMK"),
105
+ CurrencyCode("MNT", ("₮",)),
106
+ CurrencyCode("MOP", ("MOP$",)),
107
+ CurrencyCode("MRU", (), 0),
108
+ CurrencyCode("MUR"),
109
+ CurrencyCode("MVR", ("Rf",)),
110
+ CurrencyCode("MWK"),
111
+ CurrencyCode("MXN", ("Mex$",)),
112
+ CurrencyCode("MYR", ("RM",)),
113
+ CurrencyCode("MZN", ("MT",)),
114
+ CurrencyCode("NAD", ("N$",)),
115
+ CurrencyCode("NGN", ("₦",)),
116
+ CurrencyCode("NIO"),
117
+ CurrencyCode("NOK"),
118
+ CurrencyCode("NPR"),
119
+ CurrencyCode("NZD", ("NZ$",)),
120
+ CurrencyCode("OMR", (), 3),
121
+ CurrencyCode("PAB"),
122
+ CurrencyCode("PEN", ("S/",)),
123
+ CurrencyCode("PGK"),
124
+ CurrencyCode("PHP", ("₱",)),
125
+ CurrencyCode("PKR"),
126
+ CurrencyCode("PLN", ("zł",)),
127
+ CurrencyCode("PYG", ("₲",), 0),
128
+ CurrencyCode("QAR"),
129
+ CurrencyCode("RON"),
130
+ CurrencyCode("RSD"),
131
+ CurrencyCode("RUB", ("₽",)),
132
+ CurrencyCode("RWF", (), 0),
133
+ CurrencyCode("SAR"),
134
+ CurrencyCode("SBD", ("SI$",)),
135
+ CurrencyCode("SCR"),
136
+ CurrencyCode("SDG"),
137
+ CurrencyCode("SEK"),
138
+ CurrencyCode("SGD", ("S$",)),
139
+ CurrencyCode("SHP"),
140
+ CurrencyCode("SLE"),
141
+ CurrencyCode("SOS"),
142
+ CurrencyCode("SRD"),
143
+ CurrencyCode("SSP"),
144
+ CurrencyCode("STN", ("Db",)),
145
+ CurrencyCode("SYP"),
146
+ CurrencyCode("SZL"),
147
+ CurrencyCode("THB", ("฿",)),
148
+ CurrencyCode("TJS"),
149
+ CurrencyCode("TMT"),
150
+ CurrencyCode("TND", ("DT",), 3),
151
+ CurrencyCode("TOP", ("T$",)),
152
+ CurrencyCode("TRY", ("₺",)),
153
+ CurrencyCode("TTD", ("TT$",)),
154
+ CurrencyCode("TWD", ("NT$",)),
155
+ CurrencyCode("TZS", ("TSh",)),
156
+ CurrencyCode("UAH", ("₴",)),
157
+ CurrencyCode("UGX", ("USh",), 0),
158
+ CurrencyCode("USD", ("$", "US$")),
159
+ CurrencyCode("UYU"),
160
+ CurrencyCode("UZS"),
161
+ CurrencyCode("VES"),
162
+ CurrencyCode("VND", ("₫",), 0),
163
+ CurrencyCode("VUV", (), 0),
164
+ CurrencyCode("WST"),
165
+ CurrencyCode("XAF", (), 0),
166
+ CurrencyCode("XCD", ("EC$",)),
167
+ CurrencyCode("XCG"),
168
+ CurrencyCode("XOF", (), 0),
169
+ CurrencyCode("XPF", (), 0),
170
+ CurrencyCode("YER"),
171
+ CurrencyCode("ZAR"),
172
+ CurrencyCode("ZMW"),
173
+ CurrencyCode("ZWG", ("ZiG",)),
174
+ )
175
+
176
+ CurrencyName = tuple[str, str | None, str | None, str | None]
177
+
178
+
179
+ def build_currencies(
180
+ names: dict[str, CurrencyName],
181
+ aliases: dict[str, str] | None = None,
182
+ extra_symbols: dict[str, tuple[str, ...]] | None = None,
183
+ ambiguous_words: tuple[str, ...] = (),
184
+ ) -> tuple[Currency, ...]:
185
+ """Joins the code table with one language's names.
186
+
187
+ names: code -> (unit, unit plural or None, subunit or None, subunit plural or None)
188
+ aliases: other written words for a currency, e.g. {"রিয়াল": "SAR"}
189
+ extra_symbols: language-specific written forms, e.g. {"BDT": ("/-",)}
190
+ ambiguous_words: unit names that must not be read as money after a number, e.g. "pound" (weight)
191
+ """
192
+ aliases = aliases or {}
193
+ extra_symbols = extra_symbols or {}
194
+ currencies = []
195
+ for entry in CURRENCY_CODES:
196
+ if entry.code not in names:
197
+ continue
198
+ unit, unit_plural, subunit, subunit_plural = names[entry.code]
199
+ written_names = (unit, unit_plural, *(word for word, code in aliases.items() if code == entry.code))
200
+ currencies.append(
201
+ Currency(
202
+ unit=unit,
203
+ subunit=subunit,
204
+ unit_plural=unit_plural,
205
+ subunit_plural=subunit_plural,
206
+ code=entry.code,
207
+ minor_digits=entry.minor_digits if subunit else 0,
208
+ symbols=(entry.code, *entry.symbols),
209
+ suffix_symbols=(
210
+ *extra_symbols.get(entry.code, ()),
211
+ *(word for word in written_names if word and word not in ambiguous_words),
212
+ ),
213
+ )
214
+ )
215
+ return tuple(currencies)
@@ -0,0 +1,44 @@
1
+ """Digit helpers. Any Unicode decimal digit works: ASCII, Bangla, Devanagari, Arabic-Indic and so on."""
2
+
3
+ import re
4
+ import unicodedata
5
+
6
+ ZERO_DIGITS = "".join(
7
+ chr(code) for code in range(0x10000) if chr(code).isdecimal() and unicodedata.digit(chr(code)) == 0
8
+ )
9
+
10
+ _INDIAN_GROUPING = re.compile(r"[0-9]{1,2}(?:,[0-9]{2})*,[0-9]{3}")
11
+ _INTERNATIONAL_GROUPING = re.compile(r"[0-9]{1,3}(?:,[0-9]{3})+")
12
+
13
+
14
+ def to_ascii_digits(text: str) -> str:
15
+ return "".join(str(unicodedata.digit(char)) if char.isdecimal() else char for char in text)
16
+
17
+
18
+ def only_digits(text: str) -> str:
19
+ return "".join(char for char in text if char.isdecimal())
20
+
21
+
22
+ def parse_int(text: str) -> int:
23
+ digits = to_ascii_digits(only_digits(text))
24
+ return int(digits) if digits else 0
25
+
26
+
27
+ def starts_with_zero(number: str) -> bool:
28
+ return number[:1] in ZERO_DIGITS
29
+
30
+
31
+ def has_valid_grouping(number: str) -> bool:
32
+ """True for plain digits, Indian grouping (12,34,567) or international grouping (123,456)."""
33
+ number = to_ascii_digits(number)
34
+ if "," not in number:
35
+ return True
36
+ return bool(_INDIAN_GROUPING.fullmatch(number) or _INTERNATIONAL_GROUPING.fullmatch(number))
37
+
38
+
39
+ def split_number(text: str) -> tuple[bool, str, str]:
40
+ """'-১,২৫০.৫০' -> (True, '1250', '50'). Returns ASCII digits without commas."""
41
+ text = to_ascii_digits(text.strip())
42
+ is_negative = text[:1] in "-−"
43
+ integer, _, fraction = text.lstrip("+-−").replace(",", "").partition(".")
44
+ return is_negative, integer, fraction
@@ -0,0 +1,186 @@
1
+ """The interface every language implements.
2
+
3
+ A new language subclasses Language, sets `code`, `words` and `lexicon`, and implements the five
4
+ abstract methods. Everything else (finding numbers in text, money, phones, ranges ...) is shared.
5
+ """
6
+
7
+ import re
8
+ from abc import ABC, abstractmethod
9
+ from collections.abc import Callable
10
+ from decimal import Decimal
11
+ from enum import Enum
12
+
13
+ from .digits import parse_int, split_number, to_ascii_digits
14
+ from .lexicon import Currency, Lexicon
15
+ from .patterns import UNSIGNED_AMOUNT
16
+ from .words import Words
17
+
18
+ Rule = Callable[[str], str]
19
+
20
+ _NUMBER_TEXT = re.compile(rf"[-−+]?{UNSIGNED_AMOUNT}")
21
+
22
+
23
+ class NumberStyle(str, Enum):
24
+ CARDINAL = "cardinal"
25
+ DIGITWISE = "digitwise"
26
+ AUTO = "auto"
27
+
28
+
29
+ class Language(ABC):
30
+ code: str
31
+ words: Words
32
+ lexicon: Lexicon
33
+ money_inflection_pattern: str = ""
34
+ separate_number_words: bool = False
35
+
36
+ def __init__(self, lexicon: Lexicon | None = None) -> None:
37
+ """lexicon: replaces the language's built-in data, usually built with DEFAULT_LEXICON.extended(...)."""
38
+ if lexicon is not None:
39
+ self.lexicon = lexicon
40
+ self._rules: list[Rule] | None = None
41
+
42
+ @abstractmethod
43
+ def to_cardinal(self, number: int) -> str:
44
+ """2712 -> 'two thousand seven hundred twelve'"""
45
+
46
+ @abstractmethod
47
+ def to_ordinal(self, number: int) -> str:
48
+ """21 -> 'twenty-first'"""
49
+
50
+ @abstractmethod
51
+ def to_year(self, year: int) -> str:
52
+ """1971 -> 'nineteen seventy-one'"""
53
+
54
+ @abstractmethod
55
+ def to_date(self, day: int, month: int, year: str | None = None) -> str:
56
+ """(10, 5, '2024') -> 'the tenth of May, twenty twenty-four'. year keeps its written digits."""
57
+
58
+ @abstractmethod
59
+ def to_time(self, hour: int, minute: int = 0, second: int | None = None, with_period: bool = False) -> str:
60
+ """(15, 45) -> 'three forty-five PM'. hour is 0-23; with_period=True when the text said AM/PM."""
61
+
62
+ def language_rules(self) -> list[Rule]:
63
+ """Extra rules only this language needs (month names, ordinals ...).
64
+ They run after codes and scaled money, before dates, times and phones."""
65
+ return []
66
+
67
+ def build_rules(self) -> list[Rule]:
68
+ from .number_rules import NumberRules
69
+ from .text_rules import TextRules
70
+
71
+ text_rules, number_rules = TextRules(self), NumberRules(self)
72
+ return [
73
+ *text_rules.preparation_rules(),
74
+ *number_rules.early_rules(),
75
+ *self.language_rules(),
76
+ *number_rules.shape_rules(),
77
+ *number_rules.amount_rules(),
78
+ *number_rules.plain_number_rules(),
79
+ text_rules.cleanup_symbols,
80
+ ]
81
+
82
+ def to_mixed_fraction(self, whole: int, fraction: str) -> str:
83
+ """(2, '½') -> 'two point five' by default. Languages override with natural forms."""
84
+ decimal = {"½": "5", "¼": "25", "¾": "75"}[fraction]
85
+ return self.spell_number(f"{whole}.{decimal}")
86
+
87
+ def spell_scaled_amount(self, amount: str) -> str:
88
+ """The number in '৳2.5 crore' or '$5 million'. Languages may override (Bangla: আড়াই)."""
89
+ return self.spell_number(amount)
90
+
91
+ @property
92
+ def rules(self) -> list[Rule]:
93
+ if self._rules is None:
94
+ self._rules = self.build_rules()
95
+ return self._rules
96
+
97
+ def to_digitwise(self, text: str | int) -> str:
98
+ spoken = []
99
+ symbols = self.words.symbols
100
+ for char in str(text):
101
+ if char.isdecimal():
102
+ spoken.append(self.words.digits[int(to_ascii_digits(char))])
103
+ elif char in symbols:
104
+ spoken.append(symbols[char])
105
+ return " ".join(spoken)
106
+
107
+ def to_decimal(self, integer: str, fraction: str) -> str:
108
+ if self.lexicon.strip_decimal_trailing_zeros:
109
+ fraction = to_ascii_digits(fraction).rstrip("0")
110
+ whole = self.to_cardinal(parse_int(integer))
111
+ if not fraction:
112
+ return whole
113
+ return f"{whole} {self.words.decimal_point} {self.to_digitwise(fraction)}"
114
+
115
+ def spell_number(self, text: str) -> str:
116
+ if not _NUMBER_TEXT.fullmatch(text.strip()):
117
+ raise ValueError(f"Not a number: {text!r}")
118
+ is_negative, integer, fraction = split_number(text)
119
+ spoken = self.to_decimal(integer, fraction)
120
+ return f"{self.words.negative} {spoken}" if is_negative else spoken
121
+
122
+ def to_money(self, amount: str, currency: Currency) -> str:
123
+ is_negative, integer, fraction = split_number(amount)
124
+ fraction = fraction.rstrip("0")
125
+
126
+ if len(fraction) > currency.minor_digits:
127
+ spoken = f"{self.to_decimal(integer, fraction)} {currency.unit_for(2)}"
128
+ else:
129
+ major = parse_int(integer)
130
+ minor = int(fraction.ljust(currency.minor_digits, "0")) if fraction else 0
131
+ parts = []
132
+ if major or not minor:
133
+ parts.append(f"{self.to_cardinal(major)} {currency.unit_for(major)}")
134
+ if minor:
135
+ parts.append(f"{self.to_cardinal(minor)} {currency.subunit_for(minor)}")
136
+ joiner = f" {self.words.money_joiner} " if self.words.money_joiner else " "
137
+ spoken = joiner.join(parts)
138
+
139
+ return f"{self.words.negative} {spoken}" if is_negative else spoken
140
+
141
+ def to_percent(self, text: str) -> str:
142
+ return f"{self.spell_number(text)} {self.words.percent}"
143
+
144
+ def to_ratio(self, first: int, second: int) -> str:
145
+ return f"{self.to_cardinal(first)} {self.words.ratio} {self.to_cardinal(second)}"
146
+
147
+ def convert_text(self, text: str, keep: re.Pattern | None = None) -> str:
148
+ """Write out every number in the text as words.
149
+
150
+ keep: a pattern with one capturing group around the whole match, for parts that must
151
+ pass through untouched, e.g. emotion tags like "[warm]".
152
+ """
153
+ if not text:
154
+ return text
155
+ if keep is None:
156
+ return self._apply_rules(str(text))
157
+
158
+ spoken = []
159
+ for index, piece in enumerate(keep.split(str(text))):
160
+ said = piece if index % 2 else self._apply_rules(piece)
161
+ if said.strip():
162
+ spoken.append(said.strip())
163
+ return " ".join(spoken)
164
+
165
+ def number_to_text(self, value: int | float | str, style: NumberStyle | str = NumberStyle.CARDINAL) -> str:
166
+ """CARDINAL: 2712 as one number. DIGITWISE: digit by digit.
167
+ AUTO: picks from the shape (0.../+... digit by digit, *123# as a code, currency as money).
168
+ """
169
+ text = _as_text(value)
170
+ style = NumberStyle(style)
171
+ if style is NumberStyle.DIGITWISE:
172
+ return self.to_digitwise(text)
173
+ if style is NumberStyle.AUTO:
174
+ return self.convert_text(text)
175
+ return self.spell_number(text)
176
+
177
+ def _apply_rules(self, text: str) -> str:
178
+ for rule in self.rules:
179
+ text = rule(text)
180
+ return text
181
+
182
+
183
+ def _as_text(value: int | float | str) -> str:
184
+ if isinstance(value, float):
185
+ return format(Decimal(repr(value)), "f")
186
+ return str(value).strip()
@@ -0,0 +1,74 @@
1
+ """Per-language data and settings. Each language fills one Lexicon."""
2
+
3
+ from dataclasses import dataclass, field, replace
4
+
5
+
6
+ @dataclass(frozen=True)
7
+ class Currency:
8
+ """symbols may come before or after the amount (৳500, 500 BDT); suffix_symbols only after (500 টাকা).
9
+ subunit is None for currencies without a fractional unit (yen, won); minor_digits is 3 for dinars like KWD.
10
+ """
11
+
12
+ unit: str
13
+ subunit: str | None
14
+ symbols: tuple[str, ...] = ()
15
+ suffix_symbols: tuple[str, ...] = ()
16
+ unit_plural: str | None = None
17
+ subunit_plural: str | None = None
18
+ code: str = ""
19
+ minor_digits: int = 2
20
+
21
+ def unit_for(self, count: int) -> str:
22
+ return self.unit_plural if count != 1 and self.unit_plural else self.unit
23
+
24
+ def subunit_for(self, count: int) -> str:
25
+ return self.subunit_plural if count != 1 and self.subunit_plural else self.subunit
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Lexicon:
30
+ """Data and settings for one language.
31
+
32
+ digitwise_numbers: numbers always read digit by digit wherever they appear (hotlines, short codes).
33
+ fixed_phrases: written -> spoken, matched case-insensitively ("24/7").
34
+ word_replacements: plain text replacements applied first.
35
+ removed_patterns: regexes deleted before reading (e.g. citation tags like [Source 1]).
36
+ acronyms / domain_words / email_name_words: how to pronounce those parts.
37
+ """
38
+
39
+ currencies: tuple[Currency, ...] = ()
40
+ digitwise_numbers: tuple[str, ...] = ()
41
+ fixed_phrases: dict[str, str] = field(default_factory=dict)
42
+ word_replacements: dict[str, str] = field(default_factory=dict)
43
+ removed_patterns: tuple[str, ...] = ()
44
+ acronyms: dict[str, str] = field(default_factory=dict)
45
+ domain_words: dict[str, str] = field(default_factory=dict)
46
+ bare_domain_endings: tuple[str, ...] = ("com", "net", "org", "gov", "edu", "bd", "info", "io")
47
+ email_name_words: dict[str, str] = field(default_factory=dict)
48
+ units: dict[str, str] = field(default_factory=dict)
49
+ magnitudes: dict[str, int] = field(
50
+ default_factory=lambda: {"k": 1_000, "K": 1_000, "M": 1_000_000, "bn": 1_000_000_000}
51
+ )
52
+ scale_words: tuple[str, ...] = ()
53
+ year_markers_after: tuple[str, ...] = ()
54
+ year_markers_before: tuple[str, ...] = ()
55
+ digitwise_min_length: int = 10
56
+ phone_max_digits: int = 15
57
+ phone_min_digits_after_plus: int = 6
58
+ strip_decimal_trailing_zeros: bool = True
59
+
60
+ def extended(self, **changes) -> "Lexicon":
61
+ """A copy with project data added: dicts are merged, tuples appended, other fields replaced.
62
+
63
+ BANGLA_LEXICON.extended(digitwise_numbers=("999",), domain_words={"example": "এক্সাম্পল"})
64
+ """
65
+ merged = {}
66
+ for name, value in changes.items():
67
+ current = getattr(self, name)
68
+ if isinstance(current, dict):
69
+ merged[name] = {**current, **value}
70
+ elif isinstance(current, tuple):
71
+ merged[name] = (*current, *value)
72
+ else:
73
+ merged[name] = value
74
+ return replace(self, **merged)