@simplexai/localmodels-win32-x64 0.1.0-dev.60 → 0.1.0-dev.62
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 +78 -64
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +5 -3
- package/modules/localmodels/auth_proxy.py +185 -19
- package/modules/localmodels/catalog.json +363 -0
- package/modules/localmodels/catalog.py +1 -1
- package/modules/localmodels/catalog_add.py +5 -5
- package/modules/localmodels/catalog_license.py +2 -0
- package/modules/localmodels/catalog_recipes.py +2 -0
- package/modules/localmodels/cli_parser.py +6 -2
- package/modules/localmodels/context_policy.py +40 -4
- package/modules/localmodels/custom_hub_http.py +27 -104
- package/modules/localmodels/debug_mode.py +13 -0
- package/modules/localmodels/debug_stub_server.py +156 -1
- package/modules/localmodels/deploy.py +11 -2
- package/modules/localmodels/download-mirrors.json +12 -0
- package/modules/localmodels/engines-b12757-mix-ef2df21.json +26 -0
- package/modules/localmodels/engines-whisper-b5454.json +120 -1
- package/modules/localmodels/gateway_app_bifrost.py +14 -14
- package/modules/localmodels/gateway_bifrost.py +4 -1
- package/modules/localmodels/gateway_cli.py +14 -80
- package/modules/localmodels/gateway_server.py +88 -16
- package/modules/localmodels/gpu_specs.py +35 -1
- package/modules/localmodels/harness.py +1 -2
- package/modules/localmodels/hf_repo.py +12 -4
- package/modules/localmodels/install.py +4 -4
- package/modules/localmodels/library_jobs.py +4 -0
- package/modules/localmodels/library_serve.py +69 -13
- package/modules/localmodels/memcalc_load.py +9 -4
- package/modules/localmodels/npm_transport.py +4 -58
- package/modules/localmodels/recommend_cli.py +2 -1
- package/modules/localmodels/remote_ops.py +120 -713
- package/modules/localmodels/remote_ops_common.py +670 -0
- package/modules/localmodels/remote_ops_download.py +399 -381
- package/modules/localmodels/remote_ops_mirrors.py +27 -66
- package/modules/localmodels/remote_ops_prepare.py +43 -35
- package/modules/localmodels/remote_ops_ranges.py +102 -63
- package/modules/localmodels/remote_ops_redirect.py +393 -0
- package/modules/localmodels/remote_ops_remove.py +30 -22
- package/modules/localmodels/remote_ops_service.py +102 -95
- package/modules/localmodels/remote_ops_verify.py +94 -63
- package/modules/localmodels/runtime_cli.py +15 -5
- package/modules/localmodels/runtime_io.py +54 -1
- package/modules/localmodels/source_cli.py +136 -23
- package/modules/localmodels/speech-sv.txt +93 -0
- package/modules/localmodels/speech_admission.py +437 -0
- package/modules/localmodels/speech_catalog.py +170 -0
- package/modules/localmodels/speech_cli.py +273 -0
- package/modules/localmodels/speech_jobs.py +776 -0
- package/modules/localmodels/speech_model.py +404 -0
- package/modules/localmodels/speech_serve.py +287 -0
- package/modules/localmodels/speech_server.py +837 -0
- package/modules/localmodels/speech_state.py +697 -0
- package/modules/localmodels/speech_worker_sensevoice.py +255 -0
- package/modules/localmodels/speech_workers.py +783 -0
- package/modules/localmodels/stack.py +0 -33
- package/modules/localmodels/stack_auto.py +5 -3
- package/modules/localmodels/stack_aux_gpu.py +45 -4
- package/modules/localmodels/stack_capacity.py +77 -8
- package/modules/localmodels/stack_cli.py +16 -1
- package/modules/localmodels/stack_compose.py +1 -1
- package/modules/localmodels/stack_down.py +24 -1
- package/modules/localmodels/stack_hardware.py +57 -88
- package/modules/localmodels/stack_hardware_text.py +4 -59
- package/modules/localmodels/stack_memory.py +13 -3
- package/modules/localmodels/stack_suite.py +9 -10
- package/modules/localmodels/stack_summary.py +4 -4
- package/modules/localmodels/stack_view_llm.py +1 -1
- package/modules/localmodels/transport.py +4 -2
- package/modules/localmodels/tui_views.py +2 -2
- package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/RECORD +75 -61
- package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/licenses/NOTICE +9 -0
- package/package.json +1 -1
- package/tool.json +1 -1
- /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev62.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
"""Data model, schemas, closed enums, validation, and JSON/JSONL emitters for ``localmodels speech``.
|
|
2
|
+
|
|
3
|
+
Conforms byte-for-byte to the frozen v1 cross-repo speech contract:
|
|
4
|
+
- ``localmodels.speech-status/v1``
|
|
5
|
+
- ``localmodels.speech-event/v1``
|
|
6
|
+
- ``localmodels.speech-config/v1``
|
|
7
|
+
- ``localmodels.speech-runtime/v1``
|
|
8
|
+
- ``localmodels.speech-stop/v1``
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
import sys
|
|
16
|
+
from typing import Literal, TypedDict
|
|
17
|
+
|
|
18
|
+
STATUS_SCHEMA = "localmodels.speech-status/v1"
|
|
19
|
+
EVENT_SCHEMA = "localmodels.speech-event/v1"
|
|
20
|
+
CONFIG_SCHEMA = "localmodels.speech-config/v1"
|
|
21
|
+
RUNTIME_SCHEMA = "localmodels.speech-runtime/v1"
|
|
22
|
+
STOP_SCHEMA = "localmodels.speech-stop/v1"
|
|
23
|
+
|
|
24
|
+
SpeechModelState = Literal["absent", "downloading", "idle", "loading", "loaded", "failed"]
|
|
25
|
+
SPEECH_MODEL_STATES: tuple[SpeechModelState, ...] = (
|
|
26
|
+
"absent",
|
|
27
|
+
"downloading",
|
|
28
|
+
"idle",
|
|
29
|
+
"loading",
|
|
30
|
+
"loaded",
|
|
31
|
+
"failed",
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
SpeechRuntimeState = Literal["stopped", "standby", "loading", "loaded", "error"]
|
|
35
|
+
SPEECH_RUNTIME_STATES: tuple[SpeechRuntimeState, ...] = (
|
|
36
|
+
"stopped",
|
|
37
|
+
"standby",
|
|
38
|
+
"loading",
|
|
39
|
+
"loaded",
|
|
40
|
+
"error",
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
RequestedDevice = Literal["gpu", "cpu"]
|
|
44
|
+
REQUESTED_DEVICES: tuple[RequestedDevice, ...] = ("gpu", "cpu")
|
|
45
|
+
|
|
46
|
+
EffectiveDevice = Literal["cuda", "metal", "vulkan", "directml", "cpu"]
|
|
47
|
+
EFFECTIVE_DEVICES: tuple[EffectiveDevice, ...] = ("cuda", "metal", "vulkan", "directml", "cpu")
|
|
48
|
+
|
|
49
|
+
FallbackReason = Literal[
|
|
50
|
+
"insufficient_vram",
|
|
51
|
+
"insufficient_unified_memory",
|
|
52
|
+
"memory_pressure_warn",
|
|
53
|
+
"memory_pressure_critical",
|
|
54
|
+
"driver_update_required",
|
|
55
|
+
"vulkan_unavailable",
|
|
56
|
+
"gpu_engine_unavailable",
|
|
57
|
+
"gpu_unsupported_platform",
|
|
58
|
+
"cpu_optimal_for_int8",
|
|
59
|
+
"gpu_init_failed",
|
|
60
|
+
"runtime_oom_fallback",
|
|
61
|
+
"yielded_to_llm",
|
|
62
|
+
"no_supported_gpu",
|
|
63
|
+
]
|
|
64
|
+
FALLBACK_REASONS: tuple[FallbackReason, ...] = (
|
|
65
|
+
"insufficient_vram",
|
|
66
|
+
"insufficient_unified_memory",
|
|
67
|
+
"memory_pressure_warn",
|
|
68
|
+
"memory_pressure_critical",
|
|
69
|
+
"driver_update_required",
|
|
70
|
+
"vulkan_unavailable",
|
|
71
|
+
"gpu_engine_unavailable",
|
|
72
|
+
"gpu_unsupported_platform",
|
|
73
|
+
"cpu_optimal_for_int8",
|
|
74
|
+
"gpu_init_failed",
|
|
75
|
+
"runtime_oom_fallback",
|
|
76
|
+
"yielded_to_llm",
|
|
77
|
+
"no_supported_gpu",
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
DownloadStep = Literal["download", "verify"]
|
|
81
|
+
DOWNLOAD_STEPS: tuple[DownloadStep, ...] = ("download", "verify")
|
|
82
|
+
|
|
83
|
+
LoadStep = Literal["prepare", "start", "load", "warm"]
|
|
84
|
+
LOAD_STEPS: tuple[LoadStep, ...] = ("prepare", "start", "load", "warm")
|
|
85
|
+
|
|
86
|
+
DEFAULT_MODEL_ID = "whisper-large-v3-turbo"
|
|
87
|
+
DEFAULT_USE_GPU = True
|
|
88
|
+
DEFAULT_KEEP_LOADED_SECONDS = 900
|
|
89
|
+
MIN_KEEP_LOADED_SECONDS = -1
|
|
90
|
+
MAX_KEEP_LOADED_SECONDS = 86400
|
|
91
|
+
DEFAULT_LANGUAGE = "auto"
|
|
92
|
+
|
|
93
|
+
_LANGUAGE_RE = re.compile(r"^[a-zA-Z]{2,3}(?:-[a-zA-Z0-9]{2,8})*$")
|
|
94
|
+
|
|
95
|
+
EXIT_OK = 0
|
|
96
|
+
EXIT_FAILED = 1
|
|
97
|
+
EXIT_REFUSED = 2
|
|
98
|
+
EXIT_CANCELLED = 130
|
|
99
|
+
DETAIL_LIMIT = 500
|
|
100
|
+
|
|
101
|
+
ERROR_CODES = (
|
|
102
|
+
"MODEL_UNKNOWN",
|
|
103
|
+
"INVALID_CONFIG",
|
|
104
|
+
"INVALID_STATE",
|
|
105
|
+
"JOB_RUNNING",
|
|
106
|
+
"DISK_INSUFFICIENT",
|
|
107
|
+
"DOWNLOAD_FAILED",
|
|
108
|
+
"CHECKSUM_MISMATCH",
|
|
109
|
+
"NETWORK_UNAVAILABLE",
|
|
110
|
+
"ENGINE_UNAVAILABLE",
|
|
111
|
+
"NOT_IMPLEMENTED",
|
|
112
|
+
"CANCELLED",
|
|
113
|
+
"RUNTIME_ERROR",
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
REFUSALS = frozenset(
|
|
117
|
+
(
|
|
118
|
+
"MODEL_UNKNOWN",
|
|
119
|
+
"INVALID_CONFIG",
|
|
120
|
+
"INVALID_STATE",
|
|
121
|
+
"JOB_RUNNING",
|
|
122
|
+
"DISK_INSUFFICIENT",
|
|
123
|
+
"NOT_IMPLEMENTED",
|
|
124
|
+
)
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class SpeechError(Exception):
|
|
129
|
+
"""Structured speech CLI error carrying a closed code, message, and exit status."""
|
|
130
|
+
|
|
131
|
+
def __init__(
|
|
132
|
+
self,
|
|
133
|
+
code: str,
|
|
134
|
+
message: str,
|
|
135
|
+
*,
|
|
136
|
+
failed: bool = False,
|
|
137
|
+
**fields: str | int | bool,
|
|
138
|
+
) -> None:
|
|
139
|
+
if code not in ERROR_CODES:
|
|
140
|
+
raise ValueError(f"unknown speech error code: {code}")
|
|
141
|
+
super().__init__(message)
|
|
142
|
+
self.code = code
|
|
143
|
+
self.message = message[-DETAIL_LIMIT:]
|
|
144
|
+
self.failed = failed
|
|
145
|
+
self.fields = fields
|
|
146
|
+
|
|
147
|
+
@property
|
|
148
|
+
def exit_code(self) -> int:
|
|
149
|
+
if self.code == "CANCELLED":
|
|
150
|
+
return EXIT_CANCELLED
|
|
151
|
+
return EXIT_REFUSED if self.code in REFUSALS and not self.failed else EXIT_FAILED
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class SpeechConfig(TypedDict):
|
|
155
|
+
model_id: str
|
|
156
|
+
use_gpu: bool
|
|
157
|
+
keep_loaded_seconds: int
|
|
158
|
+
language: str
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class SpeechDownloadProgress(TypedDict):
|
|
162
|
+
step: DownloadStep
|
|
163
|
+
done_bytes: int
|
|
164
|
+
total_bytes: int
|
|
165
|
+
bytes_per_second: int
|
|
166
|
+
source: str
|
|
167
|
+
connections: int
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class SpeechModelError(TypedDict):
|
|
171
|
+
code: str
|
|
172
|
+
message: str
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class SpeechRuntime(TypedDict):
|
|
176
|
+
running: bool
|
|
177
|
+
state: SpeechRuntimeState
|
|
178
|
+
base_url: str | None
|
|
179
|
+
key_file: str | None
|
|
180
|
+
active_model: str | None
|
|
181
|
+
engine: str | None
|
|
182
|
+
requested_device: RequestedDevice
|
|
183
|
+
effective_device: EffectiveDevice | None
|
|
184
|
+
fallback_reason: FallbackReason | None
|
|
185
|
+
fallback_detail: dict[str, object] | None
|
|
186
|
+
vram_used_bytes: int
|
|
187
|
+
ram_used_bytes: int
|
|
188
|
+
keep_loaded_seconds: int
|
|
189
|
+
idle_remaining_seconds: int | None
|
|
190
|
+
active_sessions: int
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class SpeechModelRow(TypedDict):
|
|
194
|
+
id: str
|
|
195
|
+
name: str
|
|
196
|
+
engine: str
|
|
197
|
+
languages: list[str]
|
|
198
|
+
language_count: int
|
|
199
|
+
quality_rating: str
|
|
200
|
+
license: str
|
|
201
|
+
license_url: str
|
|
202
|
+
commercial_notice: str | None
|
|
203
|
+
disk_size_bytes: int
|
|
204
|
+
vram_estimate_bytes: int
|
|
205
|
+
ram_estimate_bytes: int
|
|
206
|
+
gpu_supported: bool
|
|
207
|
+
state: SpeechModelState
|
|
208
|
+
active: bool
|
|
209
|
+
download: SpeechDownloadProgress | None
|
|
210
|
+
error: SpeechModelError | None
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
class SpeechStatusDocument(TypedDict):
|
|
214
|
+
schema: str
|
|
215
|
+
tool_version: str
|
|
216
|
+
observed_at: str
|
|
217
|
+
config: SpeechConfig
|
|
218
|
+
runtime: SpeechRuntime
|
|
219
|
+
models: list[SpeechModelRow]
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class SpeechConfigDocument(TypedDict):
|
|
223
|
+
schema: str
|
|
224
|
+
ok: bool
|
|
225
|
+
config: SpeechConfig
|
|
226
|
+
runtime_updated: bool
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
class SpeechRuntimeDocument(TypedDict):
|
|
230
|
+
schema: str
|
|
231
|
+
ok: bool
|
|
232
|
+
runtime: SpeechRuntime
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
class SpeechStopDocument(TypedDict):
|
|
236
|
+
schema: str
|
|
237
|
+
ok: bool
|
|
238
|
+
stopped: bool
|
|
239
|
+
detail: str
|
|
240
|
+
runtime: SpeechRuntime
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def default_config() -> SpeechConfig:
|
|
244
|
+
"""Default speech configuration (opt-in models are never selected by default)."""
|
|
245
|
+
return {
|
|
246
|
+
"model_id": DEFAULT_MODEL_ID,
|
|
247
|
+
"use_gpu": DEFAULT_USE_GPU,
|
|
248
|
+
"keep_loaded_seconds": DEFAULT_KEEP_LOADED_SECONDS,
|
|
249
|
+
"language": DEFAULT_LANGUAGE,
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def stopped_runtime(config: SpeechConfig) -> SpeechRuntime:
|
|
254
|
+
"""Runtime block reported when no speech sidecar is reachable."""
|
|
255
|
+
return {
|
|
256
|
+
"running": False,
|
|
257
|
+
"state": "stopped",
|
|
258
|
+
"base_url": None,
|
|
259
|
+
"key_file": None,
|
|
260
|
+
"active_model": None,
|
|
261
|
+
"engine": None,
|
|
262
|
+
"requested_device": "gpu" if config["use_gpu"] else "cpu",
|
|
263
|
+
"effective_device": None,
|
|
264
|
+
"fallback_reason": None,
|
|
265
|
+
"fallback_detail": None,
|
|
266
|
+
"vram_used_bytes": 0,
|
|
267
|
+
"ram_used_bytes": 0,
|
|
268
|
+
"keep_loaded_seconds": config["keep_loaded_seconds"],
|
|
269
|
+
"idle_remaining_seconds": None,
|
|
270
|
+
"active_sessions": 0,
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def validate_keep_loaded_seconds(value: int) -> int:
|
|
275
|
+
"""Validate ``keep_loaded_seconds`` (-1 = never unload, 0 = immediate, 1..86400 = TTL)."""
|
|
276
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
277
|
+
raise SpeechError("INVALID_CONFIG", "keep_loaded_seconds must be an integer")
|
|
278
|
+
if value < MIN_KEEP_LOADED_SECONDS or value > MAX_KEEP_LOADED_SECONDS:
|
|
279
|
+
raise SpeechError(
|
|
280
|
+
"INVALID_CONFIG",
|
|
281
|
+
f"keep_loaded_seconds must be between {MIN_KEEP_LOADED_SECONDS} and "
|
|
282
|
+
f"{MAX_KEEP_LOADED_SECONDS} (got {value})",
|
|
283
|
+
)
|
|
284
|
+
return value
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def validate_language(value: str) -> str:
|
|
288
|
+
"""Validate ``language`` ('auto' or a BCP-47 / ISO-639-1 language tag)."""
|
|
289
|
+
cleaned = value.strip()
|
|
290
|
+
if not cleaned:
|
|
291
|
+
raise SpeechError("INVALID_CONFIG", "language must not be empty")
|
|
292
|
+
if cleaned.lower() == "auto":
|
|
293
|
+
return "auto"
|
|
294
|
+
if not _LANGUAGE_RE.fullmatch(cleaned):
|
|
295
|
+
raise SpeechError(
|
|
296
|
+
"INVALID_CONFIG",
|
|
297
|
+
f"invalid language code {value!r}; expected 'auto' or an ISO-639-1 / BCP-47 tag",
|
|
298
|
+
)
|
|
299
|
+
parts = cleaned.split("-")
|
|
300
|
+
parts[0] = parts[0].lower()
|
|
301
|
+
return "-".join(parts)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def parse_bool_flag(raw: str) -> bool:
|
|
305
|
+
"""Parse explicit CLI boolean flags ('true' or 'false')."""
|
|
306
|
+
lowered = raw.strip().lower()
|
|
307
|
+
if lowered == "true":
|
|
308
|
+
return True
|
|
309
|
+
if lowered == "false":
|
|
310
|
+
return False
|
|
311
|
+
raise SpeechError("INVALID_CONFIG", f"expected 'true' or 'false', got {raw!r}")
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _write_line(doc: object) -> None:
|
|
315
|
+
sys.stdout.write(json.dumps(doc, ensure_ascii=False, separators=(",", ":")) + "\n")
|
|
316
|
+
sys.stdout.flush()
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def emit_progress(
|
|
320
|
+
model_id: str,
|
|
321
|
+
step: DownloadStep,
|
|
322
|
+
done_bytes: int,
|
|
323
|
+
total_bytes: int,
|
|
324
|
+
bytes_per_second: int = 0,
|
|
325
|
+
*,
|
|
326
|
+
source: str = "huggingface",
|
|
327
|
+
connections: int = 0,
|
|
328
|
+
) -> None:
|
|
329
|
+
"""Emit one ``localmodels.speech-event/v1`` JSONL progress line on stdout."""
|
|
330
|
+
total = max(0, int(total_bytes))
|
|
331
|
+
done = min(max(0, int(done_bytes)), total)
|
|
332
|
+
doc: dict[str, object] = {
|
|
333
|
+
"schema": EVENT_SCHEMA,
|
|
334
|
+
"event": "progress",
|
|
335
|
+
"model": model_id,
|
|
336
|
+
"step": step,
|
|
337
|
+
"done_bytes": done,
|
|
338
|
+
"total_bytes": total,
|
|
339
|
+
"bytes_per_second": max(0, int(bytes_per_second)),
|
|
340
|
+
"source": source or "custom",
|
|
341
|
+
"connections": max(0, int(connections)),
|
|
342
|
+
}
|
|
343
|
+
_write_line(doc)
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def emit_load_progress(
|
|
347
|
+
model_id: str,
|
|
348
|
+
step: LoadStep,
|
|
349
|
+
done_steps: int,
|
|
350
|
+
total_steps: int = len(LOAD_STEPS),
|
|
351
|
+
) -> None:
|
|
352
|
+
"""Emit one ``localmodels.speech-event/v1`` JSONL load-progress line on stdout."""
|
|
353
|
+
total = max(1, int(total_steps))
|
|
354
|
+
done = min(max(0, int(done_steps)), total)
|
|
355
|
+
doc: dict[str, object] = {
|
|
356
|
+
"schema": EVENT_SCHEMA,
|
|
357
|
+
"event": "progress",
|
|
358
|
+
"model": model_id,
|
|
359
|
+
"step": step,
|
|
360
|
+
"done_steps": done,
|
|
361
|
+
"total_steps": total,
|
|
362
|
+
}
|
|
363
|
+
_write_line(doc)
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def result_event(
|
|
367
|
+
model: SpeechModelRow,
|
|
368
|
+
*,
|
|
369
|
+
runtime: SpeechRuntime | None = None,
|
|
370
|
+
) -> dict[str, object]:
|
|
371
|
+
"""Build a terminal ``localmodels.speech-event/v1`` success payload."""
|
|
372
|
+
doc: dict[str, object] = {
|
|
373
|
+
"schema": EVENT_SCHEMA,
|
|
374
|
+
"event": "result",
|
|
375
|
+
"ok": True,
|
|
376
|
+
"model": model,
|
|
377
|
+
}
|
|
378
|
+
if runtime is not None:
|
|
379
|
+
doc["runtime"] = runtime
|
|
380
|
+
return doc
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def error_event(error: SpeechError, model_id: str | None = None) -> dict[str, object]:
|
|
384
|
+
"""Build a terminal ``localmodels.speech-event/v1`` error payload."""
|
|
385
|
+
doc: dict[str, object] = {
|
|
386
|
+
"schema": EVENT_SCHEMA,
|
|
387
|
+
"event": "error",
|
|
388
|
+
"ok": False,
|
|
389
|
+
"code": error.code,
|
|
390
|
+
"message": error.message,
|
|
391
|
+
}
|
|
392
|
+
if model_id is not None:
|
|
393
|
+
doc["model"] = model_id
|
|
394
|
+
doc.update(error.fields)
|
|
395
|
+
return doc
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def emit_final(doc: object, *, jsonl: bool = False) -> None:
|
|
399
|
+
"""Write a compact JSONL line or pretty-printed JSON document to stdout."""
|
|
400
|
+
if jsonl:
|
|
401
|
+
_write_line(doc)
|
|
402
|
+
else:
|
|
403
|
+
sys.stdout.write(json.dumps(doc, ensure_ascii=False, indent=1) + "\n")
|
|
404
|
+
sys.stdout.flush()
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""Lifecycle verbs for the local speech sidecar: ``start``, ``load``, ``unload``, ``stop``.
|
|
2
|
+
|
|
3
|
+
Also exposes ``stop_if_recorded`` for ``localmodels/stack_down.py`` so desktop quit / uninstall
|
|
4
|
+
tears down the speech sidecar cleanly within <5s without breaking ``stack down`` JSON contracts.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import contextlib
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
import time
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, Literal
|
|
15
|
+
|
|
16
|
+
from localmodels import (
|
|
17
|
+
auth_proxy,
|
|
18
|
+
debug_mode,
|
|
19
|
+
process_identity,
|
|
20
|
+
speech_catalog,
|
|
21
|
+
speech_jobs,
|
|
22
|
+
speech_server,
|
|
23
|
+
speech_state,
|
|
24
|
+
stack_ports,
|
|
25
|
+
)
|
|
26
|
+
from localmodels.speech_model import (
|
|
27
|
+
RUNTIME_SCHEMA,
|
|
28
|
+
SpeechError,
|
|
29
|
+
SpeechRuntime,
|
|
30
|
+
SpeechRuntimeDocument,
|
|
31
|
+
SpeechStopDocument,
|
|
32
|
+
emit_load_progress,
|
|
33
|
+
result_event,
|
|
34
|
+
stopped_runtime,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
START_TIMEOUT_S = 30.0
|
|
38
|
+
SHUTDOWN_HTTP_TIMEOUT_S = 1.0
|
|
39
|
+
SHUTDOWN_POLL_S = 1.0
|
|
40
|
+
STOP_GRACE_S = 3.0
|
|
41
|
+
LOAD_HTTP_TIMEOUT_S = 90.0
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def choose_port(requested: int | None = None) -> int:
|
|
45
|
+
"""Validate an explicit port or select the first free loopback port from STT defaults."""
|
|
46
|
+
if requested is not None:
|
|
47
|
+
if not 1 <= requested <= 65535:
|
|
48
|
+
raise SpeechError("INVALID_CONFIG", f"--port must be in 1..65535 (got {requested})")
|
|
49
|
+
return requested
|
|
50
|
+
if debug_mode.current().mode == "simulate":
|
|
51
|
+
return auth_proxy.free_port()
|
|
52
|
+
for candidate in stack_ports.AUXILIARY_PORTS["stt"]:
|
|
53
|
+
try:
|
|
54
|
+
if not stack_ports.loopback_listening(candidate):
|
|
55
|
+
return int(candidate)
|
|
56
|
+
except Exception: # noqa: BLE001
|
|
57
|
+
continue
|
|
58
|
+
raise SpeechError(
|
|
59
|
+
"RUNTIME_ERROR",
|
|
60
|
+
"all default speech ports (18370, 18464..18495) are in use; pass --port",
|
|
61
|
+
failed=True,
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _sidecar_error(status: int, parsed: dict[str, Any] | None, fallback_msg: str) -> SpeechError:
|
|
66
|
+
err = parsed.get("error") if isinstance(parsed, dict) else None
|
|
67
|
+
code = "RUNTIME_ERROR"
|
|
68
|
+
msg = fallback_msg
|
|
69
|
+
if isinstance(err, dict):
|
|
70
|
+
raw_code = str(err.get("code") or "")
|
|
71
|
+
if raw_code in ("MODEL_UNKNOWN", "INVALID_CONFIG", "INVALID_STATE", "ENGINE_UNAVAILABLE"):
|
|
72
|
+
code = raw_code
|
|
73
|
+
if isinstance(err.get("message"), str) and err["message"]:
|
|
74
|
+
msg = err["message"]
|
|
75
|
+
return SpeechError(code, msg, failed=status >= 500 or status == 0)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _wait_sidecar_healthy(
|
|
79
|
+
base_url: str,
|
|
80
|
+
proc: Any,
|
|
81
|
+
log_path: Path,
|
|
82
|
+
timeout_s: float = START_TIMEOUT_S,
|
|
83
|
+
) -> None:
|
|
84
|
+
deadline = time.monotonic() + timeout_s
|
|
85
|
+
while time.monotonic() < deadline:
|
|
86
|
+
code = proc.poll()
|
|
87
|
+
if code is not None:
|
|
88
|
+
tail = ""
|
|
89
|
+
with contextlib.suppress(OSError):
|
|
90
|
+
tail = log_path.read_text(encoding="utf-8", errors="replace")[-500:].strip()
|
|
91
|
+
detail = f": {tail}" if tail else ""
|
|
92
|
+
raise SpeechError(
|
|
93
|
+
"RUNTIME_ERROR",
|
|
94
|
+
f"speech sidecar exited early with status {code}{detail}",
|
|
95
|
+
failed=True,
|
|
96
|
+
)
|
|
97
|
+
health = speech_state.sidecar_request(base_url, "/health", timeout=1.0)
|
|
98
|
+
if health is not None and health.get("status") == "ok":
|
|
99
|
+
return
|
|
100
|
+
time.sleep(0.1)
|
|
101
|
+
process_identity.kill_started(proc.pid)
|
|
102
|
+
raise SpeechError(
|
|
103
|
+
"RUNTIME_ERROR",
|
|
104
|
+
f"speech sidecar did not become healthy within {timeout_s:.0f}s",
|
|
105
|
+
failed=True,
|
|
106
|
+
)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _spawn_sidecar(base_dir: str, port: int, state_dir: Path | None) -> str:
|
|
110
|
+
"""Spawn detached sidecar without leaking devnull fds."""
|
|
111
|
+
resolved_state = speech_state.root(state_dir).parent
|
|
112
|
+
speech_state.ensure_api_key(state_dir)
|
|
113
|
+
speech_server.ensure_run_dir(state_dir)
|
|
114
|
+
log_path = speech_state.server_log_path(state_dir)
|
|
115
|
+
log_path.parent.mkdir(parents=True, exist_ok=True)
|
|
116
|
+
argv = [
|
|
117
|
+
sys.executable,
|
|
118
|
+
"-P",
|
|
119
|
+
"-s",
|
|
120
|
+
"-m",
|
|
121
|
+
"localmodels.speech_server",
|
|
122
|
+
"--base-dir",
|
|
123
|
+
os.path.expanduser(base_dir),
|
|
124
|
+
"--port",
|
|
125
|
+
str(port),
|
|
126
|
+
"--state-dir",
|
|
127
|
+
str(resolved_state),
|
|
128
|
+
]
|
|
129
|
+
env = dict(os.environ)
|
|
130
|
+
env["LOCALMODELS_STATE"] = str(resolved_state)
|
|
131
|
+
package_parent = str(Path(__file__).resolve().parents[1])
|
|
132
|
+
existing_pp = env.get("PYTHONPATH", "")
|
|
133
|
+
if package_parent not in existing_pp.split(os.pathsep):
|
|
134
|
+
env["PYTHONPATH"] = (
|
|
135
|
+
package_parent if not existing_pp else package_parent + os.pathsep + existing_pp
|
|
136
|
+
)
|
|
137
|
+
with open(os.devnull, "rb") as devnull, log_path.open("ab") as log_stream:
|
|
138
|
+
proc = process_identity.spawn_detached(
|
|
139
|
+
argv,
|
|
140
|
+
stdin=devnull,
|
|
141
|
+
stdout=log_stream,
|
|
142
|
+
stderr=log_stream,
|
|
143
|
+
env=env,
|
|
144
|
+
)
|
|
145
|
+
pid_file = speech_state.server_pid_path(state_dir)
|
|
146
|
+
with contextlib.suppress(OSError, RuntimeError):
|
|
147
|
+
process_identity.save(pid_file, proc.pid)
|
|
148
|
+
base_url = f"http://127.0.0.1:{port}"
|
|
149
|
+
_wait_sidecar_healthy(base_url, proc, log_path)
|
|
150
|
+
return base_url
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def start(
|
|
154
|
+
base_dir: str,
|
|
155
|
+
*,
|
|
156
|
+
standby: bool = True,
|
|
157
|
+
model_id: str | None = None,
|
|
158
|
+
port: int | None = None,
|
|
159
|
+
state_dir: Path | None = None,
|
|
160
|
+
) -> SpeechRuntimeDocument:
|
|
161
|
+
"""Idempotently start the speech sidecar (standby by default, or load ``model_id``)."""
|
|
162
|
+
if model_id is not None and model_id not in speech_catalog.V1_SPEECH_MODEL_IDS:
|
|
163
|
+
raise SpeechError("MODEL_UNKNOWN", f"unknown speech model: {model_id}")
|
|
164
|
+
if port is not None:
|
|
165
|
+
choose_port(port)
|
|
166
|
+
|
|
167
|
+
cfg = speech_state.load_config(state_dir)
|
|
168
|
+
runtime = speech_state.probe_live_runtime(cfg, state_dir)
|
|
169
|
+
if not runtime["running"]:
|
|
170
|
+
with speech_state.locked(state_dir):
|
|
171
|
+
runtime = speech_state.probe_live_runtime(cfg, state_dir)
|
|
172
|
+
if not runtime["running"]:
|
|
173
|
+
selected_port = choose_port(port)
|
|
174
|
+
_spawn_sidecar(base_dir, selected_port, state_dir)
|
|
175
|
+
runtime = speech_state.probe_live_runtime(cfg, state_dir)
|
|
176
|
+
if not runtime["running"]:
|
|
177
|
+
raise SpeechError(
|
|
178
|
+
"RUNTIME_ERROR", "speech sidecar failed health verification", failed=True
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
if model_id is not None and not standby:
|
|
182
|
+
base_url = runtime["base_url"] or ""
|
|
183
|
+
status_code, parsed = speech_state.sidecar_request_detail(
|
|
184
|
+
base_url,
|
|
185
|
+
"/v1/speech/load",
|
|
186
|
+
method="POST",
|
|
187
|
+
key_file=runtime["key_file"],
|
|
188
|
+
payload={"model_id": model_id},
|
|
189
|
+
timeout=LOAD_HTTP_TIMEOUT_S,
|
|
190
|
+
)
|
|
191
|
+
if not 200 <= status_code < 300:
|
|
192
|
+
raise _sidecar_error(status_code, parsed, f"failed to load {model_id}")
|
|
193
|
+
runtime = speech_state.probe_live_runtime(cfg, state_dir)
|
|
194
|
+
|
|
195
|
+
return {"schema": RUNTIME_SCHEMA, "ok": True, "runtime": runtime}
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def load(
|
|
199
|
+
model_id: str,
|
|
200
|
+
base_dir: str,
|
|
201
|
+
*,
|
|
202
|
+
use_gpu: bool | None = None,
|
|
203
|
+
state_dir: Path | None = None,
|
|
204
|
+
) -> dict[str, object]:
|
|
205
|
+
"""Ensure sidecar running, admit & load ``model_id``, emitting JSONL load progress."""
|
|
206
|
+
try:
|
|
207
|
+
spec = speech_catalog.speech_model(model_id)
|
|
208
|
+
except KeyError:
|
|
209
|
+
raise SpeechError("MODEL_UNKNOWN", f"unknown speech model: {model_id}") from None
|
|
210
|
+
|
|
211
|
+
emit_load_progress(spec.id, "prepare", 1, 4)
|
|
212
|
+
if not speech_jobs.weights_installed(spec, base_dir):
|
|
213
|
+
raise SpeechError(
|
|
214
|
+
"INVALID_STATE",
|
|
215
|
+
f"{spec.id} is not downloaded; run `localmodels speech download {spec.id}` first",
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
emit_load_progress(spec.id, "start", 2, 4)
|
|
219
|
+
started = start(base_dir, standby=True, state_dir=state_dir)
|
|
220
|
+
runtime = started["runtime"]
|
|
221
|
+
base_url = runtime["base_url"] or ""
|
|
222
|
+
|
|
223
|
+
emit_load_progress(spec.id, "load", 3, 4)
|
|
224
|
+
payload: dict[str, object] = {"model_id": spec.id}
|
|
225
|
+
if use_gpu is not None:
|
|
226
|
+
payload["use_gpu"] = use_gpu
|
|
227
|
+
status_code, parsed = speech_state.sidecar_request_detail(
|
|
228
|
+
base_url,
|
|
229
|
+
"/v1/speech/load",
|
|
230
|
+
method="POST",
|
|
231
|
+
key_file=runtime["key_file"],
|
|
232
|
+
payload=payload,
|
|
233
|
+
timeout=LOAD_HTTP_TIMEOUT_S,
|
|
234
|
+
)
|
|
235
|
+
if not 200 <= status_code < 300:
|
|
236
|
+
raise _sidecar_error(status_code, parsed, f"failed to load speech model {spec.id}")
|
|
237
|
+
|
|
238
|
+
emit_load_progress(spec.id, "warm", 4, 4)
|
|
239
|
+
cfg = speech_state.load_config(state_dir)
|
|
240
|
+
live: SpeechRuntime = speech_state.probe_live_runtime(cfg, state_dir)
|
|
241
|
+
if not live["running"] or live["active_model"] != spec.id or live["state"] != "loaded":
|
|
242
|
+
raise SpeechError(
|
|
243
|
+
"RUNTIME_ERROR",
|
|
244
|
+
f"speech model {spec.id} did not reach loaded state",
|
|
245
|
+
failed=True,
|
|
246
|
+
)
|
|
247
|
+
row = speech_jobs.model_row(spec.id, base_dir, state_dir=state_dir)
|
|
248
|
+
return result_event(row, runtime=live)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def unload(base_dir: str, *, state_dir: Path | None = None) -> SpeechRuntimeDocument:
|
|
252
|
+
"""Unload the active engine worker while keeping the sidecar in standby (idempotent)."""
|
|
253
|
+
_ = base_dir
|
|
254
|
+
cfg = speech_state.load_config(state_dir)
|
|
255
|
+
live = speech_state.probe_live_runtime(cfg, state_dir)
|
|
256
|
+
if not live["running"] or not live["base_url"]:
|
|
257
|
+
return {"schema": RUNTIME_SCHEMA, "ok": True, "runtime": stopped_runtime(cfg)}
|
|
258
|
+
status_code, parsed = speech_state.sidecar_request_detail(
|
|
259
|
+
live["base_url"],
|
|
260
|
+
"/v1/speech/unload",
|
|
261
|
+
method="POST",
|
|
262
|
+
key_file=live["key_file"],
|
|
263
|
+
payload={},
|
|
264
|
+
timeout=5.0,
|
|
265
|
+
)
|
|
266
|
+
if not 200 <= status_code < 300:
|
|
267
|
+
raise _sidecar_error(status_code, parsed, "failed to unload speech model")
|
|
268
|
+
refreshed = speech_state.probe_live_runtime(cfg, state_dir)
|
|
269
|
+
return {"schema": RUNTIME_SCHEMA, "ok": True, "runtime": refreshed}
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def stop(base_dir: str = "", *, state_dir: Path | None = None) -> SpeechStopDocument:
|
|
273
|
+
"""Stop the speech sidecar cleanly (HTTP shutdown -> verified process_identity.stop)."""
|
|
274
|
+
_ = base_dir
|
|
275
|
+
return speech_state.stop_sidecar(
|
|
276
|
+
state_dir,
|
|
277
|
+
http_timeout_s=SHUTDOWN_HTTP_TIMEOUT_S,
|
|
278
|
+
poll_s=SHUTDOWN_POLL_S,
|
|
279
|
+
grace_s=STOP_GRACE_S,
|
|
280
|
+
)
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def stop_if_recorded(
|
|
284
|
+
state_dir: Path | None = None,
|
|
285
|
+
) -> tuple[Literal["none", "stopped", "not-running", "failed"], str]:
|
|
286
|
+
"""Stop any speech sidecar recorded under ``state_dir`` for ``stack down``."""
|
|
287
|
+
return speech_state.stop_sidecar_if_recorded(state_dir)
|