gapiring 0.1.0__tar.gz

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 (44) hide show
  1. gapiring-0.1.0/LICENSE +4 -0
  2. gapiring-0.1.0/PKG-INFO +69 -0
  3. gapiring-0.1.0/README.md +50 -0
  4. gapiring-0.1.0/pyproject.toml +22 -0
  5. gapiring-0.1.0/setup.cfg +4 -0
  6. gapiring-0.1.0/src/gapiring/__init__.py +100 -0
  7. gapiring-0.1.0/src/gapiring/__main__.py +3 -0
  8. gapiring-0.1.0/src/gapiring/cli.py +41 -0
  9. gapiring-0.1.0/src/gapiring/engine.py +199 -0
  10. gapiring-0.1.0/src/gapiring/frontend/__init__.py +0 -0
  11. gapiring-0.1.0/src/gapiring/frontend/common.py +16 -0
  12. gapiring-0.1.0/src/gapiring/frontend/lexicon_extra.tsv +6 -0
  13. gapiring-0.1.0/src/gapiring/frontend/tashkent_dialect.py +222 -0
  14. gapiring-0.1.0/src/gapiring/frontend/terms.py +58 -0
  15. gapiring-0.1.0/src/gapiring/frontend/terms_reviewed.json +4618 -0
  16. gapiring-0.1.0/src/gapiring/frontend/terms_uz.py +71 -0
  17. gapiring-0.1.0/src/gapiring/frontend/text_to_phoneme/__init__.py +0 -0
  18. gapiring-0.1.0/src/gapiring/frontend/text_to_phoneme/phoneme_converter.py +329 -0
  19. gapiring-0.1.0/src/gapiring/frontend/text_to_phoneme/pipelene_text_to_phoneme.py +55 -0
  20. gapiring-0.1.0/src/gapiring/frontend/text_to_phoneme/text_normalization_for_tts.py +208 -0
  21. gapiring-0.1.0/src/gapiring/frontend/text_to_phoneme/tools/__init__.py +0 -0
  22. gapiring-0.1.0/src/gapiring/frontend/text_to_phoneme/tools/convert_currency_to_text.py +76 -0
  23. gapiring-0.1.0/src/gapiring/frontend/text_to_phoneme/tools/convert_date_time_to_text.py +371 -0
  24. gapiring-0.1.0/src/gapiring/frontend/text_to_phoneme/tools/convert_non_roman_numbers_to_text.py +609 -0
  25. gapiring-0.1.0/src/gapiring/frontend/text_to_phoneme/tools/convert_phone_numbers_to_text.py +268 -0
  26. gapiring-0.1.0/src/gapiring/frontend/text_to_phoneme/tools/convert_roman_numerals_to_text.py +235 -0
  27. gapiring-0.1.0/src/gapiring/frontend/text_to_phoneme/tools/convert_symbols_to_uzbek_text.py +258 -0
  28. gapiring-0.1.0/src/gapiring/frontend/text_to_phoneme/tools/expand_uzbek_abbreviations.py +293 -0
  29. gapiring-0.1.0/src/gapiring/frontend/text_to_phoneme/tools/full_normalize.py +257 -0
  30. gapiring-0.1.0/src/gapiring/frontend/text_to_phoneme/tools/pronounce_links_and_emails.py +99 -0
  31. gapiring-0.1.0/src/gapiring/frontend/text_to_phoneme/tools/split_text_numbers.py +36 -0
  32. gapiring-0.1.0/src/gapiring/frontend/text_to_phoneme/tools/spoken_lexicon.py +40 -0
  33. gapiring-0.1.0/src/gapiring/frontend/text_to_phoneme/tools/spoken_prepass.py +116 -0
  34. gapiring-0.1.0/src/gapiring/frontend/text_to_phoneme/uzbek_orthography.py +24 -0
  35. gapiring-0.1.0/src/gapiring/frontend/textnorm.py +172 -0
  36. gapiring-0.1.0/src/gapiring/frontend/tts_frontend.py +344 -0
  37. gapiring-0.1.0/src/gapiring/lexicon.py +188 -0
  38. gapiring-0.1.0/src/gapiring/text_front.py +77 -0
  39. gapiring-0.1.0/src/gapiring.egg-info/PKG-INFO +69 -0
  40. gapiring-0.1.0/src/gapiring.egg-info/SOURCES.txt +42 -0
  41. gapiring-0.1.0/src/gapiring.egg-info/dependency_links.txt +1 -0
  42. gapiring-0.1.0/src/gapiring.egg-info/entry_points.txt +2 -0
  43. gapiring-0.1.0/src/gapiring.egg-info/requires.txt +4 -0
  44. gapiring-0.1.0/src/gapiring.egg-info/top_level.txt +1 -0
gapiring-0.1.0/LICENSE ADDED
@@ -0,0 +1,4 @@
1
+ Gapiring: licence terms are not published yet. Until they are, all rights are reserved and this package is
2
+ for evaluation by people the authors gave it to.
3
+
4
+ The models are built on Kyutai Pocket TTS, licensed under CC-BY-4.0.
@@ -0,0 +1,69 @@
1
+ Metadata-Version: 2.4
2
+ Name: gapiring
3
+ Version: 0.1.0
4
+ Summary: Uzbek text-to-speech on a CPU: two voices, roles and manners by name, streaming audio
5
+ License: Gapiring: licence terms are not published yet. Until they are, all rights are reserved and this package is
6
+ for evaluation by people the authors gave it to.
7
+
8
+ The models are built on Kyutai Pocket TTS, licensed under CC-BY-4.0.
9
+
10
+ Keywords: tts,text-to-speech,uzbek,onnx,edge
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: numpy
15
+ Requires-Dist: onnxruntime>=1.23
16
+ Requires-Dist: tokenizers
17
+ Requires-Dist: huggingface_hub
18
+ Dynamic: license-file
19
+
20
+ # Gapiring
21
+
22
+ Uzbek text-to-speech that runs on an ordinary CPU, with no GPU and no server. Two voices (`f1` female, `m1` male), a
23
+ **role** and a **manner** of speech by name, including an emotional mode, and audio that streams as it is made.
24
+
25
+ ```bash
26
+ pip install gapiring
27
+ gapiring say "Assalomu alaykum! Sizga qanday yordam bera olaman?" --voice f1 --role assistant --manner warm --out hello.wav
28
+ ```
29
+
30
+ ```python
31
+ from gapiring import Gapiring
32
+
33
+ tts = Gapiring("edge", dictionary=True, normalize="literary")
34
+ tts.save("order.wav", "Buyurtmangiz 25-noyabr soat 14:30 da yetkaziladi, to'lov Payme orqali.", voice="m1", role="operator", manner="calm")
35
+
36
+ for chunk in tts.stream("Oyimning tug'ilgan kuniga sovg'a buyurtma qilgandim.", voice="f1", role="emotional", manner="upset"):
37
+ play(chunk) # float32, 24 kHz mono, the first chunk after about 20 ms on a desktop CPU
38
+ ```
39
+
40
+ | | `edge` | `large` |
41
+ | --- | --- | --- |
42
+ | Transformer layers | 6 | 24 |
43
+ | Download | 117 MB (int8) | 346 MB (int8) or 1.3 GB (full precision) |
44
+ | Speed, 2 CPU threads | about 10x real time | about 4x real time (int8) |
45
+ | For | CPU, phone class devices | server, desktop |
46
+
47
+ The model files are downloaded from `islomov/gapi-uz-gapiring-v1` on first use and cached. While that repository is private,
48
+ set `HF_TOKEN` to a token with access to it.
49
+
50
+ ## Roles and manners
51
+
52
+ | `role` | `manner` |
53
+ | --- | --- |
54
+ | `operator` | `neutral` `warm` `cheerful` `empathetic` `calm` `dictation` `persuasive` `brisk` |
55
+ | `assistant` | `neutral` `warm` `cheerful` `empathetic` `calm` `dictation` `soothing` |
56
+ | `emotional` | `angry` `upset` `irritated` `worried` `tired` `sceptical` `confused` `hurried` `joking` `grateful` `curious` `friendly` `calm` `elderly` |
57
+
58
+ `gapiring manners` prints the same list. Sounds go inside the text: `[laugh]`, `[sigh]`, `[pause]`, `[breath]`.
59
+ Give the model one sentence or a short paragraph per call.
60
+
61
+ ## Text
62
+
63
+ `normalize="literary"` reads numbers, dates, times, money, percentages, units and phone numbers out as words and
64
+ turns Cyrillic into Uzbek Latin; `"conversational"` also uses the Tashkent spoken forms. `dictionary=True` reads English
65
+ words, brands and acronyms the Uzbek way (Payme -> Peymi, CRM -> si-ar-em, deadline -> dedlayn); it takes about 4 s and
66
+ 400 MB to load, so leave it out on small devices when the text has no English. `tts.said(text)` shows the text as the
67
+ voice gets it.
68
+
69
+ Dependencies: numpy, onnxruntime, tokenizers, huggingface_hub. Built on Kyutai Pocket TTS (CC-BY-4.0).
@@ -0,0 +1,50 @@
1
+ # Gapiring
2
+
3
+ Uzbek text-to-speech that runs on an ordinary CPU, with no GPU and no server. Two voices (`f1` female, `m1` male), a
4
+ **role** and a **manner** of speech by name, including an emotional mode, and audio that streams as it is made.
5
+
6
+ ```bash
7
+ pip install gapiring
8
+ gapiring say "Assalomu alaykum! Sizga qanday yordam bera olaman?" --voice f1 --role assistant --manner warm --out hello.wav
9
+ ```
10
+
11
+ ```python
12
+ from gapiring import Gapiring
13
+
14
+ tts = Gapiring("edge", dictionary=True, normalize="literary")
15
+ tts.save("order.wav", "Buyurtmangiz 25-noyabr soat 14:30 da yetkaziladi, to'lov Payme orqali.", voice="m1", role="operator", manner="calm")
16
+
17
+ for chunk in tts.stream("Oyimning tug'ilgan kuniga sovg'a buyurtma qilgandim.", voice="f1", role="emotional", manner="upset"):
18
+ play(chunk) # float32, 24 kHz mono, the first chunk after about 20 ms on a desktop CPU
19
+ ```
20
+
21
+ | | `edge` | `large` |
22
+ | --- | --- | --- |
23
+ | Transformer layers | 6 | 24 |
24
+ | Download | 117 MB (int8) | 346 MB (int8) or 1.3 GB (full precision) |
25
+ | Speed, 2 CPU threads | about 10x real time | about 4x real time (int8) |
26
+ | For | CPU, phone class devices | server, desktop |
27
+
28
+ The model files are downloaded from `islomov/gapi-uz-gapiring-v1` on first use and cached. While that repository is private,
29
+ set `HF_TOKEN` to a token with access to it.
30
+
31
+ ## Roles and manners
32
+
33
+ | `role` | `manner` |
34
+ | --- | --- |
35
+ | `operator` | `neutral` `warm` `cheerful` `empathetic` `calm` `dictation` `persuasive` `brisk` |
36
+ | `assistant` | `neutral` `warm` `cheerful` `empathetic` `calm` `dictation` `soothing` |
37
+ | `emotional` | `angry` `upset` `irritated` `worried` `tired` `sceptical` `confused` `hurried` `joking` `grateful` `curious` `friendly` `calm` `elderly` |
38
+
39
+ `gapiring manners` prints the same list. Sounds go inside the text: `[laugh]`, `[sigh]`, `[pause]`, `[breath]`.
40
+ Give the model one sentence or a short paragraph per call.
41
+
42
+ ## Text
43
+
44
+ `normalize="literary"` reads numbers, dates, times, money, percentages, units and phone numbers out as words and
45
+ turns Cyrillic into Uzbek Latin; `"conversational"` also uses the Tashkent spoken forms. `dictionary=True` reads English
46
+ words, brands and acronyms the Uzbek way (Payme -> Peymi, CRM -> si-ar-em, deadline -> dedlayn); it takes about 4 s and
47
+ 400 MB to load, so leave it out on small devices when the text has no English. `tts.said(text)` shows the text as the
48
+ voice gets it.
49
+
50
+ Dependencies: numpy, onnxruntime, tokenizers, huggingface_hub. Built on Kyutai Pocket TTS (CC-BY-4.0).
@@ -0,0 +1,22 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "gapiring"
7
+ version = "0.1.0"
8
+ description = "Uzbek text-to-speech on a CPU: two voices, roles and manners by name, streaming audio"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = {file = "LICENSE"}
12
+ keywords = ["tts", "text-to-speech", "uzbek", "onnx", "edge"]
13
+ dependencies = ["numpy", "onnxruntime>=1.23", "tokenizers", "huggingface_hub"]
14
+
15
+ [project.scripts]
16
+ gapiring = "gapiring.cli:main"
17
+
18
+ [tool.setuptools.packages.find]
19
+ where = ["src"]
20
+
21
+ [tool.setuptools.package-data]
22
+ gapiring = ["frontend/*.json", "frontend/*.tsv"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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)
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
@@ -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()
@@ -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