@simplexai/localmodels-linux-arm64 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,748 @@
1
+ """Isolated CPU child HTTP worker serving MOSS-TTS-Nano-100M via ONNX Runtime.
2
+
3
+ Runs inside the zero-PyTorch hash-locked Python venv built from ``localmodels/tts-moss.txt``
4
+ (``<base_dir>/frontends/tts-moss/``: ``onnxruntime``, ``numpy``, ``sentencepiece`` only).
5
+ Third-party packages are imported dynamically inside ``MossSynthesizer`` so this module stays
6
+ pure stdlib at import time (Layer 0, ``SELF_CONTAINED`` floor Python 3.10) and unit-testable
7
+ without ``onnxruntime`` installed.
8
+
9
+ Compliance invariants:
10
+ - Exposes strictly the 9 curated studio voices in ``MOSS_ALLOWED_VOICES`` (default ``Junhao``).
11
+ - Custom user reference-audio cloning is permanently disabled; no codec encoder graph is loaded.
12
+ - Privacy: never log synthesis input text or synthesized audio bytes.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import contextlib
19
+ import ctypes
20
+ import importlib
21
+ import importlib.util
22
+ import json
23
+ import os
24
+ import re
25
+ import signal
26
+ import sys
27
+ import threading
28
+ import time
29
+ import unicodedata
30
+ import urllib.parse
31
+ from collections.abc import Iterator
32
+ from http import HTTPStatus
33
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
34
+ from pathlib import Path
35
+ from typing import Any, Protocol
36
+
37
+ DEFAULT_MODEL_ID = "moss-tts-nano-100m"
38
+ DEFAULT_VOICE = "Junhao"
39
+ DEFAULT_SAMPLE_RATE = 48000
40
+ MAX_INPUT_CHARS = 4096
41
+ MAX_BODY_BYTES = 1 << 20
42
+ MAX_THREADS = 4
43
+ DEFAULT_MAX_NEW_FRAMES = 375
44
+ MIN_SPEED = 0.5
45
+ MAX_SPEED = 2.0
46
+
47
+ PRESETS_PATH = Path(__file__).with_name("tts_moss_presets.json")
48
+
49
+ # Strict 9-voice studio allowlist (no public figures, celebrities, or anime characters).
50
+ MOSS_ALLOWED_VOICES: tuple[tuple[str, str, str, str], ...] = (
51
+ ("Junhao", "Junhao", "zh", "male"),
52
+ ("Zhiming", "Zhiming", "zh", "male"),
53
+ ("Weiguo", "Weiguo", "zh", "male"),
54
+ ("Yuewen", "Yuewen", "zh", "female"),
55
+ ("Lingyu", "Lingyu", "zh", "female"),
56
+ ("Ava", "Ava", "en", "female"),
57
+ ("Bella", "Bella", "en", "female"),
58
+ ("Adam", "Adam", "en", "male"),
59
+ ("Nathan", "Nathan", "en", "male"),
60
+ )
61
+ MOSS_VOICE_LOOKUP: dict[str, str] = {vid.lower(): vid for vid, _n, _l, _g in MOSS_ALLOWED_VOICES}
62
+ _DISALLOWED_CLONE_KEYS = frozenset(
63
+ ("prompt_audio_path", "prompt_audio_codes", "reference_audio", "speaker_ref")
64
+ )
65
+
66
+ _CJK_RANGE = r"\u3400-\u4dbf\u4e00-\u9fff\u3040-\u30ff"
67
+ _CJK_RE = re.compile(f"[{_CJK_RANGE}]")
68
+ _ZERO_WIDTH_RE = re.compile(r"[\u200b-\u200d\ufeff]")
69
+ _PROT_RE = re.compile(r"___PROT\d+___")
70
+ _PROTECT_PATTERNS = (
71
+ re.compile(
72
+ r"https?://[^\s\u3000\uff0c\u3002\uff01\uff1f\uff1b\u3001\uff09\u3011\u300b\u3009\u300d\u300f]+"
73
+ ),
74
+ re.compile(r"(?<![\w.+-])[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}(?![\w.-])"),
75
+ re.compile(r"(?<![A-Za-z0-9_])\.(?=[A-Za-z0-9._-]*[A-Za-z0-9])[A-Za-z0-9._-]+"),
76
+ re.compile(
77
+ r"(?<![A-Za-z0-9_])(?=[A-Za-z0-9._/+:-]*[A-Za-z])"
78
+ r"(?=[A-Za-z0-9._/+:-]*[./+:-])[A-Za-z0-9](?:[A-Za-z0-9._/+:-]*[A-Za-z0-9])?(?![A-Za-z0-9_])"
79
+ ),
80
+ )
81
+ _MD_LINK_RE = re.compile(r"\[([^\[\]]+?)\]\((https?://[^)\s]+)\)")
82
+ _MD_PREFIX_RE = re.compile(r"^(?:#{1,6}|>|[-*+]|\d+[.)])\s+")
83
+ _ARROW_RE = re.compile(r"\s*(?:<[-=]+>|[-=]+>|<[-=]+|[\u2190-\u21ff\u27f5-\u27ff])\s*")
84
+ _BRACKET_RE = re.compile(
85
+ r"[\[\{\u3010\u3016\u300e\u300c]\s*([^\]\}\u3011\u3017\u300f\u300d]+?)\s*[\]\}\u3011\u3017\u300f\u300d]"
86
+ )
87
+ _DASH_BOUNDARY_RE = re.compile(r"\s*(?:\u2014|\u2013|\u2015|-){2,}\s*")
88
+ _ELLIPSIS_RE = re.compile(r"(?:\.{3,}|\u2026{2,})")
89
+ _LATINISH = r"(?:___PROT\d+___|(?=[A-Za-z0-9._/+:-]*[A-Za-z])[A-Za-z0-9][A-Za-z0-9._/+:-]*)"
90
+ _CLOSERS = frozenset("\"'')]} \uff09\u3011\u300b\u3009\u300d\u300f\u201d\u2019")
91
+
92
+
93
+ def moss_voice_list() -> list[dict[str, str]]:
94
+ """Return the exact 9 curated studio voices for MOSS-TTS-Nano-100M."""
95
+ return [
96
+ {"id": vid, "name": label, "language": lang, "gender": gender}
97
+ for vid, label, lang, gender in MOSS_ALLOWED_VOICES
98
+ ]
99
+
100
+
101
+ def resolve_voice(voice: str | None) -> str:
102
+ """Resolve ``voice`` strictly against the 9-voice studio allowlist."""
103
+ cleaned = (voice or DEFAULT_VOICE).strip()
104
+ if not cleaned:
105
+ return DEFAULT_VOICE
106
+ canonical = MOSS_VOICE_LOOKUP.get(cleaned.lower())
107
+ if canonical is None:
108
+ raise ValueError(f"unknown MOSS voice: {cleaned!r}")
109
+ return canonical
110
+
111
+
112
+ def load_presets(path: Path = PRESETS_PATH) -> dict[str, Any]:
113
+ """Load curated MOSS prompt templates, tensor specs, and allowlisted preset voice codes."""
114
+ raw = json.loads(path.read_text(encoding="utf-8"))
115
+ if not isinstance(raw, dict) or raw.get("schema") != "localmodels.tts-moss-presets/v1":
116
+ raise RuntimeError(f"invalid MOSS presets manifest at {path}")
117
+ codes_by_voice: dict[str, list[list[int]]] = {}
118
+ for entry in raw.get("voices", []):
119
+ if not isinstance(entry, dict):
120
+ continue
121
+ vid = entry.get("id")
122
+ if isinstance(vid, str) and vid.lower() in MOSS_VOICE_LOOKUP:
123
+ canonical = MOSS_VOICE_LOOKUP[vid.lower()]
124
+ codes_by_voice[canonical] = [
125
+ [int(x) for x in row] for row in entry["prompt_audio_codes"]
126
+ ]
127
+ missing = [vid for vid, _n, _l, _g in MOSS_ALLOWED_VOICES if vid not in codes_by_voice]
128
+ if missing:
129
+ raise RuntimeError(f"MOSS presets missing allowlisted voices: {', '.join(missing)}")
130
+ return {
131
+ "tts_config": raw["tts_config"],
132
+ "codec_config": raw["codec_config"],
133
+ "prompt_templates": raw["prompt_templates"],
134
+ "voice_codes": codes_by_voice,
135
+ }
136
+
137
+
138
+ def _end_punct(line: str) -> str:
139
+ if not line:
140
+ return line
141
+ idx = len(line) - 1
142
+ while idx >= 0 and (line[idx].isspace() or line[idx] in _CLOSERS):
143
+ idx -= 1
144
+ if idx >= 0 and unicodedata.category(line[idx]).startswith("P"):
145
+ return line
146
+ return line + ("\u3002" if _CJK_RE.search(line) else ".")
147
+
148
+
149
+ def normalize_moss_text(text: str) -> str:
150
+ """Robust non-semantic text cleanup for MOSS-TTS-Nano (pure stdlib, ASCII source)."""
151
+ cleaned = _ZERO_WIDTH_RE.sub(
152
+ "", text.replace("\r\n", "\n").replace("\r", "\n").replace("\u3000", " ")
153
+ )
154
+ cleaned = "".join(
155
+ ch for ch in cleaned if ch in "\n\t " or not unicodedata.category(ch).startswith("C")
156
+ )
157
+ cleaned = _MD_LINK_RE.sub(r"\1 \2", cleaned)
158
+ lines = [_MD_PREFIX_RE.sub("", ln.strip()) for ln in cleaned.splitlines() if ln.strip()]
159
+ if not lines:
160
+ return ""
161
+ merged = "".join(_end_punct(ln) if i < len(lines) - 1 else ln for i, ln in enumerate(lines))
162
+ merged = _ARROW_RE.sub("\uff0c", merged)
163
+ protected: list[str] = []
164
+
165
+ def _stash(match: re.Match[str]) -> str:
166
+ idx = len(protected)
167
+ protected.append(match.group(0))
168
+ return f"___PROT{idx}___"
169
+
170
+ for pat in _PROTECT_PATTERNS:
171
+ merged = pat.sub(_stash, merged)
172
+ merged = "".join(
173
+ p if _PROT_RE.fullmatch(p) else p.replace("_", " ")
174
+ for p in re.split(r"(___PROT\d+___)", merged)
175
+ )
176
+ merged = _BRACKET_RE.sub(r'"\1"', merged)
177
+ merged = _DASH_BOUNDARY_RE.sub("\u3002", merged)
178
+ merged = _ELLIPSIS_RE.sub("\u3002", merged)
179
+ merged = re.sub(r"[ \t\r\f\v]+", " ", merged)
180
+ merged = re.sub(rf"([{_CJK_RANGE}])\s+(?=[{_CJK_RANGE}])", r"\1", merged)
181
+ merged = re.sub(rf"([{_CJK_RANGE}])\s+(?=\d)", r"\1", merged)
182
+ merged = re.sub(rf"(\d)\s+(?=[{_CJK_RANGE}])", r"\1", merged)
183
+ merged = re.sub(rf"([{_CJK_RANGE}])(?={_LATINISH})", r"\1 ", merged)
184
+ merged = re.sub(rf"({_LATINISH})(?=[{_CJK_RANGE}])", r"\1 ", merged)
185
+ merged = re.sub(r"\s+([,.;!?\uff0c\u3002\uff01\uff1f\uff1b\uff1a\u3001])", r"\1", merged)
186
+ merged = re.sub(r" {2,}", " ", merged).strip()
187
+ for idx, original in enumerate(protected):
188
+ merged = merged.replace(f"___PROT{idx}___", original)
189
+ return _end_punct(merged.strip())
190
+
191
+
192
+ def float_audio_to_mono_pcm16(audio: Any, valid_samples: int, np_mod: Any) -> bytes:
193
+ """Downmix MOSS (1, C, N) float32 output to mono with soft peak limiting into LE int16 PCM."""
194
+ arr = np_mod.asarray(audio, dtype=np_mod.float32)
195
+ if arr.ndim == 3:
196
+ arr = arr[0]
197
+ if arr.ndim == 2:
198
+ sliced = arr[:, : max(0, valid_samples)]
199
+ mono = sliced.mean(axis=0, dtype=np_mod.float32) if sliced.shape[0] > 1 else sliced[0]
200
+ else:
201
+ mono = arr[: max(0, valid_samples)]
202
+ if mono.size == 0:
203
+ return b""
204
+ # Smooth soft-knee limiter above 0.95 prevents hard clipping on 1.10-1.29 float peaks
205
+ # while keeping chunk gain constant across streaming frames.
206
+ knee = 0.95
207
+ mag = np_mod.abs(mono)
208
+ over = mag > knee
209
+ if bool(np_mod.any(over)):
210
+ limited = mono.copy()
211
+ excess = (mag[over] - knee) / (1.0 - knee)
212
+ limited[over] = np_mod.sign(mono[over]) * (knee + (1.0 - knee) * np_mod.tanh(excess))
213
+ mono = limited
214
+ clipped = np_mod.clip(mono, -1.0, 1.0)
215
+ return bytes((clipped * 32767.0).astype("<i2").tobytes())
216
+
217
+
218
+ def _preload_windows_onnxruntime() -> None:
219
+ """Preload onnxruntime's bundled capi DLLs by absolute path on Windows.
220
+
221
+ Prevents PreferSystem32 process-mitigation environments from binding System32's older ORT DLL.
222
+ """
223
+ if sys.platform != "win32" or "onnxruntime" in sys.modules:
224
+ return
225
+ spec = importlib.util.find_spec("onnxruntime")
226
+ if spec is None:
227
+ raise RuntimeError("onnxruntime is missing from the tts-moss runtime venv")
228
+ roots = [Path(loc) for loc in (spec.submodule_search_locations or ())]
229
+ if not roots and spec.origin:
230
+ roots = [Path(spec.origin).resolve().parent]
231
+ loaded = False
232
+ for root in roots:
233
+ capi = root / "capi"
234
+ if not capi.is_dir():
235
+ continue
236
+ add_dir = getattr(os, "add_dll_directory", None)
237
+ if callable(add_dir):
238
+ add_dir(str(capi))
239
+ for dll_name in ("onnxruntime.dll", "onnxruntime_providers_shared.dll"):
240
+ dll_path = capi / dll_name
241
+ if dll_path.is_file():
242
+ ctypes.WinDLL(str(dll_path))
243
+ loaded = True
244
+ if not loaded:
245
+ raise RuntimeError("bundled onnxruntime DLL not found under onnxruntime/capi")
246
+
247
+
248
+ def _stream_frame_budget(emitted_samples: int, sample_rate: int, first_at: float | None) -> int:
249
+ if first_at is None or sample_rate <= 0:
250
+ return 1
251
+ lead = (emitted_samples / float(sample_rate)) - max(0.0, time.perf_counter() - first_at)
252
+ if lead < 0.20:
253
+ return 1
254
+ if lead < 0.55:
255
+ return 2
256
+ if lead < 1.10:
257
+ return 4
258
+ return 8
259
+
260
+
261
+ class MossSynthProto(Protocol):
262
+ sample_rate: int
263
+
264
+ def voices(self) -> list[dict[str, str]]: ...
265
+
266
+ def synthesize_stream(self, text: str, voice: str, speed: float) -> Iterator[bytes]: ...
267
+
268
+ def synthesize(self, text: str, voice: str, speed: float) -> tuple[bytes, int, float, str]: ...
269
+
270
+
271
+ class _CodecStreamState:
272
+ """Stateful incremental decoder for ``moss_audio_tokenizer_decode_step.onnx``."""
273
+
274
+ def __init__(self, session: Any, codec_cfg: dict[str, Any], np_mod: Any) -> None:
275
+ self._session = session
276
+ self._np = np_mod
277
+ self._n_vq = int(codec_cfg["num_quantizers"])
278
+ self._offset_count = int(codec_cfg["transformer_offset_count"])
279
+ self._contexts = [int(c) for c in codec_cfg["attention_contexts"]]
280
+ self._heads = int(codec_cfg["attention_num_heads"])
281
+ self._head_dim = int(codec_cfg["attention_head_dim"])
282
+ self._output_names = [out.name for out in session.get_outputs()]
283
+ self._feeds: dict[str, Any] = {}
284
+ self.reset()
285
+
286
+ def reset(self) -> None:
287
+ np = self._np
288
+ feeds: dict[str, Any] = {
289
+ f"transformer_offset_{i}": np.zeros((1,), dtype=np.int32)
290
+ for i in range(self._offset_count)
291
+ }
292
+ for i, ctx in enumerate(self._contexts):
293
+ feeds[f"attn_offset_{i}"] = np.zeros((1,), dtype=np.int32)
294
+ feeds[f"attn_cached_keys_{i}"] = np.zeros(
295
+ (1, self._heads, ctx, self._head_dim), dtype=np.float32
296
+ )
297
+ feeds[f"attn_cached_values_{i}"] = np.zeros(
298
+ (1, self._heads, ctx, self._head_dim), dtype=np.float32
299
+ )
300
+ feeds[f"attn_cached_positions_{i}"] = np.full((1, ctx), -1, dtype=np.int32)
301
+ self._feeds = feeds
302
+
303
+ def decode_frames(self, frames: list[list[int]]) -> tuple[Any, int]:
304
+ np = self._np
305
+ count = len(frames)
306
+ codes = np.asarray(frames, dtype=np.int32).reshape((1, count, self._n_vq))
307
+ inputs: dict[str, Any] = {
308
+ "audio_codes": codes,
309
+ "audio_code_lengths": np.asarray([count], dtype=np.int32),
310
+ **self._feeds,
311
+ }
312
+ named = dict(zip(self._output_names, self._session.run(None, inputs), strict=True))
313
+ for i in range(self._offset_count):
314
+ self._feeds[f"transformer_offset_{i}"] = named[f"transformer_offset_out_{i}"]
315
+ for i in range(len(self._contexts)):
316
+ self._feeds[f"attn_offset_{i}"] = named[f"attn_offset_out_{i}"]
317
+ self._feeds[f"attn_cached_keys_{i}"] = named[f"attn_cached_keys_out_{i}"]
318
+ self._feeds[f"attn_cached_values_{i}"] = named[f"attn_cached_values_out_{i}"]
319
+ self._feeds[f"attn_cached_positions_{i}"] = named[f"attn_cached_positions_out_{i}"]
320
+ return named["audio"], int(named["audio_lengths"].reshape(-1)[0])
321
+
322
+
323
+ class MossSynthesizer:
324
+ """Thread-safe zero-PyTorch 4-session ONNX Runtime synthesizer for MOSS-TTS-Nano-100M."""
325
+
326
+ def __init__(
327
+ self,
328
+ model_dir: Path,
329
+ *,
330
+ threads: int = MAX_THREADS,
331
+ presets_path: Path = PRESETS_PATH,
332
+ max_new_frames: int = DEFAULT_MAX_NEW_FRAMES,
333
+ seed: int | None = 1234,
334
+ ) -> None:
335
+ capped = max(1, min(MAX_THREADS, int(threads)))
336
+ for env_key in (
337
+ "OMP_NUM_THREADS",
338
+ "OPENBLAS_NUM_THREADS",
339
+ "MKL_NUM_THREADS",
340
+ "NUMEXPR_NUM_THREADS",
341
+ ):
342
+ os.environ.setdefault(env_key, str(capped))
343
+ _preload_windows_onnxruntime()
344
+ self._np: Any = importlib.import_module("numpy")
345
+ self._ort: Any = importlib.import_module("onnxruntime")
346
+ spm: Any = importlib.import_module("sentencepiece")
347
+
348
+ presets = load_presets(presets_path)
349
+ self._tts_cfg: dict[str, int] = {k: int(v) for k, v in presets["tts_config"].items()}
350
+ self._codec_cfg: dict[str, Any] = presets["codec_config"]
351
+ self._templates: dict[str, list[int]] = presets["prompt_templates"]
352
+ self._voice_codes: dict[str, list[list[int]]] = presets["voice_codes"]
353
+ self.sample_rate = int(self._codec_cfg["sample_rate"])
354
+ self._max_new_frames = max(1, int(max_new_frames))
355
+ self._rng = self._np.random.default_rng(seed)
356
+ self._sp = spm.SentencePieceProcessor(model_file=str(model_dir / "tokenizer.model"))
357
+
358
+ self._prefill = self._open_session(model_dir / "moss_tts_prefill.onnx", capped)
359
+ self._decode = self._open_session(model_dir / "moss_tts_decode_step.onnx", capped)
360
+ self._local = self._open_session(
361
+ model_dir / "moss_tts_local_fixed_sampled_frame.onnx", capped
362
+ )
363
+ codec_sess = self._open_session(model_dir / "moss_audio_tokenizer_decode_step.onnx", capped)
364
+ self._codec = _CodecStreamState(codec_sess, self._codec_cfg, self._np)
365
+ self._prefill_outs = [o.name for o in self._prefill.get_outputs()]
366
+ self._decode_outs = [o.name for o in self._decode.get_outputs()]
367
+ self._local_outs = [o.name for o in self._local.get_outputs()]
368
+ self._lock = threading.Lock()
369
+
370
+ def _open_session(self, onnx_path: Path, threads: int) -> Any:
371
+ if not onnx_path.is_file():
372
+ raise FileNotFoundError(f"missing MOSS ONNX artifact: {onnx_path.name}")
373
+ opts = self._ort.SessionOptions()
374
+ opts.graph_optimization_level = self._ort.GraphOptimizationLevel.ORT_ENABLE_ALL
375
+ opts.intra_op_num_threads = threads
376
+ opts.inter_op_num_threads = 1
377
+ return self._ort.InferenceSession(
378
+ str(onnx_path), sess_options=opts, providers=["CPUExecutionProvider"]
379
+ )
380
+
381
+ def voices(self) -> list[dict[str, str]]:
382
+ return moss_voice_list()
383
+
384
+ def _build_prompt_rows(self, voice: str, text_token_ids: list[int]) -> Any:
385
+ cfg = self._tts_cfg
386
+ n_vq, pad = cfg["n_vq"], cfg["audio_pad_token_id"]
387
+ width = n_vq + 1
388
+ prefix_ids = [*self._templates["user_prompt_prefix_token_ids"], cfg["audio_start_token_id"]]
389
+ suffix_ids = [
390
+ cfg["audio_end_token_id"],
391
+ *self._templates["user_prompt_after_reference_token_ids"],
392
+ *text_token_ids,
393
+ *self._templates["assistant_prompt_prefix_token_ids"],
394
+ cfg["audio_start_token_id"],
395
+ ]
396
+ ref_codes = self._voice_codes[voice]
397
+ total_rows = len(prefix_ids) + len(ref_codes) + len(suffix_ids)
398
+ rows = self._np.full((1, total_rows, width), pad, dtype=self._np.int32)
399
+ for i, tid in enumerate(prefix_ids):
400
+ rows[0, i, 0] = int(tid)
401
+ offset = len(prefix_ids)
402
+ slot_user = cfg["audio_user_slot_token_id"]
403
+ for i, frame in enumerate(ref_codes):
404
+ rows[0, offset + i, 0] = slot_user
405
+ rows[0, offset + i, 1 : 1 + n_vq] = frame[:n_vq]
406
+ offset += len(ref_codes)
407
+ for i, tid in enumerate(suffix_ids):
408
+ rows[0, offset + i, 0] = int(tid)
409
+ return rows
410
+
411
+ def _last_hidden(self, tensor: Any) -> Any:
412
+ arr = self._np.asarray(tensor, dtype=self._np.float32)
413
+ return arr if arr.ndim == 2 else arr[:, -1, :]
414
+
415
+ def _decode_chunk_pcm(self, frames: list[list[int]]) -> tuple[bytes, int]:
416
+ audio, valid = self._codec.decode_frames(frames)
417
+ if valid <= 0:
418
+ return b"", 0
419
+ return float_audio_to_mono_pcm16(audio, valid, self._np), valid
420
+
421
+ def synthesize_stream(self, text: str, voice: str, speed: float) -> Iterator[bytes]:
422
+ _ = speed
423
+ canonical = resolve_voice(voice)
424
+ cleaned = normalize_moss_text(text)
425
+ if not cleaned:
426
+ raise ValueError("input text contains no speakable characters")
427
+ with self._lock:
428
+ np = self._np
429
+ cfg = self._tts_cfg
430
+ n_vq, codebook_size = cfg["n_vq"], cfg["audio_codebook_size"]
431
+ text_ids = [int(x) for x in self._sp.encode(cleaned, out_type=int)]
432
+ input_ids = self._build_prompt_rows(canonical, text_ids)
433
+ seq_len = int(input_ids.shape[1])
434
+ mask = np.ones((1, seq_len), dtype=np.int32)
435
+
436
+ pre = dict(
437
+ zip(
438
+ self._prefill_outs,
439
+ self._prefill.run(None, {"input_ids": input_ids, "attention_mask": mask}),
440
+ strict=True,
441
+ )
442
+ )
443
+ hidden = self._last_hidden(pre["global_hidden"])
444
+ past = {k.replace("present_", "past_"): pre[k] for k in self._prefill_outs[1:]}
445
+ rep_mask = np.zeros((1, n_vq, codebook_size), dtype=np.int32)
446
+
447
+ self._codec.reset()
448
+ pending: list[list[int]] = []
449
+ emitted_samples = 0
450
+ first_at: float | None = None
451
+ past_len = seq_len
452
+ slot_asst, pad = cfg["audio_assistant_slot_token_id"], cfg["audio_pad_token_id"]
453
+
454
+ for _ in range(self._max_new_frames):
455
+ asst_u = np.asarray([min(0.99999994, float(self._rng.random()))], dtype=np.float32)
456
+ aud_u = np.minimum(0.99999994, self._rng.random((1, n_vq))).astype(np.float32)
457
+ loc = dict(
458
+ zip(
459
+ self._local_outs,
460
+ self._local.run(
461
+ None,
462
+ {
463
+ "global_hidden": hidden,
464
+ "repetition_seen_mask": rep_mask,
465
+ "assistant_random_u": asst_u,
466
+ "audio_random_u": aud_u,
467
+ },
468
+ ),
469
+ strict=True,
470
+ )
471
+ )
472
+ if not bool(int(np.asarray(loc["should_continue"]).reshape(-1)[0])):
473
+ break
474
+ frame = [
475
+ int(x) for x in np.asarray(loc["frame_token_ids"]).reshape(-1).tolist()[:n_vq]
476
+ ]
477
+ for ch, tok in enumerate(frame):
478
+ if 0 <= tok < codebook_size:
479
+ rep_mask[0, ch, tok] = 1
480
+
481
+ next_row = np.full((1, 1, n_vq + 1), pad, dtype=np.int32)
482
+ next_row[0, 0, 0] = slot_asst
483
+ next_row[0, 0, 1 : 1 + n_vq] = frame
484
+ dec_feeds = {
485
+ "input_ids": next_row,
486
+ "past_valid_lengths": np.asarray([past_len], dtype=np.int32),
487
+ **past,
488
+ }
489
+ dec = dict(zip(self._decode_outs, self._decode.run(None, dec_feeds), strict=True))
490
+ hidden = self._last_hidden(dec["global_hidden"])
491
+ past = {k.replace("present_", "past_"): dec[k] for k in self._decode_outs[1:]}
492
+ past_len += 1
493
+
494
+ pending.append(frame)
495
+ if len(pending) >= _stream_frame_budget(
496
+ emitted_samples, self.sample_rate, first_at
497
+ ):
498
+ pcm, valid = self._decode_chunk_pcm(pending)
499
+ pending = []
500
+ if pcm:
501
+ if first_at is None:
502
+ first_at = time.perf_counter()
503
+ emitted_samples += valid
504
+ yield pcm
505
+ if pending:
506
+ pcm, _valid = self._decode_chunk_pcm(pending)
507
+ if pcm:
508
+ yield pcm
509
+
510
+ def synthesize(self, text: str, voice: str, speed: float) -> tuple[bytes, int, float, str]:
511
+ canonical = resolve_voice(voice)
512
+ pcm = b"".join(self.synthesize_stream(text, canonical, speed))
513
+ duration = (len(pcm) / 2.0) / float(self.sample_rate) if self.sample_rate > 0 else 0.0
514
+ return pcm, self.sample_rate, duration, canonical
515
+
516
+
517
+ def _send_json(
518
+ handler: BaseHTTPRequestHandler, status: HTTPStatus, payload: dict[str, Any]
519
+ ) -> None:
520
+ encoded = json.dumps(payload, ensure_ascii=False).encode("utf-8")
521
+ handler.send_response(status)
522
+ handler.send_header("Content-Type", "application/json; charset=utf-8")
523
+ handler.send_header("Content-Length", str(len(encoded)))
524
+ handler.send_header("Connection", "close")
525
+ handler.end_headers()
526
+ handler.wfile.write(encoded)
527
+
528
+
529
+ def _decode_request(raw: bytes) -> tuple[str, str, float]:
530
+ try:
531
+ obj = json.loads(raw.decode("utf-8") if raw else "{}")
532
+ except (UnicodeDecodeError, ValueError) as exc:
533
+ raise ValueError(f"invalid JSON payload: {exc}") from None
534
+ if not isinstance(obj, dict):
535
+ raise ValueError("request body must be a JSON object")
536
+ if any(k in obj and obj[k] is not None for k in _DISALLOWED_CLONE_KEYS):
537
+ raise ValueError("custom reference audio cloning is disabled")
538
+ text = obj.get("text")
539
+ if not isinstance(text, str) or not normalize_moss_text(text):
540
+ raise ValueError("text must contain speakable characters")
541
+ if len(text) > MAX_INPUT_CHARS:
542
+ raise ValueError(f"text length exceeds {MAX_INPUT_CHARS} characters")
543
+ voice_raw = obj.get("voice", DEFAULT_VOICE)
544
+ if not isinstance(voice_raw, str):
545
+ raise ValueError("voice must be a string")
546
+ canonical = resolve_voice(voice_raw)
547
+ speed_raw = obj.get("speed", 1.0)
548
+ if isinstance(speed_raw, bool) or not isinstance(speed_raw, int | float):
549
+ raise ValueError("speed must be a number")
550
+ speed = float(speed_raw)
551
+ if not (MIN_SPEED <= speed <= MAX_SPEED):
552
+ raise ValueError(f"speed must be between {MIN_SPEED} and {MAX_SPEED}")
553
+ return text, canonical, speed
554
+
555
+
556
+ def _read_request_body(handler: BaseHTTPRequestHandler) -> bytes | None:
557
+ try:
558
+ length = int(handler.headers.get("Content-Length") or "0")
559
+ except ValueError:
560
+ _send_json(
561
+ handler, HTTPStatus.BAD_REQUEST, {"error": {"message": "invalid Content-Length"}}
562
+ )
563
+ return None
564
+ if length <= 0 or length > MAX_BODY_BYTES:
565
+ code = (
566
+ HTTPStatus.REQUEST_ENTITY_TOO_LARGE
567
+ if length > MAX_BODY_BYTES
568
+ else HTTPStatus.BAD_REQUEST
569
+ )
570
+ _send_json(handler, code, {"error": {"message": "request body size out of bounds"}})
571
+ return None
572
+ return handler.rfile.read(length)
573
+
574
+
575
+ def _send_engine_error(handler: BaseHTTPRequestHandler | None, exc: Exception, label: str) -> None:
576
+ sys.stderr.write(f"moss worker {label} error: {type(exc).__name__}\n")
577
+ sys.stderr.flush()
578
+ if handler is not None:
579
+ _send_json(
580
+ handler,
581
+ HTTPStatus.INTERNAL_SERVER_ERROR,
582
+ {"error": {"message": "synthesis engine failed"}},
583
+ )
584
+
585
+
586
+ def _serve_synth(
587
+ handler: BaseHTTPRequestHandler,
588
+ synthesizer: MossSynthProto,
589
+ text: str,
590
+ voice: str,
591
+ speed: float,
592
+ ) -> None:
593
+ try:
594
+ pcm_bytes, rate, duration, canonical = synthesizer.synthesize(text, voice, speed)
595
+ except ValueError as exc:
596
+ _send_json(handler, HTTPStatus.BAD_REQUEST, {"error": {"message": str(exc)}})
597
+ return
598
+ except Exception as exc: # noqa: BLE001
599
+ _send_engine_error(handler, exc, "synthesis")
600
+ return
601
+ handler.send_response(HTTPStatus.OK)
602
+ handler.send_header("Content-Type", "audio/pcm")
603
+ handler.send_header("Content-Length", str(len(pcm_bytes)))
604
+ handler.send_header("X-Sample-Rate", str(rate))
605
+ handler.send_header("X-Audio-Seconds", f"{duration:.3f}")
606
+ handler.send_header("X-Voice", canonical)
607
+ handler.send_header("Connection", "close")
608
+ handler.end_headers()
609
+ handler.wfile.write(pcm_bytes)
610
+
611
+
612
+ def _write_chunk(handler: BaseHTTPRequestHandler, chunk: bytes) -> None:
613
+ handler.wfile.write(f"{len(chunk):x}\r\n".encode("ascii"))
614
+ handler.wfile.write(chunk)
615
+ handler.wfile.write(b"\r\n")
616
+ handler.wfile.flush()
617
+
618
+
619
+ def _serve_stream(
620
+ handler: BaseHTTPRequestHandler,
621
+ synthesizer: MossSynthProto,
622
+ text: str,
623
+ voice: str,
624
+ speed: float,
625
+ ) -> None:
626
+ stream_iter = iter(synthesizer.synthesize_stream(text, voice, speed))
627
+ first_chunk: bytes | None = None
628
+ try:
629
+ try:
630
+ for chunk in stream_iter:
631
+ if chunk:
632
+ first_chunk = chunk
633
+ break
634
+ except ValueError as exc:
635
+ _send_json(handler, HTTPStatus.BAD_REQUEST, {"error": {"message": str(exc)}})
636
+ return
637
+ except Exception as exc: # noqa: BLE001
638
+ _send_engine_error(handler, exc, "stream")
639
+ return
640
+ if first_chunk is None:
641
+ _send_json(handler, HTTPStatus.BAD_REQUEST, {"error": {"message": "empty synthesis"}})
642
+ return
643
+ handler.send_response(HTTPStatus.OK)
644
+ for k, v in (
645
+ ("Content-Type", "audio/pcm"),
646
+ ("Transfer-Encoding", "chunked"),
647
+ ("X-Sample-Rate", str(synthesizer.sample_rate)),
648
+ ("X-Voice", resolve_voice(voice)),
649
+ ("Connection", "close"),
650
+ ):
651
+ handler.send_header(k, v)
652
+ handler.end_headers()
653
+ try:
654
+ _write_chunk(handler, first_chunk)
655
+ for chunk in stream_iter:
656
+ if chunk:
657
+ _write_chunk(handler, chunk)
658
+ handler.wfile.write(b"0\r\n\r\n")
659
+ handler.wfile.flush()
660
+ except (BrokenPipeError, ConnectionResetError):
661
+ return
662
+ except Exception as exc: # noqa: BLE001
663
+ _send_engine_error(None, exc, "stream")
664
+ handler.close_connection = True
665
+ finally:
666
+ close_fn = getattr(stream_iter, "close", None)
667
+ if callable(close_fn):
668
+ close_fn()
669
+
670
+
671
+ def make_handler(
672
+ synthesizer: MossSynthProto, *, model_id: str = DEFAULT_MODEL_ID
673
+ ) -> type[BaseHTTPRequestHandler]:
674
+ """Create a loopback HTTP request handler supporting ``/synthesize`` and ``/synthesize-stream``."""
675
+
676
+ class MossHandler(BaseHTTPRequestHandler):
677
+ protocol_version = "HTTP/1.1"
678
+
679
+ def log_message(self, format: str, *args: object) -> None: # noqa: A002
680
+ _ = (format, args)
681
+
682
+ def do_GET(self) -> None: # noqa: N802
683
+ route = urllib.parse.urlsplit(self.path).path
684
+ if route == "/health":
685
+ payload = {
686
+ "status": "ok",
687
+ "engine": "onnxruntime",
688
+ "model": model_id,
689
+ "sample_rate": synthesizer.sample_rate,
690
+ }
691
+ _send_json(self, HTTPStatus.OK, payload)
692
+ return
693
+ if route == "/voices":
694
+ _send_json(self, HTTPStatus.OK, {"voices": synthesizer.voices()})
695
+ return
696
+ _send_json(self, HTTPStatus.NOT_FOUND, {"error": {"message": "not found"}})
697
+
698
+ def do_POST(self) -> None: # noqa: N802
699
+ route = urllib.parse.urlsplit(self.path).path
700
+ if route not in ("/synthesize", "/synthesize-stream"):
701
+ _send_json(self, HTTPStatus.NOT_FOUND, {"error": {"message": "not found"}})
702
+ return
703
+ raw = _read_request_body(self)
704
+ if raw is None:
705
+ return
706
+ try:
707
+ text, voice, speed = _decode_request(raw)
708
+ except ValueError as exc:
709
+ _send_json(self, HTTPStatus.BAD_REQUEST, {"error": {"message": str(exc)}})
710
+ return
711
+ if route == "/synthesize-stream":
712
+ _serve_stream(self, synthesizer, text, voice, speed)
713
+ else:
714
+ _serve_synth(self, synthesizer, text, voice, speed)
715
+
716
+ return MossHandler
717
+
718
+
719
+ def _parse_cli(argv: list[str] | None = None) -> argparse.Namespace:
720
+ parser = argparse.ArgumentParser(description="Isolated ONNX Runtime MOSS-TTS-Nano-100M worker")
721
+ parser.add_argument("--model-dir", required=True, help="directory containing MOSS ONNX files")
722
+ parser.add_argument("--model-id", default=DEFAULT_MODEL_ID, help="catalog model id")
723
+ parser.add_argument("--presets", default=str(PRESETS_PATH), help="curated presets JSON path")
724
+ parser.add_argument("--host", default="127.0.0.1")
725
+ parser.add_argument("--port", type=int, required=True)
726
+ parser.add_argument(
727
+ "--threads", type=int, default=min(MAX_THREADS, max(1, os.cpu_count() or 1))
728
+ )
729
+ return parser.parse_args(argv)
730
+
731
+
732
+ def main(argv: list[str] | None = None) -> int:
733
+ args = _parse_cli(argv)
734
+ threads = min(MAX_THREADS, max(1, int(args.threads)))
735
+ synth = MossSynthesizer(Path(args.model_dir), threads=threads, presets_path=Path(args.presets))
736
+ with ThreadingHTTPServer(
737
+ (args.host, args.port), make_handler(synth, model_id=args.model_id)
738
+ ) as server:
739
+ stop = lambda _s, _f: threading.Thread(target=server.shutdown, daemon=True).start() # noqa: E731
740
+ for sig in (signal.SIGINT, signal.SIGTERM):
741
+ with contextlib.suppress(OSError, ValueError):
742
+ signal.signal(sig, stop)
743
+ server.serve_forever(poll_interval=0.25)
744
+ return 0
745
+
746
+
747
+ if __name__ == "__main__":
748
+ raise SystemExit(main())