@simplexai/localmodels-linux-arm64 0.1.0-dev.108 → 0.1.0-dev.109

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 (36) hide show
  1. package/NOTICE +13 -6
  2. package/README.md +1 -1
  3. package/bootstrap.identity +1 -1
  4. package/bootstrap.sha256 +35 -34
  5. package/modules/localmodels/__init__.py +1 -1
  6. package/modules/localmodels/catalog.json +465 -57
  7. package/modules/localmodels/catalog_recipes.py +11 -3
  8. package/modules/localmodels/chat_template.py +6 -0
  9. package/modules/localmodels/chat_templates/qwen4-35b-a3b.jinja +223 -0
  10. package/modules/localmodels/debug_stub_server.py +1 -1
  11. package/modules/localmodels/download-mirrors.json +23 -34
  12. package/modules/localmodels/library_direct.py +2 -0
  13. package/modules/localmodels/library_model.py +4 -0
  14. package/modules/localmodels/library_order.py +44 -1
  15. package/modules/localmodels/library_presentation.py +1 -0
  16. package/modules/localmodels/suite.py +4 -0
  17. package/modules/localmodels/tts-moss.txt +78 -53
  18. package/modules/localmodels/tts_catalog.py +2 -2
  19. package/modules/localmodels/tts_cli.py +3 -3
  20. package/modules/localmodels/tts_jobs.py +1 -3
  21. package/modules/localmodels/tts_model.py +3 -3
  22. package/modules/localmodels/tts_moss_presets.json +1 -1
  23. package/modules/localmodels/tts_sidecar.py +7 -3
  24. package/modules/localmodels/tts_state.py +15 -0
  25. package/modules/localmodels/tts_worker_kokoro.py +939 -255
  26. package/modules/localmodels/tts_worker_moss.py +25 -9
  27. package/modules/localmodels/tts_workers.py +14 -18
  28. package/modules/{simplex_localmodels-0.1.0.dev108.dist-info → simplex_localmodels-0.1.0.dev109.dist-info}/METADATA +1 -1
  29. package/modules/{simplex_localmodels-0.1.0.dev108.dist-info → simplex_localmodels-0.1.0.dev109.dist-info}/RECORD +30 -29
  30. package/modules/{simplex_localmodels-0.1.0.dev108.dist-info → simplex_localmodels-0.1.0.dev109.dist-info}/licenses/NOTICE +13 -6
  31. package/package.json +1 -1
  32. package/tool.json +1 -1
  33. /package/modules/{simplex_localmodels-0.1.0.dev108.dist-info → simplex_localmodels-0.1.0.dev109.dist-info}/WHEEL +0 -0
  34. /package/modules/{simplex_localmodels-0.1.0.dev108.dist-info → simplex_localmodels-0.1.0.dev109.dist-info}/entry_points.txt +0 -0
  35. /package/modules/{simplex_localmodels-0.1.0.dev108.dist-info → simplex_localmodels-0.1.0.dev109.dist-info}/licenses/LICENSE +0 -0
  36. /package/modules/{simplex_localmodels-0.1.0.dev108.dist-info → simplex_localmodels-0.1.0.dev109.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -1,17 +1,8 @@
1
- """Isolated CPU child HTTP worker serving Kokoro-82M v1.1-zh via sherpa-onnx.
2
-
3
- Runs inside the shared hash-locked Python venv built from ``localmodels/speech-sv.txt``
4
- (``<base_dir>/frontends/speech-sv/``, ``sherpa-onnx==2.0.3``, Apache-2.0, zero ``numpy``
5
- dependency). ``sherpa_onnx`` is imported dynamically at startup so this module remains
6
- pure stdlib at import time and unit-testable without ``sherpa-onnx`` installed.
7
-
8
- Privacy rule: never log synthesis input text or synthesized audio bytes.
9
- """
1
+ """Isolated 24 kHz Kokoro v1.0 INT8 CPU worker using ONNX Runtime directly."""
10
2
 
11
3
  from __future__ import annotations
12
4
 
13
5
  import argparse
14
- import array
15
6
  import ctypes
16
7
  import importlib
17
8
  import importlib.util
@@ -21,291 +12,984 @@ import re
21
12
  import signal
22
13
  import sys
23
14
  import threading
15
+ import unicodedata
24
16
  import urllib.parse
17
+ from collections.abc import Iterator
25
18
  from http import HTTPStatus
26
19
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
27
20
  from pathlib import Path
28
21
  from typing import Any, Protocol
29
22
 
30
- DEFAULT_MODEL_ID = "kokoro-v1.1-zh"
31
- DEFAULT_VOICE = "zf_001"
23
+ DEFAULT_MODEL_ID = "kokoro-v1.0-int8"
24
+ DEFAULT_VOICE = "zf_xiaoyi"
32
25
  DEFAULT_SAMPLE_RATE = 24000
33
26
  MAX_INPUT_CHARS = 4096
34
27
  MAX_BODY_BYTES = 1 << 20
35
28
  MIN_SPEED = 0.5
36
29
  MAX_SPEED = 2.0
30
+ MAX_CHUNK_TOKENS = 500
31
+ VOICES_SHAPE = (54, 510, 1, 256)
32
+ VOICES_BYTES = 54 * 510 * 256 * 4
33
+ _SILENCE_THRESHOLD = 0.004
34
+ _LEAD_PAD_SECONDS = 0.050
35
+ _TRAIL_PAD_SECONDS = 0.060
36
+ _FADE_SECONDS = 0.005
37
37
 
38
- _ACRONYM_RE = re.compile(r"\b[A-Z]{2,6}\b")
39
-
40
- # Exact 103 speaker names embedded in csukuangfj/kokoro-multi-lang-v1_1 model.onnx metadata.
41
- KOKORO_V11_SPEAKERS: tuple[str, ...] = (
42
- "af_maple",
43
- "af_sol",
44
- "bf_vale",
45
- "zf_001",
46
- "zf_002",
47
- "zf_003",
48
- "zf_004",
49
- "zf_005",
50
- "zf_006",
51
- "zf_007",
52
- "zf_008",
53
- "zf_017",
54
- "zf_018",
55
- "zf_019",
56
- "zf_021",
57
- "zf_022",
58
- "zf_023",
59
- "zf_024",
60
- "zf_026",
61
- "zf_027",
62
- "zf_028",
63
- "zf_032",
64
- "zf_036",
65
- "zf_038",
66
- "zf_039",
67
- "zf_040",
68
- "zf_042",
69
- "zf_043",
70
- "zf_044",
71
- "zf_046",
72
- "zf_047",
73
- "zf_048",
74
- "zf_049",
75
- "zf_051",
76
- "zf_059",
77
- "zf_060",
78
- "zf_067",
79
- "zf_070",
80
- "zf_071",
81
- "zf_072",
82
- "zf_073",
83
- "zf_074",
84
- "zf_075",
85
- "zf_076",
86
- "zf_077",
87
- "zf_078",
88
- "zf_079",
89
- "zf_083",
90
- "zf_084",
91
- "zf_085",
92
- "zf_086",
93
- "zf_087",
94
- "zf_088",
95
- "zf_090",
96
- "zf_092",
97
- "zf_093",
98
- "zf_094",
99
- "zf_099",
100
- "zm_009",
101
- "zm_010",
102
- "zm_011",
103
- "zm_012",
104
- "zm_013",
105
- "zm_014",
106
- "zm_015",
107
- "zm_016",
108
- "zm_020",
109
- "zm_025",
110
- "zm_029",
111
- "zm_030",
112
- "zm_031",
113
- "zm_033",
114
- "zm_034",
115
- "zm_035",
116
- "zm_037",
117
- "zm_041",
118
- "zm_045",
119
- "zm_050",
120
- "zm_052",
121
- "zm_053",
122
- "zm_054",
123
- "zm_055",
124
- "zm_056",
125
- "zm_057",
126
- "zm_058",
127
- "zm_061",
128
- "zm_062",
129
- "zm_063",
130
- "zm_064",
131
- "zm_065",
132
- "zm_066",
133
- "zm_068",
134
- "zm_069",
135
- "zm_080",
136
- "zm_081",
137
- "zm_082",
138
- "zm_089",
139
- "zm_091",
140
- "zm_095",
141
- "zm_096",
142
- "zm_097",
143
- "zm_098",
144
- "zm_100",
145
- )
146
38
 
147
- SPEAKER_NAME_TO_SID: dict[str, int] = {name: idx for idx, name in enumerate(KOKORO_V11_SPEAKERS)}
39
+ class TtsSynthesizer(Protocol):
40
+ sample_rate: int
148
41
 
42
+ def voices(self) -> list[dict[str, str]]: ...
149
43
 
150
- def voice_descriptor(voice_id: str) -> dict[str, str]:
151
- """Return a structured voice descriptor for one Kokoro v1.1-zh speaker ID."""
152
- prefix = voice_id[:2]
153
- if prefix == "af":
154
- lang, gender, label = "en-US", "female", voice_id[3:].title()
155
- elif prefix == "bf":
156
- lang, gender, label = "en-GB", "female", voice_id[3:].title()
157
- elif prefix == "zf":
158
- lang, gender, label = "zh", "female", f"Chinese Female {voice_id[3:]}"
159
- else:
160
- lang, gender, label = "zh", "male", f"Chinese Male {voice_id[3:]}"
161
- return {"id": voice_id, "name": label, "language": lang, "gender": gender}
44
+ def synthesize(self, text: str, voice: str, speed: float) -> tuple[bytes, int, float, str]: ...
45
+
46
+
47
+ # Style-bank indices in csukuangfj/kokoro-int8-multi-lang-v1_0 voices.bin.
48
+ SPEAKERS = {
49
+ "af_heart": 3,
50
+ "af_bella": 2,
51
+ "af_nicole": 6,
52
+ "af_sarah": 9,
53
+ "af_sky": 10,
54
+ "af_kore": 5,
55
+ "am_adam": 11,
56
+ "am_michael": 16,
57
+ "am_eric": 13,
58
+ "am_fenrir": 14,
59
+ "bf_emma": 21,
60
+ "bm_george": 26,
61
+ "am_puck": 18,
62
+ "zf_xiaoyi": 48,
63
+ "zf_xiaoxiao": 47,
64
+ "zf_xiaobei": 45,
65
+ "zm_yunxi": 50,
66
+ "zm_yunyang": 52,
67
+ "zm_yunjian": 49,
68
+ "zm_yunxia": 51,
69
+ }
70
+ LANGUAGES = {"z": "zh", "a": "en-US", "b": "en-GB"}
71
+ HAN = r"[\u3400-\u9fff]"
72
+ _HAN_RE = re.compile(HAN)
73
+ WORDS = re.compile(
74
+ r"\$?\d+(?:\.\d+)*%?|(?:'[A-Za-z]+|[A-Za-z]+(?:'[A-Za-z]+)*)|[\u3400-\u9fff]+|\s+|."
75
+ )
76
+ _CAMEL_RE = re.compile(r"[A-Z]+(?=[A-Z][a-z]|$)|[A-Z]?[a-z]+")
77
+ _NUM_RE = re.compile(r"^(\$?)(\d+(?:\.\d+)*)(%?)$")
78
+ PUNCTUATION = str.maketrans(
79
+ {
80
+ "\u3002": ".",
81
+ "\u3001": ",",
82
+ "\uff0c": ",",
83
+ "\uff01": "!",
84
+ "\uff1f": "?",
85
+ "\uff1b": ";",
86
+ "\uff1a": ":",
87
+ "\u2019": "'",
88
+ "\u2018": "'",
89
+ "\u3007": "\u96f6",
90
+ }
91
+ )
92
+ _LATIN_FOLDS = {
93
+ "\u00df": "ss",
94
+ "\u00e6": "ae",
95
+ "\u00c6": "AE",
96
+ "\u0153": "oe",
97
+ "\u0152": "OE",
98
+ "\u00f8": "o",
99
+ "\u00d8": "O",
100
+ "\u0142": "l",
101
+ "\u0141": "L",
102
+ "\u0111": "d",
103
+ "\u0110": "D",
104
+ "\u00f0": "d",
105
+ "\u00d0": "D",
106
+ }
107
+ ZH_DIGITS = "\u96f6\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d"
108
+ EN_DIGITS = "zero one two three four five six seven eight nine".split()
109
+ _EN_TEENS = (
110
+ "ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen".split()
111
+ )
112
+ _EN_TENS = ("", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety")
113
+ _ZH_UNITS = frozenset(
114
+ "\u5e74\u6708\u65e5\u53f7\u70b9\u5206\u79d2\u5ea6\u4e2a\u5143\u5757\u4e07\u4ebf\u500d\u7c73\u6b21\u5c81"
115
+ )
116
+ _PUNCT_TOKENS = frozenset(
117
+ tok.encode("utf-8")
118
+ for tok in (
119
+ ";",
120
+ ":",
121
+ ",",
122
+ ".",
123
+ "!",
124
+ "?",
125
+ "\u2014",
126
+ "\u2026",
127
+ '"',
128
+ "(",
129
+ ")",
130
+ "\u201c",
131
+ "\u201d",
132
+ " ",
133
+ )
134
+ )
135
+ _STRONG_BREAK = frozenset((b".", b"!", b"?"))
136
+ _WEAK_BREAK = frozenset((b",", b";", b":"))
137
+ _SIBILANTS = frozenset(("s", "z", "\u0283", "\u0292", "\u02a7", "\u02a4"))
138
+ _VOICELESS_S = frozenset(("p", "t", "k", "f", "\u03b8"))
139
+ _VOICELESS_ED = frozenset(("p", "k", "f", "s", "\u0283", "\u02a7", "\u03b8"))
140
+ _VOWEL_FINALS = frozenset(
141
+ (
142
+ "a",
143
+ "e",
144
+ "i",
145
+ "o",
146
+ "u",
147
+ "A",
148
+ "I",
149
+ "O",
150
+ "Q",
151
+ "W",
152
+ "Y",
153
+ "\u0251",
154
+ "\u0252",
155
+ "\u00e6",
156
+ "\u0254",
157
+ "\u0259",
158
+ "\u025a",
159
+ "\u025b",
160
+ "\u025c",
161
+ "\u026a",
162
+ "\u028a",
163
+ "\u028c",
164
+ "\u02d0",
165
+ )
166
+ )
167
+ _ACRONYM_COLLISIONS = frozenset(
168
+ (
169
+ "US",
170
+ "ID",
171
+ "OS",
172
+ "IT",
173
+ "AM",
174
+ "PM",
175
+ "AI",
176
+ "UI",
177
+ "UX",
178
+ "PR",
179
+ "CI",
180
+ "CD",
181
+ "IP",
182
+ "IO",
183
+ "TV",
184
+ "PC",
185
+ "GB",
186
+ "MB",
187
+ "KB",
188
+ "TB",
189
+ "DB",
190
+ "QA",
191
+ "HR",
192
+ "VP",
193
+ )
194
+ )
195
+ _COMPOUND_SHORT_TAILS = frozenset(("up", "in", "on", "me", "to", "by", "go", "id", "ai", "ui"))
196
+ _EXTRA_EN: dict[str, bytes] = {
197
+ "multi": "m \u02c8 \u028c l t i".encode(),
198
+ "onnx": "\u02c8 \u0251 n \u026a k s".encode(),
199
+ "json": "\u02a4 \u02c8 A s \u0259 n".encode(),
200
+ "yaml": "j \u02c8 \u00e6 m \u0259 l".encode(),
201
+ "kubernetes": "k u b \u0259 \u0279 n \u02c8 \u025b t i z".encode(),
202
+ "int": "\u02c8 \u026a n t".encode(),
203
+ "macos": "m \u02c8 \u00e6 k \u02c8 O \u02c8 \u025b s".encode(),
204
+ }
205
+ _SPACE_SEP = b" | "
162
206
 
163
207
 
164
208
  def kokoro_voice_list() -> list[dict[str, str]]:
165
- """Return all 103 Kokoro v1.1-zh voices in speaker-ID order."""
166
- return [voice_descriptor(name) for name in KOKORO_V11_SPEAKERS]
209
+ return [
210
+ {
211
+ "id": name,
212
+ "name": name[3:].title(),
213
+ "language": LANGUAGES[name[0]],
214
+ "gender": "female" if name[1] == "f" else "male",
215
+ }
216
+ for name in SPEAKERS
217
+ ]
167
218
 
168
219
 
169
220
  def resolve_speaker_id(voice: str | None) -> tuple[int, str]:
170
- """Map a voice name or numeric sid string to ``(sid, canonical_voice_id)``."""
171
- raw = (voice or DEFAULT_VOICE).strip()
172
- if not raw:
173
- raw = DEFAULT_VOICE
174
- if raw in SPEAKER_NAME_TO_SID:
175
- return SPEAKER_NAME_TO_SID[raw], raw
176
- if raw.isdigit():
177
- sid = int(raw)
178
- if 0 <= sid < len(KOKORO_V11_SPEAKERS):
179
- return sid, KOKORO_V11_SPEAKERS[sid]
180
- raise ValueError(f"unknown Kokoro voice: {raw!r}")
181
-
182
-
183
- def load_lexicon_words(paths: list[Path]) -> frozenset[str]:
184
- """Read lowercase English headwords from Kokoro lexicon text files."""
185
- words: set[str] = set()
186
- for path in paths:
187
- if not path.is_file():
221
+ name = (voice or "").strip().lower() or DEFAULT_VOICE
222
+ if name.isdecimal():
223
+ name = next((key for key, index in SPEAKERS.items() if str(index) == name), name)
224
+ if name not in SPEAKERS:
225
+ raise ValueError(f"unknown Kokoro voice: {name!r}")
226
+ return SPEAKERS[name], name
227
+
228
+
229
+ def read_lexicon(path: Path) -> dict[str, bytes]:
230
+ words: dict[str, bytes] = {}
231
+ with path.open("rb") as handle:
232
+ for line in handle:
233
+ word, sep, phonemes = line.rstrip().partition(b" ")
234
+ if sep:
235
+ words.setdefault(word.decode(), phonemes)
236
+ return words
237
+
238
+
239
+ def _normalize_text(text: str) -> str:
240
+ folded = unicodedata.normalize("NFKC", text).translate(PUNCTUATION)
241
+ out: list[str] = []
242
+ for ch in folded:
243
+ code = ord(ch)
244
+ if code < 128 or 0x3400 <= code <= 0x9FFF:
245
+ out.append(ch)
246
+ continue
247
+ mapped = _LATIN_FOLDS.get(ch)
248
+ if mapped is not None:
249
+ out.append(mapped)
188
250
  continue
189
- with path.open("r", encoding="utf-8", errors="ignore") as handle:
190
- for line in handle:
191
- token = line.strip().split(" ", 1)[0].lower()
192
- if token:
193
- words.add(token)
194
- return frozenset(words)
195
-
196
-
197
- def normalize_kokoro_text(text: str, known_words: frozenset[str]) -> str:
198
- """Expand uppercase OOV English acronyms (e.g. ``CPU`` -> ``c p u``) for espeak-free Kokoro.
199
-
200
- ``sherpa-onnx >= 2.0.0`` omits ``espeak-ng`` so acronyms absent from ``lexicon-us-en.txt``
201
- would be skipped silently. Single letters ``a``..``z`` exist in the English lexicon, so
202
- spacing out unknown 2..6-letter uppercase tokens makes Kokoro spell them cleanly.
203
- """
204
- if not known_words:
205
- return text
206
-
207
- def _expand(match: re.Match[str]) -> str:
208
- word = match.group(0)
209
- if word.lower() in known_words:
210
- return word
211
- return " ".join(word.lower())
212
-
213
- return _ACRONYM_RE.sub(_expand, text)
214
-
215
-
216
- def samples_to_pcm16_bytes(samples: list[float]) -> bytes:
217
- """Encode float32 [-1.0, 1.0] mono audio samples into raw 16-bit little-endian PCM bytes."""
218
- pcm = array.array(
219
- "h",
220
- (int(max(-1.0, min(1.0, float(sample))) * 32767.0) for sample in samples),
251
+ stripped = "".join(
252
+ part for part in unicodedata.normalize("NFKD", ch) if not unicodedata.combining(part)
253
+ )
254
+ if stripped and stripped.isascii() and any(part.isalpha() for part in stripped):
255
+ out.append(stripped)
256
+ else:
257
+ out.append(ch)
258
+ return "".join(out)
259
+
260
+
261
+ def _lookup_direct(
262
+ word: str, lexicon: dict[str, bytes], secondary: dict[str, bytes] | None
263
+ ) -> bytes | None:
264
+ hit = lexicon.get(word)
265
+ if hit is not None:
266
+ return hit
267
+ return secondary.get(word) if secondary is not None else None
268
+
269
+
270
+ def _s_suffix(base: bytes) -> bytes:
271
+ final = base.split()[-1].decode()
272
+ if final in _SIBILANTS:
273
+ return "\u026a z".encode()
274
+ if final in _VOICELESS_S:
275
+ return b"s"
276
+ return b"z"
277
+
278
+
279
+ def _ed_suffix(base: bytes) -> bytes:
280
+ final = base.split()[-1].decode()
281
+ if final in ("t", "d"):
282
+ return "\u026a d".encode()
283
+ if final in _VOICELESS_ED:
284
+ return b"t"
285
+ return b"d"
286
+
287
+
288
+ def _apostrophe_suffix(
289
+ base: bytes,
290
+ ending: str,
291
+ lexicon: dict[str, bytes],
292
+ secondary: dict[str, bytes] | None,
293
+ ) -> bytes | None:
294
+ if ending == "s":
295
+ return _s_suffix(base)
296
+ if ending == "d":
297
+ final = base.split()[-1].decode()
298
+ return "\u0259 d".encode() if final in ("t", "d") else b"d"
299
+ if ending == "ve":
300
+ final = base.split()[-1].decode()
301
+ return b"v" if final in _VOWEL_FINALS else "\u0259 v".encode()
302
+ if ending == "re":
303
+ return "\u0259 \u0279".encode()
304
+ if ending == "ll":
305
+ return _lookup_direct("'ll", lexicon, secondary) or "\u0259 l".encode()
306
+ if ending == "m":
307
+ return _lookup_direct("'m", lexicon, secondary) or b"m"
308
+ if ending == "t":
309
+ return _lookup_direct("'t", lexicon, secondary) or b"t"
310
+ return _lookup_direct("'" + ending, lexicon, secondary)
311
+
312
+
313
+ def _stem_candidates_ed(word: str) -> tuple[str, ...]:
314
+ cands = [word[:-1], word[:-2]]
315
+ if len(word) > 4 and word[-3] == word[-4]:
316
+ cands.append(word[:-3])
317
+ return tuple(c for c in cands if len(c) >= 2)
318
+
319
+
320
+ def _stem_candidates_ing(word: str) -> tuple[str, ...]:
321
+ cands = [word[:-3], word[:-3] + "e"]
322
+ if len(word) > 5 and word[-4] == word[-5]:
323
+ cands.append(word[:-4])
324
+ return tuple(c for c in cands if len(c) >= 3)
325
+
326
+
327
+ def _inflect_plural(
328
+ word: str, lexicon: dict[str, bytes], secondary: dict[str, bytes] | None
329
+ ) -> bytes | None:
330
+ if len(word) > 4 and word.endswith("ies"):
331
+ base = _lookup_direct(word[:-3] + "y", lexicon, secondary)
332
+ if base is not None:
333
+ return base + b" " + _s_suffix(base)
334
+ if len(word) > 3 and word.endswith("es"):
335
+ for stem in (word[:-1], word[:-2]):
336
+ base = _lookup_direct(stem, lexicon, secondary)
337
+ if base is not None:
338
+ return base + b" " + _s_suffix(base)
339
+ if len(word) > 2 and word.endswith("s") and not word.endswith(("ss", "us", "is")):
340
+ stem = word[:-1]
341
+ base = _lookup_direct(stem, lexicon, secondary) or _compound_pronunciation(
342
+ stem, lexicon, secondary
343
+ )
344
+ if base is not None:
345
+ return base + b" " + _s_suffix(base)
346
+ return None
347
+
348
+
349
+ def _inflect_past_and_prog(
350
+ word: str, lexicon: dict[str, bytes], secondary: dict[str, bytes] | None
351
+ ) -> bytes | None:
352
+ if len(word) > 4 and word.endswith("ied"):
353
+ base = _lookup_direct(word[:-3] + "y", lexicon, secondary)
354
+ if base is not None:
355
+ return base + b" " + _ed_suffix(base)
356
+ if len(word) > 3 and word.endswith("ed"):
357
+ for stem in _stem_candidates_ed(word):
358
+ base = _lookup_direct(stem, lexicon, secondary)
359
+ if base is not None:
360
+ return base + b" " + _ed_suffix(base)
361
+ if len(word) > 5 and word.endswith("ing"):
362
+ for stem in _stem_candidates_ing(word):
363
+ base = _lookup_direct(stem, lexicon, secondary)
364
+ if base is not None:
365
+ return base + " \u026a \u014b".encode()
366
+ return None
367
+
368
+
369
+ def _try_stems(
370
+ stems: tuple[str, ...],
371
+ min_len: int,
372
+ suffix: bytes,
373
+ lexicon: dict[str, bytes],
374
+ secondary: dict[str, bytes] | None,
375
+ ) -> bytes | None:
376
+ for stem in stems:
377
+ if len(stem) >= min_len and (base := _lookup_direct(stem, lexicon, secondary)) is not None:
378
+ return base + suffix
379
+ return None
380
+
381
+
382
+ def _inflect_degree_and_adv(
383
+ word: str, lexicon: dict[str, bytes], secondary: dict[str, bytes] | None
384
+ ) -> bytes | None:
385
+ if len(word) > 5 and word.endswith("ier"):
386
+ return _try_stems((word[:-3] + "y",), 3, " \u0259 \u0279".encode(), lexicon, secondary)
387
+ if len(word) > 4 and word.endswith("er"):
388
+ cands = (
389
+ word[:-2],
390
+ word[:-1],
391
+ *((word[:-3],) if len(word) > 5 and word[-3] == word[-4] else ()),
392
+ )
393
+ return _try_stems(cands, 3, " \u0259 \u0279".encode(), lexicon, secondary)
394
+ if len(word) > 5 and word.endswith("iest"):
395
+ return _try_stems((word[:-4] + "y",), 3, " \u026a s t".encode(), lexicon, secondary)
396
+ if len(word) > 5 and word.endswith("est"):
397
+ cands = (
398
+ word[:-3],
399
+ word[:-2],
400
+ *((word[:-4],) if len(word) > 6 and word[-4] == word[-5] else ()),
401
+ )
402
+ return _try_stems(cands, 3, " \u026a s t".encode(), lexicon, secondary)
403
+ if len(word) > 5 and word.endswith("ily"):
404
+ return _try_stems((word[:-3] + "y",), 3, b" l i", lexicon, secondary)
405
+ if len(word) > 4 and word.endswith("ly"):
406
+ return _try_stems((word[:-2],), 3, b" l i", lexicon, secondary)
407
+ return None
408
+
409
+
410
+ def _inflection_pronunciation(
411
+ word: str, lexicon: dict[str, bytes], secondary: dict[str, bytes] | None
412
+ ) -> bytes | None:
413
+ return (
414
+ _inflect_plural(word, lexicon, secondary)
415
+ or _inflect_past_and_prog(word, lexicon, secondary)
416
+ or _inflect_degree_and_adv(word, lexicon, secondary)
221
417
  )
222
- if sys.byteorder == "big":
223
- pcm.byteswap()
224
- return pcm.tobytes()
225
418
 
226
419
 
227
- def _preload_windows_onnxruntime() -> None:
228
- """Preload sherpa-onnx's bundled onnxruntime.dll by full path on Windows.
420
+ def _compound_pronunciation(
421
+ word: str, lexicon: dict[str, bytes], secondary: dict[str, bytes] | None
422
+ ) -> bytes | None:
423
+ if len(word) < 5 or not word.isalpha():
424
+ return None
425
+ for min_right in (3, 2):
426
+ for cut in range(3, len(word) - min_right + 1):
427
+ left, right = word[:cut], word[cut:]
428
+ if min_right == 2 and len(right) == 2 and right not in _COMPOUND_SHORT_TAILS:
429
+ continue
430
+ lp = _lookup_direct(left, lexicon, secondary)
431
+ if lp is None:
432
+ continue
433
+ rp = _lookup_direct(right, lexicon, secondary) or _inflection_pronunciation(
434
+ right, lexicon, secondary
435
+ )
436
+ if rp is not None:
437
+ return lp + _SPACE_SEP + rp
438
+ return None
229
439
 
230
- Prevents PreferSystem32 process-mitigation environments (e.g. apps launched from
231
- Firefox-family browsers on Windows 11 24H2+) from binding System32's older ORT 1.17.
232
- """
233
- if sys.platform != "win32" or "sherpa_onnx" in sys.modules:
234
- return
235
- spec = importlib.util.find_spec("sherpa_onnx")
236
- if spec is None:
237
- raise RuntimeError("sherpa_onnx is missing from the speech-sv runtime venv")
238
- roots = [Path(loc) for loc in (spec.submodule_search_locations or ())]
239
- if not roots and spec.origin:
240
- roots = [Path(spec.origin).resolve().parent]
241
- for root in roots:
242
- dll_path = root / "lib" / "onnxruntime.dll"
243
- if dll_path.is_file():
244
- ctypes.WinDLL(str(dll_path))
245
- return
246
- raise RuntimeError("bundled onnxruntime.dll not found under sherpa_onnx package directory")
247
440
 
441
+ def _spell_letters(
442
+ word: str, lexicon: dict[str, bytes], secondary: dict[str, bytes] | None
443
+ ) -> bytes | None:
444
+ parts: list[bytes] = []
445
+ for ch in word.lower():
446
+ if ch.isalpha():
447
+ ph = _lookup_direct(ch, lexicon, secondary)
448
+ if ph is None:
449
+ return None
450
+ parts.append(ph)
451
+ return _SPACE_SEP.join(parts) if parts else None
248
452
 
249
- class TtsSynthesizer(Protocol):
250
- sample_rate: int
251
453
 
252
- def voices(self) -> list[dict[str, str]]: ...
454
+ def _camel_pronunciation(
455
+ raw_word: str, lexicon: dict[str, bytes], secondary: dict[str, bytes] | None
456
+ ) -> bytes | None:
457
+ parts = _CAMEL_RE.findall(raw_word)
458
+ if len(parts) < 2 or "".join(parts) != raw_word:
459
+ return None
460
+ resolved: list[bytes] = []
461
+ has_word = False
462
+ for part in parts:
463
+ low = part.lower()
464
+ if (
465
+ part.isupper()
466
+ and len(part) >= 2
467
+ and (part in _ACRONYM_COLLISIONS or _lookup_direct(low, lexicon, secondary) is None)
468
+ ):
469
+ spelled = _spell_letters(part, lexicon, secondary)
470
+ if spelled is None:
471
+ return None
472
+ resolved.append(spelled)
473
+ continue
474
+ ph = _lookup_direct(low, lexicon, secondary) or _inflection_pronunciation(
475
+ low, lexicon, secondary
476
+ )
477
+ if ph is None:
478
+ return None
479
+ resolved.append(ph)
480
+ if len(part) >= 2:
481
+ has_word = True
482
+ return _SPACE_SEP.join(resolved) if has_word else None
253
483
 
254
- def synthesize(self, text: str, voice: str, speed: float) -> tuple[bytes, int, float, str]: ...
484
+
485
+ def english_pronunciation(
486
+ word: str,
487
+ lexicon: dict[str, bytes],
488
+ secondary: dict[str, bytes] | None = None,
489
+ ) -> bytes | None:
490
+ """Resolve an English word via dual-lexicon, contractions, inflections, CamelCase, compounds."""
491
+ if not word:
492
+ return None
493
+ lower = word.lower()
494
+ if word.startswith("'"):
495
+ hit = _lookup_direct(lower, lexicon, secondary)
496
+ if hit is not None:
497
+ return hit
498
+ word = word.lstrip("'")
499
+ lower = word.lower()
500
+ if not word:
501
+ return None
502
+ direct = _lookup_direct(lower, lexicon, secondary)
503
+ if direct is not None:
504
+ return direct
505
+ if "'" in word:
506
+ stem_raw, _, ending_raw = word.rpartition("'")
507
+ if not stem_raw or not ending_raw:
508
+ return None
509
+ base = english_pronunciation(stem_raw, lexicon, secondary)
510
+ if base is None:
511
+ return None
512
+ suffix = _apostrophe_suffix(base, ending_raw.lower(), lexicon, secondary)
513
+ return (base + b" " + suffix) if suffix is not None else None
514
+ return (
515
+ _inflection_pronunciation(lower, lexicon, secondary)
516
+ or _camel_pronunciation(word, lexicon, secondary)
517
+ or _compound_pronunciation(lower, lexicon, secondary)
518
+ )
519
+
520
+
521
+ def _en_int_words(n: int) -> list[str]:
522
+ if n < 10:
523
+ return [EN_DIGITS[n]]
524
+ if n < 20:
525
+ return [_EN_TEENS[n - 10]]
526
+ if n < 100:
527
+ tens, rem = divmod(n, 10)
528
+ return [_EN_TENS[tens]] + ([EN_DIGITS[rem]] if rem else [])
529
+ if n < 1000:
530
+ hundreds, rem = divmod(n, 100)
531
+ return [EN_DIGITS[hundreds], "hundred"] + (_en_int_words(rem) if rem else [])
532
+ thousands, rem = divmod(n, 1000)
533
+ return [*_en_int_words(thousands), "thousand", *(_en_int_words(rem) if rem else [])]
534
+
535
+
536
+ def _zh_int_chars(n: int) -> str:
537
+ if n == 0:
538
+ return ZH_DIGITS[0]
539
+ if n < 10:
540
+ return ZH_DIGITS[n]
541
+ if n < 20:
542
+ return "\u5341" + (ZH_DIGITS[n - 10] if n > 10 else "")
543
+ if n < 100:
544
+ tens, rem = divmod(n, 10)
545
+ return ZH_DIGITS[tens] + "\u5341" + (ZH_DIGITS[rem] if rem else "")
546
+ if n < 1000:
547
+ h, rem = divmod(n, 100)
548
+ if rem == 0:
549
+ return ZH_DIGITS[h] + "\u767e"
550
+ mid = ZH_DIGITS[0] if rem < 10 else ""
551
+ tail = (
552
+ ZH_DIGITS[rem]
553
+ if rem < 10
554
+ else f"{ZH_DIGITS[rem // 10]}\u5341{ZH_DIGITS[rem % 10] if rem % 10 else ''}"
555
+ )
556
+ return ZH_DIGITS[h] + "\u767e" + mid + tail
557
+ th, rem = divmod(n, 1000)
558
+ if rem == 0:
559
+ return ZH_DIGITS[th] + "\u5343"
560
+ mid = ZH_DIGITS[0] if rem < 100 else ""
561
+ return ZH_DIGITS[th] + "\u5343" + mid + _zh_int_chars(rem)
562
+
563
+
564
+ def _is_shouting(tokens: list[str]) -> bool:
565
+ alpha = [tok for tok in tokens if tok.isascii() and any(ch.isalpha() for ch in tok)]
566
+ if len(alpha) < 2:
567
+ return False
568
+ if any(any("a" <= ch <= "z" for ch in tok) for tok in alpha):
569
+ return False
570
+ return any(len(tok.replace("'", "")) >= 3 for tok in alpha)
571
+
572
+
573
+ def _token_lang_kind(tok: str) -> str | None:
574
+ if _HAN_RE.match(tok):
575
+ return "zh"
576
+ if tok.isascii() and any(ch.isalpha() for ch in tok):
577
+ return "en"
578
+ return None
579
+
580
+
581
+ def _local_chinese_digits(tokens: list[str], index: int, voice_is_zh: bool) -> bool:
582
+ if index + 1 < len(tokens) and tokens[index + 1] and tokens[index + 1][0] in _ZH_UNITS:
583
+ return True
584
+ for dist in range(1, len(tokens)):
585
+ right = index + dist
586
+ if right < len(tokens):
587
+ kind = _token_lang_kind(tokens[right])
588
+ if kind is not None:
589
+ return kind == "zh"
590
+ left = index - dist
591
+ if left >= 0:
592
+ kind = _token_lang_kind(tokens[left])
593
+ if kind is not None:
594
+ return kind == "zh"
595
+ return voice_is_zh
596
+
597
+
598
+ def _split_phoneme_stream(raw: bytes) -> list[bytes]:
599
+ out: list[bytes] = []
600
+ for seg_idx, segment in enumerate(raw.split(_SPACE_SEP)):
601
+ if seg_idx > 0:
602
+ out.append(b" ")
603
+ out.extend(segment.split())
604
+ return out
605
+
606
+
607
+ class Pronunciations:
608
+ def __init__(self, model_dir: Path) -> None:
609
+ self.tokens = {
610
+ token: int(index)
611
+ for token, index in (
612
+ line.rsplit(b" ", 1)
613
+ for line in (model_dir / "tokens.txt").read_bytes().splitlines()
614
+ )
615
+ }
616
+ self.zh = read_lexicon(model_dir / "lexicon-zh.txt")
617
+ self.en = {
618
+ accent: read_lexicon(model_dir / f"lexicon-{accent}-en.txt") for accent in ("us", "gb")
619
+ }
620
+ self.max_word = max(map(len, self.zh)) if self.zh else 1
621
+ self._space_id = self.tokens.get(b" ")
622
+ self._non_speakable_ids = frozenset(
623
+ self.tokens[tok] for tok in _PUNCT_TOKENS if tok in self.tokens
624
+ )
625
+ self._strong_break_ids = frozenset(
626
+ self.tokens[tok] for tok in _STRONG_BREAK if tok in self.tokens
627
+ )
628
+ self._weak_break_ids = frozenset(
629
+ self.tokens[tok] for tok in _WEAK_BREAK if tok in self.tokens
630
+ )
631
+
632
+ def _valid_phonemes(self, raw: bytes | None) -> list[bytes] | None:
633
+ if raw is None:
634
+ return None
635
+ stream = _split_phoneme_stream(raw)
636
+ if not stream:
637
+ return None
638
+ filtered = [tok for tok in stream if tok != b" " or self._space_id is not None]
639
+ return filtered if all(tok in self.tokens for tok in filtered) else None
640
+
641
+ def han_words(self, text: str) -> Iterator[bytes]:
642
+ offset = 0
643
+ while offset < len(text):
644
+ for end in range(min(len(text), offset + self.max_word), offset, -1):
645
+ word = self.zh.get(text[offset:end])
646
+ if word is not None:
647
+ yield word
648
+ offset = end
649
+ break
650
+ else:
651
+ # Gracefully skip rare unlisted Hanzi instead of aborting or leaking codepoints.
652
+ offset += 1
653
+
654
+ def _english_phonemes(
655
+ self,
656
+ word: str,
657
+ primary: dict[str, bytes],
658
+ secondary: dict[str, bytes],
659
+ shouting: bool,
660
+ ) -> list[bytes]:
661
+ if not shouting and word.isupper() and word in _ACRONYM_COLLISIONS:
662
+ spelled = self._valid_phonemes(_spell_letters(word, primary, secondary))
663
+ if spelled:
664
+ return spelled
665
+ resolved = self._valid_phonemes(english_pronunciation(word, primary, secondary))
666
+ if resolved:
667
+ return resolved
668
+ extra = self._valid_phonemes(_EXTRA_EN.get(word.lower()))
669
+ if extra:
670
+ return extra
671
+ spelled = self._valid_phonemes(_spell_letters(word, primary, secondary))
672
+ return spelled or []
673
+
674
+ def _en_number_words(self, currency: str, body: str, percent: str) -> list[str]:
675
+ parts = body.split(".")
676
+ words: list[str] = []
677
+ whole = parts[0]
678
+ if len(parts) == 1:
679
+ if whole.startswith("0") and len(whole) > 1 or len(whole) > 6:
680
+ words.extend(EN_DIGITS[int(ch)] for ch in whole)
681
+ else:
682
+ words.extend(_en_int_words(int(whole)))
683
+ elif currency and len(parts) == 2 and len(parts[1]) == 2 and len(whole) <= 6:
684
+ dollars = int(whole)
685
+ cents = int(parts[1])
686
+ words.extend(_en_int_words(dollars))
687
+ words.append("dollar" if dollars == 1 else "dollars")
688
+ if cents:
689
+ words.extend(_en_int_words(cents))
690
+ words.append("cent" if cents == 1 else "cents")
691
+ return words
692
+ else:
693
+ if whole.startswith("0") and len(whole) > 1 or len(whole) > 6:
694
+ words.extend(EN_DIGITS[int(ch)] for ch in whole)
695
+ else:
696
+ words.extend(_en_int_words(int(whole)))
697
+ for frac in parts[1:]:
698
+ words.append("point")
699
+ words.extend(EN_DIGITS[int(ch)] for ch in frac)
700
+ if currency:
701
+ words.append("dollar" if body == "1" else "dollars")
702
+ if percent:
703
+ words.append("percent")
704
+ return words
705
+
706
+ def _number_phonemes(
707
+ self,
708
+ token: str,
709
+ primary: dict[str, bytes],
710
+ secondary: dict[str, bytes],
711
+ chinese_digits: bool,
712
+ followed_by_year: bool,
713
+ ) -> list[bytes]:
714
+ match = _NUM_RE.match(token)
715
+ if not match:
716
+ return []
717
+ currency, body, percent = match.groups()
718
+ if chinese_digits and self.zh:
719
+ return self._zh_number_phonemes(currency, body, percent, followed_by_year)
720
+ words = self._en_number_words(currency, body, percent)
721
+ out: list[bytes] = []
722
+ for idx, word in enumerate(words):
723
+ ph = self._valid_phonemes(_lookup_direct(word, primary, secondary))
724
+ if ph is None:
725
+ # Minimal test lexicons may only map single digits; fall back cleanly.
726
+ fallback: list[bytes] = []
727
+ for ch in body:
728
+ if ch.isdigit():
729
+ dph = self._valid_phonemes(
730
+ _lookup_direct(EN_DIGITS[int(ch)], primary, secondary)
731
+ )
732
+ if dph:
733
+ if fallback and self._space_id is not None:
734
+ fallback.append(b" ")
735
+ fallback.extend(dph)
736
+ return fallback
737
+ if idx > 0 and self._space_id is not None:
738
+ out.append(b" ")
739
+ out.extend(ph)
740
+ return out
741
+
742
+ def _zh_number_phonemes(
743
+ self, currency: str, body: str, percent: str, followed_by_year: bool
744
+ ) -> list[bytes]:
745
+ parts = body.split(".")
746
+ zh_chars: list[str] = []
747
+ if percent:
748
+ zh_chars.append("\u767e\u5206\u4e4b")
749
+ whole = parts[0]
750
+ if followed_by_year or (whole.startswith("0") and len(whole) > 1) or len(whole) > 4:
751
+ zh_chars.append("".join(ZH_DIGITS[int(ch)] for ch in whole))
752
+ else:
753
+ zh_chars.append(_zh_int_chars(int(whole)))
754
+ for frac in parts[1:]:
755
+ zh_chars.append("\u70b9" + "".join(ZH_DIGITS[int(ch)] for ch in frac))
756
+ if currency:
757
+ zh_chars.append("\u7f8e\u5143")
758
+ out: list[bytes] = []
759
+ for value in self.han_words("".join(zh_chars)):
760
+ out.extend(value.split())
761
+ return out
762
+
763
+ def phonemes(
764
+ self,
765
+ word: str,
766
+ english: dict[str, bytes],
767
+ chinese_digits: bool,
768
+ *,
769
+ secondary: dict[str, bytes] | None = None,
770
+ shouting: bool = False,
771
+ followed_by_year: bool = False,
772
+ ) -> Iterator[bytes]:
773
+ sec = secondary if secondary is not None else {}
774
+ if _NUM_RE.match(word):
775
+ yield from self._number_phonemes(word, english, sec, chinese_digits, followed_by_year)
776
+ elif word.isascii() and any(ch.isalpha() for ch in word):
777
+ yield from self._english_phonemes(word, english, sec, shouting)
778
+ elif _HAN_RE.match(word):
779
+ for value in self.han_words(word):
780
+ yield from value.split()
781
+ elif word.isspace():
782
+ if self._space_id is not None:
783
+ yield b" "
784
+ else:
785
+ raw = word.encode("utf-8")
786
+ if raw in _PUNCT_TOKENS and raw in self.tokens:
787
+ yield raw
788
+ elif self._space_id is not None:
789
+ yield b" "
790
+
791
+ def _build_units(self, text: str, voice: str) -> list[list[int]]:
792
+ norm = _normalize_text(text)
793
+ is_gb = voice.startswith("b")
794
+ primary = self.en["gb" if is_gb else "us"]
795
+ secondary = self.en["us" if is_gb else "gb"]
796
+ voice_is_zh = voice.startswith("z")
797
+ raw_tokens = WORDS.findall(norm)
798
+ shouting = _is_shouting(raw_tokens)
799
+ units: list[list[int]] = []
800
+ prev_kind: str | None = None
801
+ for idx, tok in enumerate(raw_tokens):
802
+ is_num = _NUM_RE.match(tok) is not None
803
+ chinese_digits = (
804
+ _local_chinese_digits(raw_tokens, idx, voice_is_zh) if is_num else False
805
+ )
806
+ followed_year = (
807
+ is_num and idx + 1 < len(raw_tokens) and raw_tokens[idx + 1].startswith("\u5e74")
808
+ )
809
+ kind = ("zh" if chinese_digits else "en") if is_num else _token_lang_kind(tok)
810
+ if (
811
+ kind in ("zh", "en")
812
+ and prev_kind in ("zh", "en")
813
+ and kind != prev_kind
814
+ and self._space_id is not None
815
+ ):
816
+ units.append([self._space_id])
817
+ ph_ids = [
818
+ self.tokens[ph]
819
+ for ph in self.phonemes(
820
+ tok,
821
+ primary,
822
+ secondary=secondary,
823
+ chinese_digits=chinese_digits,
824
+ shouting=shouting,
825
+ followed_by_year=followed_year,
826
+ )
827
+ if ph in self.tokens
828
+ ]
829
+ if not ph_ids:
830
+ continue
831
+ if ph_ids == [self._space_id]:
832
+ if not units or units[-1] == [self._space_id]:
833
+ continue
834
+ units.append(ph_ids)
835
+ prev_kind = "space"
836
+ else:
837
+ units.append(ph_ids)
838
+ prev_kind = kind or "punct"
839
+ return units
840
+
841
+ def _trim_chunk(self, ids: list[int]) -> list[int]:
842
+ if self._space_id is None:
843
+ return ids
844
+ start = 0
845
+ end = len(ids)
846
+ while start < end and ids[start] == self._space_id:
847
+ start += 1
848
+ while end > start and ids[end - 1] == self._space_id:
849
+ end -= 1
850
+ return ids[start:end]
851
+
852
+ def _best_split(self, ids: list[int]) -> int | None:
853
+ floor = MAX_CHUNK_TOKENS // 2
854
+ for break_set in (self._strong_break_ids, self._weak_break_ids):
855
+ for pos in range(len(ids) - 1, floor - 1, -1):
856
+ if ids[pos] in break_set:
857
+ return pos + 1
858
+ return None
859
+
860
+ def chunks(self, text: str, voice: str) -> Iterator[list[int]]:
861
+ units = self._build_units(text, voice)
862
+ has_speakable = any(tid not in self._non_speakable_ids for unit in units for tid in unit)
863
+ if not has_speakable:
864
+ raise ValueError("No speakable text provided")
865
+ buf: list[int] = []
866
+ for unit in units:
867
+ if len(unit) > MAX_CHUNK_TOKENS:
868
+ if cleaned := self._trim_chunk(buf):
869
+ yield cleaned
870
+ buf = []
871
+ for pos in range(0, len(unit), MAX_CHUNK_TOKENS):
872
+ if piece := self._trim_chunk(unit[pos : pos + MAX_CHUNK_TOKENS]):
873
+ yield piece
874
+ continue
875
+ if buf and len(buf) + len(unit) > MAX_CHUNK_TOKENS:
876
+ split_at = self._best_split(buf)
877
+ if split_at is not None:
878
+ head = self._trim_chunk(buf[:split_at])
879
+ tail = self._trim_chunk(buf[split_at:])
880
+ if head:
881
+ yield head
882
+ buf = tail
883
+ else:
884
+ if head := self._trim_chunk(buf):
885
+ yield head
886
+ buf = []
887
+ if not buf and unit == [self._space_id]:
888
+ continue
889
+ buf.extend(unit)
890
+ if tail := self._trim_chunk(buf):
891
+ yield tail
892
+
893
+
894
+ def _preload_windows_onnxruntime() -> None:
895
+ """Bind onnxruntime's venv capi DLLs first on Windows (PreferSystem32 protection)."""
896
+ if sys.platform != "win32" or "onnxruntime" in sys.modules:
897
+ return
898
+ ort_spec = importlib.util.find_spec("onnxruntime")
899
+ if ort_spec is None:
900
+ raise RuntimeError("onnxruntime is missing from the Kokoro TTS runtime venv")
901
+ dirs = [Path(loc) for loc in (ort_spec.submodule_search_locations or ())]
902
+ if not dirs and ort_spec.origin:
903
+ dirs = [Path(ort_spec.origin).resolve().parent]
904
+ found_dll = False
905
+ add_dll_dir = getattr(os, "add_dll_directory", None)
906
+ for pkg_dir in dirs:
907
+ capi_dir = pkg_dir / "capi"
908
+ if not capi_dir.is_dir():
909
+ continue
910
+ if callable(add_dll_dir):
911
+ add_dll_dir(str(capi_dir))
912
+ for name in ("onnxruntime.dll", "onnxruntime_providers_shared.dll"):
913
+ candidate = capi_dir / name
914
+ if candidate.is_file():
915
+ ctypes.WinDLL(str(candidate))
916
+ found_dll = True
917
+ if not found_dll:
918
+ raise RuntimeError("bundled onnxruntime DLL not found under onnxruntime/capi")
919
+
920
+
921
+ def trim_kokoro_silence(audio: Any, sample_rate: int, np_mod: Any) -> Any:
922
+ """Trim excessive dead head/tail silence while keeping ~50 ms lead, ~60 ms trail, 5 ms fade."""
923
+ wav = np_mod.asarray(audio, dtype=np_mod.float32).reshape(-1)
924
+ total = int(wav.size)
925
+ if total == 0:
926
+ return wav
927
+ active = np_mod.flatnonzero(np_mod.abs(wav) >= _SILENCE_THRESHOLD)
928
+ if int(active.size) == 0:
929
+ return wav
930
+ lead_pad = int(sample_rate * _LEAD_PAD_SECONDS)
931
+ trail_pad = int(sample_rate * _TRAIL_PAD_SECONDS)
932
+ start = max(0, int(active[0]) - lead_pad)
933
+ end = min(total, int(active[-1]) + 1 + trail_pad)
934
+ trimmed = wav[start:end].copy()
935
+ fade_len = min(int(sample_rate * _FADE_SECONDS), int(trimmed.size) // 4)
936
+ if fade_len > 1:
937
+ ramp = np_mod.linspace(0.0, 1.0, fade_len, dtype=np_mod.float32)
938
+ if start > 0:
939
+ trimmed[:fade_len] *= ramp
940
+ if end < total:
941
+ trimmed[-fade_len:] *= ramp[::-1]
942
+ return trimmed
255
943
 
256
944
 
257
945
  class KokoroSynthesizer:
258
- """Thread-safe sherpa-onnx OfflineTts wrapper for Kokoro-82M v1.1-zh."""
946
+ sample_rate = DEFAULT_SAMPLE_RATE
259
947
 
260
948
  def __init__(self, model_dir: Path, *, threads: int = 2) -> None:
261
949
  _preload_windows_onnxruntime()
262
- sherpa = importlib.import_module("sherpa_onnx")
263
- lexicon_paths = [
264
- model_dir / "lexicon-us-en.txt",
265
- model_dir / "lexicon-gb-en.txt",
266
- model_dir / "lexicon-zh.txt",
267
- ]
268
- fst_paths = [
269
- model_dir / "date-zh.fst",
270
- model_dir / "number-zh.fst",
271
- model_dir / "phone-zh.fst",
272
- ]
273
- kokoro_cfg = sherpa.OfflineTtsKokoroModelConfig(
274
- model=str(model_dir / "model.onnx"),
275
- voices=str(model_dir / "voices.bin"),
276
- tokens=str(model_dir / "tokens.txt"),
277
- lexicon=",".join(str(p) for p in lexicon_paths if p.is_file()),
278
- )
279
- model_cfg = sherpa.OfflineTtsModelConfig(
280
- kokoro=kokoro_cfg,
281
- num_threads=max(1, threads),
282
- provider="cpu",
283
- )
284
- tts_cfg = sherpa.OfflineTtsConfig(
285
- model=model_cfg,
286
- rule_fsts=",".join(str(p) for p in fst_paths if p.is_file()),
950
+ self.np = importlib.import_module("numpy")
951
+ ort = importlib.import_module("onnxruntime")
952
+ self.frontend = Pronunciations(model_dir)
953
+ voices_path = model_dir / "voices.bin"
954
+ if not voices_path.is_file() or voices_path.stat().st_size != VOICES_BYTES:
955
+ raise ValueError(f"invalid Kokoro voices bank: expected {VOICES_BYTES} bytes")
956
+ onnx_path = model_dir / "onnx" / "model_quantized.onnx"
957
+ if not onnx_path.is_file():
958
+ raise FileNotFoundError(f"missing Kokoro ONNX artifact: {onnx_path.name}")
959
+ self.styles = self.np.memmap(voices_path, dtype="<f4", mode="r", shape=VOICES_SHAPE)
960
+ options = ort.SessionOptions()
961
+ options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
962
+ options.intra_op_num_threads = max(1, threads)
963
+ options.inter_op_num_threads = 1
964
+ self.session = ort.InferenceSession(
965
+ str(onnx_path),
966
+ sess_options=options,
967
+ providers=["CPUExecutionProvider"],
287
968
  )
288
- if not tts_cfg.validate():
289
- raise RuntimeError(f"invalid sherpa-onnx Kokoro config under {model_dir}")
290
- self._tts: Any = sherpa.OfflineTts(tts_cfg)
291
- self.sample_rate = int(getattr(self._tts, "sample_rate", DEFAULT_SAMPLE_RATE))
292
- self._known_en_words = load_lexicon_words(lexicon_paths[:2])
293
- self._lock = threading.Lock()
969
+ self.lock = threading.Lock()
294
970
 
295
971
  def voices(self) -> list[dict[str, str]]:
296
972
  return kokoro_voice_list()
297
973
 
298
974
  def synthesize(self, text: str, voice: str, speed: float) -> tuple[bytes, int, float, str]:
299
- sid, canonical_voice = resolve_speaker_id(voice)
300
- normalized = normalize_kokoro_text(text, self._known_en_words)
301
- # Never pass callback= here: sherpa-onnx's Python wrapper imports numpy when callback is set.
302
- with self._lock:
303
- audio = self._tts.generate(normalized, sid=sid, speed=speed)
304
- samples = list(audio.samples)
305
- rate = int(getattr(audio, "sample_rate", self.sample_rate) or self.sample_rate)
306
- pcm_bytes = samples_to_pcm16_bytes(samples)
307
- duration = len(samples) / float(rate) if rate > 0 else 0.0
308
- return pcm_bytes, rate, duration, canonical_voice
975
+ sid, name = resolve_speaker_id(voice)
976
+ pcm = bytearray()
977
+ np = self.np
978
+ with self.lock:
979
+ for ids in self.frontend.chunks(text, name):
980
+ feeds = {
981
+ "input_ids": np.array([[0, *ids, 0]], dtype=np.int64),
982
+ "style": self.styles[sid, len(ids)],
983
+ "speed": np.array([speed], dtype=np.float32),
984
+ }
985
+ audio = self.session.run(["waveform"], feeds)[0]
986
+ if not np.isfinite(audio).all():
987
+ raise RuntimeError("Kokoro generated invalid audio")
988
+ trimmed = trim_kokoro_silence(audio, self.sample_rate, np)
989
+ pcm.extend(np.rint(np.clip(trimmed, -1, 1) * 32767).astype("<i2").tobytes())
990
+ if not pcm:
991
+ raise ValueError("No speakable text provided")
992
+ return bytes(pcm), self.sample_rate, len(pcm) / (2 * self.sample_rate), name
309
993
 
310
994
 
311
995
  def _write_json(handler: BaseHTTPRequestHandler, status: HTTPStatus, body: dict[str, Any]) -> None:
@@ -363,7 +1047,7 @@ def make_handler(
363
1047
  HTTPStatus.OK,
364
1048
  {
365
1049
  "status": "ok",
366
- "engine": "sherpa-onnx",
1050
+ "engine": "onnxruntime",
367
1051
  "model": model_id,
368
1052
  "sample_rate": synthesizer.sample_rate,
369
1053
  },
@@ -427,7 +1111,7 @@ def make_handler(
427
1111
 
428
1112
 
429
1113
  def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
430
- parser = argparse.ArgumentParser(description="Isolated sherpa-onnx Kokoro-82M v1.1-zh worker")
1114
+ parser = argparse.ArgumentParser(description="Isolated ONNX Runtime Kokoro v1.0 INT8 worker")
431
1115
  parser.add_argument("--model-dir", required=True, help="directory containing Kokoro ONNX files")
432
1116
  parser.add_argument("--model-id", default=DEFAULT_MODEL_ID, help="catalog model id")
433
1117
  parser.add_argument("--host", default="127.0.0.1")