@simplexai/localmodels-win32-x64 0.1.0-dev.102 → 0.1.0-dev.103

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 (47) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +46 -27
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +3 -1
  5. package/modules/localmodels/catalog.json +306 -1
  6. package/modules/localmodels/cli_parser.py +4 -0
  7. package/modules/localmodels/debug_stub_server.py +280 -7
  8. package/modules/localmodels/download-mirrors.json +76 -0
  9. package/modules/localmodels/engines-speechcpp-v0.11.3.json +84 -0
  10. package/modules/localmodels/library_serve.py +46 -26
  11. package/modules/localmodels/remote_ops_common.py +12 -2
  12. package/modules/localmodels/sidecar_downloads.py +426 -0
  13. package/modules/localmodels/sidecar_http.py +396 -0
  14. package/modules/localmodels/sidecar_state.py +466 -0
  15. package/modules/localmodels/speech_admission.py +13 -0
  16. package/modules/localmodels/speech_jobs.py +81 -370
  17. package/modules/localmodels/speech_server.py +17 -8
  18. package/modules/localmodels/speech_state.py +87 -454
  19. package/modules/localmodels/speech_workers.py +41 -163
  20. package/modules/localmodels/stack.py +18 -0
  21. package/modules/localmodels/stack_down.py +19 -14
  22. package/modules/localmodels/stack_ports.py +1 -0
  23. package/modules/localmodels/stack_up.py +51 -1
  24. package/modules/localmodels/strata_poly_server.py +140 -3
  25. package/modules/localmodels/tts-moss.txt +321 -0
  26. package/modules/localmodels/tts_admission.py +396 -0
  27. package/modules/localmodels/tts_backend_speechcpp.py +487 -0
  28. package/modules/localmodels/tts_catalog.py +251 -0
  29. package/modules/localmodels/tts_cli.py +333 -0
  30. package/modules/localmodels/tts_http.py +617 -0
  31. package/modules/localmodels/tts_jobs.py +496 -0
  32. package/modules/localmodels/tts_model.py +591 -0
  33. package/modules/localmodels/tts_moss_presets.json +1 -0
  34. package/modules/localmodels/tts_serve.py +451 -0
  35. package/modules/localmodels/tts_sidecar.py +750 -0
  36. package/modules/localmodels/tts_state.py +395 -0
  37. package/modules/localmodels/tts_worker_kokoro.py +463 -0
  38. package/modules/localmodels/tts_worker_moss.py +748 -0
  39. package/modules/localmodels/tts_workers.py +696 -0
  40. package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/METADATA +1 -1
  41. package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/RECORD +43 -24
  42. package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/licenses/NOTICE +29 -0
  43. package/package.json +1 -1
  44. package/tool.json +1 -1
  45. /package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/WHEEL +0 -0
  46. /package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/entry_points.txt +0 -0
  47. /package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,463 @@
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
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import array
15
+ import ctypes
16
+ import importlib
17
+ import importlib.util
18
+ import json
19
+ import os
20
+ import re
21
+ import signal
22
+ import sys
23
+ import threading
24
+ import urllib.parse
25
+ from http import HTTPStatus
26
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
27
+ from pathlib import Path
28
+ from typing import Any, Protocol
29
+
30
+ DEFAULT_MODEL_ID = "kokoro-v1.1-zh"
31
+ DEFAULT_VOICE = "zf_001"
32
+ DEFAULT_SAMPLE_RATE = 24000
33
+ MAX_INPUT_CHARS = 4096
34
+ MAX_BODY_BYTES = 1 << 20
35
+ MIN_SPEED = 0.5
36
+ MAX_SPEED = 2.0
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
+
147
+ SPEAKER_NAME_TO_SID: dict[str, int] = {name: idx for idx, name in enumerate(KOKORO_V11_SPEAKERS)}
148
+
149
+
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}
162
+
163
+
164
+ 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]
167
+
168
+
169
+ 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():
188
+ 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),
221
+ )
222
+ if sys.byteorder == "big":
223
+ pcm.byteswap()
224
+ return pcm.tobytes()
225
+
226
+
227
+ def _preload_windows_onnxruntime() -> None:
228
+ """Preload sherpa-onnx's bundled onnxruntime.dll by full path on Windows.
229
+
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
+
248
+
249
+ class TtsSynthesizer(Protocol):
250
+ sample_rate: int
251
+
252
+ def voices(self) -> list[dict[str, str]]: ...
253
+
254
+ def synthesize(self, text: str, voice: str, speed: float) -> tuple[bytes, int, float, str]: ...
255
+
256
+
257
+ class KokoroSynthesizer:
258
+ """Thread-safe sherpa-onnx OfflineTts wrapper for Kokoro-82M v1.1-zh."""
259
+
260
+ def __init__(self, model_dir: Path, *, threads: int = 2) -> None:
261
+ _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()),
287
+ )
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()
294
+
295
+ def voices(self) -> list[dict[str, str]]:
296
+ return kokoro_voice_list()
297
+
298
+ 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
309
+
310
+
311
+ def _write_json(handler: BaseHTTPRequestHandler, status: HTTPStatus, body: dict[str, Any]) -> None:
312
+ raw = json.dumps(body, ensure_ascii=False).encode("utf-8")
313
+ handler.send_response(status)
314
+ handler.send_header("Content-Type", "application/json; charset=utf-8")
315
+ handler.send_header("Content-Length", str(len(raw)))
316
+ handler.send_header("Connection", "close")
317
+ handler.end_headers()
318
+ handler.wfile.write(raw)
319
+
320
+
321
+ def _parse_synth_body(raw: bytes) -> tuple[str, str, float]:
322
+ try:
323
+ payload = json.loads(raw.decode("utf-8") if raw else "{}")
324
+ except (UnicodeDecodeError, ValueError) as exc:
325
+ raise ValueError(f"invalid JSON payload: {exc}") from None
326
+ if not isinstance(payload, dict):
327
+ raise ValueError("request body must be a JSON object")
328
+ text = payload.get("text")
329
+ if not isinstance(text, str) or not text.strip():
330
+ raise ValueError("text must be a non-empty string")
331
+ if len(text) > MAX_INPUT_CHARS:
332
+ raise ValueError(f"text length exceeds {MAX_INPUT_CHARS} characters")
333
+ voice_raw = payload.get("voice", DEFAULT_VOICE)
334
+ if not isinstance(voice_raw, str):
335
+ raise ValueError("voice must be a string")
336
+ speed_raw = payload.get("speed", 1.0)
337
+ if isinstance(speed_raw, bool) or not isinstance(speed_raw, int | float):
338
+ raise ValueError("speed must be a number")
339
+ speed = float(speed_raw)
340
+ if not (MIN_SPEED <= speed <= MAX_SPEED):
341
+ raise ValueError(f"speed must be between {MIN_SPEED} and {MAX_SPEED}")
342
+ return text, voice_raw, speed
343
+
344
+
345
+ def make_handler(
346
+ synthesizer: TtsSynthesizer,
347
+ *,
348
+ model_id: str = DEFAULT_MODEL_ID,
349
+ ) -> type[BaseHTTPRequestHandler]:
350
+ """Create a loopback HTTP request handler bound to ``synthesizer``."""
351
+
352
+ class KokoroHandler(BaseHTTPRequestHandler):
353
+ protocol_version = "HTTP/1.1"
354
+
355
+ def log_message(self, format: str, *args: object) -> None: # noqa: A002
356
+ _ = (format, args)
357
+
358
+ def do_GET(self) -> None: # noqa: N802
359
+ path = urllib.parse.urlsplit(self.path).path
360
+ if path == "/health":
361
+ _write_json(
362
+ self,
363
+ HTTPStatus.OK,
364
+ {
365
+ "status": "ok",
366
+ "engine": "sherpa-onnx",
367
+ "model": model_id,
368
+ "sample_rate": synthesizer.sample_rate,
369
+ },
370
+ )
371
+ return
372
+ if path == "/voices":
373
+ _write_json(self, HTTPStatus.OK, {"voices": synthesizer.voices()})
374
+ return
375
+ _write_json(self, HTTPStatus.NOT_FOUND, {"error": {"message": "not found"}})
376
+
377
+ def do_POST(self) -> None: # noqa: N802
378
+ path = urllib.parse.urlsplit(self.path).path
379
+ if path != "/synthesize":
380
+ _write_json(self, HTTPStatus.NOT_FOUND, {"error": {"message": "not found"}})
381
+ return
382
+ try:
383
+ content_length = int(self.headers.get("Content-Length") or "0")
384
+ except ValueError:
385
+ _write_json(
386
+ self, HTTPStatus.BAD_REQUEST, {"error": {"message": "invalid Content-Length"}}
387
+ )
388
+ return
389
+ if content_length <= 0 or content_length > MAX_BODY_BYTES:
390
+ _write_json(
391
+ self,
392
+ HTTPStatus.REQUEST_ENTITY_TOO_LARGE
393
+ if content_length > MAX_BODY_BYTES
394
+ else HTTPStatus.BAD_REQUEST,
395
+ {"error": {"message": "request body size out of bounds"}},
396
+ )
397
+ return
398
+ raw = self.rfile.read(content_length)
399
+ try:
400
+ text, voice, speed = _parse_synth_body(raw)
401
+ pcm_bytes, rate, duration, resolved_voice = synthesizer.synthesize(
402
+ text, voice, speed
403
+ )
404
+ except ValueError as exc:
405
+ _write_json(self, HTTPStatus.BAD_REQUEST, {"error": {"message": str(exc)}})
406
+ return
407
+ except Exception as exc: # noqa: BLE001
408
+ sys.stderr.write(f"kokoro worker synthesis error: {type(exc).__name__}\n")
409
+ sys.stderr.flush()
410
+ _write_json(
411
+ self,
412
+ HTTPStatus.INTERNAL_SERVER_ERROR,
413
+ {"error": {"message": "synthesis engine failed"}},
414
+ )
415
+ return
416
+ self.send_response(HTTPStatus.OK)
417
+ self.send_header("Content-Type", "audio/pcm")
418
+ self.send_header("Content-Length", str(len(pcm_bytes)))
419
+ self.send_header("X-Sample-Rate", str(rate))
420
+ self.send_header("X-Audio-Seconds", f"{duration:.3f}")
421
+ self.send_header("X-Voice", resolved_voice)
422
+ self.send_header("Connection", "close")
423
+ self.end_headers()
424
+ self.wfile.write(pcm_bytes)
425
+
426
+ return KokoroHandler
427
+
428
+
429
+ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
430
+ parser = argparse.ArgumentParser(description="Isolated sherpa-onnx Kokoro-82M v1.1-zh worker")
431
+ parser.add_argument("--model-dir", required=True, help="directory containing Kokoro ONNX files")
432
+ parser.add_argument("--model-id", default=DEFAULT_MODEL_ID, help="catalog model id")
433
+ parser.add_argument("--host", default="127.0.0.1")
434
+ parser.add_argument("--port", type=int, required=True)
435
+ parser.add_argument("--threads", type=int, default=min(4, max(1, os.cpu_count() or 1)))
436
+ return parser.parse_args(argv)
437
+
438
+
439
+ def main(argv: list[str] | None = None) -> int:
440
+ args = _parse_args(argv)
441
+ synth = KokoroSynthesizer(Path(args.model_dir), threads=args.threads)
442
+ server = ThreadingHTTPServer(
443
+ (args.host, args.port),
444
+ make_handler(synth, model_id=args.model_id),
445
+ )
446
+
447
+ def _request_shutdown(_signum: int, _frame: Any) -> None:
448
+ threading.Thread(target=server.shutdown, daemon=True).start()
449
+
450
+ for sig in (signal.SIGINT, signal.SIGTERM):
451
+ try:
452
+ signal.signal(sig, _request_shutdown)
453
+ except (OSError, ValueError):
454
+ pass
455
+ try:
456
+ server.serve_forever(poll_interval=0.25)
457
+ finally:
458
+ server.server_close()
459
+ return 0
460
+
461
+
462
+ if __name__ == "__main__":
463
+ raise SystemExit(main())