ovoz 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 (48) hide show
  1. ovoz/__init__.py +26 -0
  2. ovoz/__main__.py +3 -0
  3. ovoz/_gapiring/LICENSE +24 -0
  4. ovoz/_gapiring/NOTICE +5 -0
  5. ovoz/_gapiring/__init__.py +147 -0
  6. ovoz/_gapiring/dictionary.py +192 -0
  7. ovoz/_gapiring/engine.py +306 -0
  8. ovoz/_gapiring/frontend/__init__.py +0 -0
  9. ovoz/_gapiring/frontend/common.py +16 -0
  10. ovoz/_gapiring/frontend/lexicon_extra.tsv +6 -0
  11. ovoz/_gapiring/frontend/tashkent_dialect.py +216 -0
  12. ovoz/_gapiring/frontend/terms.py +58 -0
  13. ovoz/_gapiring/frontend/terms_reviewed.json +4618 -0
  14. ovoz/_gapiring/frontend/terms_uz.py +71 -0
  15. ovoz/_gapiring/frontend/text_to_phoneme/__init__.py +0 -0
  16. ovoz/_gapiring/frontend/text_to_phoneme/phoneme_converter.py +304 -0
  17. ovoz/_gapiring/frontend/text_to_phoneme/pipelene_text_to_phoneme.py +49 -0
  18. ovoz/_gapiring/frontend/text_to_phoneme/text_normalization_for_tts.py +65 -0
  19. ovoz/_gapiring/frontend/text_to_phoneme/tools/__init__.py +0 -0
  20. ovoz/_gapiring/frontend/text_to_phoneme/tools/convert_currency_to_text.py +39 -0
  21. ovoz/_gapiring/frontend/text_to_phoneme/tools/convert_date_time_to_text.py +327 -0
  22. ovoz/_gapiring/frontend/text_to_phoneme/tools/convert_non_roman_numbers_to_text.py +518 -0
  23. ovoz/_gapiring/frontend/text_to_phoneme/tools/convert_phone_numbers_to_text.py +159 -0
  24. ovoz/_gapiring/frontend/text_to_phoneme/tools/convert_roman_numerals_to_text.py +201 -0
  25. ovoz/_gapiring/frontend/text_to_phoneme/tools/convert_symbols_to_uzbek_text.py +160 -0
  26. ovoz/_gapiring/frontend/text_to_phoneme/tools/expand_uzbek_abbreviations.py +182 -0
  27. ovoz/_gapiring/frontend/text_to_phoneme/tools/full_normalize.py +184 -0
  28. ovoz/_gapiring/frontend/text_to_phoneme/tools/pronounce_links_and_emails.py +81 -0
  29. ovoz/_gapiring/frontend/text_to_phoneme/tools/split_text_numbers.py +9 -0
  30. ovoz/_gapiring/frontend/text_to_phoneme/tools/spoken_lexicon.py +40 -0
  31. ovoz/_gapiring/frontend/text_to_phoneme/tools/spoken_prepass.py +116 -0
  32. ovoz/_gapiring/frontend/text_to_phoneme/uzbek_orthography.py +24 -0
  33. ovoz/_gapiring/frontend/textnorm.py +136 -0
  34. ovoz/_gapiring/frontend/tts_frontend.py +336 -0
  35. ovoz/_gapiring/lexicon.py +28 -0
  36. ovoz/_gapiring/nano.py +111 -0
  37. ovoz/_gapiring/text_front.py +129 -0
  38. ovoz/audio.py +79 -0
  39. ovoz/cli.py +99 -0
  40. ovoz/stt.py +196 -0
  41. ovoz/translit.py +150 -0
  42. ovoz/tts.py +109 -0
  43. ovoz-0.1.0.dist-info/METADATA +113 -0
  44. ovoz-0.1.0.dist-info/RECORD +48 -0
  45. ovoz-0.1.0.dist-info/WHEEL +4 -0
  46. ovoz-0.1.0.dist-info/entry_points.txt +2 -0
  47. ovoz-0.1.0.dist-info/licenses/LICENSE +21 -0
  48. ovoz-0.1.0.dist-info/licenses/NOTICE +30 -0
ovoz/__init__.py ADDED
@@ -0,0 +1,26 @@
1
+ """ovoz — offline o'zbekcha nutq: ovoz → matn (STT) va matn → ovoz (TTS). Torch kerak emas.
2
+
3
+ from ovoz import STT, TTS
4
+
5
+ stt = STT() # 744 MB, bir marta yuklanadi, keyin offline
6
+ print(stt.transcribe("ovoz.ogg")) # lotin: oʻ, gʻ
7
+ print(stt.transcribe("ovoz.ogg", script="cyrl")) # kirill
8
+ print(stt.transcribe("ovoz.ogg", script="new")) # yangi alifbo: ö, ğ, ş, ç
9
+
10
+ tts = TTS() # 117 MB, bir marta yuklanadi
11
+ tts.save("javob.ogg", "Besh ming so'm chiqim yozildi.", voice="f1", style="warm")
12
+
13
+ Modellar faqat ishlatilganda yuklanadi: faqat TTS kerak bo'lsa, STT modeli yuklanmaydi.
14
+ """
15
+
16
+ from .audio import decode_audio, encode_audio, save_audio
17
+ from .stt import DEFAULT_REPO, STT, Result, Segment, Word, to_srt
18
+ from .translit import SCRIPTS, to_script
19
+ from .tts import PACES, STYLES, TTS, VOICES
20
+
21
+ __version__ = "0.1.0"
22
+ __all__ = [
23
+ "STT", "TTS", "Segment", "Word", "Result", "to_srt", "DEFAULT_REPO",
24
+ "STYLES", "VOICES", "PACES", "SCRIPTS", "to_script",
25
+ "decode_audio", "encode_audio", "save_audio",
26
+ ]
ovoz/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
ovoz/_gapiring/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ Gapiring is open source: free for any use, commercial use included.
2
+
3
+ 1. Code (the runtimes, the libraries, the text normaliser): MIT License
4
+
5
+ Copyright (c) 2026 Gapi (https://gapi.uz)
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
8
+ documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
9
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
10
+ persons to whom the Software is furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
13
+ Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
16
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
17
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
18
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19
+
20
+ 2. Model files, voices and dictionary: Creative Commons Attribution 4.0 International (CC BY 4.0)
21
+ https://creativecommons.org/licenses/by/4.0/
22
+
23
+ Credit to give when you share them or what you make from them: "Gapiring by Gapi (https://gapi.uz), an adaptation of
24
+ Kyutai Pocket TTS (https://huggingface.co/kyutai/pocket-tts), CC BY 4.0".
ovoz/_gapiring/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ This folder is a vendored copy of the Gapiring 0.2.0 Python package (https://pypi.org/project/gapiring/),
2
+ by Gapi (https://gapi.uz), used under the MIT License (see LICENSE). Changes for the ovoz package:
3
+ - imports changed from `gapiring` to `ovoz._gapiring`;
4
+ - models are downloaded from the mirror `ziyodev/ovoz-tts` (unchanged copies of the Gapi models, CC BY 4.0);
5
+ - the command-line entry points were removed; only int8 models are offered.
@@ -0,0 +1,147 @@
1
+ """Gapiring: Uzbek text-to-speech on a CPU. Two voices, roles and manners by name, a narrator, streaming audio.
2
+
3
+ from ovoz._gapiring import Gapiring
4
+ tts = Gapiring() # Large int8; Gapiring("edge") is the small model, Gapiring("nano") the tiny one
5
+ tts.save("hello.wav", "Assalomu alaykum! Namuna kompaniyasining virtual yordamchisiman, sizga qanday yordam bera olaman?", voice="f1", role="assistant", manner="warm")
6
+ tts.save("chapter.wav", open("chapter.txt").read(), voice="m1", role="narrator", manner="book")
7
+ for chunk in tts.stream("Bugun obunani rasmiylashtirsangiz, birinchi oy uchun to'liq ellik foiz chegirma beriladi, imkoniyatni qo'ldan boy bermang.", voice="m1", role="operator", manner="calm"):
8
+ play(chunk) # float32, 24 kHz, as it is made
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ import warnings
15
+ import wave
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+
20
+ from .engine import PACE_MANNERS, PACES, ROLE_MANNERS, PocketONNX, tags_for
21
+ from .text_front import prepare_readings
22
+
23
+ __version__ = "0.2.0"
24
+ __all__ = ["Gapiring", "MODELS", "VOICES", "ROLES", "PACES", "PACE_MANNERS", "manners", "SAMPLE_RATE"]
25
+
26
+ # ovoz: modellar o'z nusxamizdan yuklanadi (edge/, large/, nano/ papkalari) — asl repo o'chirilsa ham ishlaydi.
27
+ # Asl manba: islomov/gapi-uz-gapiring-v2 va islomov/gapi-uz-gapiring-nano-v1 (Gapi, CC BY 4.0).
28
+ REPO = os.environ.get("OVOZ_TTS_REPO", "ziyodev/ovoz-tts")
29
+ NANO_REPO = REPO
30
+ MODELS = ("edge", "large", "nano")
31
+ NANO_SPEED = {None: 1.0, "slow": 0.85, "fast": 1.2} # Nano has a speed setting: pace maps onto it
32
+ VOICES = ("f1", "m1")
33
+ ROLES = tuple(ROLE_MANNERS)
34
+ SAMPLE_RATE = 24000
35
+ _GRAPHS = ("text_conditioner", "flow_lm_main", "flow_lm_flow", "mimi_decoder")
36
+
37
+
38
+ def manners(role: str) -> tuple[str, ...]:
39
+ """The manners a role speaks in: manners("emotional") -> ("angry", "upset", ...); for the narrator, the genres."""
40
+ return ROLE_MANNERS[role]
41
+
42
+
43
+ def fetch(model: str = "large", precision: str | None = None, dictionary: bool | None = None, revision: str | None = None,
44
+ token: str | None = None) -> Path:
45
+ """Download (once; cached by huggingface_hub) the files of a model and return the folder that holds them.
46
+ dictionary: for nano, False leaves the dictionary of English words out; for the other models it changes nothing."""
47
+ from huggingface_hub import snapshot_download
48
+
49
+ if model not in MODELS:
50
+ raise ValueError(f"model {model!r}: choose from {MODELS}")
51
+ if model == "nano": # one graph and its settings, and the dictionary of English words it reads through
52
+ patterns = ["nano/nano.onnx", "nano/nano.json"] + ([] if dictionary is False else ["nano/lexicon/en_uz.tsv"])
53
+ return Path(snapshot_download(NANO_REPO, allow_patterns=patterns, revision=revision, token=token)) / "nano"
54
+ suffix = _suffix(model, precision)
55
+ patterns = [f"{model}/{g}{suffix}.onnx" for g in _GRAPHS] + [f"{model}/bundle.json", f"{model}/tokenizer.json", f"{model}/voices/*.npy"]
56
+ return Path(snapshot_download(REPO, allow_patterns=patterns, revision=revision, token=token))
57
+
58
+
59
+ def _suffix(model: str, precision: str | None) -> str:
60
+ precision = precision or "int8"
61
+ if precision != "int8": # ovoz nusxasida faqat int8 bor (to'liq aniqlikdagi Large asl repo'da)
62
+ raise ValueError(f"precision {precision!r}: ovoz faqat int8 modellarini qo'llaydi")
63
+ return "_int8" if precision == "int8" else ""
64
+
65
+
66
+ class Gapiring:
67
+ """One loaded model.
68
+
69
+ model "large" (Gapiring Large v2, 24 layers, the default: the cleaner sound), "edge" (Gapiring Edge v2,
70
+ 6 layers, 117 MB, about 2.5 times faster, phone class) or "nano" (Gapiring Nano, 31 MB, one
71
+ voice, no roles or manners, for very small devices)
72
+ precision "int8" (the default: 346 MB for large) or "full" (large only, 1.3 GB)
73
+ threads CPU threads for the model
74
+ dictionary nano only: the dictionary of English words is on unless this is False (it takes about 4 s and
75
+ 400 MB to load); Edge and Large read English words as they are written and ignore it
76
+ normalize "literary" (the default) or "conversational": numbers, dates, money and phone numbers become words,
77
+ English words stay as written; None gives the text to the model as written
78
+ path a local folder with the repository's layout (edge/) instead of downloading
79
+ """
80
+
81
+ def __init__(self, model: str = "large", *, precision: str | None = None, threads: int = 2, dictionary: bool | None = None,
82
+ normalize: str | None = "literary", path: str | Path | None = None, revision: str | None = None, token: str | None = None):
83
+ if model not in MODELS:
84
+ raise ValueError(f"model {model!r}: choose from {MODELS}")
85
+ self.model, self.sample_rate, self._normalize = model, SAMPLE_RATE, normalize
86
+ if model == "nano":
87
+ from .nano import Nano
88
+
89
+ if precision == "full" or precision not in (None, "int8", "full"):
90
+ warnings.warn("precision is ignored: Gapiring Nano is one file", UserWarning, stacklevel=2)
91
+ root = Path(path) if path else fetch(model, None, dictionary, revision, token)
92
+ self._nano = Nano(root, threads)
93
+ self._dictionary = None
94
+ if dictionary is not False:
95
+ from .dictionary import Dictionary
96
+
97
+ self._dictionary = Dictionary.load(root / "lexicon/en_uz.tsv")
98
+ return
99
+ suffix = _suffix(model, precision)
100
+ if dictionary: # an argument of 0.1: mapped to v2 with a warning, never an error
101
+ warnings.warn("dictionary=True is ignored: Gapiring v2 reads English words as they are written", UserWarning, stacklevel=2)
102
+ root = Path(path) if path else fetch(model, precision, revision=revision, token=token)
103
+ self._tts = PocketONNX(root / model, threads=threads, suffix=suffix, normalize=normalize)
104
+
105
+ def stream(self, text: str, voice: str = "f1", role: str = "assistant", manner: str | None = None, seed: int = 0, *,
106
+ pace: str | None = None, serious: bool = False, hesitant: bool = False):
107
+ """Yield float32 chunks (24 kHz mono) as they are made. A text of any length: a longer one is spoken piece by
108
+ piece. manner: neutral when left out; for the narrator the genre (book, article, news, tale), book when left
109
+ out. One optional mark at a time: pace "slow" or "fast"; serious=True for the narrator's article and news;
110
+ hesitant=True for the lively assistant with small hesitations.
111
+ Nano has one voice (f1) and no roles or manners: it takes the text and pace; the rest is ignored with a
112
+ warning. It makes each piece in one pass, so a chunk is a whole sentence or two."""
113
+ if voice not in VOICES:
114
+ raise ValueError(f"voice {voice!r}: choose from {VOICES}")
115
+ if self.model == "nano":
116
+ if pace not in NANO_SPEED:
117
+ raise ValueError(f"pace {pace!r}: choose from {tuple(PACES)}")
118
+ ignored = [name for name, given in (("voice", voice != "f1"), ("role", role != "assistant"), ("manner", manner is not None),
119
+ ("serious", serious), ("hesitant", hesitant)) if given]
120
+ if ignored:
121
+ warnings.warn(f"Gapiring Nano has one voice and no roles or manners: {', '.join(ignored)} ignored", UserWarning, stacklevel=2)
122
+ return self._nano.stream(self.said(text), NANO_SPEED[pace])
123
+ tags_for(role, manner, pace, serious, hesitant) # a wrong name fails here, not at the first chunk
124
+ return self._tts.speak(text, voice=voice, role=role, manner=manner, pace=pace, serious=serious, hesitant=hesitant, seed=seed)
125
+
126
+ def speak(self, text: str, voice: str = "f1", role: str = "assistant", manner: str | None = None, seed: int = 0, **marks) -> np.ndarray:
127
+ """The whole text as one float32 array (24 kHz mono)."""
128
+ chunks = list(self.stream(text, voice, role, manner, seed, **marks))
129
+ return np.concatenate(chunks) if chunks else np.zeros(0, np.float32)
130
+
131
+ def save(self, path: str | Path, text: str, voice: str = "f1", role: str = "assistant", manner: str | None = None, seed: int = 0, **marks) -> float:
132
+ """Write the text as a 16-bit WAV; returns its length in seconds."""
133
+ audio = self.speak(text, voice, role, manner, seed, **marks)
134
+ with wave.open(str(path), "wb") as f:
135
+ f.setnchannels(1)
136
+ f.setsampwidth(2)
137
+ f.setframerate(SAMPLE_RATE)
138
+ f.writeframes((np.clip(audio, -1, 1) * 32767).astype("<i2").tobytes())
139
+ return len(audio) / SAMPLE_RATE
140
+
141
+ def said(self, text: str) -> str:
142
+ """The text as the voice gets it: after the normaliser and, for nano, the dictionary of English words."""
143
+ if self.model != "nano":
144
+ return self._tts.prepared(text)
145
+ if self._normalize:
146
+ return prepare_readings(text, self._dictionary, self._normalize)
147
+ return self._dictionary.apply(text) if self._dictionary else text
@@ -0,0 +1,192 @@
1
+ """The dictionary of English words for Gapiring Nano (Edge and Large v2 read English as it is written and do not use
2
+ it): a word the voice would misread (an English word, a brand, an acronym) is replaced by its reading in Uzbek Latin
3
+ before the model sees the text: box -> boks, CRM -> si-ar-em, Payme -> Peymi, Paymedan ->
4
+ Peymidan. The matching:
5
+
6
+ - `term<TAB>reading[<TAB>...]` rows, `#` comments; the first row of a term wins;
7
+ - the longest term at a position wins; a term is never matched inside a longer word or number, inside a [tag], nor
8
+ right after an @;
9
+ - a term matches only as written if it is all capitals (IT is not "it"), one or two characters long, or shorter than
10
+ six characters with a capital inside (eSIM, iPad); every other term matches in any case;
11
+ - an Uzbek suffix may follow after an apostrophe (Drive'ga; the apostrophe is dropped) or a hyphen (CRM-ga); glued
12
+ (CRMga, Paymedan) only in lower case after a term spelt as the lexicon has it, with a capital or a digit in it;
13
+ - a reading that differs from what is written only by case changes nothing, unless what is written is all capitals.
14
+
15
+ lex = Lexicon.load("lexicon/en_uz.tsv"); lex.apply("To'lovni Paymedan qiling, CRMga o'zi tushadi.")
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from pathlib import Path
21
+
22
+ SUFFIXES = ("lar", "imiz", "ingiz", "miz", "ngiz", "im", "ing", "si", "i", "ning", "ni", "gacha", "kacha", "qacha", "ga", "ka",
23
+ "qa", "dagi", "dan", "da", "niki", "dek", "day", "lik", "li", "siz", "chi", "cha", "mi", "dir")
24
+ MAX_SUFFIXES = 4
25
+ ANY_CASE_CAMEL_LEN = 6
26
+ APOSTROPHES = "'’‘ʻʼ`"
27
+
28
+
29
+ def _fold(c: str) -> str:
30
+ return "'" if c in APOSTROPHES else c.lower()[:1] or c
31
+
32
+
33
+ def _normalise(s: str) -> str:
34
+ return " ".join("".join("'" if c in APOSTROPHES else c for c in w) for w in s.split())
35
+
36
+
37
+ def _suffix_chain(tail: str, left: int) -> bool:
38
+ return not tail or (left > 0 and any(tail.startswith(s) and _suffix_chain(tail[len(s):], left - 1) for s in SUFFIXES))
39
+
40
+
41
+ class Lexicon:
42
+ def __init__(self, rows: list[tuple[str, str]]):
43
+ # folded term -> [(term, reading, exact, glued)] in file order; the longest term length bounds the scan
44
+ self.entries: dict[str, list[tuple[str, str, bool, bool]]] = {}
45
+ seen: set[str] = set()
46
+ self.max_len = 0
47
+ for term, reading in rows:
48
+ term, reading = _normalise(term), _normalise(reading)
49
+ if not term or term.startswith("#") or not reading or term in seen:
50
+ continue
51
+ seen.add(term)
52
+ capital = any(c.isupper() for c in term)
53
+ upper = capital and not any(c.islower() for c in term)
54
+ camel = any(c.isupper() for c in term[1:])
55
+ exact = upper or len(term) <= 2 or (camel and len(term) < ANY_CASE_CAMEL_LEN)
56
+ glued = len(term) >= 2 and (capital or any(c.isnumeric() for c in term))
57
+ key = "".join(_fold(c) for c in term)
58
+ self.entries.setdefault(key, []).append((term, reading, exact, glued))
59
+ self.max_len = max(self.max_len, len(key))
60
+
61
+ @classmethod
62
+ def from_tsv(cls, tsv: str) -> "Lexicon":
63
+ rows = []
64
+ for line in tsv.splitlines():
65
+ f = line.split("\t")
66
+ if len(f) >= 2:
67
+ rows.append((f[0], f[1]))
68
+ return cls(rows)
69
+
70
+ @classmethod
71
+ def load(cls, path: str | Path) -> "Lexicon":
72
+ return cls.from_tsv(Path(path).read_text(encoding="utf-8"))
73
+
74
+ def __len__(self) -> int:
75
+ return sum(len(v) for v in self.entries.values())
76
+
77
+ def apply(self, text: str) -> str:
78
+ """The text with every known term replaced by its reading."""
79
+ return self._replace(text, lambda reading: reading)
80
+
81
+ def hold(self, text: str) -> "Held":
82
+ """As apply(), with a letters-only stand-in (zqentaqz, zqentbqz, ...) where each reading belongs, for a later
83
+ stage that would rewrite the readings (the text normaliser); Held.restore() puts them back."""
84
+ readings: list[tuple[str, str]] = []
85
+
86
+ def put(reading: str) -> str:
87
+ key = "zqent" + "".join(chr(ord("a") + int(d)) for d in str(len(readings))) + "qz"
88
+ readings.append((key, reading))
89
+ return key
90
+
91
+ return Held(self._replace(text, put), readings)
92
+
93
+ def _replace(self, text: str, put) -> str:
94
+ out, i, n = [], 0, len(text)
95
+ while i < n:
96
+ found = self._longest(text, i) if text[i].isalnum() and _starts_word(text, i) else None
97
+ if found is None:
98
+ out.append(text[i])
99
+ i += 1
100
+ continue
101
+ reading, end, suffix, nxt = found
102
+ term = text[i:end]
103
+ same = "".join(map(_fold, term)) == "".join(map(_fold, reading))
104
+ capitals = any(c.isupper() for c in term) and not any(c.islower() for c in term)
105
+ if same and (not capitals or term == reading):
106
+ out.append(text[i:nxt])
107
+ else:
108
+ out.append(put(reading) + text[suffix:nxt])
109
+ i = nxt
110
+ return "".join(out)
111
+
112
+ def _longest(self, s: str, i: int):
113
+ key, j, best, n = [], i, None, len(s)
114
+ while j < n and len(key) < self.max_len:
115
+ if s[j].isspace():
116
+ key.append(" ")
117
+ while j < n and s[j].isspace():
118
+ j += 1
119
+ else:
120
+ key.append(_fold(s[j]))
121
+ j += 1
122
+ entries = self.entries.get("".join(key))
123
+ if not entries:
124
+ continue
125
+ written = _normalise(s[i:j])
126
+ entry = next((e for e in entries if e[0] == written), None) or next((e for e in entries if not e[2]), None)
127
+ if entry is None:
128
+ continue
129
+ ends = _ends_word(s, j, entry[3] and entry[0] == written)
130
+ if ends is not None:
131
+ best = (entry[1], j, ends[0], ends[1])
132
+ return best
133
+
134
+
135
+ class Held:
136
+ def __init__(self, text: str, readings: list[tuple[str, str]]):
137
+ self.text, self.readings = text, readings
138
+
139
+ def restore(self, said: str) -> str | None:
140
+ """`said` (what the later stage made of `text`) with the readings back in; a stand-in that stage capitalised
141
+ brings its reading back capitalised. None if a stand-in did not survive."""
142
+ for key, reading in self.readings:
143
+ start = key.replace("z", "Z", 1)
144
+ if key not in said and start not in said:
145
+ return None
146
+ said = said.replace(start, reading[:1].upper() + reading[1:]).replace(key, reading)
147
+ return said
148
+
149
+
150
+ def _starts_word(s: str, i: int) -> bool:
151
+ if i == 0:
152
+ return True
153
+ prev = s[i - 1]
154
+ if prev.isalpha() or prev in "[@" or (prev.isnumeric() and s[i].isnumeric()):
155
+ return False
156
+ # o'zbek: an apostrophe after a letter is inside a word; after anything else it opens a quote
157
+ return not (prev in APOSTROPHES and i >= 2 and s[i - 2].isalpha())
158
+
159
+
160
+ def _ends_word(s: str, j: int, glued: bool):
161
+ if j >= len(s):
162
+ return (j, j)
163
+ nxt = s[j]
164
+ if nxt.isnumeric():
165
+ return (j, j) if not s[j - 1].isnumeric() else None # Bitrix24 is Bitrix + 24, K50 is not K5
166
+ start = j + 1 if nxt in APOSTROPHES else j
167
+ k = start
168
+ while k < len(s) and (s[k].isalpha() or s[k] in APOSTROPHES):
169
+ k += 1
170
+ if k == start:
171
+ return (j, j) # punctuation, a space, a hyphen or a closing quote
172
+ if start == j and not glued:
173
+ return None
174
+ tail = s[start:k] # suffixes are written in lower case: CRMga, never CRMGA
175
+ return (start, k) if not any(c.isupper() for c in tail) and _suffix_chain(_normalise(tail), MAX_SUFFIXES) else None
176
+
177
+
178
+ if __name__ == "__main__":
179
+ import sys
180
+
181
+ held = sys.argv[1] == "--held"
182
+ args = sys.argv[2:] if held else sys.argv[1:]
183
+ lex = Lexicon.load(args[0])
184
+ for line in (args[1:] or sys.stdin.read().splitlines()):
185
+ if held:
186
+ h = lex.hold(line)
187
+ print(h.text + "\t" + "|".join(f"{k}={r}" for k, r in h.readings))
188
+ else:
189
+ print(lex.apply(line))
190
+
191
+
192
+ Dictionary = Lexicon