@simplexai/localmodels-darwin-x64 0.1.0-dev.101 → 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 (57) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +56 -37
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +3 -1
  5. package/modules/localmodels/app.py +35 -7
  6. package/modules/localmodels/catalog.json +306 -1
  7. package/modules/localmodels/cli_parser.py +4 -0
  8. package/modules/localmodels/debug_stub_server.py +280 -7
  9. package/modules/localmodels/download-mirrors.json +76 -0
  10. package/modules/localmodels/engine_adapters/suite_plan.py +4 -2
  11. package/modules/localmodels/engines-speechcpp-v0.11.3.json +84 -0
  12. package/modules/localmodels/library_serve.py +46 -26
  13. package/modules/localmodels/remote_ops_common.py +12 -2
  14. package/modules/localmodels/sidecar_downloads.py +426 -0
  15. package/modules/localmodels/sidecar_http.py +396 -0
  16. package/modules/localmodels/sidecar_state.py +466 -0
  17. package/modules/localmodels/speech_admission.py +13 -0
  18. package/modules/localmodels/speech_jobs.py +81 -370
  19. package/modules/localmodels/speech_server.py +17 -8
  20. package/modules/localmodels/speech_state.py +87 -454
  21. package/modules/localmodels/speech_workers.py +41 -163
  22. package/modules/localmodels/stack.py +18 -0
  23. package/modules/localmodels/stack_capacity.py +37 -1
  24. package/modules/localmodels/stack_cli.py +1 -0
  25. package/modules/localmodels/stack_down.py +19 -14
  26. package/modules/localmodels/stack_hardware.py +18 -16
  27. package/modules/localmodels/stack_plan.py +21 -0
  28. package/modules/localmodels/stack_ports.py +1 -0
  29. package/modules/localmodels/stack_progress.py +15 -0
  30. package/modules/localmodels/stack_run.py +25 -2
  31. package/modules/localmodels/stack_suite.py +54 -12
  32. package/modules/localmodels/stack_up.py +51 -1
  33. package/modules/localmodels/strata_poly_server.py +140 -3
  34. package/modules/localmodels/suite.py +10 -1
  35. package/modules/localmodels/tts-moss.txt +321 -0
  36. package/modules/localmodels/tts_admission.py +396 -0
  37. package/modules/localmodels/tts_backend_speechcpp.py +487 -0
  38. package/modules/localmodels/tts_catalog.py +251 -0
  39. package/modules/localmodels/tts_cli.py +333 -0
  40. package/modules/localmodels/tts_http.py +617 -0
  41. package/modules/localmodels/tts_jobs.py +496 -0
  42. package/modules/localmodels/tts_model.py +591 -0
  43. package/modules/localmodels/tts_moss_presets.json +1 -0
  44. package/modules/localmodels/tts_serve.py +451 -0
  45. package/modules/localmodels/tts_sidecar.py +750 -0
  46. package/modules/localmodels/tts_state.py +395 -0
  47. package/modules/localmodels/tts_worker_kokoro.py +463 -0
  48. package/modules/localmodels/tts_worker_moss.py +748 -0
  49. package/modules/localmodels/tts_workers.py +696 -0
  50. package/modules/{simplex_localmodels-0.1.0.dev101.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/METADATA +1 -1
  51. package/modules/{simplex_localmodels-0.1.0.dev101.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/RECORD +53 -34
  52. package/modules/{simplex_localmodels-0.1.0.dev101.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/licenses/NOTICE +29 -0
  53. package/package.json +1 -1
  54. package/tool.json +1 -1
  55. /package/modules/{simplex_localmodels-0.1.0.dev101.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/WHEEL +0 -0
  56. /package/modules/{simplex_localmodels-0.1.0.dev101.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/entry_points.txt +0 -0
  57. /package/modules/{simplex_localmodels-0.1.0.dev101.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,396 @@
1
+ """Shared loopback HTTP, PCM16 WAV, bearer-key, and child-worker primitives for voice sidecars.
2
+
3
+ Pure stdlib plus layer-0 ``http_local`` and ``windows_job`` helpers, shared by both
4
+ ``localmodels speech`` (STT) and ``localmodels tts`` (TTS) sidecars and workers.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import array
10
+ import contextlib
11
+ import http.client
12
+ import io
13
+ import json
14
+ import math
15
+ import os
16
+ import secrets
17
+ import subprocess
18
+ import sys
19
+ import time
20
+ import urllib.error
21
+ import urllib.request
22
+ import wave
23
+ from collections.abc import Mapping
24
+ from http import HTTPStatus
25
+ from http.server import BaseHTTPRequestHandler
26
+ from pathlib import Path
27
+ from typing import Any, Literal
28
+
29
+ from localmodels import http_local, windows_job
30
+
31
+ RequestedDevice = Literal["gpu", "cpu"]
32
+ REQUESTED_DEVICES: tuple[RequestedDevice, ...] = ("gpu", "cpu")
33
+
34
+ EffectiveDevice = Literal["cuda", "metal", "vulkan", "directml", "cpu"]
35
+ EFFECTIVE_DEVICES: tuple[EffectiveDevice, ...] = ("cuda", "metal", "vulkan", "directml", "cpu")
36
+
37
+ DownloadStep = Literal["download", "verify"]
38
+ LoadStep = Literal["prepare", "start", "load", "warm"]
39
+
40
+ WORKER_STOP_GRACE_S = 3.0
41
+ WORKER_READY_TIMEOUT_S = 60.0
42
+ WINDOWS_CREATE_NO_WINDOW = 0x08000000
43
+ DETAIL_LIMIT = 500
44
+
45
+ _POSIX_WATCHDOG_SH = (
46
+ 'read _; kill -TERM "$0" 2>/dev/null; n=0; '
47
+ 'while kill -0 "$0" 2>/dev/null && [ "$n" -lt 3 ]; do sleep 1; n=$((n+1)); done; '
48
+ 'kill -KILL "$0" 2>/dev/null'
49
+ )
50
+
51
+ GPU_OOM_SIGNATURES: tuple[str, ...] = (
52
+ "oom",
53
+ "out of memory",
54
+ "cuda",
55
+ "cublas",
56
+ "metal",
57
+ "vulkan",
58
+ "vkresult",
59
+ "directml",
60
+ "failed to allocate",
61
+ "unable to allocate",
62
+ "not enough memory",
63
+ "insufficient memory",
64
+ "bad_alloc",
65
+ "kioreturnnomemory",
66
+ "newbufferwithlength",
67
+ )
68
+
69
+
70
+ class SidecarWorkerError(RuntimeError):
71
+ """Raised when an isolated voice engine child fails to start or serve a request."""
72
+
73
+ def __init__(self, message: str, *, detail: str = "", exit_status: int | None = None) -> None:
74
+ super().__init__(message)
75
+ self.detail = detail or message
76
+ self.exit_status = exit_status
77
+
78
+
79
+ def is_gpu_oom_error(message: str) -> bool:
80
+ """Return True when ``message`` matches any known GPU or OOM failure signature."""
81
+ lowered = message.lower()
82
+ return any(sig in lowered for sig in GPU_OOM_SIGNATURES)
83
+
84
+
85
+ def stderr_tail(detail: str, limit: int = DETAIL_LIMIT) -> str:
86
+ """Last ``limit`` characters of worker stderr, starting at a line boundary when cut."""
87
+ text = detail.strip()
88
+ if len(text) <= limit:
89
+ return text
90
+ tail = text[-limit:]
91
+ newline = tail.find("\n")
92
+ return tail[newline + 1 :] if 0 <= newline < len(tail) - 1 else tail
93
+
94
+
95
+ def send_json_response(
96
+ handler: BaseHTTPRequestHandler,
97
+ status: HTTPStatus,
98
+ payload: Any,
99
+ ) -> None:
100
+ """Write a JSON response with explicit Content-Length and ``Connection: close``."""
101
+ raw = json.dumps(payload, ensure_ascii=False).encode("utf-8")
102
+ send_binary_response(handler, status, raw, "application/json")
103
+
104
+
105
+ def send_binary_response(
106
+ handler: BaseHTTPRequestHandler,
107
+ status: HTTPStatus,
108
+ data: bytes,
109
+ content_type: str,
110
+ extra_headers: Mapping[str, str] | None = None,
111
+ ) -> None:
112
+ """Write a binary response with explicit Content-Length and ``Connection: close``."""
113
+ handler.send_response(status)
114
+ handler.send_header("Content-Type", content_type)
115
+ handler.send_header("Content-Length", str(len(data)))
116
+ if extra_headers:
117
+ for name, value in extra_headers.items():
118
+ handler.send_header(name, value)
119
+ handler.send_header("Connection", "close")
120
+ handler.end_headers()
121
+ handler.wfile.write(data)
122
+ handler.close_connection = True
123
+
124
+
125
+ def encode_pcm16_bytes(samples: list[float]) -> bytes:
126
+ """Encode normalized [-1.0, 1.0] float samples into little-endian 16-bit mono PCM bytes."""
127
+ pcm = array.array("h", (int(max(-1.0, min(1.0, x)) * 32767) for x in samples))
128
+ if sys.byteorder == "big":
129
+ pcm.byteswap()
130
+ return pcm.tobytes()
131
+
132
+
133
+ def wrap_pcm16_wav(pcm_bytes: bytes, sample_rate: int) -> bytes:
134
+ """Wrap raw 16-bit signed little-endian mono PCM frames in a standard RIFF WAV container."""
135
+ if sample_rate <= 0:
136
+ raise ValueError(f"invalid WAV sample rate: {sample_rate}")
137
+ buf = io.BytesIO()
138
+ with wave.open(buf, "wb") as out:
139
+ out.setnchannels(1)
140
+ out.setsampwidth(2)
141
+ out.setframerate(sample_rate)
142
+ out.writeframes(pcm_bytes)
143
+ return buf.getvalue()
144
+
145
+
146
+ def encode_pcm16_wav(samples: list[float], sample_rate: int) -> bytes:
147
+ """Encode normalized [-1.0, 1.0] float samples as 16-bit mono PCM WAV bytes."""
148
+ return wrap_pcm16_wav(encode_pcm16_bytes(samples), sample_rate)
149
+
150
+
151
+ def read_api_key(key_file: str | None) -> str | None:
152
+ """Read the loopback bearer token from ``key_file`` when present."""
153
+ if not key_file:
154
+ return None
155
+ try:
156
+ token = Path(key_file).expanduser().read_text(encoding="utf-8").strip()
157
+ return token or None
158
+ except OSError:
159
+ return None
160
+
161
+
162
+ def ensure_api_key(path: Path) -> tuple[Path, str]:
163
+ """Return ``(path, token)``, creating a 0600 bearer key at ``path`` if missing or empty."""
164
+ existing = read_api_key(str(path))
165
+ if existing:
166
+ return path, existing
167
+ token = secrets.token_urlsafe(32)
168
+ http_local.write_private_text(path, token + "\n")
169
+ return path, token
170
+
171
+
172
+ def sidecar_request_detail(
173
+ base_url: str,
174
+ path: str,
175
+ *,
176
+ method: str = "GET",
177
+ key_file: str | None = None,
178
+ payload: Mapping[str, object] | None = None,
179
+ timeout: float = 2.0,
180
+ ) -> tuple[int, dict[str, Any] | None]:
181
+ """Authenticated loopback JSON request returning ``(http_status, parsed_json_or_none)``.
182
+
183
+ Returns ``(0, None)`` when unreachable. Uses ``no_proxy_opener(allow_redirects=False)`` and
184
+ ``Connection: close`` to avoid proxy hijacking, credential leaks, and Windows resets.
185
+ """
186
+ url = base_url.rstrip("/") + "/" + path.lstrip("/")
187
+ headers: dict[str, str] = {"Connection": "close"}
188
+ token = read_api_key(key_file)
189
+ if token:
190
+ headers["Authorization"] = f"Bearer {token}"
191
+ body: bytes | None = None
192
+ if payload is not None:
193
+ body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
194
+ headers["Content-Type"] = "application/json"
195
+ req = urllib.request.Request(url, data=body, headers=headers, method=method)
196
+ opener = http_local.no_proxy_opener(allow_redirects=False)
197
+ try:
198
+ with opener.open(req, timeout=timeout) as resp:
199
+ status = int(getattr(resp, "status", 200))
200
+ raw = resp.read().decode("utf-8", "replace").strip()
201
+ if not raw:
202
+ return status, {}
203
+ parsed = json.loads(raw)
204
+ return status, parsed if isinstance(parsed, dict) else None
205
+ except urllib.error.HTTPError as exc:
206
+ try:
207
+ raw = exc.read().decode("utf-8", "replace").strip()
208
+ parsed = json.loads(raw) if raw else None
209
+ return int(exc.code), parsed if isinstance(parsed, dict) else None
210
+ except (OSError, ValueError):
211
+ return int(exc.code), None
212
+ except (urllib.error.URLError, OSError, ValueError):
213
+ return 0, None
214
+
215
+
216
+ def sidecar_request(
217
+ base_url: str,
218
+ path: str,
219
+ *,
220
+ method: str = "GET",
221
+ key_file: str | None = None,
222
+ payload: Mapping[str, object] | None = None,
223
+ timeout: float = 2.0,
224
+ ) -> dict[str, Any] | None:
225
+ """Best-effort authenticated loopback JSON request returning parsed JSON on 2xx, else None."""
226
+ status, parsed = sidecar_request_detail(
227
+ base_url,
228
+ path,
229
+ method=method,
230
+ key_file=key_file,
231
+ payload=payload,
232
+ timeout=timeout,
233
+ )
234
+ return parsed if 200 <= status < 300 else None
235
+
236
+
237
+ class ChildWatchdog:
238
+ """Binds a child worker's lifetime to this sidecar via POSIX pipe guard or Windows Job."""
239
+
240
+ def __init__(self, proc: subprocess.Popen[bytes]) -> None:
241
+ self._guard: subprocess.Popen[bytes] | None = None
242
+ self._write_fd: int | None = None
243
+ if sys.platform == "win32":
244
+ handle = getattr(proc, "_handle", None)
245
+ if isinstance(handle, int):
246
+ windows_job.end_with_this_process(handle)
247
+ return
248
+ if os.name == "posix":
249
+ read_fd, write_fd = os.pipe()
250
+ try:
251
+ self._guard = subprocess.Popen(
252
+ ["/bin/sh", "-c", _POSIX_WATCHDOG_SH, str(proc.pid)],
253
+ stdin=read_fd,
254
+ stdout=subprocess.DEVNULL,
255
+ stderr=subprocess.DEVNULL,
256
+ )
257
+ self._write_fd = write_fd
258
+ except OSError:
259
+ os.close(write_fd)
260
+ finally:
261
+ os.close(read_fd)
262
+
263
+ def close(self) -> None:
264
+ """Stop the POSIX watchdog before closing its pipe so it does not signal a reused PID."""
265
+ if self._guard is not None:
266
+ with contextlib.suppress(OSError):
267
+ self._guard.kill()
268
+ with contextlib.suppress(OSError, subprocess.TimeoutExpired):
269
+ self._guard.wait(timeout=2.0)
270
+ self._guard = None
271
+ if self._write_fd is not None:
272
+ with contextlib.suppress(OSError):
273
+ os.close(self._write_fd)
274
+ self._write_fd = None
275
+
276
+
277
+ def stop_subprocess(
278
+ proc: subprocess.Popen[bytes],
279
+ watchdog: ChildWatchdog | None = None,
280
+ *,
281
+ grace_s: float = WORKER_STOP_GRACE_S,
282
+ ) -> None:
283
+ """Terminate ``proc`` with ``SIGTERM -> grace_s -> SIGKILL`` and release its watchdog."""
284
+ try:
285
+ if proc.poll() is None:
286
+ with contextlib.suppress(OSError):
287
+ proc.terminate()
288
+ try:
289
+ proc.wait(timeout=max(0.1, grace_s))
290
+ except subprocess.TimeoutExpired:
291
+ with contextlib.suppress(OSError):
292
+ proc.kill()
293
+ with contextlib.suppress(OSError, subprocess.TimeoutExpired):
294
+ proc.wait(timeout=5.0)
295
+ finally:
296
+ if watchdog is not None:
297
+ watchdog.close()
298
+
299
+
300
+ def wait_worker_ready(
301
+ proc: subprocess.Popen[bytes],
302
+ port: int,
303
+ engine: str,
304
+ stderr_path: Path,
305
+ timeout_s: float = WORKER_READY_TIMEOUT_S,
306
+ *,
307
+ paths: tuple[str, ...] = ("/health",),
308
+ ) -> None:
309
+ """Wait until the child engine answers loopback HTTP 200 or exits early."""
310
+ deadline = time.monotonic() + timeout_s
311
+ opener = http_local.no_proxy_opener(allow_redirects=False)
312
+ while time.monotonic() < deadline:
313
+ code = proc.poll()
314
+ if code is not None:
315
+ tail = ""
316
+ with contextlib.suppress(OSError):
317
+ tail = stderr_path.read_text(encoding="utf-8", errors="replace")[-1200:].strip()
318
+ raise SidecarWorkerError(
319
+ f"{engine} worker exited with status {code}",
320
+ detail=tail or f"exit code {code}",
321
+ exit_status=code,
322
+ )
323
+ for path in paths:
324
+ req = urllib.request.Request(
325
+ f"http://127.0.0.1:{port}{path}",
326
+ headers={"Connection": "close"},
327
+ method="GET",
328
+ )
329
+ try:
330
+ with opener.open(req, timeout=1.0) as resp:
331
+ if 200 <= getattr(resp, "status", 200) < 300:
332
+ return
333
+ except (urllib.error.URLError, OSError, http.client.HTTPException):
334
+ continue
335
+ time.sleep(0.1)
336
+ raise SidecarWorkerError(f"{engine} worker did not become ready within {timeout_s:.0f}s")
337
+
338
+
339
+ def launch_worker_subprocess(
340
+ argv: list[str],
341
+ env: dict[str, str],
342
+ run_cwd: Path,
343
+ stderr_path: Path,
344
+ port: int,
345
+ engine: str,
346
+ *,
347
+ ready_paths: tuple[str, ...] = ("/health",),
348
+ timeout_s: float = WORKER_READY_TIMEOUT_S,
349
+ ) -> tuple[subprocess.Popen[bytes], ChildWatchdog]:
350
+ """Spawn, watchdog-bind, and health-check a loopback sidecar child worker."""
351
+ kwargs: dict[str, Any] = {"cwd": str(run_cwd), "env": env}
352
+ if sys.platform == "win32":
353
+ kwargs["creationflags"] = WINDOWS_CREATE_NO_WINDOW
354
+ with stderr_path.open("wb") as err_stream:
355
+ try:
356
+ proc = subprocess.Popen(
357
+ argv,
358
+ stdin=subprocess.DEVNULL,
359
+ stdout=subprocess.DEVNULL,
360
+ stderr=err_stream,
361
+ **kwargs,
362
+ )
363
+ except OSError as exc:
364
+ raise SidecarWorkerError(f"failed to launch {engine} worker: {exc}") from None
365
+ watchdog = ChildWatchdog(proc)
366
+ try:
367
+ wait_worker_ready(proc, port, engine, stderr_path, timeout_s=timeout_s, paths=ready_paths)
368
+ except Exception:
369
+ stop_subprocess(proc, watchdog)
370
+ raise
371
+ return proc, watchdog
372
+
373
+
374
+ def sweep_wait_seconds(ttl: int, base_interval_s: float) -> float:
375
+ """Polling interval for a sidecar idle sweeper given ``keep_loaded_seconds``."""
376
+ if 0 < ttl < base_interval_s * 2:
377
+ return max(0.2, min(base_interval_s, ttl / 2.0))
378
+ return base_interval_s
379
+
380
+
381
+ def idle_remaining_seconds(
382
+ *,
383
+ loaded: bool,
384
+ ttl: int,
385
+ active_sessions: int,
386
+ now: float,
387
+ last_used: float,
388
+ ) -> int | None:
389
+ """Compute remaining idle TTL seconds for a loaded sidecar worker."""
390
+ if not loaded or ttl < 0:
391
+ return None
392
+ if ttl == 0:
393
+ return 0
394
+ if active_sessions > 0:
395
+ return ttl
396
+ return max(0, int(math.ceil(ttl - max(0.0, now - last_used))))