bg-text-normalizer 1.0.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.
@@ -0,0 +1,40 @@
1
+ """
2
+ bg-text-norm: Bulgarian Text Normalizer for TTS
3
+ =================================================
4
+ Converts written Bulgarian text (numbers, dates, times, currency,
5
+ abbreviations) into spoken word forms for TTS preprocessing.
6
+
7
+ Usage:
8
+ from bg_text_normalizer import normalize_text
9
+ result = normalize_text("На 15.02.2026 г. в 14:30 ч. цената е 1500.50 лв.")
10
+
11
+ from bg_text_normalizer import BulgarianTextNormalizer
12
+ normalizer = BulgarianTextNormalizer()
13
+ result = normalizer.normalize("...")
14
+ """
15
+
16
+ from .bg_normalizer import BulgarianTextNormalizer, normalize_text
17
+ from .bg_numbers import number_to_words_cardinal, number_to_words_ordinal, float_to_words
18
+ from .bg_dates import normalize_date, normalize_year
19
+ from .bg_time import normalize_time
20
+ from .bg_currency import normalize_currency
21
+ from .bg_abbreviations import normalize_abbreviations, expand_abbreviation
22
+ from .bg_phone import normalize_phone_number
23
+ from .bg_roman import roman_to_arabic
24
+
25
+ __version__ = "1.0.0"
26
+ __all__ = [
27
+ 'BulgarianTextNormalizer',
28
+ 'normalize_text',
29
+ 'number_to_words_cardinal',
30
+ 'number_to_words_ordinal',
31
+ 'float_to_words',
32
+ 'normalize_date',
33
+ 'normalize_year',
34
+ 'normalize_time',
35
+ 'normalize_currency',
36
+ 'normalize_abbreviations',
37
+ 'expand_abbreviation',
38
+ 'normalize_phone_number',
39
+ 'roman_to_arabic',
40
+ ]
@@ -0,0 +1,238 @@
1
+ """
2
+ Bulgarian Abbreviation Expansion
3
+ ===================================
4
+ Expands common Bulgarian abbreviations to their full spoken forms.
5
+
6
+ Categories:
7
+ - Address abbreviations (бул., ул., пл., ж.к., кв.)
8
+ - Title abbreviations (г-н, г-жа, д-р, проф., инж.)
9
+ - Geographic (гр., с., обл.)
10
+ - Measurement units (км, м, кг, л, мм, см)
11
+ - Administrative (ЕТ, ООД, ЕООД, АД, ЕАД)
12
+ - Common abbreviations (т.е., т.н., напр., и т.н., и др.)
13
+ - Institution abbreviations (НАП, НОИ, МОН, МВР, НЗОК)
14
+ """
15
+
16
+ import re
17
+ from typing import Dict, Tuple
18
+
19
+ # Abbreviation → (full form, is_case_sensitive)
20
+ # Order matters: longer abbreviations should be checked first
21
+
22
+ # Address abbreviations
23
+ ADDRESS_ABBREVS: Dict[str, str] = {
24
+ 'бул.': 'булевард',
25
+ 'ул.': 'улица',
26
+ 'пл.': 'площад',
27
+ 'ж.к.': 'жилищен комплекс',
28
+ 'ж. к.': 'жилищен комплекс',
29
+ 'кв.': 'квартал',
30
+ 'бл.': 'блок',
31
+ 'вх.': 'вход',
32
+ 'ет.': 'етаж',
33
+ 'ап.': 'апартамент',
34
+ 'п.к.': 'пощенски код',
35
+ }
36
+
37
+ # Geographic abbreviations
38
+ GEO_ABBREVS: Dict[str, str] = {
39
+ 'гр.': 'град',
40
+ 'с.': 'село',
41
+ 'обл.': 'област',
42
+ 'общ.': 'община',
43
+ 'р-н': 'район',
44
+ }
45
+
46
+ # Title abbreviations
47
+ TITLE_ABBREVS: Dict[str, str] = {
48
+ 'г-н': 'господин',
49
+ 'г-жа': 'госпожа',
50
+ 'г-ца': 'госпожица',
51
+ 'д-р': 'доктор',
52
+ 'проф.': 'професор',
53
+ 'доц.': 'доцент',
54
+ 'акад.': 'академик',
55
+ 'инж.': 'инженер',
56
+ 'арх.': 'архитект',
57
+ 'адв.': 'адвокат',
58
+ 'св.': 'свети',
59
+ }
60
+
61
+ # Measurement unit abbreviations
62
+ MEASUREMENT_ABBREVS: Dict[str, str] = {
63
+ 'км/ч': 'километра в час',
64
+ 'м/с': 'метра в секунда',
65
+ 'кв.м': 'квадратни метра',
66
+ 'кв. м': 'квадратни метра',
67
+ 'кв.м.': 'квадратни метра',
68
+ 'куб.м': 'кубически метра',
69
+ 'куб. м': 'кубически метра',
70
+ 'км': 'километра',
71
+ 'м': 'метра',
72
+ 'см': 'сантиметра',
73
+ 'мм': 'милиметра',
74
+ 'кг': 'килограма',
75
+ 'гр': 'грама', # Note: context-dependent (could also be "град")
76
+ 'мг': 'милиграма',
77
+ 'т': 'тона',
78
+ 'л': 'литра',
79
+ 'мл': 'милилитра',
80
+ 'дка': 'декара',
81
+ 'ха': 'хектара',
82
+ }
83
+
84
+ # Administrative/business abbreviations
85
+ BUSINESS_ABBREVS: Dict[str, str] = {
86
+ 'ЕООД': 'еоод', # Spelled out as abbreviation
87
+ 'ООД': 'оод',
88
+ 'ЕТ': 'едноличен търговец',
89
+ 'АД': 'акционерно дружество',
90
+ 'ЕАД': 'еад',
91
+ 'КД': 'командитно дружество',
92
+ 'СД': 'събирателно дружество',
93
+ }
94
+
95
+ # Common text abbreviations
96
+ COMMON_ABBREVS: Dict[str, str] = {
97
+ 'т.е.': 'тоест',
98
+ 'т. е.': 'тоест',
99
+ 'т.н.': 'така наречен',
100
+ 'т. н.': 'така наречен',
101
+ 'т.нар.': 'така наречен',
102
+ 'напр.': 'например',
103
+ 'и т.н.': 'и така нататък',
104
+ 'и т. н.': 'и така нататък',
105
+ 'и др.': 'и други',
106
+ 'вж.': 'виж',
107
+ 'ср.': 'сравни',
108
+ 'вкл.': 'включително',
109
+ 'изд.': 'издание',
110
+ 'стр.': 'страница',
111
+ 'гл.': 'глава',
112
+ 'чл.': 'член',
113
+ 'ал.': 'алинея',
114
+ 'б.р.': 'бележка на редактора',
115
+ 'б. р.': 'бележка на редактора',
116
+ 'б.а.': 'бележка на автора',
117
+ 'б. а.': 'бележка на автора',
118
+ 'пр.н.е.': 'преди новата ера',
119
+ 'пр. н. е.': 'преди новата ера',
120
+ 'сл.н.е.': 'след новата ера',
121
+ 'сл. н. е.': 'след новата ера',
122
+ 'пр.Хр.': 'преди Христа',
123
+ 'сл.Хр.': 'след Христа',
124
+ }
125
+
126
+ # Institution abbreviations (spelled out letter by letter or as words)
127
+ INSTITUTION_ABBREVS: Dict[str, str] = {
128
+ 'НАП': 'национална агенция по приходите',
129
+ 'НОИ': 'национален осигурителен институт',
130
+ 'НЗОК': 'национална здравноосигурителна каса',
131
+ 'МОН': 'министерство на образованието и науката',
132
+ 'МВР': 'министерство на вътрешните работи',
133
+ 'МЗ': 'министерство на здравеопазването',
134
+ 'МФ': 'министерство на финансите',
135
+ 'МРРБ': 'министерство на регионалното развитие и благоустройството',
136
+ 'БНБ': 'българска народна банка',
137
+ 'БНТ': 'бнт',
138
+ 'БТВ': 'бтв',
139
+ 'НС': 'народно събрание',
140
+ 'ЕС': 'европейски съюз',
141
+ 'ООН': 'организация на обединените нации',
142
+ 'НАТО': 'нато',
143
+ 'ДДС': 'данък добавена стойност',
144
+ 'ДАНС': 'данс',
145
+ 'ЕГН': 'единен граждански номер',
146
+ 'БУЛСТАТ': 'булстат',
147
+ 'ПИН': 'пин',
148
+ 'ПДФ': 'пдф',
149
+ 'СМС': 'есемес',
150
+ }
151
+
152
+ # Number sign / hash
153
+ SYMBOL_ABBREVS: Dict[str, str] = {
154
+ '№': 'номер',
155
+ '&': 'и',
156
+ '@': 'кльомба',
157
+ }
158
+
159
+
160
+ def expand_abbreviation(abbrev: str) -> str:
161
+ """
162
+ Expand a single abbreviation to its full form.
163
+
164
+ Args:
165
+ abbrev: The abbreviation to expand
166
+
167
+ Returns:
168
+ Full form or original if not found
169
+ """
170
+ # Check all dictionaries
171
+ for d in [ADDRESS_ABBREVS, GEO_ABBREVS, TITLE_ABBREVS,
172
+ MEASUREMENT_ABBREVS, BUSINESS_ABBREVS, COMMON_ABBREVS,
173
+ INSTITUTION_ABBREVS, SYMBOL_ABBREVS]:
174
+ if abbrev in d:
175
+ return d[abbrev]
176
+ # Case-insensitive check
177
+ for key, val in d.items():
178
+ if key.lower() == abbrev.lower():
179
+ return val
180
+ return abbrev
181
+
182
+
183
+ def normalize_abbreviations(text: str) -> str:
184
+ """
185
+ Expand all recognized abbreviations in the text.
186
+
187
+ Processes abbreviations in order of specificity (longer first)
188
+ to avoid partial matches.
189
+ """
190
+ # Collect all abbreviations, sorted by length (longest first)
191
+ all_abbrevs = {}
192
+ for d in [COMMON_ABBREVS, ADDRESS_ABBREVS, GEO_ABBREVS, TITLE_ABBREVS,
193
+ BUSINESS_ABBREVS, INSTITUTION_ABBREVS, SYMBOL_ABBREVS]:
194
+ all_abbrevs.update(d)
195
+
196
+ # Sort by length descending to match longer abbreviations first
197
+ sorted_abbrevs = sorted(all_abbrevs.items(), key=lambda x: len(x[0]), reverse=True)
198
+
199
+ for abbrev, full_form in sorted_abbrevs:
200
+ # Escape special regex characters in the abbreviation
201
+ escaped = re.escape(abbrev)
202
+ # Use word boundary or space/start/end boundary
203
+ # Be careful with dots - they're part of some abbreviations
204
+ pattern = r'(?<!\w)' + escaped + r'(?!\w)'
205
+ text = re.sub(pattern, full_form, text, flags=re.IGNORECASE)
206
+
207
+ # Handle measurement units (these need number context)
208
+ # Match: digit + space? + unit
209
+ for unit, full_form in sorted(MEASUREMENT_ABBREVS.items(),
210
+ key=lambda x: len(x[0]), reverse=True):
211
+ escaped_unit = re.escape(unit)
212
+ pattern = r'(\d)\s*' + escaped_unit + r'\b'
213
+ text = re.sub(pattern, r'\1 ' + full_form, text)
214
+
215
+ return text
216
+
217
+
218
+ if __name__ == '__main__':
219
+ test_cases = [
220
+ "бул. Витоша №10, гр. София",
221
+ "г-н Иванов е д-р по медицина",
222
+ "Офис на 5 км от центъра",
223
+ "Площ: 120 кв.м",
224
+ "т.е. не може да се направи",
225
+ "Фирма Тест ЕООД",
226
+ "Скорост: 60 км/ч",
227
+ "Заплата: 2500 лв. (вкл. ДДС)",
228
+ "ж.к. Люлин, бл. 305, вх. А, ет. 5, ап. 20",
229
+ "проф. д-р Петров",
230
+ "и т.н. и т.н.",
231
+ ]
232
+
233
+ print("=== Abbreviation Expansion ===")
234
+ for test in test_cases:
235
+ result = normalize_abbreviations(test)
236
+ print(f" Input: {test}")
237
+ print(f" Output: {result}")
238
+ print()
@@ -0,0 +1,124 @@
1
+ """
2
+ Bulgarian Currency Normalization
3
+ ==================================
4
+ Converts currency amounts to spoken Bulgarian form.
5
+
6
+ Supported currencies:
7
+ - BGN (лева / стотинки)
8
+ - EUR (евро / цента)
9
+ - USD (долара / цента)
10
+ - GBP (лири / пенса)
11
+ """
12
+
13
+ from .bg_numbers import number_to_words_cardinal
14
+
15
+ CURRENCY_INFO = {
16
+ 'BGN': {
17
+ 'main_singular': 'лев',
18
+ 'main_plural': 'лева',
19
+ 'sub_singular': 'стотинка',
20
+ 'sub_plural': 'стотинки',
21
+ 'main_gender': 'm',
22
+ 'sub_gender': 'f',
23
+ },
24
+ 'EUR': {
25
+ 'main_singular': 'евро',
26
+ 'main_plural': 'евро',
27
+ 'sub_singular': 'цент',
28
+ 'sub_plural': 'цента',
29
+ 'main_gender': 'n',
30
+ 'sub_gender': 'm',
31
+ },
32
+ 'USD': {
33
+ 'main_singular': 'долар',
34
+ 'main_plural': 'долара',
35
+ 'sub_singular': 'цент',
36
+ 'sub_plural': 'цента',
37
+ 'main_gender': 'm',
38
+ 'sub_gender': 'm',
39
+ },
40
+ 'GBP': {
41
+ 'main_singular': 'лира',
42
+ 'main_plural': 'лири',
43
+ 'sub_singular': 'пени',
44
+ 'sub_plural': 'пенса',
45
+ 'main_gender': 'f',
46
+ 'sub_gender': 'm',
47
+ },
48
+ }
49
+
50
+
51
+ def normalize_currency(amount_str: str, currency: str = 'BGN') -> str:
52
+ """
53
+ Convert a currency amount to spoken Bulgarian form.
54
+
55
+ Args:
56
+ amount_str: Amount as string, e.g., "1500.50", "1500,50", "25"
57
+ currency: Currency code (BGN, EUR, USD, GBP)
58
+
59
+ Returns:
60
+ Spoken form, e.g., "хиляда и петстотин лева и петдесет стотинки"
61
+ """
62
+ currency = currency.upper()
63
+ if currency not in CURRENCY_INFO:
64
+ currency = 'BGN'
65
+
66
+ info = CURRENCY_INFO[currency]
67
+
68
+ # Parse amount using string-based approach to avoid float precision issues
69
+ amount_str = amount_str.replace(',', '.').replace(' ', '')
70
+ if '.' in amount_str:
71
+ parts = amount_str.split('.', 1)
72
+ try:
73
+ main_amount = int(parts[0]) if parts[0] else 0
74
+ except ValueError:
75
+ return amount_str
76
+ sub_str = (parts[1] + '00')[:2]
77
+ sub_amount = int(sub_str)
78
+ else:
79
+ try:
80
+ main_amount = int(amount_str)
81
+ except ValueError:
82
+ return amount_str
83
+ sub_amount = 0
84
+
85
+ parts = []
86
+
87
+ # Main currency
88
+ if main_amount > 0:
89
+ main_words = number_to_words_cardinal(main_amount, info['main_gender'])
90
+ main_unit = info['main_singular'] if main_amount == 1 else info['main_plural']
91
+ parts.append(f"{main_words} {main_unit}")
92
+
93
+ # Sub currency (stotinki, cents, etc.)
94
+ if sub_amount > 0:
95
+ if parts:
96
+ parts.append('и')
97
+ sub_words = number_to_words_cardinal(sub_amount, info['sub_gender'])
98
+ sub_unit = info['sub_singular'] if sub_amount == 1 else info['sub_plural']
99
+ parts.append(f"{sub_words} {sub_unit}")
100
+
101
+ if not parts:
102
+ return f"нула {info['main_plural']}"
103
+
104
+ return ' '.join(parts)
105
+
106
+
107
+ if __name__ == '__main__':
108
+ test_amounts = [
109
+ ("1500.50", "BGN"),
110
+ ("1", "BGN"),
111
+ ("2", "BGN"),
112
+ ("25", "BGN"),
113
+ ("99.99", "BGN"),
114
+ ("0.50", "BGN"),
115
+ ("100", "EUR"),
116
+ ("50.25", "USD"),
117
+ ("1", "EUR"),
118
+ ("1000000", "BGN"),
119
+ ]
120
+
121
+ print("=== Currency Normalization ===")
122
+ for amount, currency in test_amounts:
123
+ result = normalize_currency(amount, currency)
124
+ print(f" {amount} {currency} → {result}")
@@ -0,0 +1,97 @@
1
+ """
2
+ Bulgarian Date Normalization
3
+ =============================
4
+ Converts date patterns to spoken Bulgarian form.
5
+
6
+ Bulgarian date specifics:
7
+ - Day is ordinal (masculine by default): "петнадесети"
8
+ - Month names: януари, февруари, март, etc.
9
+ - Year is read as cardinal: две хиляди двадесет и шеста
10
+ - "година" (year) suffix is common
11
+ """
12
+
13
+ from .bg_numbers import number_to_words_ordinal, number_to_words_cardinal
14
+
15
+ MONTH_NAMES = {
16
+ 1: 'януари', 2: 'февруари', 3: 'март', 4: 'април',
17
+ 5: 'май', 6: 'юни', 7: 'юли', 8: 'август',
18
+ 9: 'септември', 10: 'октомври', 11: 'ноември', 12: 'декември',
19
+ }
20
+
21
+
22
+ def normalize_date(day: int, month: int, year: int = None,
23
+ include_year_suffix: bool = False) -> str:
24
+ """
25
+ Convert a date to spoken Bulgarian form.
26
+
27
+ Args:
28
+ day: Day of month (1-31)
29
+ month: Month number (1-12)
30
+ year: Optional year (e.g., 2026)
31
+ include_year_suffix: Whether to append "година"
32
+
33
+ Returns:
34
+ Spoken form, e.g., "петнадесети февруари две хиляди двадесет и шеста година"
35
+ """
36
+ if month < 1 or month > 12:
37
+ return f"{day}.{month}" + (f".{year}" if year else "")
38
+
39
+ # Day as ordinal (masculine, since "ден" is masculine)
40
+ day_word = number_to_words_ordinal(day, gender='m')
41
+
42
+ # Month name
43
+ month_word = MONTH_NAMES[month]
44
+
45
+ parts = [day_word, month_word]
46
+
47
+ if year is not None:
48
+ year_word = normalize_year(year)
49
+ parts.append(year_word)
50
+ if include_year_suffix:
51
+ parts.append('година')
52
+
53
+ return ' '.join(parts)
54
+
55
+
56
+ def normalize_year(year: int) -> str:
57
+ """
58
+ Convert a year to spoken Bulgarian form.
59
+
60
+ Bulgarian years are typically read as:
61
+ - 2026 → "две хиляди двадесет и шеста" (ordinal feminine, since "година" is feminine)
62
+ - 1989 → "хиляда деветстотин осемдесет и девета"
63
+ - 2000 → "двехилядна" (ordinal feminine)
64
+ - 1900 → "хиляда и деветстотна"
65
+
66
+ For year context, the last component is typically ordinal feminine
67
+ (agreeing with "година").
68
+ """
69
+ if year <= 0:
70
+ return number_to_words_cardinal(year)
71
+
72
+ # Use ordinal feminine since "година" is feminine
73
+ return number_to_words_ordinal(year, gender='f')
74
+
75
+
76
+ if __name__ == '__main__':
77
+ test_dates = [
78
+ (15, 2, 2026, True),
79
+ (1, 1, 2000, True),
80
+ (3, 3, 1878, True),
81
+ (25, 12, None, False),
82
+ (31, 12, 1999, True),
83
+ (1, 9, 2024, False),
84
+ ]
85
+
86
+ print("=== Date Normalization ===")
87
+ for args in test_dates:
88
+ day, month = args[0], args[1]
89
+ year = args[2]
90
+ suffix = args[3] if len(args) > 3 else False
91
+ result = normalize_date(day, month, year, include_year_suffix=suffix)
92
+ date_str = f"{day:02d}.{month:02d}"
93
+ if year:
94
+ date_str += f".{year}"
95
+ if suffix:
96
+ date_str += " г."
97
+ print(f" {date_str} → {result}")