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.
- gapiring/__init__.py +100 -0
- gapiring/__main__.py +3 -0
- gapiring/cli.py +41 -0
- gapiring/engine.py +199 -0
- gapiring/frontend/__init__.py +0 -0
- gapiring/frontend/common.py +16 -0
- gapiring/frontend/lexicon_extra.tsv +6 -0
- gapiring/frontend/tashkent_dialect.py +222 -0
- gapiring/frontend/terms.py +58 -0
- gapiring/frontend/terms_reviewed.json +4618 -0
- gapiring/frontend/terms_uz.py +71 -0
- gapiring/frontend/text_to_phoneme/__init__.py +0 -0
- gapiring/frontend/text_to_phoneme/phoneme_converter.py +329 -0
- gapiring/frontend/text_to_phoneme/pipelene_text_to_phoneme.py +55 -0
- gapiring/frontend/text_to_phoneme/text_normalization_for_tts.py +208 -0
- gapiring/frontend/text_to_phoneme/tools/__init__.py +0 -0
- gapiring/frontend/text_to_phoneme/tools/convert_currency_to_text.py +76 -0
- gapiring/frontend/text_to_phoneme/tools/convert_date_time_to_text.py +371 -0
- gapiring/frontend/text_to_phoneme/tools/convert_non_roman_numbers_to_text.py +609 -0
- gapiring/frontend/text_to_phoneme/tools/convert_phone_numbers_to_text.py +268 -0
- gapiring/frontend/text_to_phoneme/tools/convert_roman_numerals_to_text.py +235 -0
- gapiring/frontend/text_to_phoneme/tools/convert_symbols_to_uzbek_text.py +258 -0
- gapiring/frontend/text_to_phoneme/tools/expand_uzbek_abbreviations.py +293 -0
- gapiring/frontend/text_to_phoneme/tools/full_normalize.py +257 -0
- gapiring/frontend/text_to_phoneme/tools/pronounce_links_and_emails.py +99 -0
- gapiring/frontend/text_to_phoneme/tools/split_text_numbers.py +36 -0
- gapiring/frontend/text_to_phoneme/tools/spoken_lexicon.py +40 -0
- gapiring/frontend/text_to_phoneme/tools/spoken_prepass.py +116 -0
- gapiring/frontend/text_to_phoneme/uzbek_orthography.py +24 -0
- gapiring/frontend/textnorm.py +172 -0
- gapiring/frontend/tts_frontend.py +344 -0
- gapiring/lexicon.py +188 -0
- gapiring/text_front.py +77 -0
- gapiring-0.1.0.dist-info/METADATA +69 -0
- gapiring-0.1.0.dist-info/RECORD +39 -0
- gapiring-0.1.0.dist-info/WHEEL +5 -0
- gapiring-0.1.0.dist-info/entry_points.txt +2 -0
- gapiring-0.1.0.dist-info/licenses/LICENSE +4 -0
- gapiring-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
from gapiring.frontend.common import TTS_UZ
|
|
8
|
+
|
|
9
|
+
from gapiring.frontend.text_to_phoneme.phoneme_converter import uzbek_to_ipa_final
|
|
10
|
+
from gapiring.frontend.text_to_phoneme.pipelene_text_to_phoneme import is_punctuation_or_symbol, tokenize_text
|
|
11
|
+
from gapiring.frontend.text_to_phoneme.text_normalization_for_tts import text_normalization_for_tts
|
|
12
|
+
from gapiring.frontend.text_to_phoneme.uzbek_orthography import normalize_uzbek_apostrophes
|
|
13
|
+
|
|
14
|
+
TAG_VOCAB = {
|
|
15
|
+
"<laugh>": "[laugh]", "<laughter>": "[laugh]", "<chuckle>": "[laugh]", "<chuckles>": "[laugh]",
|
|
16
|
+
"<giggle>": "[laugh]", "<short pause>": "[pause]", "<long pause>": "[pause]",
|
|
17
|
+
"<breath>": "[breath]", "<exhales>": "[breath]", "<sigh>": "[sigh]", "<sighs>": "[sigh]",
|
|
18
|
+
}
|
|
19
|
+
ALT_TAG_RE = re.compile(r"<[a-z][a-z -]*>")
|
|
20
|
+
DATASET_TAG = re.compile(r"\[(laugh|pause|breath|sigh)\]")
|
|
21
|
+
|
|
22
|
+
SUFFIXES = ("gacha", "larda", "dan", "da", "ga", "ni", "ning", "lar")
|
|
23
|
+
SUFFIX_RE = "|".join(SUFFIXES)
|
|
24
|
+
BAD_AFTER = re.compile(r"\d|\b(ayiruv|minus|bo'luv|kuchukcha|nuqta|dablyu)\b|\bnol nol\b|[@/\\#*_=<>{}\[\]|~^]")
|
|
25
|
+
NUMBER_WORDS = ("nol bir ikki uch to'rt besh olti yetti sakkiz to'qqiz o'n yigirma o'ttiz qirq ellik oltmish "
|
|
26
|
+
"yetmish sakson to'qson yuz ming million").split()
|
|
27
|
+
STRAY_U = re.compile(r"\b(" + "|".join(map(re.escape, NUMBER_WORDS)) + r") u\b")
|
|
28
|
+
ACRONYM = re.compile(r"\b[A-Z]{2,}\b|(?<![\w'])[A-Z](?![\w'])")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def say_number(n: int) -> str:
|
|
32
|
+
return text_normalization_for_tts(str(n)).strip()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def attach(words: str, suffix: str) -> str:
|
|
36
|
+
if not suffix:
|
|
37
|
+
return words
|
|
38
|
+
last = words[-1]
|
|
39
|
+
if suffix.startswith("g") and last in "kq":
|
|
40
|
+
suffix = last + suffix[1:]
|
|
41
|
+
return words + suffix
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def say_time(hour: int, minute: int) -> str:
|
|
45
|
+
if not (0 <= hour <= 24 and 0 <= minute <= 59):
|
|
46
|
+
raise ValueError(f"bad time {hour}:{minute}")
|
|
47
|
+
if minute == 0:
|
|
48
|
+
return say_number(hour)
|
|
49
|
+
if minute < 10:
|
|
50
|
+
raise ValueError("minutes 01-09 have no settled spoken form")
|
|
51
|
+
return f"{say_number(hour)} {say_number(minute)}"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def prenorm(text: str) -> str:
|
|
55
|
+
text = normalize_uzbek_apostrophes(" ".join(text.split()))
|
|
56
|
+
if re.search(r"https?://|www\.|@|\.uz\b|\.com\b", text):
|
|
57
|
+
raise ValueError("links and e-mails are not agent speech")
|
|
58
|
+
if ACRONYM.search(text):
|
|
59
|
+
raise ValueError("acronyms and letter codes are read inconsistently")
|
|
60
|
+
text = re.sub(r"\b(\d{1,2}):(\d{2})\s*[-–]\s*(\d{1,2}):(\d{2})\b",
|
|
61
|
+
lambda m: f"{attach(say_time(int(m[1]), int(m[2])), 'dan')} "
|
|
62
|
+
f"{attach(say_time(int(m[3]), int(m[4])), 'gacha')}", text)
|
|
63
|
+
text = re.sub(rf"\b(\d{{1,2}}):(\d{{2}})(?:\s?-?({SUFFIX_RE})\b)?",
|
|
64
|
+
lambda m: attach(say_time(int(m[1]), int(m[2])), m[3] or ""), text)
|
|
65
|
+
text = re.sub(r"\b(\d+)[.,]5\b(?!\d)", lambda m: f"{say_number(int(m[1]))} yarim", text)
|
|
66
|
+
if re.search(r"\d[.,]\d", text) and not re.search(r"\d{1,3}(?:[ .,]\d{3})+", text):
|
|
67
|
+
raise ValueError("decimal fraction")
|
|
68
|
+
def rng(m):
|
|
69
|
+
a, b = int(m[1]), int(m[2])
|
|
70
|
+
if not a < b <= 999:
|
|
71
|
+
raise ValueError(f"hyphenated digits {m[0]!r} look like a code")
|
|
72
|
+
return f"{say_number(a)}-{attach(say_number(b), m[3] or '')}"
|
|
73
|
+
text = re.sub(rf"\b(\d{{1,3}})\s?[-–]\s?(\d{{1,3}})(?:-?({SUFFIX_RE})\b)?(?=\s|[,.]|$)", rng, text)
|
|
74
|
+
if re.search(r"\d\s?[-–]\s?\d", text):
|
|
75
|
+
raise ValueError("hyphenated code")
|
|
76
|
+
def ident(m):
|
|
77
|
+
digits = m[0]
|
|
78
|
+
if digits.startswith("998") or len(digits) > 12:
|
|
79
|
+
return digits
|
|
80
|
+
groups, rest = [digits[:3]], digits[3:]
|
|
81
|
+
while rest:
|
|
82
|
+
take = 3 if len(rest) == 3 else 2
|
|
83
|
+
groups.append(rest[:take])
|
|
84
|
+
rest = rest[take:]
|
|
85
|
+
return ", ".join(say_number(int(g)) if not g.startswith("0") else
|
|
86
|
+
" ".join(say_number(int(c)) for c in g) for g in groups)
|
|
87
|
+
text = re.sub(r"(?<![+\d])\b\d{7,}\b(?! ?(so'm|sum|dollar))", ident, text)
|
|
88
|
+
return text
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def spoken_conventions(text: str) -> str:
|
|
92
|
+
text = re.sub(r"\bto'qqiz to'qqiz sakkiz\b", "to'qqiz yuz to'qson sakkiz", text)
|
|
93
|
+
text = re.sub(r"\b(" + "|".join(map(re.escape, NUMBER_WORDS)) + r") (dagi|dan|da|gacha|ga|ni|ning|larda|lardan)\b",
|
|
94
|
+
lambda m: attach(m[1], m[2]), text, flags=re.IGNORECASE)
|
|
95
|
+
text = re.sub(r"\b([Bb])ir yuz\b", lambda m: "Yuz" if m[1] == "B" else "yuz", text)
|
|
96
|
+
return text
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
FOREIGN = re.compile(r"[^A-Za-z0-9\s.,!?;:'\"()%+$№/«»“”‘’ʻʼ`\-–—]")
|
|
100
|
+
ABBREV = re.compile(r"(?<![\w'])(?:[a-z]{1,4}|ko'ch|mav|mkr)\.(?=\s*[a-z0-9])|[A-Za-z]/[A-Za-z]"
|
|
101
|
+
r"|(?<![\w'])(?:sh|t|ko'ch|mav|kv|mkr|tum|vil|r-n|d|y|ul|pr)\.(?=\s|$)")
|
|
102
|
+
UNITS = {"kg": "kilogramm", "km": "kilometr", "sm": "santimetr", "mm": "millimetr", "ml": "millilitr",
|
|
103
|
+
"gb": "gigabayt", "mb": "megabayt", "kvt": "kilovatt", "m2": "kvadrat metr", "m²": "kvadrat metr"}
|
|
104
|
+
UNIT_RE = re.compile(r"(\d)\s?(" + "|".join(sorted(map(re.escape, UNITS), key=len, reverse=True)) + r")(?![\w'])",
|
|
105
|
+
re.IGNORECASE)
|
|
106
|
+
SPAN = re.compile(r"(?:[+$№]\s?)?\d+(?:[ .,:/]\d+)*%?(?:-?[A-Za-z']+)?")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def normalize_span(span: str) -> str:
|
|
110
|
+
return " ".join(text_normalization_for_tts(span).split())
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def verbalize(raw: str, terms: str = "spoken") -> str:
|
|
114
|
+
from gapiring.frontend.terms import swap_in, swap_out
|
|
115
|
+
|
|
116
|
+
raw = normalize_uzbek_apostrophes(" ".join(raw.split()))
|
|
117
|
+
if FOREIGN.search(raw):
|
|
118
|
+
raise ValueError(f"characters outside Uzbek Latin: {FOREIGN.search(raw)[0]!r}")
|
|
119
|
+
if ABBREV.search(raw):
|
|
120
|
+
raise ValueError(f"abbreviation: {ABBREV.search(raw)[0]!r}")
|
|
121
|
+
if re.search(r"[A-Za-z]\d|\d[xX×]\d", raw):
|
|
122
|
+
raise ValueError("letters glued to digits (M500, 3x4)")
|
|
123
|
+
held, found = swap_out(raw)
|
|
124
|
+
held = re.sub(r"(\d)\s?%", r"\1 foiz", held)
|
|
125
|
+
held = UNIT_RE.sub(lambda m: f"{m[1]} {UNITS[m[2].lower()]}", held)
|
|
126
|
+
text = prenorm(held)
|
|
127
|
+
text = SPAN.sub(lambda m: normalize_span(m[0]), text)
|
|
128
|
+
out = spoken_conventions(" ".join(text.split()))
|
|
129
|
+
out = re.sub(r"\s+([,.!?;:])", r"\1", out)
|
|
130
|
+
out = re.sub(r"\b(" + "|".join(map(re.escape, NUMBER_WORDS)) + r") ta(?![\w'])", r"\1ta", out)
|
|
131
|
+
out = re.sub(r"\b([Bb])irta(?![\w'])", r"\1itta", out)
|
|
132
|
+
out = re.sub(r"\bfoiz (ni|ning|ga|dan|da|gacha|lik|lar)(?![\w'])", r"foiz\1", out)
|
|
133
|
+
out = out[:1].upper() + out[1:]
|
|
134
|
+
bad = BAD_AFTER.search(out) or STRAY_U.search(out)
|
|
135
|
+
if bad:
|
|
136
|
+
raise ValueError(f"normalizer output still unsafe: {bad[0]!r} in {out!r}")
|
|
137
|
+
out = swap_in(out, found, terms)
|
|
138
|
+
if re.search(r"zqterm", out, re.IGNORECASE):
|
|
139
|
+
raise ValueError(f"term placeholder lost in normalization: {out!r}")
|
|
140
|
+
return out[:1].upper() + out[1:] if out[:1].islower() and not out.startswith("iPhone") else out
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def to_dataset_text(tts_text: str) -> str:
|
|
144
|
+
def sub(m):
|
|
145
|
+
if m[0] not in TAG_VOCAB:
|
|
146
|
+
raise ValueError(f"tag outside the vocabulary: {m[0]}")
|
|
147
|
+
return TAG_VOCAB[m[0]]
|
|
148
|
+
return " ".join(ALT_TAG_RE.sub(sub, tts_text).split())
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def spoken_words(text: str) -> str:
|
|
152
|
+
return " ".join(DATASET_TAG.sub(" ", ALT_TAG_RE.sub(" ", text)).split())
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def phonemes(text: str) -> str:
|
|
156
|
+
out = []
|
|
157
|
+
for piece in re.split(r"(\[(?:laugh|pause|breath|sigh)\])", text):
|
|
158
|
+
if DATASET_TAG.fullmatch(piece):
|
|
159
|
+
out.append(piece)
|
|
160
|
+
continue
|
|
161
|
+
for token in tokenize_text(piece):
|
|
162
|
+
out.append(token if is_punctuation_or_symbol(token) else uzbek_to_ipa_final(token.lower()))
|
|
163
|
+
return " ".join(out)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
if __name__ == "__main__":
|
|
167
|
+
for line in sys.argv[1:]:
|
|
168
|
+
try:
|
|
169
|
+
spoken = verbalize(line)
|
|
170
|
+
print(f"{line!r}\n -> {spoken!r}\n -> {phonemes(spoken)}")
|
|
171
|
+
except ValueError as error:
|
|
172
|
+
print(f"{line!r}\n REJECT {error}")
|
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
import sys
|
|
7
|
+
import unicodedata
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
HERE = Path(__file__).resolve().parent
|
|
12
|
+
from gapiring.frontend import tashkent_dialect
|
|
13
|
+
from gapiring.frontend import textnorm
|
|
14
|
+
from gapiring.frontend.terms import LEXICON as BASE_TERMS
|
|
15
|
+
from gapiring.frontend.terms_uz import LIST_TERMS
|
|
16
|
+
|
|
17
|
+
REVIEWED_LEXICON = Path(__file__).resolve().parent / "terms_reviewed.json"
|
|
18
|
+
EXTRA_LEXICON = HERE / "lexicon_extra.tsv"
|
|
19
|
+
TAGS_OK = ("pause", "laugh", "breath")
|
|
20
|
+
ALT_TAGS = {"short pause": "pause", "long pause": "pause", "pause": "pause", "chuckle": "laugh", "laugh": "laugh",
|
|
21
|
+
"laughs": "laugh", "giggle": "laugh", "breath": "breath", "inhale": "breath", "exhales": "breath",
|
|
22
|
+
"smile": "laugh", "smiling": "laugh", "sigh": "breath"}
|
|
23
|
+
LETTERS_EN = {"A": "ey", "B": "bi", "C": "si", "D": "di", "E": "i", "F": "ef", "G": "ji", "H": "eych", "I": "ay", "J": "jey",
|
|
24
|
+
"K": "key", "L": "el", "M": "em", "N": "en", "O": "o", "P": "pi", "Q": "kyu", "R": "ar", "S": "es", "T": "ti",
|
|
25
|
+
"U": "yu", "V": "vi", "W": "dabl-yu", "X": "eks", "Y": "vay", "Z": "zed"}
|
|
26
|
+
ABBREV = {"mln": "million", "mlrd": "milliard", "h.k.": "hokazo", "va h.k.": "va hokazo", "tel.": "telefon", "sm": "santimetr"}
|
|
27
|
+
AREA = r"(?<=\d)\s?(?:m²|m2|kv\.?\s?m\b\.?|sq\.?\s?m\b)"
|
|
28
|
+
UNIT_SLASH = [(r"(?i)\bMbit/s\b|\bMb/s\b|\bMbps\b", "megabit sekund"), (r"(?i)\bGbit/s\b|\bGbps\b", "gigabit sekund"),
|
|
29
|
+
(r"(?i)\bkm/(?:soat|h)\b", "kilometr soatiga"), (r"(?i)\bm/s\b", "metr sekundiga")]
|
|
30
|
+
CYR = {"а": "a", "б": "b", "в": "v", "г": "g", "ғ": "g'", "д": "d", "е": "e", "ё": "yo", "ж": "j", "з": "z", "и": "i",
|
|
31
|
+
"й": "y", "к": "k", "қ": "q", "л": "l", "м": "m", "н": "n", "о": "o", "п": "p", "р": "r", "с": "s", "т": "t",
|
|
32
|
+
"у": "u", "ў": "o'", "ф": "f", "х": "x", "ҳ": "h", "ц": "ts", "ч": "ch", "ш": "sh", "щ": "sh", "ъ": "'", "ь": "",
|
|
33
|
+
"ы": "i", "э": "e", "ю": "yu", "я": "ya"}
|
|
34
|
+
CYR_VOWELS = set("аеёиоуыэюяў")
|
|
35
|
+
RESPELL = {"kuryer": "kurier"}
|
|
36
|
+
UZBEK_HOMOGRAPHS = {"band"}
|
|
37
|
+
PHONE_CC = r"(?<![\d+])(\+\s?)?998((?:[\s\-–()]*\d){9})(?!\d)"
|
|
38
|
+
PHONE_LOCAL = r"(?<![\d+])(?:(8)(?:[\s\-–]+|(?=\()))?(?:\((\d\d)\)\s*|(\d\d)[\s\-–]+)(\d{3})[\s\-–]?(\d\d)[\s\-–]?(\d\d)(?!\d)"
|
|
39
|
+
PHONE_SPACED = (r"(?<![\d+])(\+?998 )?(\d\d) (\d{3}) (\d\d) (\d\d)(?!\d)"
|
|
40
|
+
r"(-?[A-Za-z']+| (?:dagi|dan|da|gacha|ga|ni|ning|larda|lardan|ta)(?![\w']))?")
|
|
41
|
+
NUMBER_WORDS = ("nol bir ikki uch to'rt besh olti yetti sakkiz to'qqiz o'n yigirma o'ttiz qirq ellik oltmish yetmish "
|
|
42
|
+
"sakson to'qson yuz ming million milliard").split()
|
|
43
|
+
EMOJI = re.compile("[\U0001F000-\U0001FAFF☀-➿️]")
|
|
44
|
+
ALLOWED_FINAL = re.compile(r"[A-Za-z' \-.,!?;:…()\[\]]")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class Result:
|
|
49
|
+
text: str
|
|
50
|
+
stages: list = field(default_factory=list)
|
|
51
|
+
changes: list = field(default_factory=list)
|
|
52
|
+
warnings: list = field(default_factory=list)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _lexicon() -> tuple[dict[str, str], dict[str, str]]:
|
|
56
|
+
table = {k: v[0] for k, v in BASE_TERMS.items()}
|
|
57
|
+
table.update(LIST_TERMS)
|
|
58
|
+
if REVIEWED_LEXICON.exists():
|
|
59
|
+
for key, v in json.loads(REVIEWED_LEXICON.read_text()).items():
|
|
60
|
+
table.setdefault(v.get("term", key), v["reading"])
|
|
61
|
+
extra = {}
|
|
62
|
+
if EXTRA_LEXICON.exists():
|
|
63
|
+
for line in EXTRA_LEXICON.read_text().splitlines():
|
|
64
|
+
if line.strip() and not line.startswith("#"):
|
|
65
|
+
term, reading = line.split("\t")[:2]
|
|
66
|
+
extra[term.strip()] = reading.strip()
|
|
67
|
+
table.update(extra)
|
|
68
|
+
return table, extra
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
LEXICON, _EXTRA = _lexicon()
|
|
72
|
+
_FOLDED = {}
|
|
73
|
+
for _k, _v in LEXICON.items():
|
|
74
|
+
_FOLDED.setdefault(_k.lower(), _v)
|
|
75
|
+
_FOLDED.update({k.lower(): v for k, v in _EXTRA.items()})
|
|
76
|
+
_SUFFIX_APOSTROPHE = r"(?:'(?=[a-z])|(?![A-Za-z']))"
|
|
77
|
+
_BARE = [k for k in LEXICON if k.lower() not in UZBEK_HOMOGRAPHS]
|
|
78
|
+
_TERM_RE = re.compile(r"(?<![A-Za-z'\[])(" + "|".join(sorted(map(re.escape, _BARE), key=len, reverse=True)) + r")" + _SUFFIX_APOSTROPHE)
|
|
79
|
+
_TERM_RE_I = re.compile(r"(?<![A-Za-z'\-\[])(" + "|".join(sorted((re.escape(k) for k in _BARE if not k.isupper() and len(k) > 2),
|
|
80
|
+
key=len, reverse=True)) + r")(?:'(?=[a-z])|(?![A-Za-z\-']))", re.I)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _sub(res: Result, stage: str, rule: str, pattern, repl, text: str, flags=0) -> str:
|
|
84
|
+
def f(m):
|
|
85
|
+
out = repl(m) if callable(repl) else m.expand(repl)
|
|
86
|
+
if out != m.group(0):
|
|
87
|
+
res.changes.append((stage, rule, m.group(0), out))
|
|
88
|
+
return out
|
|
89
|
+
return re.sub(pattern, f, text, flags=flags)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def clean(text: str, res: Result) -> str:
|
|
93
|
+
from gapiring.frontend.text_to_phoneme.tools.convert_phone_numbers_to_text import UZBEK_OPERATOR_CODES
|
|
94
|
+
from gapiring.frontend.text_to_phoneme.uzbek_orthography import normalize_uzbek_apostrophes
|
|
95
|
+
|
|
96
|
+
s = unicodedata.normalize("NFC", text)
|
|
97
|
+
s2 = normalize_uzbek_apostrophes(s).replace("ʻ", "'").replace("‘", "'").replace("’", "'").replace("`", "'")
|
|
98
|
+
if s2 != s:
|
|
99
|
+
res.changes.append(("clean", "apostrophes", "ʻ ’ ‘ `", "'"))
|
|
100
|
+
s = s2
|
|
101
|
+
s = _sub(res, "clean", "markdown", r"\*\*|__|`|^#{1,6}\s*", "", s, re.M)
|
|
102
|
+
items = [re.match(r"\s*(?:[-*•–]|\d{1,2}[.)])\s+", line) for line in s.split("\n")]
|
|
103
|
+
if sum(1 for m in items if m) >= 2:
|
|
104
|
+
lines = []
|
|
105
|
+
for line, m in zip(s.split("\n"), items):
|
|
106
|
+
if m:
|
|
107
|
+
item = line[m.end():].strip()
|
|
108
|
+
lines.append(("[pause] " if lines else "") + item + ("" if item[-1:] in ".!?…" else "."))
|
|
109
|
+
elif line.strip():
|
|
110
|
+
lines.append(line.strip())
|
|
111
|
+
joined = " ".join(lines)
|
|
112
|
+
res.changes.append(("clean", "list items with a pause", s, joined))
|
|
113
|
+
s = joined
|
|
114
|
+
s = _sub(res, "clean", "list marker", r"(?m)^\s*(?:[-*•–]|\d{1,2}[.)])\s+", "", s)
|
|
115
|
+
s = _sub(res, "clean", "emoji", EMOJI, "", s)
|
|
116
|
+
s = _sub(res, "clean", "quotes", r"[«»“”„\"]", "", s)
|
|
117
|
+
s = _sub(res, "clean", "number sign after raqam", r"(?i)(raqam\w*)\s*[#№]\s?(?=\d)", r"\1 ", s)
|
|
118
|
+
s = _sub(res, "clean", "number sign", r"[#№]\s?(?=\d+[-\s]*raqam)", "", s)
|
|
119
|
+
s = _sub(res, "clean", "number sign", r"(?i)(?<![A-Za-z'])(?!(?:siz|biz|men|sen|u|ular|bu|shu|o'sha)\s)([A-Za-z']+)\s*[#№]\s?(?=\d)",
|
|
120
|
+
r"\1 raqami ", s)
|
|
121
|
+
s = _sub(res, "clean", "number sign", r"[#№]\s?(?=\d)", "raqam ", s)
|
|
122
|
+
def phone(m, out: str) -> str:
|
|
123
|
+
return (" " if m.start() and not m.string[m.start() - 1].isspace() else "") + out
|
|
124
|
+
|
|
125
|
+
def cc_phone(m):
|
|
126
|
+
d = re.sub(r"\D", "", m.group(2))
|
|
127
|
+
return phone(m, ("+" if m.group(1) else "") + f"998 {d[:2]} {d[2:5]} {d[5:7]} {d[7:]}")
|
|
128
|
+
|
|
129
|
+
def local_phone(m):
|
|
130
|
+
op = m.group(2) or m.group(3)
|
|
131
|
+
if op not in UZBEK_OPERATOR_CODES or re.match(r"\s*(?:so'm|sum|dollar)", m.string[m.end():], re.I):
|
|
132
|
+
return m.group(0)
|
|
133
|
+
return phone(m, ("8, " if m.group(1) else "") + " ".join((op, *m.group(4, 5, 6))))
|
|
134
|
+
s = _sub(res, "clean", "phone number", PHONE_CC, cc_phone, s)
|
|
135
|
+
s = _sub(res, "clean", "phone number", PHONE_LOCAL, local_phone, s)
|
|
136
|
+
s = _sub(res, "clean", "square metres", AREA, " kvadrat metr", s, re.I)
|
|
137
|
+
for pattern, repl in UNIT_SLASH:
|
|
138
|
+
s = _sub(res, "clean", "unit with slash", pattern, repl, s)
|
|
139
|
+
s = _sub(res, "clean", "abbreviation", r"(?<![A-Za-z'])(" + "|".join(map(re.escape, ABBREV)) + r")(?![A-Za-z'])",
|
|
140
|
+
lambda m: ABBREV[m.group(1)], s)
|
|
141
|
+
s = _sub(res, "clean", "dash between words", r"(?<=[A-Za-z'])[–—](?=[A-Za-z])", "-", s)
|
|
142
|
+
s = _sub(res, "clean", "quoted word", r"(?<![A-Za-z])'([^'\n]{1,60}?)'(?![A-Za-z])", r"\1", s)
|
|
143
|
+
s = _sub(res, "clean", "parentheses", r"\s*\(([^()]{1,120})\)\s*", r", \1, ", s)
|
|
144
|
+
s = _sub(res, "clean", "ampersand", r"\s&\s", " va ", s)
|
|
145
|
+
s = _sub(res, "clean", "dash", r"\s+[—–-]\s+", ", ", s)
|
|
146
|
+
s = _sub(res, "clean", "ellipsis", r"\.{3,}", "…", s)
|
|
147
|
+
s = _sub(res, "clean", "repeated punctuation", r"([!?.,])\1+", r"\1", s)
|
|
148
|
+
s = _sub(res, "clean", "e-mail", r"\b([A-Za-z0-9._-]+)@([A-Za-z0-9-]+)\.([a-z]{2,4})\b",
|
|
149
|
+
lambda m: f"{m.group(1).replace('.', ' nuqta ')} kuchukcha {m.group(2)} nuqta {m.group(3)}", s)
|
|
150
|
+
s = _sub(res, "clean", "web address", r"\b(?:https?://)?(?:www\.)?([A-Za-z0-9-]+)\.(uz|com|ru|org|net|io|ai|me)\b(/\S*)?",
|
|
151
|
+
lambda m: f"{m.group(1)} nuqta {m.group(2)}", s)
|
|
152
|
+
s = _sub(res, "clean", "word/word", r"(?<=[A-Za-z'])/(?=[A-Za-z])", " yoki ", s)
|
|
153
|
+
s = _sub(res, "clean", "colon", r":\s+", ", ", s)
|
|
154
|
+
s = _sub(res, "clean", "question particle", r"(?<=[a-z]),\s*mi\b", "mi", s)
|
|
155
|
+
s = _sub(res, "clean", "suffix written apart", r"(?<=[A-Za-z'])\s+gacha\b", "gacha", s)
|
|
156
|
+
return " ".join(s.split())
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def tags(text: str, res: Result) -> str:
|
|
160
|
+
def alt_tag(m):
|
|
161
|
+
name = m.group(1).strip().lower()
|
|
162
|
+
return f"[{ALT_TAGS[name]}]" if name in ALT_TAGS else ""
|
|
163
|
+
s = _sub(res, "tags", "alt tag", r"<([a-z][a-z ]{1,20})>", alt_tag, text)
|
|
164
|
+
s = _sub(res, "tags", "bracket tag", r"\[([a-z ]{1,20})\]",
|
|
165
|
+
lambda m: m.group(0) if m.group(1) in TAGS_OK else f"[{ALT_TAGS[m.group(1)]}]" if m.group(1) in ALT_TAGS else "", s)
|
|
166
|
+
s = _sub(res, "tags", "repeated tag", r"(\[(?:pause|laugh|breath)\])(?:\s*\[(?:pause|laugh|breath)\])+", r"\1", s)
|
|
167
|
+
s = _sub(res, "tags", "tag at the end", r"\s*\[(?:pause|breath)\]\s*([.!?…]?)\s*$", r"\1", s)
|
|
168
|
+
return " ".join(s.split())
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def script(text: str, res: Result) -> str:
|
|
172
|
+
def tr(m):
|
|
173
|
+
word, out = m.group(0), []
|
|
174
|
+
for i, c in enumerate(word):
|
|
175
|
+
low, prev, nxt = c.lower(), word[i - 1].lower() if i else "", word[i + 1].lower() if i + 1 < len(word) else ""
|
|
176
|
+
if low == "е" and (not prev or prev in CYR_VOWELS or prev in "ъь"):
|
|
177
|
+
t = "ye"
|
|
178
|
+
elif low == "ъ" and nxt in "еёюя" and prev and prev not in CYR_VOWELS:
|
|
179
|
+
t = ""
|
|
180
|
+
else:
|
|
181
|
+
t = CYR.get(low, c)
|
|
182
|
+
out.append(t.capitalize() if c.isupper() else t)
|
|
183
|
+
return "".join(out)
|
|
184
|
+
s = _sub(res, "script", "cyrillic", r"[Ѐ-ӿ]+", tr, text)
|
|
185
|
+
if s != text:
|
|
186
|
+
res.warnings.append("кириллица переведена в латиницу")
|
|
187
|
+
return s
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def terms(text: str, res: Result) -> str:
|
|
191
|
+
s = _sub(res, "terms", "braces", r"\{([^{}]{1,40})\}",
|
|
192
|
+
lambda m: _FOLDED.get(m.group(1).lower(), m.group(1)), text)
|
|
193
|
+
s = _sub(res, "terms", "lexicon", _TERM_RE, lambda m: LEXICON.get(m.group(1), _FOLDED.get(m.group(1).lower())), s)
|
|
194
|
+
s = _sub(res, "terms", "lexicon (any case)", _TERM_RE_I, lambda m: _FOLDED[m.group(1).lower()], s)
|
|
195
|
+
s = _sub(res, "terms", "respelt stem", r"(?i)\b(" + "|".join(RESPELL) + r")(?=[a-z]*\b)",
|
|
196
|
+
lambda m: RESPELL[m.group(1).lower()].capitalize() if m.group(1)[0].isupper() else RESPELL[m.group(1).lower()], s)
|
|
197
|
+
|
|
198
|
+
def spell(m):
|
|
199
|
+
word = m.group(0)
|
|
200
|
+
res.warnings.append(f"неизвестное сокращение {word} прочитано по буквам")
|
|
201
|
+
return "-".join(LETTERS_EN[c] for c in word)
|
|
202
|
+
s = _sub(res, "terms", "unknown acronym spelt", r"(?<![A-Za-z'])[A-Z]{2,6}(?![A-Za-z'])", spell, s)
|
|
203
|
+
for word in re.findall(r"[A-Za-z']+", re.sub(r"\[\w+\]", " ", s)):
|
|
204
|
+
if re.search(r"w|c(?!h)|th", word.lower()) and word.lower() not in ("ch",):
|
|
205
|
+
res.warnings.append(f"слово {word} похоже на иностранное и может прочитаться неверно")
|
|
206
|
+
return s
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _phone_key(k: int) -> str:
|
|
210
|
+
return "zqphone" + "".join(chr(97 + int(c)) for c in str(k)) + "qz"
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def phone_group(d: str) -> str:
|
|
214
|
+
from gapiring.frontend.text_to_phoneme.tools.convert_phone_numbers_to_text import _convert_chunk_to_text
|
|
215
|
+
return "nol " + phone_group(d[1:]) if len(d) > 1 and d[0] == "0" else _convert_chunk_to_text(d)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def numbers(text: str, res: Result) -> str:
|
|
219
|
+
from gapiring.frontend.text_to_phoneme.tools.convert_phone_numbers_to_text import UZBEK_COUNTRY_CODE, UZBEK_PLUS
|
|
220
|
+
from gapiring.frontend.textnorm import verbalize
|
|
221
|
+
|
|
222
|
+
from gapiring.frontend.textnorm import attach, say_number
|
|
223
|
+
|
|
224
|
+
def dims(m):
|
|
225
|
+
a, b = int(m.group(1)), int(m.group(2))
|
|
226
|
+
unit = {"m": " metr", "sm": " santimetr", "santimetr": " santimetr", "mm": " millimetr", "km": " kilometr"}.get(m.group(3) or "", "")
|
|
227
|
+
out = f"{attach(say_number(a), 'ga')} {say_number(b)}{unit}"
|
|
228
|
+
res.changes.append(("numbers", "dimensions AxB", m.group(0), out))
|
|
229
|
+
return out
|
|
230
|
+
text = re.sub(r"\b(\d{1,4})\s?[x×]\s?(\d{1,4})(?:\s?(m|sm|santimetr|mm|km)\b)?", dims, text)
|
|
231
|
+
|
|
232
|
+
def pair(d: str) -> str:
|
|
233
|
+
return say_number(int(d)) if d[0] != "0" else "nol " + ("nol" if d[1] == "0" else say_number(int(d[1])))
|
|
234
|
+
|
|
235
|
+
def card(m):
|
|
236
|
+
out = ", ".join(pair(g[:2]) + " " + pair(g[2:]) for g in m.groups())
|
|
237
|
+
res.changes.append(("numbers", "card number by groups", m.group(0), out))
|
|
238
|
+
return out
|
|
239
|
+
text = re.sub(r"\b(\d{4})[ -](\d{4})[ -](\d{4})[ -](\d{4})\b", card, text)
|
|
240
|
+
out = []
|
|
241
|
+
for sentence in re.split(r"(?<=[.!?…])\s+", text):
|
|
242
|
+
if not re.search(r"\d|%|\$|\+\d", sentence):
|
|
243
|
+
out.append(_bir_yuz(sentence))
|
|
244
|
+
continue
|
|
245
|
+
parts = re.split(r"(\[(?:pause|laugh|breath)\])", sentence)
|
|
246
|
+
def say(p: str) -> str:
|
|
247
|
+
phones = []
|
|
248
|
+
|
|
249
|
+
def hide(m):
|
|
250
|
+
cc = [f"{UZBEK_PLUS} {UZBEK_COUNTRY_CODE}" if m.group(1)[0] == "+" else UZBEK_COUNTRY_CODE] if m.group(1) else []
|
|
251
|
+
said = ", ".join(cc + [phone_group(g) for g in m.group(2, 3, 4, 5)])
|
|
252
|
+
suffix = m.group(6) or ""
|
|
253
|
+
phones.append((m.group(0), attach(said, suffix[1:]) if suffix[:1] == " " else said + suffix))
|
|
254
|
+
return _phone_key(len(phones) - 1)
|
|
255
|
+
out = verbalize(re.sub(PHONE_SPACED, hide, p.strip()))
|
|
256
|
+
out = out[:1].lower() + out[1:] if p.strip()[:1].islower() else out
|
|
257
|
+
for k, (written, said) in enumerate(phones):
|
|
258
|
+
out, n = re.subn(_phone_key(k), lambda m: said[:1].upper() + said[1:] if m.group(0)[0] == "Z" else said, out, flags=re.I)
|
|
259
|
+
if n != 1:
|
|
260
|
+
raise ValueError(f"phone placeholder lost in normalization: {out!r}")
|
|
261
|
+
res.changes.append(("numbers", "phone number by groups", written, said))
|
|
262
|
+
return out
|
|
263
|
+
try:
|
|
264
|
+
spoken = "".join(p if re.fullmatch(r"\[\w+\]", p) or not p.strip() else (" " + say(p) + " ") for p in parts)
|
|
265
|
+
spoken = " ".join(spoken.split())
|
|
266
|
+
for old, new in (("sentyabr", "sentabr"), ("oktyabr", "oktabr")):
|
|
267
|
+
spoken = spoken.replace(old, new)
|
|
268
|
+
spoken = _bir_yuz(spoken)
|
|
269
|
+
if spoken != sentence:
|
|
270
|
+
res.changes.append(("numbers", "verbalise", sentence, spoken))
|
|
271
|
+
out.append(spoken)
|
|
272
|
+
except ValueError as error:
|
|
273
|
+
res.warnings.append(f"числа не прочитаны: {error}")
|
|
274
|
+
out.append(sentence)
|
|
275
|
+
return " ".join(out)
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _bir_yuz(text: str) -> str:
|
|
279
|
+
words = text.split(" ")
|
|
280
|
+
for i, w in enumerate(words[:-1]):
|
|
281
|
+
prev = words[i - 1].lower() if i and words[i - 1][-1:].isalpha() else ""
|
|
282
|
+
nxt = re.sub(r"[^\w']", "", words[i + 1]).lower()
|
|
283
|
+
if w.lower() == "yuz" and prev not in NUMBER_WORDS and any(nxt.startswith(x) for x in NUMBER_WORDS[1:18]):
|
|
284
|
+
words[i] = ("Bir" if w[0] == "Y" else "bir") + " yuz"
|
|
285
|
+
return " ".join(words)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def dialect(text: str, res: Result, register: str) -> str:
|
|
289
|
+
if register != "conversational":
|
|
290
|
+
return text
|
|
291
|
+
parts = re.split(r"(\[(?:pause|laugh|breath)\])", text)
|
|
292
|
+
out = []
|
|
293
|
+
for p in parts:
|
|
294
|
+
if re.fullmatch(r"\[\w+\]", p) or not p.strip():
|
|
295
|
+
out.append(p)
|
|
296
|
+
continue
|
|
297
|
+
converted, changes = tashkent_dialect.convert(p, russian=False)
|
|
298
|
+
for a, b, rules in changes:
|
|
299
|
+
res.changes.append(("dialect", ", ".join(rules), a, b))
|
|
300
|
+
out.append(converted)
|
|
301
|
+
return " ".join(" ".join(out).split())
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def final(text: str, res: Result) -> str:
|
|
305
|
+
s = re.sub(r"\s+([.,!?;:…])", r"\1", text)
|
|
306
|
+
s = re.sub(r"([.,!?;:…])(?=[A-Za-z])", r"\1 ", s)
|
|
307
|
+
s = re.sub(r"\(\s*", "(", s)
|
|
308
|
+
s = s.strip(" ,;:")
|
|
309
|
+
s = re.sub(r"([.!?…]\s+(?:\[\w+\]\s+)?)([a-z])", lambda m: m.group(1) + m.group(2).upper(), s)
|
|
310
|
+
s = re.sub(r",\s*,", ",", s)
|
|
311
|
+
if s and s[0].islower():
|
|
312
|
+
s = s[0].upper() + s[1:]
|
|
313
|
+
if s and s[-1] not in ".!?…":
|
|
314
|
+
s += "."
|
|
315
|
+
bad = sorted({c for c in s if not ALLOWED_FINAL.match(c)})
|
|
316
|
+
if re.search(r"\d", s):
|
|
317
|
+
res.warnings.append("в тексте остались цифры")
|
|
318
|
+
if bad:
|
|
319
|
+
res.warnings.append("символы вне узбекской латиницы: " + " ".join(bad))
|
|
320
|
+
return s
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def normalize(text: str, register: str = "conversational") -> Result:
|
|
324
|
+
res = Result(text=text)
|
|
325
|
+
s = text
|
|
326
|
+
for name, fn in (("clean", clean), ("tags", tags), ("script", script), ("terms", terms), ("numbers", numbers)):
|
|
327
|
+
s = fn(s, res)
|
|
328
|
+
res.stages.append((name, s))
|
|
329
|
+
s = dialect(s, res, register)
|
|
330
|
+
res.stages.append(("dialect", s))
|
|
331
|
+
s = final(s, res)
|
|
332
|
+
res.stages.append(("final", s))
|
|
333
|
+
res.text = s
|
|
334
|
+
return res
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
if __name__ == "__main__":
|
|
338
|
+
for line in sys.argv[1:]:
|
|
339
|
+
r = normalize(line)
|
|
340
|
+
print(r.text)
|
|
341
|
+
for stage, rule, a, b in r.changes:
|
|
342
|
+
print(f" [{stage}] {rule}: {a!r} -> {b!r}")
|
|
343
|
+
for w in r.warnings:
|
|
344
|
+
print(" ! " + w)
|