@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,617 @@
|
|
|
1
|
+
"""Authenticated loopback HTTP server handler for the standby-first TTS sidecar.
|
|
2
|
+
|
|
3
|
+
Separated from ``localmodels/tts_sidecar.py`` so controller residency logic and HTTP transport
|
|
4
|
+
stay compact, low-complexity, and independently testable.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import contextlib
|
|
11
|
+
import hmac
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import signal
|
|
15
|
+
import threading
|
|
16
|
+
import time
|
|
17
|
+
import urllib.parse
|
|
18
|
+
from collections.abc import Callable, Iterator
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from http import HTTPStatus
|
|
21
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any, Literal, Protocol
|
|
24
|
+
|
|
25
|
+
from localmodels import process_identity, sidecar_http, tts_catalog, tts_state
|
|
26
|
+
from localmodels.tts_admission import TtsDeviceDecision
|
|
27
|
+
from localmodels.tts_model import (
|
|
28
|
+
DETAIL_LIMIT,
|
|
29
|
+
MAX_REQUEST_BYTES,
|
|
30
|
+
EffectiveDevice,
|
|
31
|
+
FallbackReason,
|
|
32
|
+
RequestedDevice,
|
|
33
|
+
TtsConfig,
|
|
34
|
+
TtsError,
|
|
35
|
+
TtsModelError,
|
|
36
|
+
TtsRuntime,
|
|
37
|
+
TtsRuntimeState,
|
|
38
|
+
TtsVoiceInfo,
|
|
39
|
+
validate_input_text,
|
|
40
|
+
validate_language,
|
|
41
|
+
validate_response_format,
|
|
42
|
+
validate_speed,
|
|
43
|
+
validate_voice_id,
|
|
44
|
+
)
|
|
45
|
+
from localmodels.tts_workers import TtsSynthRequest, TtsSynthResult, TtsWorkerError
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class _PayloadTooLargeError(TtsError):
|
|
49
|
+
"""Internal marker mapping oversized HTTP bodies to 413 Payload Too Large."""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True)
|
|
53
|
+
class CrashStreak:
|
|
54
|
+
"""Bounded consecutive crash counter for one ``(model_id, requested_device)`` target."""
|
|
55
|
+
|
|
56
|
+
target: tuple[str, str]
|
|
57
|
+
exit_status: int
|
|
58
|
+
count: int
|
|
59
|
+
first_at: float
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def next_crash_streak(
|
|
63
|
+
prev: CrashStreak | None,
|
|
64
|
+
target: tuple[str, str],
|
|
65
|
+
exit_status: int,
|
|
66
|
+
now: float,
|
|
67
|
+
*,
|
|
68
|
+
window_s: float,
|
|
69
|
+
latch_count: int,
|
|
70
|
+
tail: str,
|
|
71
|
+
exc_text: str,
|
|
72
|
+
) -> tuple[CrashStreak, bool, str]:
|
|
73
|
+
"""Advance ``CrashStreak`` and report ``(streak, latched, bounded_message)``."""
|
|
74
|
+
same = (
|
|
75
|
+
prev is not None
|
|
76
|
+
and prev.target == target
|
|
77
|
+
and prev.exit_status == exit_status
|
|
78
|
+
and now - prev.first_at <= window_s
|
|
79
|
+
)
|
|
80
|
+
count, first_at = (prev.count + 1, prev.first_at) if same and prev is not None else (1, now)
|
|
81
|
+
streak = CrashStreak(target, exit_status, count, first_at)
|
|
82
|
+
latched = count >= latch_count
|
|
83
|
+
if latched:
|
|
84
|
+
msg = (
|
|
85
|
+
f"{target[0]} crashed {count} times in a row (exit {exit_status}); "
|
|
86
|
+
f"stopped retrying: {tail or exc_text}"
|
|
87
|
+
)
|
|
88
|
+
else:
|
|
89
|
+
msg = f"{target[0]}: {exc_text}" + (f": {tail}" if tail and tail != exc_text else "")
|
|
90
|
+
return streak, latched, msg[-DETAIL_LIMIT:]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def cpu_fallback_decision(
|
|
94
|
+
requested: RequestedDevice, reason: FallbackReason, detail: dict[str, object]
|
|
95
|
+
) -> TtsDeviceDecision:
|
|
96
|
+
"""Build a CPU fallback ``TtsDeviceDecision`` with structured reason and detail."""
|
|
97
|
+
return TtsDeviceDecision(
|
|
98
|
+
requested_device=requested,
|
|
99
|
+
effective_device="cpu",
|
|
100
|
+
fallback_reason=reason,
|
|
101
|
+
fallback_detail=detail,
|
|
102
|
+
pool="system",
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def wait_until(
|
|
107
|
+
cond: threading.Condition, done: Callable[[], bool], timeout_s: float | None = None
|
|
108
|
+
) -> bool:
|
|
109
|
+
"""Wait on ``cond`` until ``done()`` is truthy or ``timeout_s`` elapses."""
|
|
110
|
+
deadline = None if timeout_s is None else (time.monotonic() + timeout_s)
|
|
111
|
+
while not done():
|
|
112
|
+
if deadline is None:
|
|
113
|
+
cond.wait()
|
|
114
|
+
continue
|
|
115
|
+
rem = deadline - time.monotonic()
|
|
116
|
+
if rem <= 0:
|
|
117
|
+
return False
|
|
118
|
+
cond.wait(timeout=rem)
|
|
119
|
+
return True
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class StreamSession:
|
|
123
|
+
"""Iterator wrapper guaranteeing ``on_close`` runs once on finish, error, or early close."""
|
|
124
|
+
|
|
125
|
+
def __init__(
|
|
126
|
+
self,
|
|
127
|
+
first_chunk: bytes,
|
|
128
|
+
rest: Iterator[tuple[bytes, int]],
|
|
129
|
+
on_error: Callable[[TtsWorkerError], None],
|
|
130
|
+
on_close: Callable[[], None],
|
|
131
|
+
) -> None:
|
|
132
|
+
self._first: bytes | None = first_chunk
|
|
133
|
+
self._rest = rest
|
|
134
|
+
self._on_error = on_error
|
|
135
|
+
self._on_close = on_close
|
|
136
|
+
self._closed = False
|
|
137
|
+
|
|
138
|
+
def __iter__(self) -> StreamSession:
|
|
139
|
+
return self
|
|
140
|
+
|
|
141
|
+
def __next__(self) -> bytes:
|
|
142
|
+
if self._closed:
|
|
143
|
+
raise StopIteration
|
|
144
|
+
if self._first is not None:
|
|
145
|
+
chunk = self._first
|
|
146
|
+
self._first = None
|
|
147
|
+
return chunk
|
|
148
|
+
try:
|
|
149
|
+
for pcm_chunk, _rate in self._rest:
|
|
150
|
+
if pcm_chunk:
|
|
151
|
+
return pcm_chunk
|
|
152
|
+
except TtsWorkerError as exc:
|
|
153
|
+
try:
|
|
154
|
+
self._on_error(exc)
|
|
155
|
+
finally:
|
|
156
|
+
self.close()
|
|
157
|
+
raise
|
|
158
|
+
except Exception:
|
|
159
|
+
self.close()
|
|
160
|
+
raise
|
|
161
|
+
self.close()
|
|
162
|
+
raise StopIteration
|
|
163
|
+
|
|
164
|
+
def close(self) -> None:
|
|
165
|
+
if self._closed:
|
|
166
|
+
return
|
|
167
|
+
self._closed = True
|
|
168
|
+
close_fn = getattr(self._rest, "close", None)
|
|
169
|
+
if callable(close_fn):
|
|
170
|
+
with contextlib.suppress(Exception):
|
|
171
|
+
close_fn()
|
|
172
|
+
self._on_close()
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class TtsController(Protocol):
|
|
176
|
+
"""Runtime controller interface served by ``make_handler``."""
|
|
177
|
+
|
|
178
|
+
state_dir: Path | None
|
|
179
|
+
base_url: str
|
|
180
|
+
|
|
181
|
+
def health_payload(self) -> dict[str, object]: ...
|
|
182
|
+
|
|
183
|
+
def runtime_payload(self) -> TtsRuntime: ...
|
|
184
|
+
|
|
185
|
+
def persist_runtime(self) -> None: ...
|
|
186
|
+
|
|
187
|
+
def start_sweeper(self) -> None: ...
|
|
188
|
+
|
|
189
|
+
def shutdown(self) -> None: ...
|
|
190
|
+
|
|
191
|
+
def voices(
|
|
192
|
+
self, model_id: str | None = None
|
|
193
|
+
) -> tuple[str, Literal["worker", "catalog"], list[TtsVoiceInfo]]: ...
|
|
194
|
+
|
|
195
|
+
def apply_config(self, raw_update: dict[str, object]) -> TtsRuntime: ...
|
|
196
|
+
|
|
197
|
+
def load_model(
|
|
198
|
+
self, model_id: str | None = None, *, use_gpu: bool | None = None
|
|
199
|
+
) -> TtsRuntime: ...
|
|
200
|
+
|
|
201
|
+
def unload(self) -> TtsRuntime: ...
|
|
202
|
+
|
|
203
|
+
def demote_to_cpu(
|
|
204
|
+
self,
|
|
205
|
+
*,
|
|
206
|
+
reason: FallbackReason = "yielded_to_llm",
|
|
207
|
+
pool: str | None = None,
|
|
208
|
+
) -> TtsRuntime: ...
|
|
209
|
+
|
|
210
|
+
def synthesize(
|
|
211
|
+
self, req: TtsSynthRequest, *, model_id: str | None = None
|
|
212
|
+
) -> tuple[TtsSynthResult, str, EffectiveDevice, FallbackReason | None]: ...
|
|
213
|
+
|
|
214
|
+
def synthesize_stream(
|
|
215
|
+
self, req: TtsSynthRequest, *, model_id: str | None = None
|
|
216
|
+
) -> tuple[str, EffectiveDevice, FallbackReason | None, int, Iterator[bytes]]: ...
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _optional_str(payload: dict[str, object], key: str) -> str | None:
|
|
220
|
+
raw = payload.get(key)
|
|
221
|
+
if raw is None:
|
|
222
|
+
return None
|
|
223
|
+
if not isinstance(raw, str):
|
|
224
|
+
raise TtsError("INVALID_INPUT", f"{key} must be a string")
|
|
225
|
+
cleaned = raw.strip()
|
|
226
|
+
return cleaned or None
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def parse_speech_request(raw: bytes, cfg: TtsConfig) -> tuple[str | None, TtsSynthRequest]:
|
|
230
|
+
"""Validate an OpenAI-compatible ``POST /v1/audio/speech`` JSON body."""
|
|
231
|
+
try:
|
|
232
|
+
payload = json.loads(raw.decode("utf-8") if raw else "{}")
|
|
233
|
+
except (UnicodeDecodeError, ValueError) as exc:
|
|
234
|
+
raise TtsError("INVALID_INPUT", f"invalid JSON body: {exc}") from None
|
|
235
|
+
if not isinstance(payload, dict):
|
|
236
|
+
raise TtsError("INVALID_INPUT", "request body must be a JSON object")
|
|
237
|
+
text = validate_input_text(payload.get("input", ""))
|
|
238
|
+
model_id = _optional_str(payload, "model")
|
|
239
|
+
voice_str = _optional_str(payload, "voice")
|
|
240
|
+
if voice_str is not None:
|
|
241
|
+
voice = validate_voice_id(voice_str)
|
|
242
|
+
elif model_id is not None and model_id != cfg["model_id"]:
|
|
243
|
+
try:
|
|
244
|
+
voice = tts_catalog.tts_model(model_id).default_voice
|
|
245
|
+
except KeyError:
|
|
246
|
+
voice = cfg["voice"]
|
|
247
|
+
else:
|
|
248
|
+
voice = cfg["voice"]
|
|
249
|
+
speed = validate_speed(payload.get("speed", cfg["speed"]))
|
|
250
|
+
fmt_raw = payload.get("response_format", cfg["response_format"])
|
|
251
|
+
if not isinstance(fmt_raw, str):
|
|
252
|
+
raise TtsError("INVALID_INPUT", "response_format must be 'wav' or 'pcm'")
|
|
253
|
+
response_format = validate_response_format(fmt_raw)
|
|
254
|
+
stream_raw = payload.get("stream", False)
|
|
255
|
+
if not isinstance(stream_raw, bool):
|
|
256
|
+
raise TtsError("INVALID_INPUT", "stream must be a boolean")
|
|
257
|
+
if stream_raw and response_format != "pcm":
|
|
258
|
+
raise TtsError("INVALID_INPUT", "stream=true requires response_format='pcm'")
|
|
259
|
+
instructions = _optional_str(payload, "instructions")
|
|
260
|
+
lang_str = _optional_str(payload, "language")
|
|
261
|
+
language = validate_language(lang_str) if lang_str is not None else cfg["language"]
|
|
262
|
+
return model_id, TtsSynthRequest(
|
|
263
|
+
text=text,
|
|
264
|
+
voice=voice,
|
|
265
|
+
speed=speed,
|
|
266
|
+
response_format=response_format,
|
|
267
|
+
stream=stream_raw,
|
|
268
|
+
instructions=instructions,
|
|
269
|
+
language=language,
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _read_body(handler: BaseHTTPRequestHandler, limit: int = MAX_REQUEST_BYTES) -> bytes:
|
|
274
|
+
try:
|
|
275
|
+
length = int(handler.headers.get("Content-Length") or "0")
|
|
276
|
+
except ValueError:
|
|
277
|
+
raise TtsError("INVALID_INPUT", "invalid Content-Length header") from None
|
|
278
|
+
if length < 0:
|
|
279
|
+
raise TtsError("INVALID_INPUT", "invalid Content-Length header")
|
|
280
|
+
if length > limit:
|
|
281
|
+
raise _PayloadTooLargeError("INVALID_INPUT", f"request body exceeds {limit} byte limit")
|
|
282
|
+
return handler.rfile.read(length) if length > 0 else b""
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _send_error(
|
|
286
|
+
handler: BaseHTTPRequestHandler, status: HTTPStatus, code: str, message: str
|
|
287
|
+
) -> None:
|
|
288
|
+
sidecar_http.send_json_response(handler, status, {"error": {"code": code, "message": message}})
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _parse_json_obj(handler: BaseHTTPRequestHandler) -> dict[str, object]:
|
|
292
|
+
raw = _read_body(handler)
|
|
293
|
+
if not raw:
|
|
294
|
+
return {}
|
|
295
|
+
try:
|
|
296
|
+
parsed = json.loads(raw.decode("utf-8"))
|
|
297
|
+
except (UnicodeDecodeError, ValueError):
|
|
298
|
+
raise TtsError("INVALID_INPUT", "invalid JSON payload") from None
|
|
299
|
+
if not isinstance(parsed, dict):
|
|
300
|
+
raise TtsError("INVALID_INPUT", "JSON object required")
|
|
301
|
+
return parsed
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def close_stream(chunks: object) -> None:
|
|
305
|
+
"""Close an iterator/generator quietly if it exposes ``close()``."""
|
|
306
|
+
close_fn = getattr(chunks, "close", None)
|
|
307
|
+
if callable(close_fn):
|
|
308
|
+
with contextlib.suppress(Exception):
|
|
309
|
+
close_fn()
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def build_runtime_payload(
|
|
313
|
+
*,
|
|
314
|
+
state: TtsRuntimeState,
|
|
315
|
+
base_url: str,
|
|
316
|
+
key_file: Path,
|
|
317
|
+
config: TtsConfig,
|
|
318
|
+
meta: tuple[str | None, str | None, TtsDeviceDecision | None, int, int],
|
|
319
|
+
last_fallback: tuple[FallbackReason | None, dict[str, object] | None],
|
|
320
|
+
idle_remaining: int | None,
|
|
321
|
+
active_sessions: int,
|
|
322
|
+
last_error: TtsModelError | None,
|
|
323
|
+
) -> TtsRuntime:
|
|
324
|
+
"""Assemble the ``TtsRuntime`` payload returned by ``/v1/tts/status`` and ``runtime.json``."""
|
|
325
|
+
model_id, engine, decision, vram_bytes, ram_bytes = meta
|
|
326
|
+
last_fb_reason, last_fb_detail = last_fallback
|
|
327
|
+
req_dev: RequestedDevice = (
|
|
328
|
+
decision.requested_device
|
|
329
|
+
if decision is not None
|
|
330
|
+
else ("gpu" if config["use_gpu"] else "cpu")
|
|
331
|
+
)
|
|
332
|
+
fb_reason = decision.fallback_reason if decision is not None else last_fb_reason
|
|
333
|
+
raw_detail = decision.fallback_detail if decision is not None else last_fb_detail
|
|
334
|
+
err: TtsModelError | None = (
|
|
335
|
+
{"code": last_error["code"], "message": last_error["message"]}
|
|
336
|
+
if state == "error" and last_error is not None
|
|
337
|
+
else None
|
|
338
|
+
)
|
|
339
|
+
return {
|
|
340
|
+
"running": True,
|
|
341
|
+
"state": state,
|
|
342
|
+
"base_url": base_url,
|
|
343
|
+
"key_file": str(key_file),
|
|
344
|
+
"active_model": model_id,
|
|
345
|
+
"engine": engine,
|
|
346
|
+
"default_voice": config["voice"],
|
|
347
|
+
"requested_device": req_dev,
|
|
348
|
+
"effective_device": decision.effective_device if decision is not None else None,
|
|
349
|
+
"fallback_reason": fb_reason,
|
|
350
|
+
"fallback_detail": dict(raw_detail) if raw_detail else None,
|
|
351
|
+
"vram_used_bytes": vram_bytes,
|
|
352
|
+
"ram_used_bytes": ram_bytes,
|
|
353
|
+
"keep_loaded_seconds": config["keep_loaded_seconds"],
|
|
354
|
+
"idle_remaining_seconds": idle_remaining,
|
|
355
|
+
"active_sessions": active_sessions,
|
|
356
|
+
"error": err,
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _write_stream_response(
|
|
361
|
+
handler: BaseHTTPRequestHandler,
|
|
362
|
+
controller: TtsController,
|
|
363
|
+
req: TtsSynthRequest,
|
|
364
|
+
model_id: str | None,
|
|
365
|
+
) -> None:
|
|
366
|
+
mid, eff, fb, rate, chunks = controller.synthesize_stream(req, model_id=model_id)
|
|
367
|
+
try:
|
|
368
|
+
try:
|
|
369
|
+
handler.send_response(HTTPStatus.OK)
|
|
370
|
+
handler.send_header("Content-Type", "audio/pcm")
|
|
371
|
+
handler.send_header("Transfer-Encoding", "chunked")
|
|
372
|
+
handler.send_header("X-Audio-Sample-Rate", str(rate))
|
|
373
|
+
handler.send_header("X-Audio-Channels", "1")
|
|
374
|
+
handler.send_header("X-Audio-Bit-Depth", "16")
|
|
375
|
+
handler.send_header("X-TTS-Model", mid)
|
|
376
|
+
canonical_voice = tts_catalog.resolve_catalog_voice(mid, req.voice) or req.voice
|
|
377
|
+
handler.send_header("X-TTS-Voice", canonical_voice)
|
|
378
|
+
handler.send_header("X-TTS-Effective-Device", eff)
|
|
379
|
+
handler.send_header("X-TTS-Fallback-Reason", fb or "")
|
|
380
|
+
handler.send_header("Connection", "close")
|
|
381
|
+
handler.end_headers()
|
|
382
|
+
for chunk in chunks:
|
|
383
|
+
handler.wfile.write(f"{len(chunk):x}\r\n".encode("ascii"))
|
|
384
|
+
handler.wfile.write(chunk)
|
|
385
|
+
handler.wfile.write(b"\r\n")
|
|
386
|
+
handler.wfile.flush()
|
|
387
|
+
handler.wfile.write(b"0\r\n\r\n")
|
|
388
|
+
handler.wfile.flush()
|
|
389
|
+
except (TtsError, TtsWorkerError, OSError):
|
|
390
|
+
handler.close_connection = True
|
|
391
|
+
finally:
|
|
392
|
+
close_stream(chunks)
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _handle_speech_post(handler: BaseHTTPRequestHandler, controller: TtsController) -> None:
|
|
396
|
+
raw = _read_body(handler)
|
|
397
|
+
model_id, req = parse_speech_request(raw, tts_state.load_config(controller.state_dir))
|
|
398
|
+
if req.stream:
|
|
399
|
+
_write_stream_response(handler, controller, req, model_id)
|
|
400
|
+
return
|
|
401
|
+
result, mid, eff, fb = controller.synthesize(req, model_id=model_id)
|
|
402
|
+
sidecar_http.send_binary_response(
|
|
403
|
+
handler,
|
|
404
|
+
HTTPStatus.OK,
|
|
405
|
+
result.audio_bytes,
|
|
406
|
+
content_type=result.content_type,
|
|
407
|
+
extra_headers={
|
|
408
|
+
"X-Audio-Seconds": f"{result.duration_seconds:.3f}",
|
|
409
|
+
"X-Audio-Sample-Rate": str(result.sample_rate),
|
|
410
|
+
"X-TTS-Model": mid,
|
|
411
|
+
"X-TTS-Voice": result.voice,
|
|
412
|
+
"X-TTS-Effective-Device": eff,
|
|
413
|
+
"X-TTS-Fallback-Reason": fb or "",
|
|
414
|
+
},
|
|
415
|
+
)
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def _handle_control_post(
|
|
419
|
+
handler: BaseHTTPRequestHandler,
|
|
420
|
+
controller: TtsController,
|
|
421
|
+
path: str,
|
|
422
|
+
on_shutdown: Callable[[], None] | None,
|
|
423
|
+
) -> None:
|
|
424
|
+
if path == "/v1/tts/unload":
|
|
425
|
+
sidecar_http.send_json_response(handler, HTTPStatus.OK, dict(controller.unload()))
|
|
426
|
+
return
|
|
427
|
+
if path == "/v1/tts/shutdown":
|
|
428
|
+
sidecar_http.send_json_response(handler, HTTPStatus.OK, {"ok": True, "state": "stopped"})
|
|
429
|
+
if on_shutdown is not None:
|
|
430
|
+
threading.Thread(target=on_shutdown, daemon=True).start()
|
|
431
|
+
return
|
|
432
|
+
payload = _parse_json_obj(handler)
|
|
433
|
+
if path == "/v1/tts/config":
|
|
434
|
+
sidecar_http.send_json_response(
|
|
435
|
+
handler, HTTPStatus.OK, dict(controller.apply_config(payload))
|
|
436
|
+
)
|
|
437
|
+
return
|
|
438
|
+
if path == "/v1/tts/load":
|
|
439
|
+
mid = payload.get("model_id")
|
|
440
|
+
use_gpu = payload.get("use_gpu")
|
|
441
|
+
rt = controller.load_model(
|
|
442
|
+
mid if isinstance(mid, str) and mid else None,
|
|
443
|
+
use_gpu=use_gpu if isinstance(use_gpu, bool) else None,
|
|
444
|
+
)
|
|
445
|
+
sidecar_http.send_json_response(handler, HTTPStatus.OK, dict(rt))
|
|
446
|
+
return
|
|
447
|
+
if path == "/v1/tts/demote-to-cpu":
|
|
448
|
+
reason: FallbackReason = (
|
|
449
|
+
"yielded_to_stt" if payload.get("reason") == "yielded_to_stt" else "yielded_to_llm"
|
|
450
|
+
)
|
|
451
|
+
pool = payload.get("pool")
|
|
452
|
+
rt = controller.demote_to_cpu(
|
|
453
|
+
reason=reason, pool=pool if isinstance(pool, str) and pool else None
|
|
454
|
+
)
|
|
455
|
+
sidecar_http.send_json_response(handler, HTTPStatus.OK, dict(rt))
|
|
456
|
+
return
|
|
457
|
+
_send_error(handler, HTTPStatus.NOT_FOUND, "INVALID_STATE", "not found")
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def _dispatch_post(
|
|
461
|
+
handler: BaseHTTPRequestHandler,
|
|
462
|
+
controller: TtsController,
|
|
463
|
+
path: str,
|
|
464
|
+
on_shutdown: Callable[[], None] | None,
|
|
465
|
+
) -> None:
|
|
466
|
+
try:
|
|
467
|
+
if path == "/v1/audio/speech":
|
|
468
|
+
_handle_speech_post(handler, controller)
|
|
469
|
+
else:
|
|
470
|
+
_handle_control_post(handler, controller, path, on_shutdown)
|
|
471
|
+
except _PayloadTooLargeError as exc:
|
|
472
|
+
_send_error(handler, HTTPStatus.REQUEST_ENTITY_TOO_LARGE, exc.code, exc.message)
|
|
473
|
+
except TtsError as exc:
|
|
474
|
+
status = HTTPStatus.INTERNAL_SERVER_ERROR if exc.failed else HTTPStatus.BAD_REQUEST
|
|
475
|
+
_send_error(handler, status, exc.code, exc.message)
|
|
476
|
+
except TtsWorkerError as exc:
|
|
477
|
+
_send_error(
|
|
478
|
+
handler, HTTPStatus.INTERNAL_SERVER_ERROR, "RUNTIME_ERROR", str(exc)[-DETAIL_LIMIT:]
|
|
479
|
+
)
|
|
480
|
+
except Exception as exc: # noqa: BLE001
|
|
481
|
+
_send_error(
|
|
482
|
+
handler,
|
|
483
|
+
HTTPStatus.INTERNAL_SERVER_ERROR,
|
|
484
|
+
"RUNTIME_ERROR",
|
|
485
|
+
f"internal tts error: {type(exc).__name__}",
|
|
486
|
+
)
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def make_handler(
|
|
490
|
+
controller: TtsController,
|
|
491
|
+
*,
|
|
492
|
+
api_key: str,
|
|
493
|
+
on_shutdown: Callable[[], None] | None = None,
|
|
494
|
+
) -> type[BaseHTTPRequestHandler]:
|
|
495
|
+
"""Build the authenticated loopback HTTP handler for ``TtsSidecar``."""
|
|
496
|
+
expected_auth = f"Bearer {api_key}".encode()
|
|
497
|
+
|
|
498
|
+
class TtsHandler(BaseHTTPRequestHandler):
|
|
499
|
+
protocol_version = "HTTP/1.1"
|
|
500
|
+
|
|
501
|
+
def log_message(self, format: str, *args: object) -> None: # noqa: A002
|
|
502
|
+
_ = (format, args)
|
|
503
|
+
|
|
504
|
+
def _authorized(self) -> bool:
|
|
505
|
+
header = (self.headers.get("Authorization") or "").encode("utf-8", errors="replace")
|
|
506
|
+
return hmac.compare_digest(header, expected_auth)
|
|
507
|
+
|
|
508
|
+
def do_GET(self) -> None: # noqa: N802
|
|
509
|
+
parsed = urllib.parse.urlsplit(self.path)
|
|
510
|
+
if parsed.path == "/health":
|
|
511
|
+
sidecar_http.send_json_response(self, HTTPStatus.OK, controller.health_payload())
|
|
512
|
+
return
|
|
513
|
+
if not self._authorized():
|
|
514
|
+
_send_error(self, HTTPStatus.UNAUTHORIZED, "INVALID_STATE", "unauthorized")
|
|
515
|
+
return
|
|
516
|
+
if parsed.path == "/v1/tts/status":
|
|
517
|
+
sidecar_http.send_json_response(
|
|
518
|
+
self, HTTPStatus.OK, dict(controller.runtime_payload())
|
|
519
|
+
)
|
|
520
|
+
return
|
|
521
|
+
if parsed.path == "/v1/audio/voices":
|
|
522
|
+
models = urllib.parse.parse_qs(parsed.query).get("model")
|
|
523
|
+
req_model = models[0] if models and models[0] else None
|
|
524
|
+
try:
|
|
525
|
+
mid, source, voice_list = controller.voices(req_model)
|
|
526
|
+
except TtsError as exc:
|
|
527
|
+
_send_error(self, HTTPStatus.BAD_REQUEST, exc.code, exc.message)
|
|
528
|
+
return
|
|
529
|
+
sidecar_http.send_json_response(
|
|
530
|
+
self, HTTPStatus.OK, {"model": mid, "source": source, "voices": voice_list}
|
|
531
|
+
)
|
|
532
|
+
return
|
|
533
|
+
_send_error(self, HTTPStatus.NOT_FOUND, "INVALID_STATE", "not found")
|
|
534
|
+
|
|
535
|
+
def do_POST(self) -> None: # noqa: N802
|
|
536
|
+
if not self._authorized():
|
|
537
|
+
_send_error(self, HTTPStatus.UNAUTHORIZED, "INVALID_STATE", "unauthorized")
|
|
538
|
+
return
|
|
539
|
+
_dispatch_post(self, controller, urllib.parse.urlsplit(self.path).path, on_shutdown)
|
|
540
|
+
|
|
541
|
+
return TtsHandler
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def start_http_server(
|
|
545
|
+
controller: TtsController,
|
|
546
|
+
*,
|
|
547
|
+
host: str,
|
|
548
|
+
port: int,
|
|
549
|
+
api_key: str,
|
|
550
|
+
) -> tuple[ThreadingHTTPServer, threading.Event]:
|
|
551
|
+
"""Create a loopback ``ThreadingHTTPServer`` wired to ``controller``."""
|
|
552
|
+
shutdown_event = threading.Event()
|
|
553
|
+
server_holder: list[ThreadingHTTPServer] = []
|
|
554
|
+
|
|
555
|
+
def _trigger_shutdown() -> None:
|
|
556
|
+
shutdown_event.set()
|
|
557
|
+
if server_holder:
|
|
558
|
+
server_holder[0].shutdown()
|
|
559
|
+
|
|
560
|
+
class _TtsServer(ThreadingHTTPServer):
|
|
561
|
+
allow_reuse_address = True
|
|
562
|
+
daemon_threads = True
|
|
563
|
+
|
|
564
|
+
handler = make_handler(controller, api_key=api_key, on_shutdown=_trigger_shutdown)
|
|
565
|
+
server = _TtsServer((host, port), handler)
|
|
566
|
+
server_holder.append(server)
|
|
567
|
+
return server, shutdown_event
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def parse_sidecar_args(argv: list[str] | None = None) -> argparse.Namespace:
|
|
571
|
+
"""Parse CLI arguments for ``python3 -m localmodels.tts_sidecar``."""
|
|
572
|
+
parser = argparse.ArgumentParser(description="localmodels standby-first TTS sidecar server")
|
|
573
|
+
parser.add_argument("--base-dir", required=True)
|
|
574
|
+
parser.add_argument("--host", default="127.0.0.1")
|
|
575
|
+
parser.add_argument("--port", type=int, required=True)
|
|
576
|
+
parser.add_argument("--state-dir", default=None)
|
|
577
|
+
parser.add_argument("--model", default=None)
|
|
578
|
+
return parser.parse_args(argv)
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def serve_sidecar(
|
|
582
|
+
controller: TtsController,
|
|
583
|
+
*,
|
|
584
|
+
host: str,
|
|
585
|
+
port: int,
|
|
586
|
+
api_key: str,
|
|
587
|
+
state_dir: Path | None,
|
|
588
|
+
preload_model: str | None = None,
|
|
589
|
+
) -> None:
|
|
590
|
+
"""Bind HTTP server, record PID/runtime, handle SIGINT/SIGTERM, and serve until shutdown."""
|
|
591
|
+
server, _shutdown_event = start_http_server(controller, host=host, port=port, api_key=api_key)
|
|
592
|
+
controller.base_url = f"http://{host}:{int(server.server_address[1])}"
|
|
593
|
+
with contextlib.suppress(OSError, RuntimeError):
|
|
594
|
+
pid_file = tts_state.server_pid_path(state_dir)
|
|
595
|
+
pid_file.parent.mkdir(parents=True, exist_ok=True)
|
|
596
|
+
process_identity.save(pid_file, os.getpid())
|
|
597
|
+
controller.persist_runtime()
|
|
598
|
+
controller.start_sweeper()
|
|
599
|
+
|
|
600
|
+
def _sig_shutdown(_signum: int, _frame: Any) -> None:
|
|
601
|
+
threading.Thread(target=server.shutdown, daemon=True).start()
|
|
602
|
+
|
|
603
|
+
prev_handlers: dict[signal.Signals, Any] = {}
|
|
604
|
+
for sig in (signal.SIGINT, signal.SIGTERM):
|
|
605
|
+
with contextlib.suppress(OSError, ValueError):
|
|
606
|
+
prev_handlers[sig] = signal.signal(sig, _sig_shutdown)
|
|
607
|
+
if preload_model:
|
|
608
|
+
with contextlib.suppress(TtsError):
|
|
609
|
+
controller.load_model(preload_model)
|
|
610
|
+
try:
|
|
611
|
+
server.serve_forever(poll_interval=0.25)
|
|
612
|
+
finally:
|
|
613
|
+
for restored_sig, prev in prev_handlers.items():
|
|
614
|
+
with contextlib.suppress(OSError, ValueError):
|
|
615
|
+
signal.signal(restored_sig, prev)
|
|
616
|
+
controller.shutdown()
|
|
617
|
+
server.server_close()
|