@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,466 @@
1
+ """Parameterized persistent state store under ``$LOCALMODELS_STATE/<namespace>/``.
2
+
3
+ Shared by standby-first voice sidecars (``speech`` for STT and ``tts`` for TTS) so state locks,
4
+ private atomic JSON persistence, download job tracking, and graceful sidecar shutdown live in
5
+ one layer-3 module with zero cross-file code duplication.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import contextlib
11
+ import json
12
+ import os
13
+ import re
14
+ import time
15
+ import uuid
16
+ from collections.abc import Callable, Iterator, Mapping
17
+ from contextlib import contextmanager
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+ from typing import Any, Literal, TypedDict
21
+
22
+ from localmodels import hosts, library_state, process_identity, sidecar_http
23
+ from localmodels.contracts import decode
24
+ from localmodels.plan_envelope import utc_now
25
+
26
+ JOB_WRITE_EVERY_S = 1.0
27
+
28
+
29
+ class SidecarModelError(TypedDict):
30
+ code: str
31
+ message: str
32
+
33
+
34
+ class _ModelRecordOptional(TypedDict, total=False):
35
+ engine_dir: str | None
36
+ engine_backend: str | None
37
+ error: SidecarModelError
38
+
39
+
40
+ class SidecarModelRecord(_ModelRecordOptional):
41
+ schema: str
42
+ id: str
43
+ base_dir: str
44
+ model_dir: str
45
+ files: list[str]
46
+ state: str
47
+ updated_at: str
48
+
49
+
50
+ class _SidecarJobOptional(TypedDict, total=False):
51
+ error: SidecarModelError
52
+
53
+
54
+ class SidecarJob(_SidecarJobOptional):
55
+ schema: str
56
+ id: str
57
+ kind: str
58
+ model: str
59
+ base_dir: str
60
+ files: list[str]
61
+ step: str
62
+ done_bytes: int
63
+ total_bytes: int
64
+ bytes_per_second: int
65
+ source: str
66
+ connections: int
67
+ started_at: str
68
+ updated_at: str
69
+
70
+
71
+ def safe_model_name(model_id: str) -> str:
72
+ return re.sub(r"[^A-Za-z0-9._-]+", "_", model_id)
73
+
74
+
75
+ def wait_pid_exit(pid_file: Path, timeout_s: float) -> bool:
76
+ deadline = time.monotonic() + timeout_s
77
+ while time.monotonic() < deadline:
78
+ state, _pid = process_identity.status(pid_file)
79
+ if state == "inactive":
80
+ return True
81
+ time.sleep(0.05)
82
+ return process_identity.status(pid_file)[0] == "inactive"
83
+
84
+
85
+ @dataclass(frozen=True)
86
+ class SidecarStore:
87
+ """Namespaced private file store for a standby-first voice sidecar."""
88
+
89
+ namespace: str
90
+ model_record_schema: str
91
+ job_schema: str
92
+ config_file_schema: str
93
+ runtime_file_schema: str
94
+ shutdown_path: str
95
+
96
+ def root(self, state_dir: Path | None = None) -> Path:
97
+ base = hosts.state_dir() if state_dir is None else state_dir
98
+ return base / self.namespace
99
+
100
+ def config_path(self, state_dir: Path | None = None) -> Path:
101
+ return self.root(state_dir) / "config.json"
102
+
103
+ def runtime_path(self, state_dir: Path | None = None) -> Path:
104
+ return self.root(state_dir) / "runtime.json"
105
+
106
+ def api_key_path(self, state_dir: Path | None = None) -> Path:
107
+ return self.root(state_dir) / "api-key"
108
+
109
+ def run_dir(self, state_dir: Path | None = None) -> Path:
110
+ return self.root(state_dir) / "run"
111
+
112
+ def server_pid_path(self, state_dir: Path | None = None) -> Path:
113
+ return self.root(state_dir) / "server.pid"
114
+
115
+ def server_log_path(self, state_dir: Path | None = None) -> Path:
116
+ return self.root(state_dir) / "server.log"
117
+
118
+ def record_path(self, model_id: str, state_dir: Path | None = None) -> Path:
119
+ return self.root(state_dir) / "models" / f"{safe_model_name(model_id)}.json"
120
+
121
+ def job_path(self, model_id: str, state_dir: Path | None = None) -> Path:
122
+ return self.root(state_dir) / "jobs" / f"{safe_model_name(model_id)}.json"
123
+
124
+ def pid_path(self, model_id: str, state_dir: Path | None = None) -> Path:
125
+ return self.root(state_dir) / "jobs" / f"{safe_model_name(model_id)}.pid"
126
+
127
+ def cancel_path(self, model_id: str, state_dir: Path | None = None) -> Path:
128
+ return self.root(state_dir) / "jobs" / f"{safe_model_name(model_id)}.cancel"
129
+
130
+ @contextmanager
131
+ def locked(self, state_dir: Path | None = None) -> Iterator[None]:
132
+ with hosts.file_lock(self.root(state_dir) / ".lock"):
133
+ yield
134
+
135
+ def ensure_api_key(self, state_dir: Path | None = None) -> tuple[Path, str]:
136
+ return sidecar_http.ensure_api_key(self.api_key_path(state_dir))
137
+
138
+ def ensure_run_dir(self, state_dir: Path | None = None) -> Path:
139
+ path = self.run_dir(state_dir)
140
+ path.mkdir(parents=True, exist_ok=True)
141
+ if os.name != "nt":
142
+ with contextlib.suppress(OSError):
143
+ path.chmod(0o700)
144
+ return path
145
+
146
+ def clear_server_pid(self, state_dir: Path | None = None) -> None:
147
+ pp = self.server_pid_path(state_dir)
148
+ for path in (pp, Path(str(pp) + ".identity.json")):
149
+ path.unlink(missing_ok=True)
150
+
151
+ def load_raw_config(self, state_dir: Path | None = None) -> dict[str, Any] | None:
152
+ try:
153
+ raw = json.loads(self.config_path(state_dir).read_text(encoding="utf-8"))
154
+ return raw if isinstance(raw, dict) else None
155
+ except (OSError, ValueError):
156
+ return None
157
+
158
+ def save_raw_config(
159
+ self, validated: Mapping[str, object], state_dir: Path | None = None
160
+ ) -> Path:
161
+ payload = {
162
+ "schema": self.config_file_schema,
163
+ **validated,
164
+ "updated_at": utc_now(),
165
+ }
166
+ return hosts.save_private(self.config_path(state_dir), payload)
167
+
168
+ def load_runtime_record(self, state_dir: Path | None = None) -> dict[str, Any] | None:
169
+ try:
170
+ raw = json.loads(self.runtime_path(state_dir).read_text(encoding="utf-8"))
171
+ return raw if isinstance(raw, dict) else None
172
+ except (OSError, ValueError):
173
+ return None
174
+
175
+ def save_runtime_record(self, record: Mapping[str, Any], state_dir: Path | None = None) -> Path:
176
+ payload = {
177
+ "schema": self.runtime_file_schema,
178
+ **record,
179
+ "updated_at": utc_now(),
180
+ }
181
+ return hosts.save_private(self.runtime_path(state_dir), payload)
182
+
183
+ def clear_runtime_record(self, state_dir: Path | None = None) -> None:
184
+ self.runtime_path(state_dir).unlink(missing_ok=True)
185
+
186
+ def push_config_update(
187
+ self,
188
+ endpoint: str,
189
+ payload: Mapping[str, object],
190
+ state_dir: Path | None = None,
191
+ *,
192
+ timeout: float = 2.0,
193
+ ) -> bool:
194
+ """Best-effort live config push to the sidecar recorded in ``runtime.json``."""
195
+ rec_rt = self.load_runtime_record(state_dir)
196
+ if rec_rt is None or not isinstance(rt_url := rec_rt.get("base_url"), str) or not rt_url:
197
+ return False
198
+ key_file = rec_rt.get("key_file")
199
+ pushed = sidecar_http.sidecar_request(
200
+ rt_url,
201
+ endpoint,
202
+ method="POST",
203
+ key_file=key_file if isinstance(key_file, str) else None,
204
+ payload=payload,
205
+ timeout=timeout,
206
+ )
207
+ return pushed is not None
208
+
209
+ def stop_sidecar_process(
210
+ self,
211
+ state_dir: Path | None = None,
212
+ *,
213
+ http_timeout_s: float = 1.0,
214
+ poll_s: float = 1.0,
215
+ grace_s: float = 3.0,
216
+ ) -> bool:
217
+ """Stop the sidecar via HTTP shutdown then verified ``process_identity.stop``."""
218
+ rec = self.load_runtime_record(state_dir)
219
+ pid_file = self.server_pid_path(state_dir)
220
+ was_running = False
221
+ if rec is not None and isinstance(base_url := rec.get("base_url"), str) and base_url:
222
+ key_file = rec.get("key_file")
223
+ status_code, _parsed = sidecar_http.sidecar_request_detail(
224
+ base_url,
225
+ self.shutdown_path,
226
+ method="POST",
227
+ key_file=key_file if isinstance(key_file, str) else None,
228
+ payload={},
229
+ timeout=http_timeout_s,
230
+ )
231
+ if 200 <= status_code < 300:
232
+ was_running = True
233
+ wait_pid_exit(pid_file, poll_s)
234
+ if os.path.lexists(pid_file):
235
+ outcome = process_identity.stop(pid_file, grace=grace_s)
236
+ if outcome == "stopped":
237
+ was_running = True
238
+ self.clear_runtime_record(state_dir)
239
+ self.clear_server_pid(state_dir)
240
+ return was_running
241
+
242
+ def stop_if_recorded(
243
+ self,
244
+ state_dir: Path | None = None,
245
+ *,
246
+ stop_fn: Callable[[Path | None], bool] | None = None,
247
+ error_types: tuple[type[Exception], ...] = (RuntimeError, OSError, ValueError),
248
+ ) -> tuple[Literal["none", "stopped", "not-running", "failed"], str]:
249
+ """Stop any sidecar recorded under ``state_dir`` for ``stack down``."""
250
+ rec = self.load_runtime_record(state_dir)
251
+ pid_file = self.server_pid_path(state_dir)
252
+ if rec is None and not os.path.lexists(pid_file):
253
+ return "none", ""
254
+ try:
255
+ stopper = stop_fn if stop_fn is not None else self.stop_sidecar_process
256
+ stopped = stopper(state_dir)
257
+ except error_types as exc:
258
+ return "failed", str(exc)[-300:]
259
+ return ("stopped" if stopped else "not-running"), ""
260
+
261
+ # ------------------------------------------------------------------ model records
262
+
263
+ def load_record(
264
+ self, model_id: str, state_dir: Path | None = None
265
+ ) -> SidecarModelRecord | None:
266
+ try:
267
+ raw = json.loads(self.record_path(model_id, state_dir).read_text(encoding="utf-8"))
268
+ return decode(raw, SidecarModelRecord)
269
+ except (OSError, ValueError):
270
+ return None
271
+
272
+ def records(self, state_dir: Path | None = None) -> list[SidecarModelRecord]:
273
+ found: list[SidecarModelRecord] = []
274
+ models_dir = self.root(state_dir) / "models"
275
+ if not models_dir.is_dir():
276
+ return found
277
+ for path in sorted(models_dir.glob("*.json")):
278
+ try:
279
+ found.append(
280
+ decode(json.loads(path.read_text(encoding="utf-8")), SidecarModelRecord)
281
+ )
282
+ except (OSError, ValueError):
283
+ continue
284
+ return found
285
+
286
+ def save_record(self, record: SidecarModelRecord, state_dir: Path | None = None) -> Path:
287
+ record["updated_at"] = utc_now()
288
+ return hosts.save_private(self.record_path(record["id"], state_dir), record)
289
+
290
+ def forget_record(self, model_id: str, state_dir: Path | None = None) -> None:
291
+ self.record_path(model_id, state_dir).unlink(missing_ok=True)
292
+
293
+ # ------------------------------------------------------------------ download jobs
294
+
295
+ def read_job(self, model_id: str, state_dir: Path | None = None) -> SidecarJob | None:
296
+ try:
297
+ raw = json.loads(self.job_path(model_id, state_dir).read_text(encoding="utf-8"))
298
+ return decode(raw, SidecarJob)
299
+ except (OSError, ValueError):
300
+ return None
301
+
302
+ def job_alive(self, model_id: str, state_dir: Path | None = None) -> bool:
303
+ try:
304
+ state, pid = process_identity.status(self.pid_path(model_id, state_dir))
305
+ except (OSError, RuntimeError, ValueError):
306
+ return False
307
+ return (
308
+ state == "active" and pid is not None and self.read_job(model_id, state_dir) is not None
309
+ )
310
+
311
+ def jobs(self, state_dir: Path | None = None) -> dict[str, tuple[SidecarJob, bool]]:
312
+ found: dict[str, tuple[SidecarJob, bool]] = {}
313
+ jobs_dir = self.root(state_dir) / "jobs"
314
+ if not jobs_dir.is_dir():
315
+ return found
316
+ for path in sorted(jobs_dir.glob("*.json")):
317
+ try:
318
+ job = decode(json.loads(path.read_text(encoding="utf-8")), SidecarJob)
319
+ except (OSError, ValueError):
320
+ continue
321
+ found[job["model"]] = (job, self.job_alive(job["model"], state_dir))
322
+ return found
323
+
324
+ def receipt(
325
+ self, model_id: str, state_dir: Path | None = None
326
+ ) -> process_identity.Identity | None:
327
+ try:
328
+ ident_path = Path(str(self.pid_path(model_id, state_dir)) + ".identity.json")
329
+ return decode(
330
+ json.loads(ident_path.read_text(encoding="utf-8")), process_identity.Identity
331
+ )
332
+ except (OSError, ValueError):
333
+ return None
334
+
335
+ def mark_cancelled(self, job: SidecarJob, state_dir: Path | None = None) -> None:
336
+ path = self.cancel_path(job["model"], state_dir)
337
+ path.parent.mkdir(parents=True, exist_ok=True)
338
+ path.write_text(str(job["id"]), encoding="utf-8")
339
+
340
+ def is_cancelled(self, job: SidecarJob, state_dir: Path | None = None) -> bool:
341
+ try:
342
+ return self.cancel_path(job["model"], state_dir).read_text(encoding="utf-8") == str(
343
+ job["id"]
344
+ )
345
+ except OSError:
346
+ return False
347
+
348
+ def clear_job(self, model_id: str, state_dir: Path | None = None) -> None:
349
+ jp = self.job_path(model_id, state_dir)
350
+ pp = self.pid_path(model_id, state_dir)
351
+ for path in (
352
+ jp,
353
+ jp.with_name(jp.name + ".tmp"),
354
+ self.cancel_path(model_id, state_dir),
355
+ pp,
356
+ Path(str(pp) + ".identity.json"),
357
+ ):
358
+ path.unlink(missing_ok=True)
359
+
360
+ def fail_job(
361
+ self, job: SidecarJob, error: SidecarModelError, state_dir: Path | None = None
362
+ ) -> None:
363
+ job["error"] = error
364
+ job["updated_at"] = utc_now()
365
+ hosts.save_private(self.job_path(job["model"], state_dir), job)
366
+ pp = self.pid_path(job["model"], state_dir)
367
+ for path in (
368
+ self.cancel_path(job["model"], state_dir),
369
+ pp,
370
+ Path(str(pp) + ".identity.json"),
371
+ ):
372
+ path.unlink(missing_ok=True)
373
+
374
+ def current_job(self, job: SidecarJob, state_dir: Path | None = None) -> bool:
375
+ found = self.read_job(job["model"], state_dir)
376
+ return found is not None and found["id"] == job["id"]
377
+
378
+ def begin_job(
379
+ self,
380
+ model_id: str,
381
+ base_dir: str,
382
+ files: list[str],
383
+ total_bytes: int,
384
+ *,
385
+ state_dir: Path | None = None,
386
+ ) -> SidecarJob | None:
387
+ """Under ``locked()``: claim a download job, returning None if one is already alive."""
388
+ existing = self.read_job(model_id, state_dir)
389
+ if existing is not None and self.job_alive(model_id, state_dir):
390
+ return None
391
+ self.clear_job(model_id, state_dir)
392
+ library_state.become_leader()
393
+ now = utc_now()
394
+ job: SidecarJob = {
395
+ "schema": self.job_schema,
396
+ "id": uuid.uuid4().hex,
397
+ "kind": "download",
398
+ "model": model_id,
399
+ "base_dir": base_dir,
400
+ "files": list(files),
401
+ "step": "download",
402
+ "done_bytes": 0,
403
+ "total_bytes": max(0, int(total_bytes)),
404
+ "bytes_per_second": 0,
405
+ "source": "huggingface",
406
+ "connections": 0,
407
+ "started_at": now,
408
+ "updated_at": now,
409
+ }
410
+ hosts.save_private(self.job_path(model_id, state_dir), job)
411
+ try:
412
+ process_identity.save(self.pid_path(model_id, state_dir), os.getpid())
413
+ except (OSError, RuntimeError):
414
+ self.clear_job(model_id, state_dir)
415
+ raise
416
+ return job
417
+
418
+ @contextmanager
419
+ def held_job(self, claims: list[SidecarJob], state_dir: Path | None = None) -> Iterator[None]:
420
+ try:
421
+ yield
422
+ finally:
423
+ with self.locked(state_dir):
424
+ for job in claims:
425
+ if self.current_job(job, state_dir):
426
+ self.clear_job(job["model"], state_dir)
427
+
428
+
429
+ class SidecarJobHandle:
430
+ """Throttled disk progress writer so ``status`` observes live sidecar downloads."""
431
+
432
+ def __init__(self, store: SidecarStore, job: SidecarJob, state_dir: Path | None = None) -> None:
433
+ self.store = store
434
+ self.job = job
435
+ self.state_dir = state_dir
436
+ self._written = 0.0
437
+
438
+ def update(
439
+ self,
440
+ step: str,
441
+ done_bytes: int,
442
+ total_bytes: int,
443
+ bytes_per_second: int = 0,
444
+ *,
445
+ source: str = "huggingface",
446
+ connections: int = 0,
447
+ ) -> None:
448
+ total = max(0, int(total_bytes))
449
+ done = min(max(0, int(done_bytes)), total)
450
+ changed = (
451
+ self.job["step"] != step
452
+ or self.job["source"] != source
453
+ or self.job["total_bytes"] != total
454
+ )
455
+ self.job["step"] = step
456
+ self.job["done_bytes"] = done
457
+ self.job["total_bytes"] = total
458
+ self.job["bytes_per_second"] = max(0, int(bytes_per_second))
459
+ self.job["source"] = source or "custom"
460
+ self.job["connections"] = max(0, int(connections))
461
+ now = time.monotonic()
462
+ if changed or now - self._written >= JOB_WRITE_EVERY_S or done >= total:
463
+ self._written = now
464
+ self.job["updated_at"] = utc_now()
465
+ with contextlib.suppress(OSError):
466
+ hosts.save_private(self.store.job_path(self.job["model"], self.state_dir), self.job)
@@ -28,6 +28,7 @@ from localmodels import (
28
28
  plan_envelope,
29
29
  speech_catalog,
30
30
  speech_state,
31
+ tts_state,
31
32
  )
32
33
  from localmodels.planning import budget
33
34
  from localmodels.probe import GPU, HostFacts
@@ -447,3 +448,15 @@ def demote_speech_if_holding_pool(
447
448
  timeout=timeout,
448
449
  )
449
450
  return response is not None
451
+
452
+
453
+ def demote_tts_for_speech(
454
+ state_dir: Path | None,
455
+ pool_id: str,
456
+ *,
457
+ timeout: float = SPEECH_DEMOTE_TIMEOUT_S,
458
+ ) -> bool:
459
+ """Ask a GPU-resident TTS sidecar (RANK 3) to yield ``pool_id`` to STT (RANK 2)."""
460
+ return tts_state.demote_if_holding_pool(
461
+ state_dir, pool_id, reason="yielded_to_stt", timeout=timeout
462
+ )