@simplexai/localmodels-darwin-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.
- package/bootstrap.identity +1 -1
- package/bootstrap.sha256 +46 -27
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +3 -1
- package/modules/localmodels/catalog.json +306 -1
- package/modules/localmodels/cli_parser.py +4 -0
- package/modules/localmodels/debug_stub_server.py +280 -7
- package/modules/localmodels/download-mirrors.json +76 -0
- package/modules/localmodels/engines-speechcpp-v0.11.3.json +84 -0
- package/modules/localmodels/library_serve.py +46 -26
- package/modules/localmodels/remote_ops_common.py +12 -2
- package/modules/localmodels/sidecar_downloads.py +426 -0
- package/modules/localmodels/sidecar_http.py +396 -0
- package/modules/localmodels/sidecar_state.py +466 -0
- package/modules/localmodels/speech_admission.py +13 -0
- package/modules/localmodels/speech_jobs.py +81 -370
- package/modules/localmodels/speech_server.py +17 -8
- package/modules/localmodels/speech_state.py +87 -454
- package/modules/localmodels/speech_workers.py +41 -163
- package/modules/localmodels/stack.py +18 -0
- package/modules/localmodels/stack_down.py +19 -14
- package/modules/localmodels/stack_ports.py +1 -0
- package/modules/localmodels/stack_up.py +51 -1
- package/modules/localmodels/strata_poly_server.py +140 -3
- package/modules/localmodels/tts-moss.txt +321 -0
- package/modules/localmodels/tts_admission.py +396 -0
- package/modules/localmodels/tts_backend_speechcpp.py +487 -0
- package/modules/localmodels/tts_catalog.py +251 -0
- package/modules/localmodels/tts_cli.py +333 -0
- package/modules/localmodels/tts_http.py +617 -0
- package/modules/localmodels/tts_jobs.py +496 -0
- package/modules/localmodels/tts_model.py +591 -0
- package/modules/localmodels/tts_moss_presets.json +1 -0
- package/modules/localmodels/tts_serve.py +451 -0
- package/modules/localmodels/tts_sidecar.py +750 -0
- package/modules/localmodels/tts_state.py +395 -0
- package/modules/localmodels/tts_worker_kokoro.py +463 -0
- package/modules/localmodels/tts_worker_moss.py +748 -0
- package/modules/localmodels/tts_workers.py +696 -0
- package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/RECORD +43 -24
- package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/licenses/NOTICE +29 -0
- package/package.json +1 -1
- package/tool.json +1 -1
- /package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/entry_points.txt +0 -0
- /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,696 @@
|
|
|
1
|
+
"""Pluggable TTS worker backends, sentence streaming chunker, and child process supervision.
|
|
2
|
+
|
|
3
|
+
Exposes ``TtsBackend`` and ``BACKENDS`` so MR 2 (``moss-tts-nano-100m``) and MR 3
|
|
4
|
+
(``qwen3-tts-*``) register cleanly without modifying ``tts_sidecar.py`` or ``tts_cli.py``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import http.client
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
import time
|
|
16
|
+
import urllib.error
|
|
17
|
+
import urllib.request
|
|
18
|
+
from collections.abc import Callable, Iterator
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Protocol, cast
|
|
22
|
+
|
|
23
|
+
from localmodels import (
|
|
24
|
+
auth_proxy,
|
|
25
|
+
component,
|
|
26
|
+
debug_mode,
|
|
27
|
+
frontend,
|
|
28
|
+
http_local,
|
|
29
|
+
sidecar_downloads,
|
|
30
|
+
sidecar_http,
|
|
31
|
+
tts_admission,
|
|
32
|
+
tts_backend_speechcpp,
|
|
33
|
+
tts_state,
|
|
34
|
+
tts_worker_kokoro,
|
|
35
|
+
tts_worker_moss,
|
|
36
|
+
)
|
|
37
|
+
from localmodels.probe import HostFacts
|
|
38
|
+
from localmodels.records import ReleaseEngine
|
|
39
|
+
from localmodels.sidecar_http import (
|
|
40
|
+
WORKER_READY_TIMEOUT_S,
|
|
41
|
+
WORKER_STOP_GRACE_S,
|
|
42
|
+
ChildWatchdog,
|
|
43
|
+
SidecarWorkerError,
|
|
44
|
+
stop_subprocess,
|
|
45
|
+
wrap_pcm16_wav,
|
|
46
|
+
)
|
|
47
|
+
from localmodels.tts_admission import TtsDeviceDecision
|
|
48
|
+
from localmodels.tts_catalog import TtsEngine, TtsModelSpec
|
|
49
|
+
from localmodels.tts_model import (
|
|
50
|
+
TtsError,
|
|
51
|
+
TtsVoiceInfo,
|
|
52
|
+
)
|
|
53
|
+
from localmodels.tts_model import (
|
|
54
|
+
TtsSynthRequest as TtsSynthRequest,
|
|
55
|
+
)
|
|
56
|
+
from localmodels.tts_model import (
|
|
57
|
+
TtsSynthResult as TtsSynthResult,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
SHERPA_REQUIREMENTS = "speech-sv.txt"
|
|
61
|
+
MOSS_REQUIREMENTS = "tts-moss.txt"
|
|
62
|
+
WORKER_REQUEST_TIMEOUT_S = 180.0
|
|
63
|
+
DEFAULT_STREAM_CHUNK_CHARS = 240
|
|
64
|
+
_STREAM_READ_BYTES = 16384
|
|
65
|
+
_SIM_MODES: dict[str, str] = {
|
|
66
|
+
"kokoro-v1.1-zh": "tts-kokoro",
|
|
67
|
+
"moss-tts-nano-100m": "tts-moss",
|
|
68
|
+
"qwen3-tts-0.6b-customvoice": "tts-qwen3",
|
|
69
|
+
"qwen3-tts-1.7b-customvoice": "tts-qwen3",
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
_SENTENCE_SPLIT_RE = re.compile(r"(?:(?<=[\u3002\uff01\uff1f\uff1b])\s*|(?<=[.!?;\n])\s+)")
|
|
73
|
+
|
|
74
|
+
TtsWorkerError = SidecarWorkerError
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass
|
|
78
|
+
class TtsWorkerHandle:
|
|
79
|
+
"""Live isolated TTS engine child subprocess owned by ``TtsSidecar``."""
|
|
80
|
+
|
|
81
|
+
model_id: str
|
|
82
|
+
engine: TtsEngine
|
|
83
|
+
port: int
|
|
84
|
+
proc: subprocess.Popen[bytes]
|
|
85
|
+
watchdog: ChildWatchdog | None
|
|
86
|
+
stderr_path: Path
|
|
87
|
+
decision: TtsDeviceDecision
|
|
88
|
+
ram_estimate_bytes: int
|
|
89
|
+
vram_estimate_bytes: int
|
|
90
|
+
sample_rate: int = 24000
|
|
91
|
+
|
|
92
|
+
def is_alive(self) -> bool:
|
|
93
|
+
return self.proc.poll() is None
|
|
94
|
+
|
|
95
|
+
def stderr_tail(self, limit: int = 2000) -> str:
|
|
96
|
+
try:
|
|
97
|
+
return self.stderr_path.read_text(encoding="utf-8", errors="replace")[-limit:].strip()
|
|
98
|
+
except OSError:
|
|
99
|
+
return ""
|
|
100
|
+
|
|
101
|
+
def stop(self, grace_s: float = WORKER_STOP_GRACE_S) -> None:
|
|
102
|
+
stop_subprocess(self.proc, self.watchdog, grace_s=grace_s)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
TtsWorkerFactory = Callable[[TtsModelSpec, TtsDeviceDecision, str, Path | None], TtsWorkerHandle]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class TtsBackend(Protocol):
|
|
109
|
+
"""Contract implemented by each pluggable TTS engine backend."""
|
|
110
|
+
|
|
111
|
+
runtime: TtsEngine
|
|
112
|
+
|
|
113
|
+
def resolve_engine(
|
|
114
|
+
self,
|
|
115
|
+
spec: TtsModelSpec,
|
|
116
|
+
base_dir: str,
|
|
117
|
+
*,
|
|
118
|
+
include_gpu: bool,
|
|
119
|
+
facts: HostFacts | None,
|
|
120
|
+
) -> ReleaseEngine | None: ...
|
|
121
|
+
|
|
122
|
+
def build_launch(
|
|
123
|
+
self,
|
|
124
|
+
spec: TtsModelSpec,
|
|
125
|
+
decision: TtsDeviceDecision,
|
|
126
|
+
base_dir: str,
|
|
127
|
+
state_dir: Path | None,
|
|
128
|
+
port: int,
|
|
129
|
+
) -> tuple[list[str], dict[str, str]]: ...
|
|
130
|
+
|
|
131
|
+
def synthesize(self, worker: TtsWorkerHandle, req: TtsSynthRequest) -> TtsSynthResult: ...
|
|
132
|
+
|
|
133
|
+
def synthesize_stream(
|
|
134
|
+
self, worker: TtsWorkerHandle, req: TtsSynthRequest
|
|
135
|
+
) -> Iterator[tuple[bytes, int]]: ...
|
|
136
|
+
|
|
137
|
+
def list_voices(self, worker: TtsWorkerHandle) -> list[TtsVoiceInfo]: ...
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def split_sentences(text: str, *, max_chars: int = DEFAULT_STREAM_CHUNK_CHARS) -> list[str]:
|
|
141
|
+
"""Split text into sentence-sized segments in pure stdlib for streaming PCM synthesis."""
|
|
142
|
+
cleaned = text.strip()
|
|
143
|
+
if not cleaned:
|
|
144
|
+
return []
|
|
145
|
+
raw_parts = [part.strip() for part in _SENTENCE_SPLIT_RE.split(cleaned) if part.strip()]
|
|
146
|
+
segments: list[str] = []
|
|
147
|
+
limit = max(20, max_chars)
|
|
148
|
+
for part in raw_parts:
|
|
149
|
+
remaining = part
|
|
150
|
+
while len(remaining) > limit:
|
|
151
|
+
cut = remaining.rfind(" ", 0, limit + 1)
|
|
152
|
+
if cut < limit // 3:
|
|
153
|
+
for punct in ("\uff0c", ",", "\u3001", ":", "\uff1a"):
|
|
154
|
+
pos = remaining.rfind(punct, 0, limit + 1)
|
|
155
|
+
if pos > cut:
|
|
156
|
+
cut = pos + 1
|
|
157
|
+
if cut <= 0:
|
|
158
|
+
cut = limit
|
|
159
|
+
piece = remaining[:cut].strip()
|
|
160
|
+
if piece:
|
|
161
|
+
segments.append(piece)
|
|
162
|
+
remaining = remaining[cut:].strip()
|
|
163
|
+
if remaining:
|
|
164
|
+
segments.append(remaining)
|
|
165
|
+
return segments
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def ensure_run_dir(state_dir: Path | None) -> Path:
|
|
169
|
+
"""Ensure ``$LOCALMODELS_STATE/tts/run`` exists with private permissions."""
|
|
170
|
+
return tts_state.STORE.ensure_run_dir(state_dir)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _resolve_frontend_python(base_dir: str, requirements: str, label: str) -> str:
|
|
174
|
+
venv = component.front_venv(base_dir, requirements)
|
|
175
|
+
if not frontend.ready(base_dir, requirements):
|
|
176
|
+
try:
|
|
177
|
+
frontend.install(base_dir, requirements)
|
|
178
|
+
except frontend.FrontendError as exc:
|
|
179
|
+
raise TtsWorkerError(f"cannot prepare {label} TTS venv: {exc}") from None
|
|
180
|
+
return component.venv_python(venv)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def resolve_sherpa_python(base_dir: str) -> str:
|
|
184
|
+
"""Ensure the shared hash-locked ``speech-sv.txt`` venv exists and return its python path."""
|
|
185
|
+
return _resolve_frontend_python(base_dir, SHERPA_REQUIREMENTS, "sherpa-onnx")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def resolve_moss_python(base_dir: str) -> str:
|
|
189
|
+
"""Ensure the zero-PyTorch ``tts-moss.txt`` venv exists and return its python path."""
|
|
190
|
+
return _resolve_frontend_python(base_dir, MOSS_REQUIREMENTS, "onnxruntime")
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _worker_argv(
|
|
194
|
+
python_bin: str,
|
|
195
|
+
script: str,
|
|
196
|
+
model_dir: str,
|
|
197
|
+
model_id: str,
|
|
198
|
+
port: int,
|
|
199
|
+
*,
|
|
200
|
+
threads: int | None = None,
|
|
201
|
+
) -> list[str]:
|
|
202
|
+
num_threads = threads if threads is not None else min(4, max(1, os.cpu_count() or 1))
|
|
203
|
+
capped = min(4, max(1, num_threads))
|
|
204
|
+
return [
|
|
205
|
+
python_bin,
|
|
206
|
+
script,
|
|
207
|
+
"--model-dir",
|
|
208
|
+
model_dir,
|
|
209
|
+
"--model-id",
|
|
210
|
+
model_id,
|
|
211
|
+
"--host",
|
|
212
|
+
"127.0.0.1",
|
|
213
|
+
"--port",
|
|
214
|
+
str(port),
|
|
215
|
+
"--threads",
|
|
216
|
+
str(capped),
|
|
217
|
+
]
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def kokoro_argv(
|
|
221
|
+
python_bin: str,
|
|
222
|
+
model_dir: str,
|
|
223
|
+
model_id: str,
|
|
224
|
+
port: int,
|
|
225
|
+
*,
|
|
226
|
+
threads: int | None = None,
|
|
227
|
+
) -> list[str]:
|
|
228
|
+
"""Build isolated ``tts_worker_kokoro.py`` child argv."""
|
|
229
|
+
script = str(Path(tts_worker_kokoro.__file__).resolve())
|
|
230
|
+
return _worker_argv(python_bin, script, model_dir, model_id, port, threads=threads)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def moss_argv(
|
|
234
|
+
python_bin: str,
|
|
235
|
+
model_dir: str,
|
|
236
|
+
model_id: str,
|
|
237
|
+
port: int,
|
|
238
|
+
*,
|
|
239
|
+
threads: int | None = None,
|
|
240
|
+
) -> list[str]:
|
|
241
|
+
"""Build isolated ``tts_worker_moss.py`` child argv."""
|
|
242
|
+
script = str(Path(tts_worker_moss.__file__).resolve())
|
|
243
|
+
return _worker_argv(python_bin, script, model_dir, model_id, port, threads=threads)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def fetch_worker_voices(port: int, *, timeout: float = 5.0) -> list[TtsVoiceInfo]:
|
|
247
|
+
"""Query ``GET /voices`` on a running loopback TTS worker."""
|
|
248
|
+
parsed = sidecar_http.sidecar_request(f"http://127.0.0.1:{port}", "/voices", timeout=timeout)
|
|
249
|
+
if parsed is None or not isinstance(parsed.get("voices"), list):
|
|
250
|
+
raise TtsWorkerError("TTS worker did not return a valid voices list")
|
|
251
|
+
out: list[TtsVoiceInfo] = []
|
|
252
|
+
for item in parsed["voices"]:
|
|
253
|
+
if isinstance(item, dict) and isinstance(item.get("id"), str):
|
|
254
|
+
out.append(
|
|
255
|
+
{
|
|
256
|
+
"id": item["id"],
|
|
257
|
+
"name": str(item.get("name") or item["id"]),
|
|
258
|
+
"language": str(item.get("language") or "auto"),
|
|
259
|
+
"gender": str(item.get("gender") or "unspecified"),
|
|
260
|
+
}
|
|
261
|
+
)
|
|
262
|
+
return out
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _extract_worker_error_message(raw_body: str, fallback: str) -> str:
|
|
266
|
+
try:
|
|
267
|
+
parsed = json.loads(raw_body)
|
|
268
|
+
except ValueError:
|
|
269
|
+
return raw_body.strip() or fallback
|
|
270
|
+
if isinstance(parsed, dict):
|
|
271
|
+
err = parsed.get("error")
|
|
272
|
+
if isinstance(err, dict):
|
|
273
|
+
msg = err.get("message")
|
|
274
|
+
if isinstance(msg, str) and msg.strip():
|
|
275
|
+
return msg.strip()[:500]
|
|
276
|
+
return raw_body.strip() or fallback
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _raise_worker_http_error(status: int, raw_body: bytes) -> None:
|
|
280
|
+
detail = raw_body.decode("utf-8", errors="replace")[:500]
|
|
281
|
+
if 400 <= status < 500:
|
|
282
|
+
msg = _extract_worker_error_message(detail, f"invalid synthesis request (HTTP {status})")
|
|
283
|
+
code = "VOICE_UNKNOWN" if "voice" in msg.lower() else "INVALID_INPUT"
|
|
284
|
+
raise TtsError(code, msg)
|
|
285
|
+
raise TtsWorkerError(f"TTS worker returned HTTP {status}", detail=detail)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _synth_payload_bytes(
|
|
289
|
+
req: TtsSynthRequest,
|
|
290
|
+
*,
|
|
291
|
+
text_override: str | None = None,
|
|
292
|
+
voice_override: str | None = None,
|
|
293
|
+
) -> bytes:
|
|
294
|
+
payload: dict[str, object] = {
|
|
295
|
+
"text": req.text if text_override is None else text_override,
|
|
296
|
+
"voice": req.voice if voice_override is None else voice_override,
|
|
297
|
+
"speed": req.speed,
|
|
298
|
+
}
|
|
299
|
+
if req.instructions:
|
|
300
|
+
payload["instructions"] = req.instructions
|
|
301
|
+
if req.language:
|
|
302
|
+
payload["language"] = req.language
|
|
303
|
+
return json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def call_worker_synthesize(
|
|
307
|
+
port: int,
|
|
308
|
+
req: TtsSynthRequest,
|
|
309
|
+
*,
|
|
310
|
+
text_override: str | None = None,
|
|
311
|
+
voice_override: str | None = None,
|
|
312
|
+
timeout: float = WORKER_REQUEST_TIMEOUT_S,
|
|
313
|
+
) -> tuple[bytes, int, float, str]:
|
|
314
|
+
"""POST ``/synthesize`` to an isolated loopback TTS worker, returning raw PCM16 + metadata."""
|
|
315
|
+
raw_body = _synth_payload_bytes(req, text_override=text_override, voice_override=voice_override)
|
|
316
|
+
request = urllib.request.Request(
|
|
317
|
+
f"http://127.0.0.1:{port}/synthesize",
|
|
318
|
+
data=raw_body,
|
|
319
|
+
headers={"Content-Type": "application/json"},
|
|
320
|
+
method="POST",
|
|
321
|
+
)
|
|
322
|
+
opener = http_local.no_proxy_opener(allow_redirects=False)
|
|
323
|
+
try:
|
|
324
|
+
with opener.open(request, timeout=timeout) as resp:
|
|
325
|
+
pcm_bytes = resp.read()
|
|
326
|
+
rate = int(resp.headers.get("X-Sample-Rate") or "24000")
|
|
327
|
+
duration_hdr = resp.headers.get("X-Audio-Seconds")
|
|
328
|
+
duration = (
|
|
329
|
+
float(duration_hdr)
|
|
330
|
+
if duration_hdr is not None
|
|
331
|
+
else (len(pcm_bytes) / float(2 * max(1, rate)))
|
|
332
|
+
)
|
|
333
|
+
voice = str(resp.headers.get("X-Voice") or voice_override or req.voice)
|
|
334
|
+
return pcm_bytes, rate, duration, voice
|
|
335
|
+
except urllib.error.HTTPError as exc:
|
|
336
|
+
_raise_worker_http_error(int(exc.code), exc.read())
|
|
337
|
+
raise AssertionError("unreachable") from None
|
|
338
|
+
except (urllib.error.URLError, http.client.HTTPException, OSError, ValueError) as exc:
|
|
339
|
+
raise TtsWorkerError(f"TTS worker request failed: {exc}", detail=str(exc)) from None
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def call_worker_synthesize_stream(
|
|
343
|
+
port: int,
|
|
344
|
+
req: TtsSynthRequest,
|
|
345
|
+
*,
|
|
346
|
+
text_override: str | None = None,
|
|
347
|
+
voice_override: str | None = None,
|
|
348
|
+
timeout: float = WORKER_REQUEST_TIMEOUT_S,
|
|
349
|
+
) -> Iterator[tuple[bytes, int]]:
|
|
350
|
+
"""POST ``/synthesize-stream`` to a streaming loopback worker, yielding PCM16 chunks live."""
|
|
351
|
+
raw_body = _synth_payload_bytes(req, text_override=text_override, voice_override=voice_override)
|
|
352
|
+
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=timeout)
|
|
353
|
+
try:
|
|
354
|
+
conn.request(
|
|
355
|
+
"POST",
|
|
356
|
+
"/synthesize-stream",
|
|
357
|
+
body=raw_body,
|
|
358
|
+
headers={"Content-Type": "application/json", "Connection": "close"},
|
|
359
|
+
)
|
|
360
|
+
resp = conn.getresponse()
|
|
361
|
+
if resp.status != 200:
|
|
362
|
+
_raise_worker_http_error(resp.status, resp.read())
|
|
363
|
+
rate = int(resp.getheader("X-Sample-Rate") or str(tts_worker_moss.DEFAULT_SAMPLE_RATE))
|
|
364
|
+
carry = b""
|
|
365
|
+
while True:
|
|
366
|
+
raw_chunk = resp.read1(_STREAM_READ_BYTES)
|
|
367
|
+
if not raw_chunk:
|
|
368
|
+
break
|
|
369
|
+
data = carry + raw_chunk
|
|
370
|
+
if len(data) % 2:
|
|
371
|
+
carry, data = data[-1:], data[:-1]
|
|
372
|
+
else:
|
|
373
|
+
carry = b""
|
|
374
|
+
if data:
|
|
375
|
+
yield data, rate
|
|
376
|
+
except (http.client.HTTPException, OSError, ValueError) as exc:
|
|
377
|
+
raise TtsWorkerError(f"TTS worker stream failed: {exc}", detail=str(exc)) from None
|
|
378
|
+
finally:
|
|
379
|
+
conn.close()
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _moss_segments(text: str, *, max_chars: int = DEFAULT_STREAM_CHUNK_CHARS) -> list[str]:
|
|
383
|
+
"""Keep short utterances whole for coherent prosody; pack longer text within frame caps."""
|
|
384
|
+
cleaned = text.strip()
|
|
385
|
+
if not cleaned:
|
|
386
|
+
return []
|
|
387
|
+
if len(cleaned) <= max_chars:
|
|
388
|
+
return [cleaned]
|
|
389
|
+
packed: list[str] = []
|
|
390
|
+
buf = ""
|
|
391
|
+
for part in split_sentences(cleaned, max_chars=max_chars):
|
|
392
|
+
if not buf:
|
|
393
|
+
buf = part
|
|
394
|
+
elif len(buf) + 1 + len(part) <= max_chars:
|
|
395
|
+
buf = f"{buf} {part}"
|
|
396
|
+
else:
|
|
397
|
+
packed.append(buf)
|
|
398
|
+
buf = part
|
|
399
|
+
if buf:
|
|
400
|
+
packed.append(buf)
|
|
401
|
+
return packed
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def _default_synthesize(worker: TtsWorkerHandle, req: TtsSynthRequest) -> TtsSynthResult:
|
|
405
|
+
pcm_bytes, rate, duration, voice = call_worker_synthesize(worker.port, req)
|
|
406
|
+
if req.response_format == "wav":
|
|
407
|
+
audio = wrap_pcm16_wav(pcm_bytes, rate)
|
|
408
|
+
ctype = "audio/wav"
|
|
409
|
+
else:
|
|
410
|
+
audio = pcm_bytes
|
|
411
|
+
ctype = "audio/pcm"
|
|
412
|
+
return TtsSynthResult(
|
|
413
|
+
audio_bytes=audio,
|
|
414
|
+
content_type=ctype,
|
|
415
|
+
sample_rate=rate,
|
|
416
|
+
duration_seconds=round(duration, 3),
|
|
417
|
+
voice=voice,
|
|
418
|
+
)
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def _default_synthesize_stream(
|
|
422
|
+
worker: TtsWorkerHandle, req: TtsSynthRequest
|
|
423
|
+
) -> Iterator[tuple[bytes, int]]:
|
|
424
|
+
for segment in split_sentences(req.text):
|
|
425
|
+
pcm_bytes, rate, _duration, _voice = call_worker_synthesize(
|
|
426
|
+
worker.port, req, text_override=segment
|
|
427
|
+
)
|
|
428
|
+
if pcm_bytes:
|
|
429
|
+
yield pcm_bytes, rate
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
class SherpaKokoroBackend:
|
|
433
|
+
"""``TtsBackend`` implementation for Kokoro-82M v1.1-zh via ``sherpa-onnx``."""
|
|
434
|
+
|
|
435
|
+
runtime: TtsEngine = "sherpa-onnx"
|
|
436
|
+
|
|
437
|
+
def resolve_engine(
|
|
438
|
+
self,
|
|
439
|
+
spec: TtsModelSpec,
|
|
440
|
+
base_dir: str,
|
|
441
|
+
*,
|
|
442
|
+
include_gpu: bool,
|
|
443
|
+
facts: HostFacts | None,
|
|
444
|
+
) -> ReleaseEngine | None:
|
|
445
|
+
_ = (spec, base_dir, include_gpu, facts)
|
|
446
|
+
return None
|
|
447
|
+
|
|
448
|
+
def build_launch(
|
|
449
|
+
self,
|
|
450
|
+
spec: TtsModelSpec,
|
|
451
|
+
decision: TtsDeviceDecision,
|
|
452
|
+
base_dir: str,
|
|
453
|
+
state_dir: Path | None,
|
|
454
|
+
port: int,
|
|
455
|
+
) -> tuple[list[str], dict[str, str]]:
|
|
456
|
+
_ = (decision, state_dir)
|
|
457
|
+
py_bin = resolve_sherpa_python(base_dir)
|
|
458
|
+
mdir = str(sidecar_downloads.model_dir(base_dir, "tts", spec.id))
|
|
459
|
+
argv = kokoro_argv(py_bin, mdir, spec.id, port)
|
|
460
|
+
env = dict(os.environ)
|
|
461
|
+
env.setdefault("OMP_NUM_THREADS", "1")
|
|
462
|
+
env.setdefault("OPENBLAS_NUM_THREADS", "1")
|
|
463
|
+
env.setdefault("MKL_NUM_THREADS", "1")
|
|
464
|
+
return argv, env
|
|
465
|
+
|
|
466
|
+
def synthesize(self, worker: TtsWorkerHandle, req: TtsSynthRequest) -> TtsSynthResult:
|
|
467
|
+
return _default_synthesize(worker, req)
|
|
468
|
+
|
|
469
|
+
def synthesize_stream(
|
|
470
|
+
self, worker: TtsWorkerHandle, req: TtsSynthRequest
|
|
471
|
+
) -> Iterator[tuple[bytes, int]]:
|
|
472
|
+
return _default_synthesize_stream(worker, req)
|
|
473
|
+
|
|
474
|
+
def list_voices(self, worker: TtsWorkerHandle) -> list[TtsVoiceInfo]:
|
|
475
|
+
return fetch_worker_voices(worker.port)
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
class OnnxMossBackend:
|
|
479
|
+
"""``TtsBackend`` implementation for MOSS-TTS-Nano-100M via zero-PyTorch ONNX Runtime."""
|
|
480
|
+
|
|
481
|
+
runtime: TtsEngine = "onnxruntime"
|
|
482
|
+
|
|
483
|
+
def resolve_engine(
|
|
484
|
+
self,
|
|
485
|
+
spec: TtsModelSpec,
|
|
486
|
+
base_dir: str,
|
|
487
|
+
*,
|
|
488
|
+
include_gpu: bool,
|
|
489
|
+
facts: HostFacts | None,
|
|
490
|
+
) -> ReleaseEngine | None:
|
|
491
|
+
_ = (spec, base_dir, include_gpu, facts)
|
|
492
|
+
return None
|
|
493
|
+
|
|
494
|
+
def build_launch(
|
|
495
|
+
self,
|
|
496
|
+
spec: TtsModelSpec,
|
|
497
|
+
decision: TtsDeviceDecision,
|
|
498
|
+
base_dir: str,
|
|
499
|
+
state_dir: Path | None,
|
|
500
|
+
port: int,
|
|
501
|
+
) -> tuple[list[str], dict[str, str]]:
|
|
502
|
+
_ = (decision, state_dir)
|
|
503
|
+
py_bin = resolve_moss_python(base_dir)
|
|
504
|
+
mdir = str(sidecar_downloads.model_dir(base_dir, "tts", spec.id))
|
|
505
|
+
threads = min(tts_worker_moss.MAX_THREADS, max(1, os.cpu_count() or 1))
|
|
506
|
+
argv = moss_argv(py_bin, mdir, spec.id, port, threads=threads)
|
|
507
|
+
env = dict(os.environ)
|
|
508
|
+
for key in (
|
|
509
|
+
"OMP_NUM_THREADS",
|
|
510
|
+
"OPENBLAS_NUM_THREADS",
|
|
511
|
+
"MKL_NUM_THREADS",
|
|
512
|
+
"NUMEXPR_NUM_THREADS",
|
|
513
|
+
):
|
|
514
|
+
env[key] = str(threads)
|
|
515
|
+
return argv, env
|
|
516
|
+
|
|
517
|
+
def synthesize(self, worker: TtsWorkerHandle, req: TtsSynthRequest) -> TtsSynthResult:
|
|
518
|
+
try:
|
|
519
|
+
canonical = tts_worker_moss.resolve_voice(req.voice)
|
|
520
|
+
except ValueError as exc:
|
|
521
|
+
raise TtsError("VOICE_UNKNOWN", str(exc)) from None
|
|
522
|
+
segments = _moss_segments(req.text)
|
|
523
|
+
pcm_parts: list[bytes] = []
|
|
524
|
+
rate = worker.sample_rate
|
|
525
|
+
total_duration = 0.0
|
|
526
|
+
for segment in segments:
|
|
527
|
+
pcm, seg_rate, seg_dur, _voice = call_worker_synthesize(
|
|
528
|
+
worker.port, req, text_override=segment, voice_override=canonical
|
|
529
|
+
)
|
|
530
|
+
pcm_parts.append(pcm)
|
|
531
|
+
rate = seg_rate
|
|
532
|
+
total_duration += seg_dur
|
|
533
|
+
pcm_bytes = b"".join(pcm_parts)
|
|
534
|
+
audio = wrap_pcm16_wav(pcm_bytes, rate) if req.response_format == "wav" else pcm_bytes
|
|
535
|
+
ctype = "audio/wav" if req.response_format == "wav" else "audio/pcm"
|
|
536
|
+
return TtsSynthResult(
|
|
537
|
+
audio_bytes=audio,
|
|
538
|
+
content_type=ctype,
|
|
539
|
+
sample_rate=rate,
|
|
540
|
+
duration_seconds=round(total_duration, 3),
|
|
541
|
+
voice=canonical,
|
|
542
|
+
)
|
|
543
|
+
|
|
544
|
+
def synthesize_stream(
|
|
545
|
+
self, worker: TtsWorkerHandle, req: TtsSynthRequest
|
|
546
|
+
) -> Iterator[tuple[bytes, int]]:
|
|
547
|
+
try:
|
|
548
|
+
canonical = tts_worker_moss.resolve_voice(req.voice)
|
|
549
|
+
except ValueError as exc:
|
|
550
|
+
raise TtsError("VOICE_UNKNOWN", str(exc)) from None
|
|
551
|
+
segments = _moss_segments(req.text)
|
|
552
|
+
|
|
553
|
+
def _stream() -> Iterator[tuple[bytes, int]]:
|
|
554
|
+
for segment in segments:
|
|
555
|
+
yield from call_worker_synthesize_stream(
|
|
556
|
+
worker.port, req, text_override=segment, voice_override=canonical
|
|
557
|
+
)
|
|
558
|
+
|
|
559
|
+
return _stream()
|
|
560
|
+
|
|
561
|
+
def list_voices(self, worker: TtsWorkerHandle) -> list[TtsVoiceInfo]:
|
|
562
|
+
return fetch_worker_voices(worker.port)
|
|
563
|
+
|
|
564
|
+
|
|
565
|
+
BACKENDS: dict[TtsEngine, TtsBackend] = {}
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def register_backend(backend: TtsBackend) -> None:
|
|
569
|
+
"""Register a pluggable ``TtsBackend`` implementation by its runtime key."""
|
|
570
|
+
BACKENDS[backend.runtime] = backend
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def get_backend(engine: TtsEngine) -> TtsBackend:
|
|
574
|
+
"""Return the registered ``TtsBackend`` for ``engine``, or raise ``TtsWorkerError``."""
|
|
575
|
+
backend = BACKENDS.get(engine)
|
|
576
|
+
if backend is None:
|
|
577
|
+
raise TtsWorkerError(f"no TTS backend registered for engine {engine!r}")
|
|
578
|
+
return backend
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
register_backend(SherpaKokoroBackend())
|
|
582
|
+
register_backend(OnnxMossBackend())
|
|
583
|
+
register_backend(tts_backend_speechcpp.SpeechCppBackend())
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def _launch_worker(
|
|
587
|
+
spec: TtsModelSpec,
|
|
588
|
+
decision: TtsDeviceDecision,
|
|
589
|
+
argv: list[str],
|
|
590
|
+
env: dict[str, str],
|
|
591
|
+
port: int,
|
|
592
|
+
state_dir: Path | None,
|
|
593
|
+
) -> TtsWorkerHandle:
|
|
594
|
+
run_cwd = ensure_run_dir(state_dir)
|
|
595
|
+
stderr_path = run_cwd / f"worker-{spec.id}-{port}.stderr.log"
|
|
596
|
+
proc, watchdog = sidecar_http.launch_worker_subprocess(
|
|
597
|
+
argv,
|
|
598
|
+
env,
|
|
599
|
+
run_cwd,
|
|
600
|
+
stderr_path,
|
|
601
|
+
port,
|
|
602
|
+
spec.engine,
|
|
603
|
+
timeout_s=WORKER_READY_TIMEOUT_S,
|
|
604
|
+
)
|
|
605
|
+
return TtsWorkerHandle(
|
|
606
|
+
model_id=spec.id,
|
|
607
|
+
engine=spec.engine,
|
|
608
|
+
port=port,
|
|
609
|
+
proc=proc,
|
|
610
|
+
watchdog=watchdog,
|
|
611
|
+
stderr_path=stderr_path,
|
|
612
|
+
decision=decision,
|
|
613
|
+
sample_rate=spec.sample_rate,
|
|
614
|
+
ram_estimate_bytes=spec.ram_estimate_bytes,
|
|
615
|
+
vram_estimate_bytes=spec.vram_estimate_bytes,
|
|
616
|
+
)
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def decide_simulated_device(
|
|
620
|
+
spec: TtsModelSpec,
|
|
621
|
+
use_gpu: bool,
|
|
622
|
+
facts: HostFacts | None = None,
|
|
623
|
+
) -> TtsDeviceDecision:
|
|
624
|
+
"""Deterministic TTS device admission for ``LOCALMODELS_DEBUG=simulate``."""
|
|
625
|
+
host = (
|
|
626
|
+
facts
|
|
627
|
+
if facts is not None
|
|
628
|
+
else cast(HostFacts, debug_mode.simulated_facts(debug_mode.current()))
|
|
629
|
+
)
|
|
630
|
+
return tts_admission.decide_tts_device(spec, use_gpu, host, require_engine_build=False)
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
def spawn_simulated_worker(
|
|
634
|
+
spec: TtsModelSpec,
|
|
635
|
+
decision: TtsDeviceDecision,
|
|
636
|
+
base_dir: str,
|
|
637
|
+
state_dir: Path | None,
|
|
638
|
+
) -> TtsWorkerHandle:
|
|
639
|
+
"""Launch ``debug_stub_server`` as a deterministic TTS worker in simulate mode."""
|
|
640
|
+
cfg = debug_mode.current()
|
|
641
|
+
if cfg.load_ms > 0:
|
|
642
|
+
time.sleep(min(cfg.load_ms, 5000) / 1000.0)
|
|
643
|
+
if fail_reason := cfg.fail.get("load"):
|
|
644
|
+
raise TtsWorkerError(
|
|
645
|
+
f"simulated TTS load failure: {fail_reason}",
|
|
646
|
+
detail=fail_reason,
|
|
647
|
+
exit_status=1,
|
|
648
|
+
)
|
|
649
|
+
if not sidecar_downloads.weights_installed(spec, base_dir, "tts"):
|
|
650
|
+
raise TtsError(
|
|
651
|
+
"INVALID_STATE",
|
|
652
|
+
f"tts model {spec.id} is not downloaded; run `localmodels tts download {spec.id}`",
|
|
653
|
+
)
|
|
654
|
+
port = auth_proxy.free_port()
|
|
655
|
+
stub_mode = _SIM_MODES.get(
|
|
656
|
+
spec.id, "tts-qwen3" if spec.engine == "speech.cpp" else f"tts-{spec.engine}"
|
|
657
|
+
)
|
|
658
|
+
argv = [
|
|
659
|
+
sys.executable,
|
|
660
|
+
"-P",
|
|
661
|
+
"-s",
|
|
662
|
+
"-m",
|
|
663
|
+
"localmodels.debug_stub_server",
|
|
664
|
+
"--bind",
|
|
665
|
+
"127.0.0.1",
|
|
666
|
+
"--port",
|
|
667
|
+
str(port),
|
|
668
|
+
"--model",
|
|
669
|
+
spec.id,
|
|
670
|
+
"--mode",
|
|
671
|
+
stub_mode,
|
|
672
|
+
]
|
|
673
|
+
env = dict(os.environ)
|
|
674
|
+
pkg_root = str(Path(__file__).resolve().parents[1])
|
|
675
|
+
cur_pp = env.get("PYTHONPATH", "")
|
|
676
|
+
if pkg_root not in cur_pp.split(os.pathsep):
|
|
677
|
+
env["PYTHONPATH"] = pkg_root if not cur_pp else pkg_root + os.pathsep + cur_pp
|
|
678
|
+
return _launch_worker(spec, decision, argv, env, port, state_dir)
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
def spawn_real_worker(
|
|
682
|
+
spec: TtsModelSpec,
|
|
683
|
+
decision: TtsDeviceDecision,
|
|
684
|
+
base_dir: str,
|
|
685
|
+
state_dir: Path | None,
|
|
686
|
+
) -> TtsWorkerHandle:
|
|
687
|
+
"""Spawn the registered backend child worker for ``spec``."""
|
|
688
|
+
if not sidecar_downloads.weights_installed(spec, base_dir, "tts"):
|
|
689
|
+
raise TtsError(
|
|
690
|
+
"INVALID_STATE",
|
|
691
|
+
f"tts model {spec.id} is not downloaded; run `localmodels tts download {spec.id}`",
|
|
692
|
+
)
|
|
693
|
+
backend = get_backend(spec.engine)
|
|
694
|
+
port = auth_proxy.free_port()
|
|
695
|
+
argv, env = backend.build_launch(spec, decision, base_dir, state_dir, port)
|
|
696
|
+
return _launch_worker(spec, decision, argv, env, port, state_dir)
|