gapiring 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 (39) hide show
  1. gapiring/__init__.py +100 -0
  2. gapiring/__main__.py +3 -0
  3. gapiring/cli.py +41 -0
  4. gapiring/engine.py +199 -0
  5. gapiring/frontend/__init__.py +0 -0
  6. gapiring/frontend/common.py +16 -0
  7. gapiring/frontend/lexicon_extra.tsv +6 -0
  8. gapiring/frontend/tashkent_dialect.py +222 -0
  9. gapiring/frontend/terms.py +58 -0
  10. gapiring/frontend/terms_reviewed.json +4618 -0
  11. gapiring/frontend/terms_uz.py +71 -0
  12. gapiring/frontend/text_to_phoneme/__init__.py +0 -0
  13. gapiring/frontend/text_to_phoneme/phoneme_converter.py +329 -0
  14. gapiring/frontend/text_to_phoneme/pipelene_text_to_phoneme.py +55 -0
  15. gapiring/frontend/text_to_phoneme/text_normalization_for_tts.py +208 -0
  16. gapiring/frontend/text_to_phoneme/tools/__init__.py +0 -0
  17. gapiring/frontend/text_to_phoneme/tools/convert_currency_to_text.py +76 -0
  18. gapiring/frontend/text_to_phoneme/tools/convert_date_time_to_text.py +371 -0
  19. gapiring/frontend/text_to_phoneme/tools/convert_non_roman_numbers_to_text.py +609 -0
  20. gapiring/frontend/text_to_phoneme/tools/convert_phone_numbers_to_text.py +268 -0
  21. gapiring/frontend/text_to_phoneme/tools/convert_roman_numerals_to_text.py +235 -0
  22. gapiring/frontend/text_to_phoneme/tools/convert_symbols_to_uzbek_text.py +258 -0
  23. gapiring/frontend/text_to_phoneme/tools/expand_uzbek_abbreviations.py +293 -0
  24. gapiring/frontend/text_to_phoneme/tools/full_normalize.py +257 -0
  25. gapiring/frontend/text_to_phoneme/tools/pronounce_links_and_emails.py +99 -0
  26. gapiring/frontend/text_to_phoneme/tools/split_text_numbers.py +36 -0
  27. gapiring/frontend/text_to_phoneme/tools/spoken_lexicon.py +40 -0
  28. gapiring/frontend/text_to_phoneme/tools/spoken_prepass.py +116 -0
  29. gapiring/frontend/text_to_phoneme/uzbek_orthography.py +24 -0
  30. gapiring/frontend/textnorm.py +172 -0
  31. gapiring/frontend/tts_frontend.py +344 -0
  32. gapiring/lexicon.py +188 -0
  33. gapiring/text_front.py +77 -0
  34. gapiring-0.1.0.dist-info/METADATA +69 -0
  35. gapiring-0.1.0.dist-info/RECORD +39 -0
  36. gapiring-0.1.0.dist-info/WHEEL +5 -0
  37. gapiring-0.1.0.dist-info/entry_points.txt +2 -0
  38. gapiring-0.1.0.dist-info/licenses/LICENSE +4 -0
  39. gapiring-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,76 @@
1
+ import re
2
+
3
+
4
+ def convert_currency_to_text(text: str) -> str:
5
+
6
+ currency_rules = [
7
+ {"abbr": "USD", "name": "dollar", "symbols": ["$"]},
8
+ {"abbr": "EUR", "name": "yevro", "symbols": ["€", "EUR"]},
9
+ {"abbr": "GBP", "name": "funt sterling", "symbols": ["£"]},
10
+ {"abbr": "UZS", "name": "so'm", "symbols": []},
11
+ {"abbr": "RUB", "name": "rubl", "symbols": ["₽"]},
12
+ {"abbr": "KZT", "name": "tenge", "symbols": ["₸"]},
13
+ {"abbr": "CNY", "name": "yuan", "symbols": ["CN¥"]},
14
+ {"abbr": "JPY", "name": "iyena", "symbols": ["¥"]},
15
+ ]
16
+
17
+ processed_text = text
18
+
19
+ number_pattern = r"((?:\d{1,3}(?:[,']\d{3})+|\d+)(?:\.\d+)?)"
20
+
21
+ for rule in currency_rules:
22
+ full_name = rule["name"]
23
+ abbr_val = rule["abbr"]
24
+
25
+ abbr_regex = re.compile(rf"{number_pattern}\s*{abbr_val}\b", re.IGNORECASE)
26
+ processed_text = abbr_regex.sub(rf"\1 {full_name}", processed_text)
27
+
28
+ for symbol in rule["symbols"]:
29
+ escaped_symbol = re.escape(symbol)
30
+
31
+ symbol_before_regex = re.compile(rf"{escaped_symbol}\s*({number_pattern})")
32
+ processed_text = symbol_before_regex.sub(rf"\1 {full_name}", processed_text)
33
+
34
+ symbol_after_regex = re.compile(rf"({number_pattern})\s*{escaped_symbol}")
35
+ processed_text = symbol_after_regex.sub(rf"\1 {full_name}", processed_text)
36
+
37
+ return processed_text
38
+
39
+
40
+ if __name__ == "__main__":
41
+ test_texts = [
42
+ "$5",
43
+ "5 000 $",
44
+ "5 $",
45
+ "5$",
46
+ "Narx: $10.50.",
47
+ "Bu 25000 UZS turadi.",
48
+ "Menimcha 100 USD yetadi.",
49
+ "Yevropa Ittifoqida €500 katta pul.",
50
+ "Angliyada £20 non olish mumkin.",
51
+ "Rossiyada 1000₽ nima degani?",
52
+ "Qozog'istonda 500₸ ga ovqatlanish mumkin.",
53
+ "Yaponiyada ¥10000 lik sovg'a.",
54
+ "Xitoyda CN¥50 turadi.",
55
+ "Xitoyda ¥50 turadi (bu JPY qoidasi bilan 'iyena'ga aylanadi).",
56
+ "Aralash: $50, 100 UZS va €25.",
57
+ "Raqamlar: 12345 va $1,234.56 yoki 7,890KZT.",
58
+ "Yana bir misol 50$ va 60 USD.",
59
+ "Qisqartma belgi bilan: 50 EUR.",
60
+ "Qiymati 5.5KZT.",
61
+ "No valid: UZS5000 (raqam oldinda emas)"
62
+ ]
63
+
64
+ for text_item in test_texts:
65
+ converted_text = convert_currency_to_text(text_item)
66
+ print(f"Original: '{text_item}' -> O'zgartirilgan (Converted): '{converted_text}'")
67
+
68
+ print("\n--- Maxsus 'xkz' uchun tekshiruv (KZT sifatida qabul qilingan) ---")
69
+ print("--- Special check for 'xkz' (assumed as KZT) ---")
70
+ text_xkz = "1000 xkz miqdori"
71
+ if "xkz" in text_xkz.lower():
72
+ text_xkz_kzt = text_xkz.lower().replace("xkz", "KZT")
73
+ print(
74
+ f"Original (xkz): '{text_xkz}' -> KZT ga o'zgartirib (Converted to KZT): '{convert_currency_to_text(text_xkz_kzt)}'")
75
+ else:
76
+ print(f"Original (xkz): '{text_xkz}' -> O'zgartirilgan (Converted): '{convert_currency_to_text(text_xkz)}'")
@@ -0,0 +1,371 @@
1
+ import re
2
+ from datetime import datetime
3
+
4
+ UZBEK_UNITS_DATE = {0: "", 1: "bir", 2: "ikki", 3: "uch", 4: "toʻrt", 5: "besh", 6: "olti", 7: "yetti", 8: "sakkiz",
5
+ 9: "toʻqqiz"}
6
+ UZBEK_TENS_DATE = {1: "oʻn", 2: "yigirma", 3: "oʻttiz", 4: "qirq", 5: "ellik", 6: "oltmish", 7: "yetmish", 8: "sakson",
7
+ 9: "toʻqson"}
8
+ UZBEK_MONTHS_OUTPUT = {1: "yanvar", 2: "fevral", 3: "mart", 4: "aprel", 5: "may", 6: "iyun", 7: "iyul", 8: "avgust",
9
+ 9: "sentyabr", 10: "oktyabr", 11: "noyabr", 12: "dekabr"}
10
+ UZBEK_DAY_ORDINALS = {1: "birinchi", 2: "ikkinchi", 3: "uchinchi", 4: "toʻrtinchi", 5: "beshinchi", 6: "oltinchi",
11
+ 7: "yettinchi", 8: "sakkizinchi", 9: "toʻqqizinchi", 10: "oʻninchi", 11: "oʻn birinchi",
12
+ 12: "oʻn ikkinchi", 13: "oʻn uchinchi", 14: "oʻn toʻrtinchi", 15: "oʻn beshinchi",
13
+ 16: "oʻn oltinchi", 17: "oʻn yettinchi", 18: "oʻn sakkizinchi", 19: "oʻn toʻqqizinchi",
14
+ 20: "yigirmanchi", 21: "yigirma birinchi", 22: "yigirma ikkinchi", 23: "yigirma uchinchi",
15
+ 24: "yigirma toʻrtinchi", 25: "yigirma beshinchi", 26: "yigirma oltinchi",
16
+ 27: "yigirma yettinchi", 28: "yigirma sakkizinchi", 29: "yigirma toʻqqizinchi", 30: "oʻttizinchi",
17
+ 31: "oʻttiz birinchi"}
18
+ UZBEK_YEAR_PART_ORDINALS = {"bir": "birinchi", "ikki": "ikkinchi", "uch": "uchinchi", "toʻrt": "toʻrtinchi",
19
+ "besh": "beshinchi", "olti": "oltinchi", "yetti": "yettinchi", "sakkiz": "sakkizinchi",
20
+ "toʻqqiz": "toʻqqizinchi", "oʻn": "oʻninchi", "yigirma": "yigirmanchi",
21
+ "oʻttiz": "oʻttizinchi", "qirq": "qirqinchi", "ellik": "ellikinchi",
22
+ "oltmish": "oltmishinchi", "yetmish": "yetmishinchi", "sakson": "saksoninchi",
23
+ "toʻqson": "toʻqsoninchi", "yuz": "yuzinchi", "ming": "minginchi"}
24
+ UZBEK_MONTH_NAMES_INPUT_MAP = {"yanvar": 1, "fevral": 2, "mart": 3, "aprel": 4, "may": 5, "iyun": 6, "iyul": 7,
25
+ "avgust": 8, "sentyabr": 9, "oktyabr": 10, "noyabr": 11, "dekabr": 12}
26
+ UZBEK_MONTH_ABBREVIATIONS_INPUT_MAP = {"yan": 1, "fev": 2, "mar": 3, "apr": 4, "iyn": 6, "iyl": 7, "avg": 8, "sen": 9,
27
+ "okt": 10, "noy": 11, "dek": 12, "may": 5}
28
+
29
+ UZBEK_COMMON_ATTACHING_SUFFIXES = sorted(["ning", "ga", "da", "dan", "ni", "cha"], key=len, reverse=True)
30
+
31
+ all_unique_uz_months = sorted(
32
+ list(set(list(UZBEK_MONTH_NAMES_INPUT_MAP.keys()) + list(UZBEK_MONTH_ABBREVIATIONS_INPUT_MAP.keys()))), key=len,
33
+ reverse=True)
34
+ _ALL_UZ_MONTH_OPTIONS_FOR_REGEX = [name + r"\.?" for name in all_unique_uz_months]
35
+ _UZ_MONTHS_MASTER_REGEX_PART = r"(?:" + "|".join(_ALL_UZ_MONTH_OPTIONS_FOR_REGEX) + r")"
36
+ DATE_FORMATS_TO_TRY = ["%d/%m/%Y", "%d-%m-%Y", "%d.%m.%Y", "%d/%m/%y", "%d-%m-%y", "%d.%m.%y", "%m/%d/%Y", "%m-%d-%Y",
37
+ "%m.%d.%Y", "%m/%d/%y", "%m-%d-%y", "%m.%d.%y", "%Y/%m/%d", "%Y-%m-%d", "%Y.%m.%d", "%d %b %Y",
38
+ "%d %B %Y", "%d %b %y", "%d %B %y", "%b %d, %Y", "%B %d, %Y", "%b %d %Y", "%B %d %Y",
39
+ "%b %d, %y", "%B %d, %y", "%b %d %y", "%B %d %y", "%Y %b %d", "%Y %B %d", "%d-%m-%Y_custom"]
40
+ _EN_MONTHS_SHORT_LIST = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
41
+
42
+ UZBEK_UNITS_TIME = ["", "bir", "ikki", "uch", "to'rt", "besh", "olti", "yetti", "sakkiz", "to'qqiz"]
43
+ UZBEK_TENS_TIME = ["", "o'n", "yigirma", "o'ttiz", "qirq", "ellik", "oltmish", "yetmish", "sakson", "to'qson"]
44
+ VOWELS_UZBEK = ['a', 'e', 'i', 'o', 'u', 'oʻ']
45
+
46
+
47
+ def number_to_uzbek_text_time(n: int) -> str:
48
+ if not 0 <= n <= 59:
49
+ raise ValueError("Number for time conversion out of range (0-59)")
50
+ if n == 0:
51
+ return "nol"
52
+ elif n < 10:
53
+ return UZBEK_UNITS_TIME[n]
54
+ elif n < 20:
55
+ return UZBEK_TENS_TIME[1] + (" " + UZBEK_UNITS_TIME[n % 10] if n % 10 != 0 else "")
56
+ else:
57
+ tens_digit = n // 10
58
+ units_digit = n % 10
59
+ if units_digit == 0:
60
+ return UZBEK_TENS_TIME[tens_digit]
61
+ else:
62
+ return UZBEK_TENS_TIME[tens_digit] + " " + UZBEK_UNITS_TIME[units_digit]
63
+
64
+
65
+ def time_to_uzbek_text(time_str: str) -> str:
66
+ if not re.fullmatch(r'\d{2}:\d{2}', time_str):
67
+ return time_str
68
+ parts = time_str.split(':')
69
+ hours_str, minutes_str = parts[0], parts[1]
70
+ try:
71
+ hours = int(hours_str)
72
+ minutes = int(minutes_str)
73
+ except ValueError:
74
+ return time_str
75
+ if not (0 <= hours <= 23 and 0 <= minutes <= 59): return time_str
76
+
77
+ hours_text = number_to_uzbek_text_time(hours)
78
+
79
+ connector = "u"
80
+ if hours_text and hours_text[-1].lower() in VOWELS_UZBEK:
81
+ connector = "yu"
82
+ elif hours_text and hours_text[-2:].lower() == "o'":
83
+ if hours_text == "to'rt":
84
+ connector = "u"
85
+
86
+ if minutes == 0:
87
+ minutes_text = "nol nol"
88
+ else:
89
+ minutes_text = number_to_uzbek_text_time(minutes)
90
+
91
+ return f"{hours_text} {connector} {minutes_text}"
92
+
93
+
94
+ def _num_to_uzbek_words_lt_1000(n):
95
+ if n >= 1000 or n < 0: raise ValueError("Num out of range (0-999)")
96
+ if n == 0: return []
97
+ parts = []
98
+ if n >= 100:
99
+ if n // 100 != 1: parts.append(UZBEK_UNITS_DATE[n // 100])
100
+ parts.append("yuz"); n %= 100
101
+ if n >= 10: parts.append(UZBEK_TENS_DATE[n // 10]); n %= 10
102
+ if n > 0: parts.append(UZBEK_UNITS_DATE[n])
103
+ return [p for p in parts if p]
104
+
105
+
106
+ def _year_to_uzbek_cardinal_words(year):
107
+ if not (0 <= year <= 9999): raise ValueError("Year out of range (0-9999)")
108
+ if year == 0: return ["nol"]
109
+ parts = []
110
+ if year >= 1000: parts.append(UZBEK_UNITS_DATE[year // 1000]); parts.append("ming"); year %= 1000
111
+ if year > 0: parts.extend(_num_to_uzbek_words_lt_1000(year))
112
+ return [p for p in parts if p]
113
+
114
+
115
+ def _get_uzbek_year_ordinal_text(year_val):
116
+ if year_val == 0: return "nolinchi yil"
117
+ cardinal_words = _year_to_uzbek_cardinal_words(year_val)
118
+ if not cardinal_words: raise ValueError(f"Could not convert year {year_val} to cardinal.")
119
+ last_word = cardinal_words[-1]
120
+ if last_word in UZBEK_YEAR_PART_ORDINALS:
121
+ ordinal_last_word = UZBEK_YEAR_PART_ORDINALS[last_word]
122
+ else:
123
+ ends_with_vowel = any(last_word.endswith(v) for v in VOWELS_UZBEK)
124
+ if not ends_with_vowel and last_word:
125
+ if last_word[-1] in ('a', 'e', 'i', 'o', 'u'):
126
+ if not (last_word.endswith("o") and len(last_word) > 1 and last_word[-2] == "'"):
127
+ ends_with_vowel = True
128
+
129
+ if ends_with_vowel:
130
+ ordinal_last_word = last_word + "nchi"
131
+ else:
132
+ ordinal_last_word = last_word + "inchi"
133
+ year_text = " ".join(cardinal_words[:-1] + [ordinal_last_word]) if len(cardinal_words) > 0 else ordinal_last_word
134
+ return year_text + " yil"
135
+
136
+
137
+ def date_to_uzbek_text(date_str_input, is_pre_processed_uzbek=False, year_first=False):
138
+ parsed_date = None
139
+ original_input_for_error = date_str_input
140
+ if is_pre_processed_uzbek:
141
+ try:
142
+ parsed_date = datetime.strptime(date_str_input, "%d-%m-%Y")
143
+ except ValueError as e:
144
+ raise ValueError(f"Pre-processed Uzbek date '{date_str_input}' parse error: {e}")
145
+ else:
146
+ temp_date_str = date_str_input
147
+ for en_abbr in _EN_MONTHS_SHORT_LIST:
148
+ temp_date_str = re.sub(r"(\b" + re.escape(en_abbr) + r")\.(?!\w)", r"\1", temp_date_str,
149
+ flags=re.IGNORECASE)
150
+
151
+ for fmt in DATE_FORMATS_TO_TRY:
152
+ if "_custom" in fmt: continue
153
+ try:
154
+ current_input_str_to_parse = temp_date_str if ("%b" in fmt or "%B" in fmt) else date_str_input
155
+ parsed_date = datetime.strptime(current_input_str_to_parse, fmt)
156
+ break
157
+ except ValueError:
158
+ continue
159
+ if parsed_date is None: raise ValueError(f"Date string '{original_input_for_error}' could not be parsed.")
160
+ day, month, year = parsed_date.day, parsed_date.month, parsed_date.year
161
+ uzbek_year_str = _get_uzbek_year_ordinal_text(year)
162
+ if day not in UZBEK_DAY_ORDINALS: raise ValueError(f"Day {day} not supported.")
163
+ uzbek_day_str = UZBEK_DAY_ORDINALS[day]
164
+ if month not in UZBEK_MONTHS_OUTPUT: raise ValueError(f"Month {month} not supported.")
165
+ uzbek_month_str = UZBEK_MONTHS_OUTPUT[month]
166
+ if year_first:
167
+ return f"{uzbek_year_str} {uzbek_day_str} {uzbek_month_str}"
168
+ return f"{uzbek_day_str} {uzbek_month_str} {uzbek_year_str}"
169
+
170
+
171
+ def _normalize_year(year_str):
172
+ if len(year_str) == 2:
173
+ y = int(year_str)
174
+ current_year_short = datetime.now().year % 100
175
+ if y > current_year_short + 20 and y <= 99:
176
+ return str(1900 + y)
177
+ else:
178
+ return str(2000 + y)
179
+ return year_str
180
+
181
+
182
+ _YEAR_DIGITS_FLEXIBLE = r"\b(?:[12]\d{3}|\d{2})\b"
183
+ _YEAR_DIGITS_STRICT_YYYY = r"\b(?:[12]\d{3})\b"
184
+ _DAY_DIGITS = r"\b(?:0?[1-9]|[12]\d|3[01])\b"
185
+ _EN_MONTHS_SHORT_PATTERN_LIST = [m + r"\.?" for m in _EN_MONTHS_SHORT_LIST]
186
+ _EN_MONTHS_SHORT_REGEX = r"(?:" + "|".join(_EN_MONTHS_SHORT_PATTERN_LIST) + r")"
187
+ _EN_MONTHS_LONG = r"(?:January|February|March|April|May|June|July|August|September|October|November|December)"
188
+ _EN_MONTHS_ANY = f"(?:{_EN_MONTHS_LONG}|{_EN_MONTHS_SHORT_REGEX})"
189
+
190
+ _P_D_UZ_MONTH_Y_STR = r"(?P<day>" + _DAY_DIGITS + r")\s+(?P<month_raw>" + _UZ_MONTHS_MASTER_REGEX_PART + r")(?:\s*,\s*)?\s+(?P<year>" + _YEAR_DIGITS_FLEXIBLE + r")"
191
+ _P_UZ_MONTH_D_Y_STR = r"(?P<month_raw>" + _UZ_MONTHS_MASTER_REGEX_PART + r")\s+(?P<day>" + _DAY_DIGITS + r")(?:\s*,\s*)?\s+(?P<year>" + _YEAR_DIGITS_FLEXIBLE + r")"
192
+ _P_Y_UZ_MONTH_D_STR = r"(?P<year>" + _YEAR_DIGITS_STRICT_YYYY + r")\s+(?P<month_raw>" + _UZ_MONTHS_MASTER_REGEX_PART + r")\s+(?P<day>" + _DAY_DIGITS + r")"
193
+ _P_D_EN_MONTH_Y_STR = r"(?P<day>" + _DAY_DIGITS + r")\s+(?P<month_raw>" + _EN_MONTHS_ANY + r")(?:\s*,\s*)?\s+(?P<year>" + _YEAR_DIGITS_FLEXIBLE + r")"
194
+ _P_EN_MONTH_D_Y_STR = r"(?P<month_raw>" + _EN_MONTHS_ANY + r")\s+(?P<day>" + _DAY_DIGITS + r")(?:\s*,\s*)?\s+(?P<year>" + _YEAR_DIGITS_FLEXIBLE + r")"
195
+ _P_Y_EN_MONTH_D_STR = r"(?P<year>" + _YEAR_DIGITS_STRICT_YYYY + r")\s+(?P<month_raw>" + _EN_MONTHS_ANY + r")\s+(?P<day>" + _DAY_DIGITS + r")"
196
+ _YEAR_DIGITS_FLEXIBLE_NO_B = r"(?:[12]\d{3}|\d{2})"
197
+ _YEAR_DIGITS_STRICT_YYYY_NO_B = r"(?:[12]\d{3})"
198
+ _DAY_DIGITS_NO_B = r"(?:0?[1-9]|[12]\d|3[01])"
199
+ _MONTH_DIGITS_NO_B = r"(?:0?[1-9]|1[0-2])"
200
+ _P_Y_M_D_NUMERIC_STR = r"\b(?P<year>" + _YEAR_DIGITS_STRICT_YYYY_NO_B + r")[-/.](?P<month_num>" + _MONTH_DIGITS_NO_B + r")[-/.](?P<day_num>" + _DAY_DIGITS_NO_B + r")\b"
201
+ _P_D_M_Y_NUMERIC_STR = r"\b(?P<part1>" + _DAY_DIGITS_NO_B + r")[-/.](?P<part2>" + _MONTH_DIGITS_NO_B + r")[-/.](?P<year>" + _YEAR_DIGITS_FLEXIBLE_NO_B + r")\b"
202
+ _P_TIME_STR = r"\b(?P<hours>\d{2}):(?P<minutes>\d{2})\b"
203
+
204
+ PATTERNS_TO_TRY_ORDERED = [
205
+ {"name": "D_UZM_Y", "type": "uzbek_month", "regex": re.compile(_P_D_UZ_MONTH_Y_STR, re.IGNORECASE)},
206
+ {"name": "UZM_D_Y", "type": "uzbek_month", "regex": re.compile(_P_UZ_MONTH_D_Y_STR, re.IGNORECASE)},
207
+ {"name": "Y_UZM_D", "type": "uzbek_month", "regex": re.compile(_P_Y_UZ_MONTH_D_STR, re.IGNORECASE)},
208
+ {"name": "D_ENM_Y", "type": "english_month", "regex": re.compile(_P_D_EN_MONTH_Y_STR, re.IGNORECASE)},
209
+ {"name": "ENM_D_Y", "type": "english_month", "regex": re.compile(_P_EN_MONTH_D_Y_STR, re.IGNORECASE)},
210
+ {"name": "Y_ENM_D", "type": "english_month", "regex": re.compile(_P_Y_EN_MONTH_D_STR, re.IGNORECASE)},
211
+ {"name": "YMD_NUM", "type": "numeric_ymd", "regex": re.compile(_P_Y_M_D_NUMERIC_STR, re.IGNORECASE)},
212
+ {"name": "DMY_MDY_NUM", "type": "numeric_dmy_mdy", "regex": re.compile(_P_D_M_Y_NUMERIC_STR, re.IGNORECASE)},
213
+ {"name": "TIME_HHMM", "type": "time_hhmm", "regex": re.compile(_P_TIME_STR)}
214
+ ]
215
+
216
+
217
+ def _convert_match_to_uzbek(match_obj, p_info):
218
+ original_match_str = match_obj.group(0)
219
+ pattern_name = p_info["name"]
220
+ pattern_type = p_info["type"]
221
+
222
+ try:
223
+ if pattern_type == "uzbek_month":
224
+ day_str = match_obj.group("day")
225
+ month_raw = match_obj.group("month_raw")
226
+ year_str = _normalize_year(match_obj.group("year"))
227
+ month_cleaned = month_raw.lower().rstrip('.')
228
+ month_number = UZBEK_MONTH_NAMES_INPUT_MAP.get(month_cleaned) or \
229
+ UZBEK_MONTH_ABBREVIATIONS_INPUT_MAP.get(month_cleaned)
230
+ if month_number and day_str and year_str:
231
+ std_date = f"{int(day_str):02d}-{month_number:02d}-{year_str}"
232
+ return date_to_uzbek_text(std_date, is_pre_processed_uzbek=True,
233
+ year_first=pattern_name.startswith("Y_"))
234
+ else:
235
+ return original_match_str
236
+ elif pattern_type == "english_month":
237
+ return date_to_uzbek_text(original_match_str)
238
+ elif pattern_type == "numeric_ymd":
239
+ year_str = match_obj.group("year")
240
+ month_str = match_obj.group("month_num")
241
+ day_str = match_obj.group("day_num")
242
+ std_date = f"{int(day_str):02d}-{int(month_str):02d}-{year_str}"
243
+ return date_to_uzbek_text(std_date, is_pre_processed_uzbek=True, year_first=True)
244
+ elif pattern_type == "numeric_dmy_mdy":
245
+ return date_to_uzbek_text(original_match_str)
246
+ elif pattern_type == "time_hhmm":
247
+ return time_to_uzbek_text(original_match_str)
248
+
249
+ except ValueError:
250
+ return original_match_str
251
+ except Exception as e:
252
+ return original_match_str
253
+ return original_match_str
254
+
255
+
256
+ def convert_date_time_to_text(full_text):
257
+ found_items = []
258
+ for i, p_info in enumerate(PATTERNS_TO_TRY_ORDERED):
259
+ for match in p_info["regex"].finditer(full_text):
260
+ found_items.append({
261
+ "start": match.start(),
262
+ "end": match.end(),
263
+ "match_obj": match,
264
+ "p_info": p_info,
265
+ "text": match.group(0),
266
+ "priority": i
267
+ })
268
+ if not found_items: return full_text
269
+
270
+ found_items.sort(key=lambda x: (x["start"], -(x["end"] - x["start"]), x["priority"]))
271
+
272
+ final_replacements = []
273
+ current_coverage_end = -1
274
+ for item_info in found_items:
275
+ if item_info["start"] >= current_coverage_end:
276
+ final_replacements.append(item_info)
277
+ current_coverage_end = item_info["end"]
278
+
279
+ result_parts = []
280
+ current_text_pos = 0
281
+ for item_info in final_replacements:
282
+ result_parts.append(full_text[current_text_pos:item_info["start"]])
283
+
284
+ original_matched_text_segment = item_info["text"]
285
+ converted_text = _convert_match_to_uzbek(item_info["match_obj"], item_info["p_info"])
286
+
287
+ current_processed_text_end_pos = item_info["end"]
288
+
289
+ was_successfully_converted = (converted_text != original_matched_text_segment)
290
+
291
+ if was_successfully_converted:
292
+ cursor_for_suffix_check = item_info["end"]
293
+ has_space_before_suffix = False
294
+ if cursor_for_suffix_check < len(full_text) and full_text[cursor_for_suffix_check] == ' ':
295
+ has_space_before_suffix = True
296
+
297
+ suffix_start_pos_in_full_text = cursor_for_suffix_check + (1 if has_space_before_suffix else 0)
298
+
299
+ for suffix_candidate in UZBEK_COMMON_ATTACHING_SUFFIXES:
300
+ if full_text.startswith(suffix_candidate, suffix_start_pos_in_full_text):
301
+ idx_after_suffix_candidate_in_full_text = suffix_start_pos_in_full_text + len(suffix_candidate)
302
+
303
+ is_standalone_suffix_token = (
304
+ idx_after_suffix_candidate_in_full_text == len(full_text) or
305
+ (idx_after_suffix_candidate_in_full_text < len(full_text) and
306
+ not full_text[idx_after_suffix_candidate_in_full_text].isalnum())
307
+ )
308
+
309
+ if is_standalone_suffix_token:
310
+ if converted_text:
311
+ text_parts = converted_text.rsplit(' ', 1)
312
+ if len(text_parts) > 1:
313
+ head, tail = text_parts
314
+ converted_text = f"{head} {tail}{suffix_candidate}"
315
+ else:
316
+ converted_text = f"{text_parts[0]}{suffix_candidate}"
317
+
318
+ current_processed_text_end_pos = idx_after_suffix_candidate_in_full_text
319
+ break
320
+
321
+ result_parts.append(converted_text)
322
+ current_text_pos = current_processed_text_end_pos
323
+
324
+ result_parts.append(full_text[current_text_pos:])
325
+ return "".join(result_parts)
326
+
327
+
328
+ if __name__ == "__main__":
329
+ print("--- Testing individual date_to_uzbek_text ---")
330
+ print(f"'10/05/2023' -> {date_to_uzbek_text('10/05/2023')}")
331
+ print(f"'Dec. 25, 2024' -> {date_to_uzbek_text('Dec. 25, 2024')}")
332
+ print(f"'01/09/1991' -> {date_to_uzbek_text('01/09/1991')}")
333
+
334
+ print("\n--- Testing individual time_to_uzbek_text ---")
335
+ print(f"'13:00' -> {time_to_uzbek_text('13:00')}")
336
+ print(f"'08:05' -> {time_to_uzbek_text('08:05')}")
337
+ print(f"'20:05' -> {time_to_uzbek_text('20:05')}")
338
+ print(f"'02:05' -> {time_to_uzbek_text('02:05')}")
339
+ print(f"'06:00' -> {time_to_uzbek_text('06:00')}")
340
+ print(f"'04:00' -> {time_to_uzbek_text('04:00')}")
341
+ print(f"'25:00' -> {time_to_uzbek_text('25:00')}")
342
+
343
+ print("\n--- Testing process_text_for_dates_and_time (finding and replacing in text) ---")
344
+ sample_texts = [
345
+ "The event is on 10/05/2023 at 14:30, and the deadline is May 20, 2023.",
346
+ "Uchrashuv 15 may 2024 kuni soat 09:00 da. Keyingisi esa 20 dekabr 2024 soat 18:45. Vaqt 20:05.",
347
+ "Historical date: 01-01-2000. Future date: 2025/12/31. Meeting time: 10:00, 02:30.",
348
+ "Reference: Project started 2022 Jan. 15 (time 11:15) and ended on 15 Fevral 2023.",
349
+ "Invalid date 99/99/9999, but valid 03.04.2021 and valid time 00:00.",
350
+ "US format: 12/31/2023. Also: 2025 yanvar 05. Va 10 fev. 2026 soat 23:59.",
351
+ "Short year test: 01/01/25 (08:08) and meeting on 15 avgust 24. Also 1 mar 27 at 17:00 and 06:10.",
352
+ "This text has no dates or times, only numbers like 12345.",
353
+ "The date 20.03.2024 is Navruz (begins 05:30), an important holiday.",
354
+ "Date: Dec. 25, 2024 (time 20:00) is Christmas. Another one: 5 Sen. 2023.",
355
+ "Yana bir sana: 2027 Noy 15. Vaqt: 01:05.",
356
+ "01/09/1991 da mustaqil boʻldik.",
357
+ "Uchrashuv 14:00 da.",
358
+ "Mustaqillik 01/09/1991da boshlandi (no space before suffix - current logic might miss this, needs space).",
359
+ "Mustaqillik 01/09/1991 ning tongida boshlandi.",
360
+ "10/05/2023ga xat yuborildi.",
361
+ "10/05/2023 dan keyin.",
362
+ "Invalid date string 01/32/2023da (should not attach 'da' to original if not converted).",
363
+ "Valid date 03.04.2021da and also 03.04.2021 dan and time 00:00.",
364
+ "Soat 06:00da uchrashamiz.",
365
+ "Soat 04:00da uchrashamiz."
366
+ ]
367
+
368
+ for i, text in enumerate(sample_texts):
369
+ print(f"\nOriginal Text {i + 1}: {text}")
370
+ processed_text = convert_date_time_to_text(text)
371
+ print(f"Processed Text {i + 1}: {processed_text}")