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
gapiring/__init__.py ADDED
@@ -0,0 +1,100 @@
1
+ """Gapiring: Uzbek text-to-speech on a CPU. Two voices, roles and manners by name, streaming audio.
2
+
3
+ from gapiring import Gapiring
4
+ tts = Gapiring("edge") # or "large"; fetched once, then cached
5
+ tts.save("hello.wav", "Assalomu alaykum! Sizga qanday yordam bera olaman?", voice="f1", role="assistant", manner="warm")
6
+ for chunk in tts.stream("Buyurtmangiz yo'lda.", voice="m1", role="operator", manner="calm"):
7
+ play(chunk) # float32, 24 kHz, as it is made
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import wave
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+
18
+ from .engine import MANNERS, ROLE_MANNERS, PocketONNX
19
+
20
+ __version__ = "0.1.0"
21
+ __all__ = ["Gapiring", "MODELS", "VOICES", "ROLES", "manners", "SAMPLE_RATE"]
22
+
23
+ REPO = os.environ.get("GAPIRING_REPO", "islomov/gapi-uz-gapiring-v1")
24
+ MODELS = ("edge", "large")
25
+ VOICES = ("f1", "m1")
26
+ ROLES = tuple(ROLE_MANNERS)
27
+ SAMPLE_RATE = 24000
28
+ _GRAPHS = ("text_conditioner", "flow_lm_main", "flow_lm_flow", "mimi_decoder")
29
+
30
+
31
+ def manners(role: str) -> tuple[str, ...]:
32
+ """The manners a role speaks in: manners("emotional") -> ("angry", "upset", ...)."""
33
+ return ROLE_MANNERS[role]
34
+
35
+
36
+ def fetch(model: str = "edge", precision: str | None = None, dictionary: bool = False, revision: str | None = None,
37
+ token: str | None = None) -> Path:
38
+ """Download (once; cached by huggingface_hub) the files of a model and return the folder that holds them."""
39
+ from huggingface_hub import snapshot_download
40
+
41
+ if model not in MODELS:
42
+ raise ValueError(f"model {model!r}: choose from {MODELS}")
43
+ suffix = _suffix(model, precision)
44
+ patterns = [f"{model}/{g}{suffix}.onnx" for g in _GRAPHS] + [f"{model}/bundle.json", f"{model}/tokenizer.json", f"{model}/voices/*.npy"]
45
+ if dictionary:
46
+ patterns.append("lexicon/en_uz.tsv")
47
+ return Path(snapshot_download(REPO, allow_patterns=patterns, revision=revision, token=token))
48
+
49
+
50
+ def _suffix(model: str, precision: str | None) -> str:
51
+ precision = precision or ("int8" if model == "edge" else "full")
52
+ if precision not in ("int8", "full") or (model == "edge" and precision == "full"):
53
+ raise ValueError(f"precision {precision!r} for {model}: edge has int8; large has int8 and full")
54
+ return "_int8" if precision == "int8" else ""
55
+
56
+
57
+ class Gapiring:
58
+ """One loaded model.
59
+
60
+ model "edge" (6 layers, 117 MB, CPU and phone class) or "large" (24 layers)
61
+ precision "int8" or "full"; default int8 for edge, full for large
62
+ threads CPU threads for the model
63
+ dictionary True reads English words, brands and acronyms the Uzbek way (Payme -> Peymi); adds ~4 s and ~400 MB
64
+ normalize "literary" or "conversational": numbers, dates, money, phone numbers and terms become words;
65
+ None gives the text to the model as written
66
+ path a local folder with the repository's layout (edge/, large/, lexicon/) instead of downloading
67
+ """
68
+
69
+ def __init__(self, model: str = "edge", *, precision: str | None = None, threads: int = 2, dictionary: bool = False,
70
+ normalize: str | None = None, path: str | Path | None = None, revision: str | None = None, token: str | None = None):
71
+ suffix = _suffix(model, precision)
72
+ root = Path(path) if path else fetch(model, precision, dictionary, revision, token)
73
+ self.model, self.sample_rate = model, SAMPLE_RATE
74
+ self._tts = PocketONNX(root / model, threads=threads, suffix=suffix, lexicon=root / "lexicon/en_uz.tsv" if dictionary else None,
75
+ normalize=normalize)
76
+
77
+ def stream(self, text: str, voice: str = "f1", role: str = "assistant", manner: str = "neutral", seed: int = 0):
78
+ """Yield float32 chunks (24 kHz mono) of one sentence or short paragraph as they are made."""
79
+ if voice not in VOICES:
80
+ raise ValueError(f"voice {voice!r}: choose from {VOICES}")
81
+ return self._tts.speak(text, voice=voice, role=role, manner=manner, seed=seed)
82
+
83
+ def speak(self, text: str, voice: str = "f1", role: str = "assistant", manner: str = "neutral", seed: int = 0) -> np.ndarray:
84
+ """The whole line as one float32 array (24 kHz mono)."""
85
+ return np.concatenate(list(self.stream(text, voice, role, manner, seed)))
86
+
87
+ def save(self, path: str | Path, text: str, voice: str = "f1", role: str = "assistant", manner: str = "neutral", seed: int = 0) -> float:
88
+ """Write the line as a 16-bit WAV; returns its length in seconds."""
89
+ audio = self.speak(text, voice, role, manner, seed)
90
+ with wave.open(str(path), "wb") as f:
91
+ f.setnchannels(1)
92
+ f.setsampwidth(2)
93
+ f.setframerate(SAMPLE_RATE)
94
+ f.writeframes((np.clip(audio, -1, 1) * 32767).astype("<i2").tobytes())
95
+ return len(audio) / SAMPLE_RATE
96
+
97
+ def said(self, text: str) -> str:
98
+ """The text as the voice gets it, after the dictionary and the normaliser."""
99
+ t = self._tts
100
+ return t._prepare(text, t.lexicon, t.normalize) if t.normalize else (t.lexicon.apply(text) if t.lexicon else text)
gapiring/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
gapiring/cli.py ADDED
@@ -0,0 +1,41 @@
1
+ """gapiring say "Assalomu alaykum!" --out hello.wav [--model edge] [--voice f1] [--role assistant] [--manner warm]"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import time
7
+
8
+ from . import MODELS, ROLES, VOICES, Gapiring, __version__, manners
9
+
10
+
11
+ def main() -> None:
12
+ ap = argparse.ArgumentParser(prog="gapiring", description="Uzbek text-to-speech on a CPU.")
13
+ ap.add_argument("--version", action="version", version=__version__)
14
+ sub = ap.add_subparsers(dest="cmd", required=True)
15
+ say = sub.add_parser("say", help="voice a line into a WAV file")
16
+ say.add_argument("text")
17
+ say.add_argument("--out", required=True)
18
+ say.add_argument("--model", default="edge", choices=MODELS)
19
+ say.add_argument("--precision", choices=("int8", "full"))
20
+ say.add_argument("--voice", default="f1", choices=VOICES)
21
+ say.add_argument("--role", default="assistant", choices=ROLES)
22
+ say.add_argument("--manner", default="neutral")
23
+ say.add_argument("--dictionary", action="store_true", help="English words and brands read the Uzbek way")
24
+ say.add_argument("--normalize", choices=("literary", "conversational"), help="numbers, dates, money and terms to words")
25
+ say.add_argument("--threads", type=int, default=2)
26
+ say.add_argument("--seed", type=int, default=0)
27
+ say.add_argument("--path", help="a local folder with the models instead of downloading")
28
+ sub.add_parser("manners", help="list the roles and their manners")
29
+ a = ap.parse_args()
30
+ if a.cmd == "manners":
31
+ for role in ROLES:
32
+ print(f"{role}: {', '.join(manners(role))}")
33
+ return
34
+ tts = Gapiring(a.model, precision=a.precision, threads=a.threads, dictionary=a.dictionary, normalize=a.normalize, path=a.path)
35
+ started = time.perf_counter()
36
+ seconds = tts.save(a.out, a.text, a.voice, a.role, a.manner, a.seed)
37
+ print(f"{a.out}: {seconds:.2f} s of speech in {time.perf_counter() - started:.2f} s")
38
+
39
+
40
+ if __name__ == "__main__":
41
+ main()
gapiring/engine.py ADDED
@@ -0,0 +1,199 @@
1
+ #!/usr/bin/env python3
2
+ """Gapiring v1 runtime: Uzbek TTS with role and manner tags from an ONNX bundle, numpy + onnxruntime + tokenizers, no PyTorch.
3
+
4
+ The loop: voice conditioning and the text prompt fill flow_lm_main's caches, then
5
+ one latent per step (NaN = BOS first): flow_lm_main -> conditioning + EOS logit; latent = noise + flow_lm_flow(c,
6
+ s=0, t=1, noise) (LSD, one step; noise ~ N(0, temperature)); EOS after >= 6 frames ends the line 1-3 frames
7
+ later; mimi_decoder turns latents into 24 kHz audio as they come (first frame alone, for first audio).
8
+ Text goes through pocket_text (role + style symbols glued before it, event tags as symbols).
9
+
10
+ python pocket_onnx.py --bundle DIR --voice f1 --role assistant --manner warm [--lexicon en_uz.tsv] [--normalize literary]
11
+ --text "..." --out x.wav
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import re
19
+ import time
20
+ from pathlib import Path
21
+
22
+ import numpy as np
23
+ import onnxruntime as ort
24
+
25
+ EVENTS = {"[laugh]": "§", "[pause]": "¦", "[breath]": "¶", "[sigh]": "¤"}
26
+ # roles and manners by name (owner 2026-11-23: the symbols stay in the code): operator, assistant, and emotional mode
27
+ ROLES = {"operator": "\u2460", "assistant": "\u2462", "emotional": "\u2461"} # emotional: a caller with a feeling (owner 2026-11-23)
28
+ MANNERS = {"calm": "\u2464", "neutral": "\u2472", "warm": "\u2473", "cheerful": "\u2474", "empathetic": "\u2475",
29
+ "dictation": "\u2476", "persuasive": "\u2477", "brisk": "\u2478", "soothing": "\u2479", "angry": "\u246c", "upset": "\u246e", "irritated": "\u246b", "worried": "\u246d", "tired": "\u2470", "sceptical": "\u246f", "confused": "\u2469", "hurried": "\u246a", "joking": "\u2466", "grateful": "\u2467", "curious": "\u2468", "friendly": "\u2465", "elderly": "\u2471"}
30
+ ROLE_MANNERS = {"operator": ("neutral", "warm", "cheerful", "empathetic", "calm", "dictation", "persuasive", "brisk"),
31
+ "assistant": ("neutral", "warm", "cheerful", "empathetic", "calm", "dictation", "soothing"),
32
+ "emotional": ("angry", "upset", "irritated", "worried", "tired", "sceptical", "confused", "hurried", "joking", "grateful", "curious", "friendly", "calm", "elderly")}
33
+
34
+
35
+ def tags_for(role: str, manner: str) -> str:
36
+ """The two symbols the model reads before the text, from a role and a manner name."""
37
+ if role not in ROLE_MANNERS or manner not in ROLE_MANNERS[role]:
38
+ raise ValueError(f"role/manner {role}/{manner}: choose from {ROLE_MANNERS}")
39
+ return ROLES[role] + MANNERS[manner]
40
+ _EVENT = re.compile(r"\s*(\[(?:laugh|pause|breath|sigh)\])\s*")
41
+ _MAP = str.maketrans({"…": "...", "«": "", "»": "", '"': "", "“": "", "”": "", "„": "", "(": "", ")": "", ":": ",", ";": ","})
42
+ _DASH = re.compile(r"\s+[—–-]\s+|[—–]")
43
+
44
+
45
+ def pocket_text(text: str, tags: str = "") -> str:
46
+ """The text front: punctuation normalised, event tags as symbols, the role and manner symbols in front."""
47
+ text = _DASH.sub(", ", text.translate(_MAP))
48
+ text = re.sub(r"\s+([,.!?])", r"\1", re.sub(r",(\s*,)+", ",", text))
49
+ text = _EVENT.sub(lambda m: EVENTS[m.group(1)], " ".join(text.split()))
50
+ return tags + text.strip()
51
+
52
+
53
+ class PocketONNX:
54
+ def __init__(self, bundle: str | Path, threads: int = 2, suffix: str = "", lexicon: str | Path | None = None,
55
+ normalize: str | None = None):
56
+ from tokenizers import Tokenizer
57
+
58
+ # normalize="literary" | "conversational": the text front (text_front.py) reads numbers, dates, money, phone
59
+ # numbers and terms out and cleans the text; None feeds the text as written (after the dictionary, if any)
60
+ self.normalize = normalize
61
+ if normalize:
62
+ from gapiring import text_front
63
+
64
+ self._prepare = text_front.prepare
65
+
66
+ self.lexicon = None
67
+ if lexicon: # English words, brands and acronyms read the Uzbek way before the text front (lexicon.py)
68
+ from gapiring.lexicon import Lexicon
69
+
70
+ self.lexicon = Lexicon.load(lexicon)
71
+
72
+ self.dir = Path(bundle)
73
+ self.meta = json.loads((self.dir / "bundle.json").read_text())
74
+ opt = ort.SessionOptions()
75
+ opt.intra_op_num_threads, opt.inter_op_num_threads = threads, 1
76
+ opt.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
77
+
78
+ def session(name): # the asked suffix, else fp32, else int8 (the v2 release ships int8 only)
79
+ path = next((p for s in (suffix, "", "_int8") if (p := self.dir / f"{name}{s}.onnx").exists()), None)
80
+ if path is None:
81
+ raise FileNotFoundError(f"{name}*.onnx not in {self.dir}")
82
+ return ort.InferenceSession(str(path), opt, providers=["CPUExecutionProvider"])
83
+
84
+ self.text_cond, self.main, self.flow, self.dec = (session(n) for n in ("text_conditioner", "flow_lm_main", "flow_lm_flow", "mimi_decoder"))
85
+ self.tok = Tokenizer.from_file(str(self.dir / "tokenizer.json"))
86
+ self.ldim, self.dim = self.meta["latent_dim"], self.meta["conditioning_dim"]
87
+ self.voices: dict[str, list[np.ndarray]] = {}
88
+
89
+ @staticmethod
90
+ def _init(manifest: list[dict]) -> list[np.ndarray]:
91
+ out = []
92
+ for m in manifest:
93
+ dtype = {"float32": np.float32, "int64": np.int64, "bool": np.bool_}[m["dtype"]]
94
+ out.append(np.ones(m["shape"], dtype) if m["fill"] == "ones" else np.zeros(m["shape"], dtype))
95
+ return out
96
+
97
+ def _main(self, sequence: np.ndarray, text_emb: np.ndarray, states: list[np.ndarray]):
98
+ feed = {"sequence": sequence, "text_embeddings": text_emb}
99
+ feed.update({m["input_name"]: s for m, s in zip(self.meta["flow_lm_state_manifest"], states)})
100
+ cond, eos, *new = self.main.run(None, feed)
101
+ return cond, float(eos.reshape(-1)[0]), new
102
+
103
+ def voice_state(self, voice: str) -> list[np.ndarray]:
104
+ """The voice's conditioning (precomputed from its fixed clip, voices/<voice>.npy) run through the backbone once."""
105
+ if voice not in self.voices:
106
+ emb = np.load(self.dir / "voices" / f"{voice}.npy").astype(np.float32)
107
+ _, _, st = self._main(np.zeros((1, 0, self.ldim), np.float32), emb, self._init(self.meta["flow_lm_state_manifest"]))
108
+ self.voices[voice] = st
109
+ return self.voices[voice]
110
+
111
+ def tokens(self, text: str, tags: str) -> list[int]:
112
+ if self.normalize:
113
+ text = self._prepare(text, self.lexicon, self.normalize)
114
+ elif self.lexicon:
115
+ text = self.lexicon.apply(text)
116
+ t = pocket_text(text, tags)
117
+ if t[-1] not in ".!?…":
118
+ t += "."
119
+ return self.tok.encode(t).ids
120
+
121
+ def speak(self, text: str, voice: str = "f1", role: str = "assistant", manner: str = "neutral", **kw):
122
+ """stream() with the role and the manner by name: yields 24 kHz float32 chunks."""
123
+ return self.stream(text, tags_for(role, manner), voice, **kw)
124
+
125
+ def stream(self, text: str, tags: str, voice: str, seed: int = 0, temperature: float | None = None, chunk_frames: int = 3):
126
+ """Yield float32 audio chunks (24 kHz) of one line: the first after one latent, then every chunk_frames."""
127
+ m = self.meta
128
+ rng = np.random.default_rng(seed)
129
+ std = float(np.sqrt(m["temperature"] if temperature is None else temperature))
130
+ ids = self.tokens(text, tags)
131
+ emb = self.text_cond.run(None, {"token_ids": np.array([ids], np.int64)})[0]
132
+ _, _, st = self._main(np.zeros((1, 0, self.ldim), np.float32), emb, self.voice_state(voice))
133
+ max_gen = int((len(ids) / m["tokens_per_second_estimate"] + m["gen_seconds_padding"]) * m["frame_rate"])
134
+ after = (3 if len(text.split()) <= 4 else 1) + 2
135
+ dstate = self._init(m["mimi_state_manifest"])
136
+ seq = np.full((1, 1, self.ldim), np.nan, np.float32)
137
+ empty = np.zeros((1, 0, self.dim), np.float32)
138
+ s0, s1 = np.zeros((1, 1), np.float32), np.ones((1, 1), np.float32)
139
+ pending, eos_step, first = [], None, True
140
+
141
+ def decode(latents):
142
+ nonlocal dstate
143
+ feed = {"latent": np.concatenate(latents, axis=1)}
144
+ feed.update({x["input_name"]: s for x, s in zip(m["mimi_state_manifest"], dstate)})
145
+ audio, *dstate = self.dec.run(None, feed)
146
+ return audio.reshape(-1)
147
+
148
+ for step in range(max_gen):
149
+ cond, eos, st = self._main(seq, empty, st)
150
+ if eos > m["eos_threshold"] and eos_step is None and step >= m["min_frames_before_eos"]:
151
+ eos_step = step
152
+ if eos_step is not None and step >= eos_step + after:
153
+ break
154
+ noise = (rng.standard_normal((1, self.ldim)) * std).astype(np.float32)
155
+ latent = noise + self.flow.run(None, {"c": cond, "s": s0, "t": s1, "x": noise})[0]
156
+ seq = latent[:, None, :]
157
+ pending.append(seq)
158
+ if first or len(pending) >= chunk_frames:
159
+ audio = decode(pending)
160
+ pending = []
161
+ if first:
162
+ n = min(m["fade_in_samples"], len(audio))
163
+ audio[:n] *= np.linspace(0, 1, m["fade_in_samples"], dtype=np.float32)[:n]
164
+ first = False
165
+ yield audio
166
+ if pending:
167
+ yield decode(pending)
168
+
169
+
170
+ def main() -> None:
171
+ import soundfile as sf
172
+
173
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
174
+ parser.add_argument("--bundle", required=True)
175
+ parser.add_argument("--text", required=True)
176
+ parser.add_argument("--voice", default="f1")
177
+ parser.add_argument("--role", default="assistant", choices=sorted(ROLE_MANNERS))
178
+ parser.add_argument("--manner", default="neutral", choices=sorted(MANNERS))
179
+ parser.add_argument("--lexicon", help="readings TSV (lexicon/en_uz.tsv): English words and brands the Uzbek way")
180
+ parser.add_argument("--normalize", choices=("literary", "conversational"), help="numbers, dates, money, terms to words (text_front.py)")
181
+ parser.add_argument("--out", required=True)
182
+ parser.add_argument("--threads", type=int, default=2)
183
+ parser.add_argument("--suffix", default="", help="e.g. _int8 for the quantized graphs")
184
+ parser.add_argument("--seed", type=int, default=0)
185
+ args = parser.parse_args()
186
+ tts = PocketONNX(args.bundle, args.threads, args.suffix, args.lexicon, args.normalize)
187
+ tts.voice_state(args.voice)
188
+ started, first, chunks = time.perf_counter(), None, []
189
+ for chunk in tts.speak(args.text, args.voice, args.role, args.manner, seed=args.seed):
190
+ first = first or time.perf_counter() - started
191
+ chunks.append(chunk)
192
+ total = time.perf_counter() - started
193
+ audio = np.concatenate(chunks)
194
+ sf.write(args.out, audio, tts.meta["sample_rate"])
195
+ print(json.dumps({"first_audio_ms": round(1000 * first, 1), "seconds": round(len(audio) / tts.meta["sample_rate"], 2), "rtf": round(total / (len(audio) / tts.meta["sample_rate"]), 3)}))
196
+
197
+
198
+ if __name__ == "__main__":
199
+ main()
File without changes
@@ -0,0 +1,16 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ HERE = Path(__file__).resolve().parent
7
+ OUT = HERE
8
+ TTS_UZ = HERE
9
+
10
+
11
+ def read_jsonl(path):
12
+ return [json.loads(line) for line in Path(path).read_text(encoding="utf-8").splitlines() if line.strip()]
13
+
14
+
15
+ def write_jsonl(path, rows):
16
+ Path(path).write_text("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rows), encoding="utf-8")
@@ -0,0 +1,6 @@
1
+ # term<TAB>reading; these win over every other term table, in any case.
2
+ Router Router
3
+ Ok okey
4
+ OK okey
5
+ ok okey
6
+ ponyal ponyl
@@ -0,0 +1,222 @@
1
+
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ import sys
6
+
7
+ VOWELS = set("aeiouAEIOU")
8
+ WORD = re.compile(r"[A-Za-zʻʼ'’]+(?:-[A-Za-z]+)?")
9
+ PROGRESSIVE_END = {"man": "vomman", "san": "vossan", "ti": "votti", "miz": "vommiz", "siz": "vossiz",
10
+ "sizlar": "vossizlar", "tilar": "vottila"}
11
+ L_DROP_STEMS = {"kel", "qil", "bo'l", "ol"}
12
+ WORDS = {"hozir": "hozi", "menga": "manga", "senga": "sanga", "qanday": "qanaqa",
13
+ "shunday": "shunaqa", "bunday": "bunaqa", "unday": "unaqa",
14
+ "men": "man", "meni": "mani", "mening": "mani", "mendan": "mandan", "menda": "manda",
15
+ "menimcha": "manimcha", "sen": "san", "seni": "sani", "sening": "sani", "sendan": "sandan",
16
+ "kerak": "kere", "kelgan": "kegan", "ular": "ula", "qayerda": "qayoda",
17
+ "allo": "alyo", "bizning": "bizi", "qo'ng'iroq": "qo'ng'iro", "aytavering": "etuvring",
18
+ "kechirasiz": "kechiras"}
19
+ PHRASES = [(r"\bshuning uchun\b", "shunga"), (r"\bnima uchun\b", "nimaga"), (r"\bqanday yordam\b", "qando yordam")]
20
+ SHORT_STEMS = {"kel", "qil", "bo'l", "ol", "bor", "yoz", "kut", "ber", "tur", "ket", "ko'r", "top", "ayt", "et", "bil",
21
+ "qayt", "yur", "kir", "chiq", "tush", "o'tir", "yet", "ich", "sot", "ayt", "tekshir", "eshit", "kuz"}
22
+ AS_STEMS = ("qil", "bil", "kel", "ol", "ber", "kut", "tur", "ko'r", "yoz", "top", "ket", "bor", "et")
23
+ NUMBER_WORDS = ("nol bir ikki uch to'rt to'r besh olti yetti sakkiz to'qqiz o'n yigirma o'ttiz qirq ellik oltmish yetmish "
24
+ "sakson to'qson yuz ming million milliard").split()
25
+ TENS = ("yigirma", "o'ttiz", "qirq", "ellik", "oltmish", "yetmish", "sakson", "to'qson")
26
+ RUSSIAN_PHRASES = [(r"\bmuddatli to'lov", "rassrochka"), (r"\byetkazib berish", "dostavka")]
27
+ RUSSIAN_STEMS = {"chegirma": "skidka", "manzil": "adres", "havola": "ssilka", "ariza": "zayavka", "to'lov": "oplata"}
28
+ KEEP_UZBEK = [(r"to'lov", r"havola|bo'lim"), ]
29
+ KEEP_BEFORE = {"kerak": "edi"}
30
+ CONVERB_NEXT = ("kel", "bor", "ket", "ko'r", "chiq")
31
+
32
+
33
+ def ends_vowel(stem: str) -> bool:
34
+ return stem[-1:] in VOWELS
35
+
36
+
37
+ def adapt_suffix(suffix: str, from_vowel: bool, to_vowel: bool) -> str:
38
+ if from_vowel == to_vowel or not suffix:
39
+ return suffix
40
+ if from_vowel and not to_vowel:
41
+ for a, b in (("ngiz", "ingiz"), ("ng", "ing"), ("si", "i"), ("m", "im")):
42
+ if suffix.startswith(a) and not suffix.startswith("ni"):
43
+ return b + suffix[len(a):]
44
+ return suffix
45
+ for a, b in (("ingiz", "ngiz"), ("ing", "ng"), ("im", "m"), ("i", "si")):
46
+ if suffix.startswith(a):
47
+ return b + suffix[len(a):]
48
+ return suffix
49
+
50
+
51
+ def l_drop(stem: str) -> str:
52
+ return stem[:-1] if stem.lower() in L_DROP_STEMS else stem
53
+
54
+
55
+ def convert_word(word: str, russian: bool) -> tuple[str, list[str]]:
56
+ w, rules = word, []
57
+ low = w.lower()
58
+ if low in WORDS:
59
+ return keep_case(word, WORDS[low]), ["words"]
60
+ if low in NUMBER_WORDS:
61
+ return word, []
62
+ if russian:
63
+ for stem, rus in RUSSIAN_STEMS.items():
64
+ if low.startswith(stem):
65
+ suffix = low[len(stem):]
66
+ w = rus + adapt_suffix(suffix, ends_vowel(stem), ends_vowel(rus))
67
+ low, rules = w, rules + ["russian"]
68
+ break
69
+ if low.startswith("ayt") and not low.startswith("ayts"):
70
+ low = "et" + low[3:]
71
+ rules.append("ayt->et")
72
+ m = re.fullmatch(r"(.+?)(?:yap|moqda)(man|san|ti|miz|siz|sizlar|tilar)?(mi)?", low)
73
+ if m and len(m.group(1)) >= 2 and not low.endswith("yapti-yu") and not m.group(1).endswith("ma"):
74
+ stem, end, q = m.group(1), m.group(2) or "ti", m.group(3) or ""
75
+ if end in PROGRESSIVE_END:
76
+ low = l_drop(stem) + PROGRESSIVE_END[end] + q
77
+ rules.append("verb")
78
+ m = re.fullmatch(r"(.+?)yotgan(.*)", low)
79
+ if m and "verb" not in rules and not re.search(r"ma(?:yotgan|yap)", low):
80
+ stem = m.group(1)
81
+ if stem.endswith("a") and stem[:-1] in SHORT_STEMS:
82
+ stem = stem[:-1]
83
+ low = l_drop(stem) + "votgan" + m.group(2)
84
+ rules.append("verb")
85
+ m = re.fullmatch(r"(.+l)ay(di|miz)(mi)?", low)
86
+ if m and "verb" not in rules:
87
+ low = m.group(1) + "i" + m.group(2) + (m.group(3) or "")
88
+ rules.append("verb")
89
+ m = re.fullmatch(r"(" + "|".join(AS_STEMS) + r")asiz", low)
90
+ if m:
91
+ low = m.group(1) + "as"
92
+ rules.append("verb")
93
+ if re.search(r"dingiz(mi|lar)?$", low):
94
+ low = re.sub(r"dingiz((?:mi|lar)?)$", r"diz\1", low)
95
+ rules.append("past2pl")
96
+ m = re.fullmatch(r"(.+?[^aeiou'])ingiz(.*)", low)
97
+ if m and low not in ("ingliz",) and "past2pl" not in rules:
98
+ low = m.group(1) + "iz" + m.group(2)
99
+ rules.append("poss2pl")
100
+ m = re.fullmatch(r"(.{2,}?[^s])angiz(.*)", low)
101
+ if m and "past2pl" not in rules and "poss2pl" not in rules:
102
+ low = m.group(1) + "ez" + m.group(2)
103
+ rules.append("poss2pl")
104
+ m = re.fullmatch(r"(bo'l|qil)(s|m|g)(.*)", low) or re.fullmatch(r"(kel)(g)(.*)", low)
105
+ if m:
106
+ low = m.group(1)[:-1] + m.group(2) + m.group(3)
107
+ rules.append("l-drop")
108
+ if low != word.lower() or rules:
109
+ return keep_case(word, low), rules
110
+ return word, []
111
+
112
+
113
+ def keep_case(src: str, out: str) -> str:
114
+ return out[:1].upper() + out[1:] if src[:1].isupper() else out
115
+
116
+
117
+ def convert(text: str, russian: bool = True) -> tuple[str, list[tuple[str, str, list[str]]]]:
118
+ changes = []
119
+
120
+ def phrase(pattern: str, repl: str, rule: str, s: str) -> str:
121
+ def sub(m):
122
+ out = keep_case(m.group(0), repl)
123
+ changes.append((m.group(0), out, [rule]))
124
+ return out
125
+ return re.sub(pattern, sub, s, flags=re.IGNORECASE)
126
+
127
+ s = text
128
+ for pattern, repl in PHRASES:
129
+ s = phrase(pattern, repl, "words", s)
130
+ if russian:
131
+ for pattern, repl in RUSSIAN_PHRASES:
132
+ s = phrase(pattern, repl, "russian", s)
133
+ def edi(m):
134
+ first, rest = m.group(1), m.group(2)
135
+ out = first + ("y" + rest[1:] if first.lower().endswith("chi") else rest[1:])
136
+ changes.append((m.group(0), out, ["edi"]))
137
+ return out
138
+ s = re.sub(r"(?<![\w'’ʻʼ])([\w'’ʻʼ]*(?:gan|moqchi))\s+(edi\w*)\b", edi, s, flags=re.IGNORECASE)
139
+ def olib(m):
140
+ out = keep_case(m.group(1), "ob" if m.group(2).lower().startswith("bor") else "op") + m.group(2)
141
+ changes.append((m.group(0), out, ["converb"]))
142
+ return out
143
+ s = re.sub(r"\b(olib)\s+((?:" + "|".join(CONVERB_NEXT) + r")\w*)", olib, s, flags=re.IGNORECASE)
144
+ def yubor(m):
145
+ word = m.group(1)
146
+ stem = word[:-2] if word.lower().endswith("ib") else word[:-1]
147
+ out = stem + "vor" + m.group(2)
148
+ changes.append((m.group(0), out, ["converb"]))
149
+ return out
150
+ s = re.sub(r"\b(\w+?i?b)\s+yubor(\w*)", yubor, s, flags=re.IGNORECASE)
151
+ for a, b in (("qilib", "qip"), ("bo'lib", "bo'p"), ("kelib", "kep")):
152
+ s = phrase(r"\b" + a + r"\b", b, "converb", s)
153
+ def olma(m):
154
+ out = m.group(1) + "oma" + m.group(2)
155
+ changes.append((m.group(0), out, ["verb"]))
156
+ return out
157
+ s = re.sub(r"\b(\w+?)a olma(\w*)", olma, s, flags=re.IGNORECASE)
158
+ s = numbers(s, changes)
159
+
160
+ def word_sub(m):
161
+ if russian:
162
+ before, after = m.string[:m.start()], m.string[m.end():]
163
+ for stem, nxt in KEEP_UZBEK:
164
+ if (re.match(stem, m.group(0), re.I) and re.match(r"\s+(?:" + nxt + ")", after, re.I)) or \
165
+ (re.match(nxt, m.group(0), re.I) and re.search(stem + r"\s+$", before, re.I)):
166
+ return m.group(0)
167
+ low = m.group(0).lower()
168
+ if low in KEEP_BEFORE and re.match(r"\s+" + KEEP_BEFORE[low] + r"\b", m.string[m.end():], re.I):
169
+ return m.group(0)
170
+ new, rules = convert_word(m.group(0), russian)
171
+ if rules:
172
+ changes.append((m.group(0), new, rules))
173
+ return new
174
+ s = WORD.sub(word_sub, s)
175
+ return s, changes
176
+
177
+
178
+ def numbers(s: str, changes: list) -> str:
179
+ def run(m):
180
+ words = m.group(0).split()
181
+ follow = re.match(r"\s+([\w']+)", m.string[m.end():])
182
+ follow = follow.group(1) if follow and any(follow.group(1).lower().startswith(w) for w in NUMBER_WORDS) else ""
183
+ out = []
184
+ for i, w in enumerate(words):
185
+ nxt = words[i + 1] if i + 1 < len(words) else follow
186
+ low = w.lower()
187
+ if low == "to'rt":
188
+ w = keep_case(w, "to'ru" if nxt[:1].lower() in "aeiou" and nxt else "to'r")
189
+ elif low == "qirq" and nxt[:1].lower() in "aeiou" and nxt:
190
+ w = keep_case(w, "qir")
191
+ elif low == "yuz" and i and words[i - 1].lower() == "bir" and nxt.lower() in TENS \
192
+ and not any(x.lower() in ("ming", "million", "milliard") for x in words[i + 1:]):
193
+ w = keep_case(w, "yuzu")
194
+ out.append(w)
195
+ new = " ".join(out)
196
+ if new != m.group(0):
197
+ changes.append((m.group(0), new, ["numbers"]))
198
+ return new
199
+ alt = "|".join(re.escape(w) for w in sorted(NUMBER_WORDS, key=len, reverse=True))
200
+ return re.sub(r"(?<![\w'])(?:" + alt + r")(?:\s+(?:" + alt + r"))*(?![\w'])", run, s, flags=re.IGNORECASE)
201
+
202
+
203
+ def russian_only(text: str) -> str:
204
+ s = text
205
+ for pattern, repl in RUSSIAN_PHRASES:
206
+ s = re.sub(pattern, lambda m: keep_case(m.group(0), repl), s, flags=re.IGNORECASE)
207
+
208
+ def sub(m):
209
+ word, low = m.group(0), m.group(0).lower()
210
+ for stem, rus in RUSSIAN_STEMS.items():
211
+ if low.startswith(stem):
212
+ return keep_case(word, rus + adapt_suffix(low[len(stem):], ends_vowel(stem), ends_vowel(rus)))
213
+ return word
214
+ return WORD.sub(sub, s)
215
+
216
+
217
+ if __name__ == "__main__":
218
+ for line in sys.argv[1:] or [sys.stdin.read()]:
219
+ out, changes = convert(line)
220
+ print(out)
221
+ for a, b, r in changes:
222
+ print(f" {a} -> {b} [{', '.join(r)}]")
@@ -0,0 +1,58 @@
1
+
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import os
7
+ import re
8
+
9
+ from gapiring.frontend.common import HERE, OUT, read_jsonl, write_jsonl
10
+
11
+ LEXICON = {
12
+ "SMS": ("es-em-es", "acronym"), "IT": ("ay-ti", "acronym"), "AI": ("ey-ay", "acronym"),
13
+ "SMM": ("es-em-em", "acronym"), "HR": ("eych-ar", "acronym"), "CRM": ("si-ar-em", "acronym"),
14
+ "ID": ("ay-di", "acronym"), "VIP": ("vip", "acronym"), "IELTS": ("ayelts", "acronym"),
15
+ "TOEFL": ("tofl", "acronym"), "PDF": ("pe-de-ef", "acronym"), "QR": ("kyu-ar", "acronym"),
16
+ "Wi-Fi": ("vay-fay", "acronym"), "MRT": ("em-er-te", "acronym_ru"), "UZI": ("uzi", "acronym_ru"),
17
+ "EKG": ("e-ka-ge", "acronym_ru"), "MSKT": ("em-es-ka-te", "acronym_ru"), "NDS": ("en-de-es", "acronym_ru"),
18
+ "YouTube": ("Yutub", "brand"), "iPhone": ("Ayfon", "brand"), "WhatsApp": ("Vatsap", "brand"),
19
+ "Google": ("Gugl", "brand"), "Zoom": ("Zum", "brand"), "Click": ("Klik", "brand"),
20
+ "Payme": ("Peymi", "brand"), "Uzcard": ("Uzkard", "brand"), "BYD": ("bi-vay-di", "brand"),
21
+ "Chevrolet": ("Shevrole", "brand"), "Excel": ("Eksel", "brand"), "Gmail": ("Jimeyl", "brand"),
22
+ }
23
+ SEND_WRITTEN = {"MSKT"}
24
+ _TERM_RE = re.compile(r"(?<![\w'-])(" + "|".join(sorted(map(re.escape, LEXICON), key=len, reverse=True))
25
+ + r")(?![\w'-])")
26
+
27
+
28
+ def find_terms(text: str) -> list[str]:
29
+ return _TERM_RE.findall(text)
30
+
31
+
32
+ def swap_out(text: str) -> tuple[str, list[str]]:
33
+ found = []
34
+
35
+ def sub(m):
36
+ found.append(m[1])
37
+ return f"zqterm{'abcdefghij'[len(found) - 1]}qz"
38
+ return _TERM_RE.sub(sub, text), found
39
+
40
+
41
+ def swap_in(text: str, found: list[str], form: str) -> str:
42
+ for k, term in enumerate(found):
43
+ written = form == "written" or (form == "tts" and term in SEND_WRITTEN)
44
+ value = term if written else LEXICON[term][0]
45
+ text = re.sub(f"zqterm{'abcdefghij'[k]}qz", value, text, flags=re.IGNORECASE)
46
+ return text
47
+
48
+
49
+ def canonical(normalized: str) -> str:
50
+ for written, (spoken, _) in LEXICON.items():
51
+ token = re.sub(r"\W", "", written.lower())
52
+ forms = {re.sub(r"[-\s]+", " ", written.lower()), re.sub(r"[-\s]+", " ", spoken.lower()),
53
+ re.sub(r"[-\s]+", "", spoken.lower()), token}
54
+ for form in sorted(forms, key=len, reverse=True):
55
+ normalized = re.sub(rf"(?<![\w']){re.escape(form)}(?![\w'])", token, normalized)
56
+ return normalized
57
+
58
+