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.
- multilingual_num2text/__init__.py +57 -0
- multilingual_num2text/core/__init__.py +16 -0
- multilingual_num2text/core/currencies.py +215 -0
- multilingual_num2text/core/digits.py +44 -0
- multilingual_num2text/core/language.py +186 -0
- multilingual_num2text/core/lexicon.py +74 -0
- multilingual_num2text/core/number_rules.py +415 -0
- multilingual_num2text/core/patterns.py +22 -0
- multilingual_num2text/core/registry.py +19 -0
- multilingual_num2text/core/text_rules.py +128 -0
- multilingual_num2text/core/words.py +29 -0
- multilingual_num2text/languages/__init__.py +4 -0
- multilingual_num2text/languages/bangla/__init__.py +3 -0
- multilingual_num2text/languages/bangla/currencies.py +191 -0
- multilingual_num2text/languages/bangla/language.py +110 -0
- multilingual_num2text/languages/bangla/lexicon.py +60 -0
- multilingual_num2text/languages/bangla/rules.py +75 -0
- multilingual_num2text/languages/bangla/vocabulary.py +86 -0
- multilingual_num2text/languages/english/__init__.py +3 -0
- multilingual_num2text/languages/english/currencies.py +208 -0
- multilingual_num2text/languages/english/language.py +113 -0
- multilingual_num2text/languages/english/lexicon.py +27 -0
- multilingual_num2text/languages/english/rules.py +71 -0
- multilingual_num2text/languages/english/vocabulary.py +71 -0
- multilingual_num2text-0.1.0.dist-info/METADATA +197 -0
- multilingual_num2text-0.1.0.dist-info/RECORD +29 -0
- multilingual_num2text-0.1.0.dist-info/WHEEL +5 -0
- multilingual_num2text-0.1.0.dist-info/licenses/LICENSE +202 -0
- multilingual_num2text-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
"""Rules that find numbers in running text and hand them to the language for spelling.
|
|
2
|
+
|
|
3
|
+
The groups run in a fixed order (see Language.build_rules): specific shapes such as dates, phones
|
|
4
|
+
and money must run before the generic decimal and integer rules, which would otherwise read them
|
|
5
|
+
as plain numbers.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import calendar
|
|
11
|
+
import re
|
|
12
|
+
from decimal import Decimal
|
|
13
|
+
from typing import TYPE_CHECKING
|
|
14
|
+
|
|
15
|
+
from .digits import ZERO_DIGITS, has_valid_grouping, only_digits, parse_int, starts_with_zero, to_ascii_digits
|
|
16
|
+
from .patterns import (
|
|
17
|
+
NEGATIVE_SIGN,
|
|
18
|
+
NOT_DIGIT_AFTER,
|
|
19
|
+
NOT_DIGIT_BEFORE,
|
|
20
|
+
NOT_LETTER_AFTER,
|
|
21
|
+
NOT_NUMBER_BEFORE,
|
|
22
|
+
NUMBER,
|
|
23
|
+
UNSIGNED_AMOUNT,
|
|
24
|
+
WORD_CHARS,
|
|
25
|
+
alternation,
|
|
26
|
+
compile_if_any,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
if TYPE_CHECKING:
|
|
30
|
+
from .language import Language, Rule
|
|
31
|
+
|
|
32
|
+
_STAR_CODE = re.compile(r"(?<![\w*#])[*#][\d*#]*\d[\d*#]*")
|
|
33
|
+
_CARD_NUMBER = re.compile(r"(?<!\d)\d{4}(?: \d{4}){3}(?!\d)")
|
|
34
|
+
_YEAR_SPAN = re.compile(r"(?<![\d./-])(\d{4})[-–/](\d{2})(?!\d|[-/.]\d)")
|
|
35
|
+
_DAY_MONTH_YEAR = re.compile(r"(?<![\d./-])(\d{1,2})([/.-])(\d{1,2})\2(\d{4}|\d{2})(?!\d|[/.-]\d)")
|
|
36
|
+
_YEAR_MONTH_DAY = re.compile(r"(?<![\d./-])(\d{4})([/.-])(\d{1,2})\2(\d{1,2})(?!\d|[/.-]\d)")
|
|
37
|
+
_CLOCK_WITH_PERIOD = re.compile(r"(?<![\d:.])(\d{1,2})(?::(\d{2})(?::(\d{2}))?)?\s?([AaPp])\.?[Mm]\.?(?![A-Za-z])")
|
|
38
|
+
_CLOCK_TIME = re.compile(r"(?<![\d:])(\d{1,2}):(\d{2})(?::(\d{2}))?(?![\d:])")
|
|
39
|
+
_AREA_CODE = re.compile(rf"(?<!\w)\(([{ZERO_DIGITS}]\d{{1,4}})\)\s?(?=\d)")
|
|
40
|
+
_ARITHMETIC = re.compile(r"(?<=\d)\s?([+×÷=])\s?(?=[-−]?\d)")
|
|
41
|
+
_MORE_THAN = re.compile(r"(?<=\d)\+(?![\d+])")
|
|
42
|
+
_MIXED_FRACTION = re.compile(r"(?<![\d.])(\d+)?\s?([½¼¾])")
|
|
43
|
+
_LEADING_DOT_DECIMAL = re.compile(r"(?:^|(?<=[\s(]))(?P<sign>[-−])?\.(?P<fraction>\d+)(?!\d|\.\d)", re.MULTILINE)
|
|
44
|
+
_LETTER_BEFORE_DIGIT = re.compile(rf"(?<=[{WORD_CHARS}])(?<![\d_])(?=\d)")
|
|
45
|
+
_RATIO = re.compile(r"(?<![\d:])\d+(?::\d+)+(?![\d:])")
|
|
46
|
+
_PHONE = re.compile(rf"(?<![{WORD_CHARS}.,+/])(?<!\d-)(?:\+\d|[{ZERO_DIGITS}]\d)(?:\d|[ -](?=\d))*(?!\d|[.,]\d)")
|
|
47
|
+
_PHONE_GROUP_SEPARATOR = re.compile(r"([ -])")
|
|
48
|
+
_HYPHENATED_CODE = re.compile(r"(?<![\d-])\d+(?:-\d+){2,}(?!\d|-\d)")
|
|
49
|
+
_DOTTED_NUMBER = re.compile(rf"(?<![\d.])\d+(?:\.\d+){{2,}}{NOT_DIGIT_AFTER}")
|
|
50
|
+
_SPACE_SPLIT_GROUPING = re.compile(rf"(?<![\d,])\d{{1,2}}(?:\s*,\s*\d{{2}})*\s*,\s*\d{{3}}{NOT_DIGIT_AFTER}")
|
|
51
|
+
_PERCENT = re.compile(rf"{NEGATIVE_SIGN}{NOT_NUMBER_BEFORE}(?P<amount>{UNSIGNED_AMOUNT})\s?%", re.MULTILINE)
|
|
52
|
+
_SLASH_LIST = re.compile(rf"{NOT_DIGIT_BEFORE}\d+(?:/\d+){{2,}}{NOT_DIGIT_AFTER}")
|
|
53
|
+
_SLASH_PAIR = re.compile(r"(?<=\d)/(?=\d)")
|
|
54
|
+
_DECIMAL = re.compile(rf"{NEGATIVE_SIGN}{NOT_NUMBER_BEFORE}(?P<amount>{NUMBER}\.\d+)(?!\d|\.\d)", re.MULTILINE)
|
|
55
|
+
_INTEGER = re.compile(rf"{NEGATIVE_SIGN}{NOT_DIGIT_BEFORE}(?P<amount>{NUMBER}){NOT_DIGIT_AFTER}", re.MULTILINE)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _days_in_month(month: int, year: str) -> int:
|
|
59
|
+
"""Uses the real calendar for a 4-digit year; a 2-digit year allows 29 February."""
|
|
60
|
+
if len(year) == 4:
|
|
61
|
+
return calendar.monthrange(int(year), month)[1]
|
|
62
|
+
return 29 if month == 2 else calendar.monthrange(2001, month)[1]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def spaced(spoken: str) -> str:
|
|
66
|
+
return f" {spoken} "
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class NumberRules:
|
|
70
|
+
def __init__(self, language: Language) -> None:
|
|
71
|
+
self.language = language
|
|
72
|
+
self.lexicon = lexicon = language.lexicon
|
|
73
|
+
|
|
74
|
+
self._symbol_to_currency = self._map_written_forms(lexicon.currencies)
|
|
75
|
+
prefix_symbols = [symbol for currency in lexicon.currencies for symbol in currency.symbols]
|
|
76
|
+
prefix_signs = [symbol for symbol in prefix_symbols if not symbol[0].isalpha()]
|
|
77
|
+
prefix_words = [symbol for symbol in prefix_symbols if symbol[0].isalpha()]
|
|
78
|
+
|
|
79
|
+
self._money_ahead = compile_if_any(self._symbol_to_currency, lambda symbols: rf"\s?(?:{symbols})(?![A-Za-z])")
|
|
80
|
+
self._money_after_amount = compile_if_any(
|
|
81
|
+
self._symbol_to_currency,
|
|
82
|
+
lambda symbols: (
|
|
83
|
+
rf"{NEGATIVE_SIGN}{NOT_NUMBER_BEFORE}(?P<amount>{UNSIGNED_AMOUNT})\s?(?P<symbol>{symbols})"
|
|
84
|
+
rf"(?P<inflection>{language.money_inflection_pattern})(?![A-Za-z])"
|
|
85
|
+
),
|
|
86
|
+
re.MULTILINE,
|
|
87
|
+
)
|
|
88
|
+
prefix_alternatives = [f"(?:{alternation(prefix_signs)})"] if prefix_signs else []
|
|
89
|
+
if prefix_words:
|
|
90
|
+
prefix_alternatives.append(f"(?<![A-Za-z])(?:{alternation(prefix_words)})")
|
|
91
|
+
prefix_symbol = f"(?P<symbol>{'|'.join(prefix_alternatives)})"
|
|
92
|
+
repeated_unit = (
|
|
93
|
+
rf"(?:\s?(?:{alternation(self._symbol_to_currency)})(?P<inflection>{language.money_inflection_pattern}))?"
|
|
94
|
+
if self._symbol_to_currency
|
|
95
|
+
else ""
|
|
96
|
+
)
|
|
97
|
+
self._money_before_amount = (
|
|
98
|
+
re.compile(
|
|
99
|
+
rf"{prefix_symbol}\s?(?P<sign>[-−])?(?P<amount>{UNSIGNED_AMOUNT}){NOT_DIGIT_AFTER}{repeated_unit}(?![A-Za-z])"
|
|
100
|
+
)
|
|
101
|
+
if prefix_alternatives
|
|
102
|
+
else None
|
|
103
|
+
)
|
|
104
|
+
self._scaled_money = (
|
|
105
|
+
compile_if_any(
|
|
106
|
+
lexicon.scale_words,
|
|
107
|
+
lambda scales: rf"{prefix_symbol}\s?(?P<amount>{UNSIGNED_AMOUNT})\s?(?P<scale>{scales})(?![A-Za-z])",
|
|
108
|
+
)
|
|
109
|
+
if prefix_alternatives
|
|
110
|
+
else None
|
|
111
|
+
)
|
|
112
|
+
currency_signs = re.escape("".join(prefix_signs))
|
|
113
|
+
self._range_dash = re.compile(rf"(?<=[\d%])\s*[-–—]\s*(?=[{currency_signs}]?\s?\d)" if prefix_signs else r"(?<=[\d%])\s*[-–—]\s*(?=\d)")
|
|
114
|
+
|
|
115
|
+
self._year_after_number = compile_if_any(
|
|
116
|
+
lexicon.year_markers_after, lambda markers: rf"{NOT_DIGIT_BEFORE}(\d{{4}})(?=\s?(?:{markers}))"
|
|
117
|
+
)
|
|
118
|
+
self._year_before_number = compile_if_any(
|
|
119
|
+
lexicon.year_markers_before,
|
|
120
|
+
lambda markers: rf"\b((?:{markers})\s)(\d{{4}})(?!\d|[.,]\d)",
|
|
121
|
+
re.IGNORECASE,
|
|
122
|
+
)
|
|
123
|
+
self._unit = compile_if_any(
|
|
124
|
+
lexicon.units, lambda units: rf"(?<=\d)\s?({units}){NOT_LETTER_AFTER}", re.IGNORECASE
|
|
125
|
+
)
|
|
126
|
+
self._magnitude = compile_if_any(
|
|
127
|
+
lexicon.magnitudes, lambda names: rf"{NOT_NUMBER_BEFORE}({UNSIGNED_AMOUNT})\s?({names}){NOT_LETTER_AFTER}"
|
|
128
|
+
)
|
|
129
|
+
self._long_digit_run = re.compile(rf"{NOT_NUMBER_BEFORE}\d{{{lexicon.digitwise_min_length},}}{NOT_DIGIT_AFTER}")
|
|
130
|
+
|
|
131
|
+
@staticmethod
|
|
132
|
+
def _map_written_forms(currencies) -> dict:
|
|
133
|
+
"""Codes and signs match exactly (so 'all' is not ALL, 'ft' is not Ft).
|
|
134
|
+
Currency names also match in lower, Title and UPPER case ('Dollars', 'DOLLARS')."""
|
|
135
|
+
written_forms = {}
|
|
136
|
+
for currency in currencies:
|
|
137
|
+
for symbol in currency.symbols:
|
|
138
|
+
written_forms.setdefault(symbol, currency)
|
|
139
|
+
for name in currency.suffix_symbols:
|
|
140
|
+
for form in (name, name.lower(), name.title(), name.upper()):
|
|
141
|
+
written_forms.setdefault(form, currency)
|
|
142
|
+
return written_forms
|
|
143
|
+
|
|
144
|
+
def early_rules(self) -> list[Rule]:
|
|
145
|
+
return [
|
|
146
|
+
self.read_star_codes,
|
|
147
|
+
self.read_card_numbers,
|
|
148
|
+
self.read_scaled_money,
|
|
149
|
+
self.read_year_spans,
|
|
150
|
+
]
|
|
151
|
+
|
|
152
|
+
def shape_rules(self) -> list[Rule]:
|
|
153
|
+
return [
|
|
154
|
+
self.read_dates,
|
|
155
|
+
self.read_clock_times,
|
|
156
|
+
self.read_ratios,
|
|
157
|
+
self.read_area_codes,
|
|
158
|
+
self.read_phone_numbers,
|
|
159
|
+
self.read_hyphenated_codes,
|
|
160
|
+
self.read_years,
|
|
161
|
+
self.read_dotted_numbers,
|
|
162
|
+
]
|
|
163
|
+
|
|
164
|
+
def amount_rules(self) -> list[Rule]:
|
|
165
|
+
return [
|
|
166
|
+
self.read_arithmetic,
|
|
167
|
+
self.read_more_than,
|
|
168
|
+
self.read_mixed_fractions,
|
|
169
|
+
self.mark_ranges,
|
|
170
|
+
self.join_space_split_grouping,
|
|
171
|
+
self.expand_units,
|
|
172
|
+
self.expand_magnitudes,
|
|
173
|
+
self.read_money,
|
|
174
|
+
self.read_percentages,
|
|
175
|
+
self.read_slashes,
|
|
176
|
+
]
|
|
177
|
+
|
|
178
|
+
def plain_number_rules(self) -> list[Rule]:
|
|
179
|
+
return [
|
|
180
|
+
self.separate_letters_from_numbers,
|
|
181
|
+
self.read_decimals,
|
|
182
|
+
self.read_long_digit_runs,
|
|
183
|
+
self.read_integers,
|
|
184
|
+
]
|
|
185
|
+
|
|
186
|
+
def read_star_codes(self, text: str) -> str:
|
|
187
|
+
"""*123# is read digit by digit with the symbols spoken."""
|
|
188
|
+
return _STAR_CODE.sub(lambda match: spaced(self.language.to_digitwise(match.group())), text)
|
|
189
|
+
|
|
190
|
+
def read_card_numbers(self, text: str) -> str:
|
|
191
|
+
"""1234 5678 9012 3456 is read digit by digit."""
|
|
192
|
+
return _CARD_NUMBER.sub(lambda match: spaced(self.language.to_digitwise(match.group())), text)
|
|
193
|
+
|
|
194
|
+
def read_scaled_money(self, text: str) -> str:
|
|
195
|
+
"""৳5 লাখ -> পাঁচ লাখ টাকা, $2.5 million -> two point five million dollars."""
|
|
196
|
+
if not self._scaled_money:
|
|
197
|
+
return text
|
|
198
|
+
return self._scaled_money.sub(self._speak_scaled_money, text)
|
|
199
|
+
|
|
200
|
+
def _speak_scaled_money(self, match: re.Match) -> str:
|
|
201
|
+
currency = self._symbol_to_currency[match["symbol"]]
|
|
202
|
+
amount = self.language.spell_scaled_amount(match["amount"])
|
|
203
|
+
return spaced(f"{amount} {match['scale']} {currency.unit_for(2)}")
|
|
204
|
+
|
|
205
|
+
def read_year_spans(self, text: str) -> str:
|
|
206
|
+
"""Fiscal or academic years: 2024-25 -> <2024 as a year> <25>. Only when the years are consecutive."""
|
|
207
|
+
return _YEAR_SPAN.sub(self._speak_year_span, text)
|
|
208
|
+
|
|
209
|
+
def _speak_year_span(self, match: re.Match) -> str:
|
|
210
|
+
first, second = parse_int(match[1]), parse_int(match[2])
|
|
211
|
+
if (first + 1) % 100 != second:
|
|
212
|
+
return match.group()
|
|
213
|
+
return spaced(f"{self.language.to_year(first)} {self.language.to_cardinal(second)}")
|
|
214
|
+
|
|
215
|
+
def read_dates(self, text: str) -> str:
|
|
216
|
+
"""10/05/2024, 10-05-2024, 10.05.2024 and 2024-05-10."""
|
|
217
|
+
text = _YEAR_MONTH_DAY.sub(self._speak_year_month_day, text)
|
|
218
|
+
return _DAY_MONTH_YEAR.sub(self._speak_day_month_year, text)
|
|
219
|
+
|
|
220
|
+
def _speak_year_month_day(self, match: re.Match) -> str:
|
|
221
|
+
year, _, month, day = match.groups()
|
|
222
|
+
return self._speak_date(parse_int(day), parse_int(month), year) or match.group()
|
|
223
|
+
|
|
224
|
+
def _speak_day_month_year(self, match: re.Match) -> str:
|
|
225
|
+
day, _, month, year = match.groups()
|
|
226
|
+
if len(year) == 2 and (len(day) < 2 or len(month) < 2):
|
|
227
|
+
return match.group()
|
|
228
|
+
return self._speak_date(parse_int(day), parse_int(month), year) or match.group()
|
|
229
|
+
|
|
230
|
+
def _speak_date(self, day: int, month: int, year: str) -> str | None:
|
|
231
|
+
"""Day first, else month first (US). None when neither is a real calendar date."""
|
|
232
|
+
year = to_ascii_digits(year)
|
|
233
|
+
for day_value, month_value in ((day, month), (month, day)):
|
|
234
|
+
if 1 <= month_value <= 12 and 1 <= day_value <= _days_in_month(month_value, year):
|
|
235
|
+
return spaced(self.language.to_date(day_value, month_value, year))
|
|
236
|
+
return None
|
|
237
|
+
|
|
238
|
+
def read_clock_times(self, text: str) -> str:
|
|
239
|
+
"""10:30, 10:30:20, 24:00, 10 AM, 10:30 p.m. Anything else with a colon is left for read_ratios."""
|
|
240
|
+
text = _CLOCK_WITH_PERIOD.sub(self._speak_clock_with_period, text)
|
|
241
|
+
return _CLOCK_TIME.sub(self._speak_clock_time, text)
|
|
242
|
+
|
|
243
|
+
def _speak_clock_with_period(self, match: re.Match) -> str:
|
|
244
|
+
hour = parse_int(match[1])
|
|
245
|
+
minute = parse_int(match[2]) if match[2] else 0
|
|
246
|
+
second = parse_int(match[3]) if match[3] else None
|
|
247
|
+
if not 1 <= hour <= 12 or minute > 59 or (second is not None and second > 59):
|
|
248
|
+
return match.group()
|
|
249
|
+
is_pm = match[4].lower() == "p"
|
|
250
|
+
hour = hour % 12 + (12 if is_pm else 0)
|
|
251
|
+
return spaced(self.language.to_time(hour, minute, second, with_period=True))
|
|
252
|
+
|
|
253
|
+
def _speak_clock_time(self, match: re.Match) -> str:
|
|
254
|
+
hour, minute = parse_int(match[1]), parse_int(match[2])
|
|
255
|
+
second = parse_int(match[3]) if match[3] else None
|
|
256
|
+
if hour == 24 and minute == 0 and not second:
|
|
257
|
+
hour = 0
|
|
258
|
+
if hour > 23 or minute > 59 or (second is not None and second > 59):
|
|
259
|
+
return match.group()
|
|
260
|
+
return spaced(self.language.to_time(hour, minute, second))
|
|
261
|
+
|
|
262
|
+
def read_area_codes(self, text: str) -> str:
|
|
263
|
+
"""(02) 9566300 -> 02-9566300, so the phone rule reads the whole number digit by digit."""
|
|
264
|
+
return _AREA_CODE.sub(r"\1-", text)
|
|
265
|
+
|
|
266
|
+
def read_ratios(self, text: str) -> str:
|
|
267
|
+
"""1:2 -> one to two, 1:2:3 -> one to two to three"""
|
|
268
|
+
return _RATIO.sub(lambda match: spaced(self._speak_ratio(match.group())), text)
|
|
269
|
+
|
|
270
|
+
def _speak_ratio(self, written: str) -> str:
|
|
271
|
+
parts = [parse_int(part) for part in written.split(":")]
|
|
272
|
+
spoken = self.language.to_ratio(parts[0], parts[1])
|
|
273
|
+
for part in parts[2:]:
|
|
274
|
+
spoken += f" {self.language.words.ratio} {self.language.to_cardinal(part)}"
|
|
275
|
+
return spoken
|
|
276
|
+
|
|
277
|
+
def read_phone_numbers(self, text: str) -> str:
|
|
278
|
+
"""Numbers starting with + or 0 are read digit by digit, with hyphen or space separated groups."""
|
|
279
|
+
return _PHONE.sub(self._speak_phone, text)
|
|
280
|
+
|
|
281
|
+
def _speak_phone(self, match: re.Match) -> str:
|
|
282
|
+
pieces = _PHONE_GROUP_SEPARATOR.split(match.group())
|
|
283
|
+
is_money = bool(self._money_ahead and self._money_ahead.match(match.string, match.end()))
|
|
284
|
+
if is_money and len(pieces) == 1:
|
|
285
|
+
return match.group()
|
|
286
|
+
usable_pieces = len(pieces) - 2 if is_money else len(pieces)
|
|
287
|
+
|
|
288
|
+
phone, digit_count, index = pieces[0], len(only_digits(pieces[0])), 1
|
|
289
|
+
while index + 1 < usable_pieces:
|
|
290
|
+
separator, group = pieces[index], pieces[index + 1]
|
|
291
|
+
if digit_count + len(group) > self.lexicon.phone_max_digits or (separator == " " and len(group) < 3):
|
|
292
|
+
break
|
|
293
|
+
phone, digit_count, index = phone + group, digit_count + len(group), index + 2
|
|
294
|
+
rest = "".join(pieces[index:])
|
|
295
|
+
|
|
296
|
+
if phone.startswith("+") and digit_count < self.lexicon.phone_min_digits_after_plus:
|
|
297
|
+
return spaced(f"{self.language.words.plus} {self.language.to_cardinal(parse_int(phone))}") + rest
|
|
298
|
+
return spaced(self.language.to_digitwise(phone)) + rest
|
|
299
|
+
|
|
300
|
+
def read_hyphenated_codes(self, text: str) -> str:
|
|
301
|
+
"""Card or reference numbers like 1234-5678-9012 are read digit by digit."""
|
|
302
|
+
return _HYPHENATED_CODE.sub(lambda match: spaced(self.language.to_digitwise(match.group())), text)
|
|
303
|
+
|
|
304
|
+
def read_years(self, text: str) -> str:
|
|
305
|
+
if self._year_after_number:
|
|
306
|
+
text = self._year_after_number.sub(lambda match: self.language.to_year(parse_int(match[1])), text)
|
|
307
|
+
if self._year_before_number:
|
|
308
|
+
text = self._year_before_number.sub(self._speak_year_after_marker, text)
|
|
309
|
+
return text
|
|
310
|
+
|
|
311
|
+
def _speak_year_after_marker(self, match: re.Match) -> str:
|
|
312
|
+
year = parse_int(match[2])
|
|
313
|
+
return match[1] + self.language.to_year(year) if 1000 <= year <= 2099 else match.group()
|
|
314
|
+
|
|
315
|
+
def read_dotted_numbers(self, text: str) -> str:
|
|
316
|
+
"""Versions and IP addresses: 1.2.3 is read with the language's word for dot."""
|
|
317
|
+
joiner = f" {self.language.words.dot} "
|
|
318
|
+
return _DOTTED_NUMBER.sub(
|
|
319
|
+
lambda match: spaced(joiner.join(self.language.to_cardinal(parse_int(part)) for part in match.group().split("."))),
|
|
320
|
+
text,
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
def read_arithmetic(self, text: str) -> str:
|
|
324
|
+
"""2+2=4 -> 2 <add> 2 <equals> 4, using the language's words. Skipped when a word is missing."""
|
|
325
|
+
return _ARITHMETIC.sub(self._speak_operator, text)
|
|
326
|
+
|
|
327
|
+
def _speak_operator(self, match: re.Match) -> str:
|
|
328
|
+
words = self.language.words
|
|
329
|
+
word = {"+": words.add, "×": words.times, "÷": words.divided_by, "=": words.equals}[match[1]]
|
|
330
|
+
return f" {word} " if word else match.group()
|
|
331
|
+
|
|
332
|
+
def read_more_than(self, text: str) -> str:
|
|
333
|
+
"""500+ users -> 500 <plus> users"""
|
|
334
|
+
word = self.language.words.more_than or self.language.words.plus
|
|
335
|
+
return _MORE_THAN.sub(f" {word}", text)
|
|
336
|
+
|
|
337
|
+
def read_mixed_fractions(self, text: str) -> str:
|
|
338
|
+
"""2½ -> two point five (English: two and a half, Bangla: আড়াই)"""
|
|
339
|
+
return _MIXED_FRACTION.sub(
|
|
340
|
+
lambda match: spaced(self.language.to_mixed_fraction(parse_int(match[1] or "0"), match[2])), text
|
|
341
|
+
)
|
|
342
|
+
|
|
343
|
+
def mark_ranges(self, text: str) -> str:
|
|
344
|
+
"""500-1000 -> 500 <range word> 1000"""
|
|
345
|
+
return self._range_dash.sub(f" {self.language.words.range} ", text)
|
|
346
|
+
|
|
347
|
+
def join_space_split_grouping(self, text: str) -> str:
|
|
348
|
+
"""'10, 000' -> '10,000', only when the shape is real digit grouping, not a list."""
|
|
349
|
+
return _SPACE_SPLIT_GROUPING.sub(lambda match: re.sub(r"\s+", "", match.group()), text)
|
|
350
|
+
|
|
351
|
+
def expand_units(self, text: str) -> str:
|
|
352
|
+
if not self._unit:
|
|
353
|
+
return text
|
|
354
|
+
return self._unit.sub(lambda match: f" {self.lexicon.units[match[1].lower()]}", text)
|
|
355
|
+
|
|
356
|
+
def expand_magnitudes(self, text: str) -> str:
|
|
357
|
+
"""5K -> 5000. Produces digits so money and number rules still apply."""
|
|
358
|
+
if not self._magnitude:
|
|
359
|
+
return text
|
|
360
|
+
return self._magnitude.sub(self._expand_magnitude, text)
|
|
361
|
+
|
|
362
|
+
def _expand_magnitude(self, match: re.Match) -> str:
|
|
363
|
+
value = Decimal(to_ascii_digits(match[1]).replace(",", "")) * self.lexicon.magnitudes[match[2]]
|
|
364
|
+
plain = format(value, "f")
|
|
365
|
+
return plain.rstrip("0").rstrip(".") if "." in plain else plain
|
|
366
|
+
|
|
367
|
+
def read_money(self, text: str) -> str:
|
|
368
|
+
"""Symbol before the amount wins, and swallows a repeated unit after it (৳১০০০/-, ৳৫০০ টাকা)."""
|
|
369
|
+
if self._money_before_amount:
|
|
370
|
+
text = self._money_before_amount.sub(self._speak_money, text)
|
|
371
|
+
if self._money_after_amount:
|
|
372
|
+
text = self._money_after_amount.sub(self._speak_money, text)
|
|
373
|
+
return text
|
|
374
|
+
|
|
375
|
+
def _speak_money(self, match: re.Match) -> str:
|
|
376
|
+
currency = self._symbol_to_currency[match["symbol"]]
|
|
377
|
+
amount = (match["sign"] or "") + match["amount"]
|
|
378
|
+
inflection = match.groupdict().get("inflection") or ""
|
|
379
|
+
return spaced(self.language.to_money(amount, currency) + inflection)
|
|
380
|
+
|
|
381
|
+
def read_percentages(self, text: str) -> str:
|
|
382
|
+
return _PERCENT.sub(lambda match: spaced(self.language.to_percent((match["sign"] or "") + match["amount"])), text)
|
|
383
|
+
|
|
384
|
+
def read_slashes(self, text: str) -> str:
|
|
385
|
+
"""6/12/24 is a list; 12/3 is read with the language's word for slash."""
|
|
386
|
+
text = _SLASH_LIST.sub(lambda match: match.group().replace("/", ", "), text)
|
|
387
|
+
return _SLASH_PAIR.sub(f" {self.language.words.slash} ", text)
|
|
388
|
+
|
|
389
|
+
def separate_letters_from_numbers(self, text: str) -> str:
|
|
390
|
+
"""মোট৫০০ -> মোট ৫০০. Number-then-suffix (৫টি) stays joined."""
|
|
391
|
+
return _LETTER_BEFORE_DIGIT.sub(" ", text)
|
|
392
|
+
|
|
393
|
+
def read_decimals(self, text: str) -> str:
|
|
394
|
+
"""1.49 and .5"""
|
|
395
|
+
text = _DECIMAL.sub(lambda match: spaced(self.language.spell_number((match["sign"] or "") + match["amount"])), text)
|
|
396
|
+
return _LEADING_DOT_DECIMAL.sub(
|
|
397
|
+
lambda match: spaced(self.language.spell_number(f"{match['sign'] or ''}0.{match['fraction']}")), text
|
|
398
|
+
)
|
|
399
|
+
|
|
400
|
+
def read_long_digit_runs(self, text: str) -> str:
|
|
401
|
+
"""Account numbers and other long digit runs are read digit by digit."""
|
|
402
|
+
return self._long_digit_run.sub(lambda match: spaced(self.language.to_digitwise(match.group())), text)
|
|
403
|
+
|
|
404
|
+
def read_integers(self, text: str) -> str:
|
|
405
|
+
return _INTEGER.sub(self._speak_integer, text)
|
|
406
|
+
|
|
407
|
+
def _speak_integer(self, match: re.Match) -> str:
|
|
408
|
+
number = match["amount"]
|
|
409
|
+
if not has_valid_grouping(number):
|
|
410
|
+
return ", ".join(self.language.to_cardinal(parse_int(part)) for part in number.split(","))
|
|
411
|
+
if len(number) > 1 and starts_with_zero(number):
|
|
412
|
+
return spaced(self.language.to_digitwise(number))
|
|
413
|
+
value = parse_int(number)
|
|
414
|
+
spoken = self.language.to_cardinal(-value if match["sign"] else value)
|
|
415
|
+
return spaced(spoken) if self.language.separate_number_words else spoken
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Regex building blocks shared by the rule classes. \\d matches a digit in any script."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
NUMBER = r"\d(?:\d|,(?=\d))*"
|
|
6
|
+
UNSIGNED_AMOUNT = rf"{NUMBER}(?:\.\d+)?"
|
|
7
|
+
NEGATIVE_SIGN = r"(?P<sign>(?:^|(?<=[\s(]))[-−])?"
|
|
8
|
+
NOT_DIGIT_BEFORE = r"(?<!\d)"
|
|
9
|
+
NOT_DIGIT_AFTER = r"(?!\d)"
|
|
10
|
+
NOT_NUMBER_BEFORE = r"(?<![\d.,])"
|
|
11
|
+
NOT_LETTER_AFTER = r"(?![^\W\d_])"
|
|
12
|
+
WORD_CHARS = r"\wऀ-"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def alternation(options) -> str:
|
|
16
|
+
return "|".join(re.escape(option) for option in sorted(options, key=len, reverse=True))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def compile_if_any(options, build_pattern, flags: int = 0) -> re.Pattern | None:
|
|
20
|
+
"""Compiles build_pattern(alternation) only when there is something to match."""
|
|
21
|
+
options = list(options)
|
|
22
|
+
return re.compile(build_pattern(alternation(options)), flags) if options else None
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from .language import Language
|
|
2
|
+
|
|
3
|
+
_LANGUAGES: dict[str, Language] = {}
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def register_language(language: Language, code: str | None = None) -> None:
|
|
7
|
+
"""Adds or replaces a language. code defaults to language.code, e.g. register a variant as 'en-IN'."""
|
|
8
|
+
_LANGUAGES[(code or language.code).lower()] = language
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def get_language(code: str) -> Language:
|
|
12
|
+
try:
|
|
13
|
+
return _LANGUAGES[code.lower()]
|
|
14
|
+
except KeyError:
|
|
15
|
+
raise ValueError(f"Unknown language {code!r}. Available: {', '.join(available_languages())}") from None
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def available_languages() -> list[str]:
|
|
19
|
+
return sorted(_LANGUAGES)
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Rules for everything around the numbers: removed patterns, links, acronyms and leftover symbols."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import unicodedata
|
|
7
|
+
from typing import TYPE_CHECKING
|
|
8
|
+
|
|
9
|
+
from .digits import to_ascii_digits
|
|
10
|
+
from .patterns import WORD_CHARS, compile_if_any
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from .language import Language, Rule
|
|
14
|
+
|
|
15
|
+
_BOLD = re.compile(r"(\*\*|__)(.+?)\1")
|
|
16
|
+
_EMAIL = re.compile(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+")
|
|
17
|
+
_URL = re.compile(r"(?:https?://|www\.)[^\s)\]]*[^\s)\].,!?।]", re.IGNORECASE)
|
|
18
|
+
_DIGIT_RUN = re.compile(r"(?<![\d,.])\d+(?!\d|[,.]\d)")
|
|
19
|
+
_GROUPING_SPACE = re.compile(r"(?<=\d)[ ](?=\d{3}(?!\d))")
|
|
20
|
+
_SPACE_VARIANTS =str.maketrans({" ": " ", " ": " ", " ": " ", " ": " ", "": ""})
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class TextRules:
|
|
24
|
+
def __init__(self, language: Language) -> None:
|
|
25
|
+
self.language = language
|
|
26
|
+
self.lexicon = language.lexicon
|
|
27
|
+
self._removed = re.compile("|".join(self.lexicon.removed_patterns)) if self.lexicon.removed_patterns else None
|
|
28
|
+
self._acronym = compile_if_any(self.lexicon.acronyms, lambda names: rf"(?<![A-Za-z])(?:{names})(?![A-Za-z])")
|
|
29
|
+
self._bare_domain = compile_if_any(
|
|
30
|
+
self.lexicon.bare_domain_endings,
|
|
31
|
+
lambda endings: rf"(?<![{WORD_CHARS}@.])[{WORD_CHARS}-]+(?:\.[{WORD_CHARS}-]+)*\.(?:{endings})(?!\w)",
|
|
32
|
+
re.IGNORECASE,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
def preparation_rules(self) -> list[Rule]:
|
|
36
|
+
return [
|
|
37
|
+
self.normalize_unicode,
|
|
38
|
+
self.remove_patterns,
|
|
39
|
+
self.remove_markdown_emphasis,
|
|
40
|
+
self.apply_word_replacements,
|
|
41
|
+
self.apply_fixed_phrases,
|
|
42
|
+
self.read_digitwise_numbers,
|
|
43
|
+
self.read_emails,
|
|
44
|
+
self.read_urls,
|
|
45
|
+
self.read_bare_domains,
|
|
46
|
+
self.expand_acronyms,
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
def normalize_unicode(self, text: str) -> str:
|
|
50
|
+
"""NFC, digit groups joined by no-break or thin spaces (10 000), other space variants to plain spaces."""
|
|
51
|
+
text = _GROUPING_SPACE.sub("", unicodedata.normalize("NFC", text))
|
|
52
|
+
return text.translate(_SPACE_VARIANTS)
|
|
53
|
+
|
|
54
|
+
def remove_patterns(self, text: str) -> str:
|
|
55
|
+
return self._removed.sub("", text) if self._removed else text
|
|
56
|
+
|
|
57
|
+
def remove_markdown_emphasis(self, text: str) -> str:
|
|
58
|
+
return _BOLD.sub(r"\2", text)
|
|
59
|
+
|
|
60
|
+
def apply_word_replacements(self, text: str) -> str:
|
|
61
|
+
for written, spoken in self.lexicon.word_replacements.items():
|
|
62
|
+
text = text.replace(written, spoken)
|
|
63
|
+
return text
|
|
64
|
+
|
|
65
|
+
def apply_fixed_phrases(self, text: str) -> str:
|
|
66
|
+
for written, spoken in self.lexicon.fixed_phrases.items():
|
|
67
|
+
pattern = re.escape(written)
|
|
68
|
+
if written[0].isdecimal():
|
|
69
|
+
pattern = rf"(?<!\d){pattern}"
|
|
70
|
+
if written[-1].isdecimal():
|
|
71
|
+
pattern = rf"{pattern}(?!\d)"
|
|
72
|
+
text = re.sub(pattern, spoken, text, flags=re.IGNORECASE)
|
|
73
|
+
return text
|
|
74
|
+
|
|
75
|
+
def read_digitwise_numbers(self, text: str) -> str:
|
|
76
|
+
"""Helplines and other listed numbers, written in any digit script or a mix."""
|
|
77
|
+
if not self.lexicon.digitwise_numbers:
|
|
78
|
+
return text
|
|
79
|
+
return _DIGIT_RUN.sub(self._digitwise_if_listed, text)
|
|
80
|
+
|
|
81
|
+
def _digitwise_if_listed(self, match: re.Match) -> str:
|
|
82
|
+
number = match.group()
|
|
83
|
+
if to_ascii_digits(number) in self.lexicon.digitwise_numbers:
|
|
84
|
+
return self.language.to_digitwise(number)
|
|
85
|
+
return number
|
|
86
|
+
|
|
87
|
+
def read_emails(self, text: str) -> str:
|
|
88
|
+
return _EMAIL.sub(lambda match: f" {self.speak_email(match.group())} ", text)
|
|
89
|
+
|
|
90
|
+
def read_urls(self, text: str) -> str:
|
|
91
|
+
return _URL.sub(lambda match: f" {self.speak_url(match.group())} ", text)
|
|
92
|
+
|
|
93
|
+
def read_bare_domains(self, text: str) -> str:
|
|
94
|
+
if not self._bare_domain:
|
|
95
|
+
return text
|
|
96
|
+
return self._bare_domain.sub(lambda match: f" {self.speak_host(match.group())} ", text)
|
|
97
|
+
|
|
98
|
+
def expand_acronyms(self, text: str) -> str:
|
|
99
|
+
if not self._acronym:
|
|
100
|
+
return text
|
|
101
|
+
return self._acronym.sub(lambda match: self.lexicon.acronyms[match.group()], text)
|
|
102
|
+
|
|
103
|
+
def speak_email(self, email: str) -> str:
|
|
104
|
+
name, domain = email.split("@", 1)
|
|
105
|
+
spoken_name = self.lexicon.email_name_words.get(name.lower()) or self.speak_host(name)
|
|
106
|
+
return f"{spoken_name} {self.language.words.at} {self.speak_host(domain)}"
|
|
107
|
+
|
|
108
|
+
def speak_url(self, url: str) -> str:
|
|
109
|
+
host = re.sub(r"^https?://", "", url, flags=re.IGNORECASE).split("/")[0].split(":")[0]
|
|
110
|
+
return self.speak_host(host)
|
|
111
|
+
|
|
112
|
+
def speak_host(self, host: str) -> str:
|
|
113
|
+
return f" {self.language.words.dot} ".join(self._speak_host_part(part) for part in host.split(".") if part)
|
|
114
|
+
|
|
115
|
+
def _speak_host_part(self, part: str) -> str:
|
|
116
|
+
if part.lower() in self.lexicon.domain_words:
|
|
117
|
+
return self.lexicon.domain_words[part.lower()]
|
|
118
|
+
spoken = re.sub(r"\d+", lambda match: f" {self.language.to_digitwise(match.group())} ", part)
|
|
119
|
+
return re.sub(r"\s+", " ", spoken).strip()
|
|
120
|
+
|
|
121
|
+
def cleanup_symbols(self, text: str) -> str:
|
|
122
|
+
text = text.replace("\\", "").replace("/-", " ")
|
|
123
|
+
text = re.sub(r"[\"“”‘’`]|(?<!\w)'|'(?!\w)", "", text)
|
|
124
|
+
text = re.sub(r"[()\[\]{}【】]", " ", text)
|
|
125
|
+
text = re.sub(r"[*#@&+=<>|~^_/]", " ", text)
|
|
126
|
+
text = re.sub(r"।\s*।", "।", text)
|
|
127
|
+
text = re.sub(r"\s+([,।?!.])", r"\1", text)
|
|
128
|
+
return re.sub(r"\s+", " ", text).strip()
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""The small set of words every language must provide for the shared rules."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@dataclass(frozen=True)
|
|
7
|
+
class Words:
|
|
8
|
+
digits: tuple[str, ...]
|
|
9
|
+
negative: str
|
|
10
|
+
decimal_point: str
|
|
11
|
+
percent: str
|
|
12
|
+
range: str
|
|
13
|
+
slash: str
|
|
14
|
+
ratio: str
|
|
15
|
+
dot: str
|
|
16
|
+
at: str
|
|
17
|
+
star: str
|
|
18
|
+
hash: str
|
|
19
|
+
plus: str
|
|
20
|
+
money_joiner: str = ""
|
|
21
|
+
add: str = ""
|
|
22
|
+
times: str = ""
|
|
23
|
+
divided_by: str = ""
|
|
24
|
+
equals: str = ""
|
|
25
|
+
more_than: str = ""
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def symbols(self) -> dict[str, str]:
|
|
29
|
+
return {"*": self.star, "#": self.hash, "+": self.plus}
|