@simplexai/localmodels-win32-x64 0.1.0-dev.60 → 0.1.0-dev.61

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 (74) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +73 -60
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +5 -3
  5. package/modules/localmodels/auth_proxy.py +185 -19
  6. package/modules/localmodels/catalog.json +363 -0
  7. package/modules/localmodels/catalog.py +1 -1
  8. package/modules/localmodels/catalog_add.py +5 -5
  9. package/modules/localmodels/catalog_license.py +2 -0
  10. package/modules/localmodels/catalog_recipes.py +2 -0
  11. package/modules/localmodels/cli_parser.py +6 -2
  12. package/modules/localmodels/context_policy.py +40 -4
  13. package/modules/localmodels/debug_mode.py +13 -0
  14. package/modules/localmodels/debug_stub_server.py +156 -1
  15. package/modules/localmodels/deploy.py +11 -2
  16. package/modules/localmodels/download-mirrors.json +12 -0
  17. package/modules/localmodels/engines-b12757-mix-ef2df21.json +26 -0
  18. package/modules/localmodels/engines-whisper-b5454.json +120 -1
  19. package/modules/localmodels/gateway_app_bifrost.py +14 -14
  20. package/modules/localmodels/gateway_bifrost.py +4 -1
  21. package/modules/localmodels/gateway_cli.py +14 -80
  22. package/modules/localmodels/gateway_server.py +88 -16
  23. package/modules/localmodels/gpu_specs.py +35 -1
  24. package/modules/localmodels/harness.py +1 -2
  25. package/modules/localmodels/hf_repo.py +12 -4
  26. package/modules/localmodels/install.py +4 -4
  27. package/modules/localmodels/library_serve.py +69 -13
  28. package/modules/localmodels/npm_transport.py +4 -58
  29. package/modules/localmodels/recommend_cli.py +2 -1
  30. package/modules/localmodels/remote_ops.py +120 -713
  31. package/modules/localmodels/remote_ops_common.py +729 -0
  32. package/modules/localmodels/remote_ops_download.py +397 -381
  33. package/modules/localmodels/remote_ops_mirrors.py +26 -65
  34. package/modules/localmodels/remote_ops_prepare.py +43 -35
  35. package/modules/localmodels/remote_ops_ranges.py +98 -62
  36. package/modules/localmodels/remote_ops_remove.py +30 -22
  37. package/modules/localmodels/remote_ops_service.py +102 -95
  38. package/modules/localmodels/remote_ops_verify.py +94 -63
  39. package/modules/localmodels/runtime_cli.py +15 -5
  40. package/modules/localmodels/runtime_io.py +54 -1
  41. package/modules/localmodels/speech-sv.txt +93 -0
  42. package/modules/localmodels/speech_admission.py +437 -0
  43. package/modules/localmodels/speech_catalog.py +170 -0
  44. package/modules/localmodels/speech_cli.py +273 -0
  45. package/modules/localmodels/speech_jobs.py +772 -0
  46. package/modules/localmodels/speech_model.py +404 -0
  47. package/modules/localmodels/speech_serve.py +287 -0
  48. package/modules/localmodels/speech_server.py +837 -0
  49. package/modules/localmodels/speech_state.py +697 -0
  50. package/modules/localmodels/speech_worker_sensevoice.py +255 -0
  51. package/modules/localmodels/speech_workers.py +783 -0
  52. package/modules/localmodels/stack.py +0 -33
  53. package/modules/localmodels/stack_auto.py +5 -3
  54. package/modules/localmodels/stack_aux_gpu.py +45 -4
  55. package/modules/localmodels/stack_capacity.py +77 -8
  56. package/modules/localmodels/stack_cli.py +16 -1
  57. package/modules/localmodels/stack_compose.py +1 -1
  58. package/modules/localmodels/stack_down.py +24 -1
  59. package/modules/localmodels/stack_hardware.py +57 -88
  60. package/modules/localmodels/stack_hardware_text.py +4 -59
  61. package/modules/localmodels/stack_memory.py +13 -3
  62. package/modules/localmodels/stack_suite.py +9 -10
  63. package/modules/localmodels/stack_summary.py +4 -4
  64. package/modules/localmodels/stack_view_llm.py +1 -1
  65. package/modules/localmodels/transport.py +3 -2
  66. package/modules/localmodels/tui_views.py +2 -2
  67. package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/METADATA +1 -1
  68. package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/RECORD +70 -57
  69. package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/licenses/NOTICE +9 -0
  70. package/package.json +1 -1
  71. package/tool.json +1 -1
  72. /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/WHEEL +0 -0
  73. /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/entry_points.txt +0 -0
  74. /package/modules/{simplex_localmodels-0.1.0.dev60.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,437 @@
1
+ """Bidirectional VRAM / unified-memory admission for local speech and LLM coordination.
2
+
3
+ Core invariant: Speech (``RANK = 2``) NEVER evicts, degrades, or OOMs an active or loading
4
+ local LLM (``RANK = 0``). Before placing a speech model on GPU, this module checks live host
5
+ memory minus in-flight LLM load reservations minus safety cushions, falling back to CPU with
6
+ structured ``fallback_reason`` codes from ``localmodels.speech-status/v1``.
7
+
8
+ Conversely, when a local LLM load needs GPU or unified memory that speech currently holds,
9
+ ``demote_speech_if_holding_pool`` asks the speech sidecar to demote to CPU via
10
+ ``POST /v1/speech/demote-to-cpu`` before the LLM fails with ``LOAD_NO_ROOM`` or steps down its
11
+ elastic posture.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import ctypes
17
+ import os
18
+ from collections.abc import Mapping
19
+ from dataclasses import dataclass
20
+ from pathlib import Path
21
+
22
+ from localmodels import (
23
+ app,
24
+ budget,
25
+ engines,
26
+ hosts,
27
+ library_state,
28
+ metal,
29
+ plan_envelope,
30
+ speech_catalog,
31
+ speech_state,
32
+ )
33
+ from localmodels.probe import GPU, HostFacts
34
+ from localmodels.speech_catalog import SpeechModelSpec
35
+ from localmodels.speech_model import EffectiveDevice, FallbackReason, RequestedDevice
36
+
37
+ MIB = 1 << 20
38
+ SPEECH_DISCRETE_VRAM_HEADROOM = 1024 * MIB # 1.0 GiB cushion for active LLM KV / desktop DWM
39
+ SPEECH_METAL_WIRED_HEADROOM = 512 * MIB # 512 MiB cushion under Metal wired ceiling
40
+ SPEECH_RAM_FLOOR = 1024 * MIB # 1.0 GiB minimum OS RAM remaining
41
+ SPEECH_DEMOTE_TIMEOUT_S = 3.5
42
+
43
+ _GPU_EFFECTIVE_DEVICES = frozenset(("cuda", "metal", "vulkan", "directml"))
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class DeviceDecision:
48
+ """Result of speech device admission: requested vs effective backend and fallback telemetry."""
49
+
50
+ requested_device: RequestedDevice
51
+ effective_device: EffectiveDevice
52
+ fallback_reason: FallbackReason | None = None
53
+ fallback_detail: dict[str, object] | None = None
54
+ pool: str | None = None
55
+ gpu_index: int | None = None
56
+ gpu_uuid: str | None = None
57
+ verify_on_start: bool = False
58
+
59
+ def to_runtime_fields(self) -> dict[str, object]:
60
+ """Fields matching ``runtime`` in ``localmodels.speech-status/v1``."""
61
+ return {
62
+ "requested_device": self.requested_device,
63
+ "effective_device": self.effective_device,
64
+ "fallback_reason": self.fallback_reason,
65
+ "fallback_detail": dict(self.fallback_detail) if self.fallback_detail else None,
66
+ }
67
+
68
+
69
+ def _probe_local() -> HostFacts:
70
+ facts = app.probe(hosts.LOCAL_ID)
71
+ if foreign := metal.foreign_cached_bytes(facts):
72
+ facts["ram"]["available_bytes"] = max(0, facts["ram"]["available_bytes"] - foreign)
73
+ return facts
74
+
75
+
76
+ def visible_cuda_indices(facts: HostFacts) -> set[int] | None:
77
+ """NVIDIA GPU indices exposed by ``CUDA_VISIBLE_DEVICES``, or ``None`` if unset."""
78
+ given = os.environ.get("CUDA_VISIBLE_DEVICES")
79
+ if given is None:
80
+ return None
81
+ names = {part.strip() for part in given.split(",") if part.strip()}
82
+ return {
83
+ g["index"]
84
+ for g in facts.get("gpus") or []
85
+ if str(g["index"]) in names or g["uuid"] in names
86
+ }
87
+
88
+
89
+ def in_flight_library_load_bytes() -> dict[str, int]:
90
+ """Memory bytes reserved per pool by live in-flight ``library load`` jobs."""
91
+ reserved: dict[str, int] = {}
92
+ for job, alive in library_state.jobs().values():
93
+ if alive and job.get("kind") == "load":
94
+ pool = str(job["pool"])
95
+ reserved[pool] = reserved.get(pool, 0) + max(0, int(job.get("memory_bytes") or 0))
96
+ return reserved
97
+
98
+
99
+ def active_llm_pools() -> set[str]:
100
+ """Pools currently hosting a loaded or starting local LLM."""
101
+ return {
102
+ str(rec["pool"])
103
+ for rec in library_state.records()
104
+ if rec.get("state") in ("loaded", "starting") and rec.get("pool")
105
+ }
106
+
107
+
108
+ def vulkan_loader_available(facts: HostFacts) -> bool:
109
+ """Return True if a Vulkan loader library is available on this Linux or Windows host."""
110
+ platform = facts.get("platform", "")
111
+ shared = facts.get("shared_libraries")
112
+ if platform.startswith("linux"):
113
+ if isinstance(shared, dict) and "libvulkan.so.1" in shared:
114
+ return bool(shared["libvulkan.so.1"])
115
+ try:
116
+ ctypes.CDLL("libvulkan.so.1")
117
+ return True
118
+ except OSError:
119
+ return False
120
+ if platform == "win32":
121
+ if isinstance(shared, dict) and "vulkan-1.dll" in shared:
122
+ return bool(shared["vulkan-1.dll"])
123
+ loader = getattr(ctypes, "WinDLL", ctypes.CDLL)
124
+ try:
125
+ loader("vulkan-1.dll")
126
+ return True
127
+ except OSError:
128
+ return False
129
+ return False
130
+
131
+
132
+ def _resolve_model(model: SpeechModelSpec | str) -> SpeechModelSpec:
133
+ return speech_catalog.speech_model(model) if isinstance(model, str) else model
134
+
135
+
136
+ def _decide_metal(
137
+ spec: SpeechModelSpec,
138
+ facts: HostFacts,
139
+ reserved: Mapping[str, int],
140
+ ) -> DeviceDecision:
141
+ adm = budget.admission_budget(facts, "unified", delta_bytes=reserved.get("unified", 0))
142
+ if adm is None or adm.critical_pressure:
143
+ return DeviceDecision(
144
+ requested_device="gpu",
145
+ effective_device="cpu",
146
+ fallback_reason="memory_pressure_critical",
147
+ fallback_detail={"pool": "unified", "memory_pressure": "critical"},
148
+ pool="system",
149
+ )
150
+ if adm.pressure_level == metal.PRESSURE_WARN:
151
+ return DeviceDecision(
152
+ requested_device="gpu",
153
+ effective_device="cpu",
154
+ fallback_reason="memory_pressure_warn",
155
+ fallback_detail={"pool": "unified", "memory_pressure": "warn"},
156
+ pool="system",
157
+ )
158
+ need = spec.vram_estimate_bytes + SPEECH_METAL_WIRED_HEADROOM
159
+ free_avail = min(adm.soft_budget_bytes, adm.hard_ceiling_bytes)
160
+ if adm.soft_budget_bytes < need or adm.hard_ceiling_bytes < need:
161
+ return DeviceDecision(
162
+ requested_device="gpu",
163
+ effective_device="cpu",
164
+ fallback_reason="insufficient_unified_memory",
165
+ fallback_detail={
166
+ "pool": "unified",
167
+ "free_bytes": max(0, free_avail),
168
+ "required_bytes": need,
169
+ },
170
+ pool="system",
171
+ )
172
+ return DeviceDecision(
173
+ requested_device="gpu",
174
+ effective_device="metal",
175
+ fallback_reason=None,
176
+ pool="unified",
177
+ )
178
+
179
+
180
+ def _select_cuda_gpu(
181
+ spec: SpeechModelSpec,
182
+ nvidia: list[GPU],
183
+ reserved: Mapping[str, int],
184
+ llm_pools: set[str],
185
+ ) -> DeviceDecision:
186
+ best_gpu: GPU | None = None
187
+ best_rank: tuple[bool, int, int] | None = None
188
+ for gpu in nvidia:
189
+ pool_id = f"gpu:{gpu['index']}"
190
+ eff_free = max(
191
+ 0, gpu["free_bytes"] - reserved.get(pool_id, 0) - SPEECH_DISCRETE_VRAM_HEADROOM
192
+ )
193
+ if eff_free < spec.vram_estimate_bytes:
194
+ continue
195
+ is_free_of_llm = pool_id not in llm_pools and reserved.get(pool_id, 0) == 0
196
+ rank = (is_free_of_llm, eff_free, -gpu["index"])
197
+ if best_rank is None or rank > best_rank:
198
+ best_gpu = gpu
199
+ best_rank = rank
200
+ if best_gpu is not None:
201
+ return DeviceDecision(
202
+ requested_device="gpu",
203
+ effective_device="cuda",
204
+ fallback_reason=None,
205
+ pool=f"gpu:{best_gpu['index']}",
206
+ gpu_index=best_gpu["index"],
207
+ gpu_uuid=best_gpu["uuid"],
208
+ )
209
+ best_raw_gpu = max(
210
+ nvidia,
211
+ key=lambda g: max(0, g["free_bytes"] - reserved.get(f"gpu:{g['index']}", 0)),
212
+ )
213
+ max_free = max(0, best_raw_gpu["free_bytes"] - reserved.get(f"gpu:{best_raw_gpu['index']}", 0))
214
+ return DeviceDecision(
215
+ requested_device="gpu",
216
+ effective_device="cpu",
217
+ fallback_reason="insufficient_vram",
218
+ fallback_detail={
219
+ "pool": f"gpu:{best_raw_gpu['index']}",
220
+ "free_bytes": max_free,
221
+ "required_bytes": spec.vram_estimate_bytes + SPEECH_DISCRETE_VRAM_HEADROOM,
222
+ },
223
+ pool="system",
224
+ )
225
+
226
+
227
+ def _decide_cuda(
228
+ spec: SpeechModelSpec,
229
+ facts: HostFacts,
230
+ nvidia: list[GPU],
231
+ reserved: Mapping[str, int],
232
+ llm_pools: set[str],
233
+ lock_path: Path,
234
+ *,
235
+ require_engine_build: bool = True,
236
+ ) -> DeviceDecision:
237
+ if require_engine_build:
238
+ try:
239
+ engines.select_engine_build(facts, "cuda", lock_path)
240
+ except engines.CudaDriverError as exc:
241
+ detail: dict[str, object] = {"required_cuda": exc.required_cuda}
242
+ if exc.detected_cuda:
243
+ detail["detected_cuda"] = exc.detected_cuda
244
+ if exc.required_driver:
245
+ detail["required_driver"] = exc.required_driver
246
+ return DeviceDecision(
247
+ requested_device="gpu",
248
+ effective_device="cpu",
249
+ fallback_reason="driver_update_required",
250
+ fallback_detail=detail,
251
+ pool="system",
252
+ )
253
+ except (engines.EngineUnavailableError, plan_envelope.PlanError):
254
+ return DeviceDecision(
255
+ requested_device="gpu",
256
+ effective_device="cpu",
257
+ fallback_reason="gpu_engine_unavailable",
258
+ fallback_detail={"backend": "cuda"},
259
+ pool="system",
260
+ )
261
+ return _select_cuda_gpu(spec, nvidia, reserved, llm_pools)
262
+
263
+
264
+ def _decide_vulkan(
265
+ facts: HostFacts,
266
+ lock_path: Path,
267
+ ) -> DeviceDecision:
268
+ if not vulkan_loader_available(facts):
269
+ return DeviceDecision(
270
+ requested_device="gpu",
271
+ effective_device="cpu",
272
+ fallback_reason="vulkan_unavailable",
273
+ fallback_detail={"vendor": facts.get("gpu_vendor_class", "unknown")},
274
+ pool="system",
275
+ )
276
+ try:
277
+ engines.select_engine_build(facts, "vulkan", lock_path)
278
+ except (engines.EngineUnavailableError, plan_envelope.PlanError):
279
+ return DeviceDecision(
280
+ requested_device="gpu",
281
+ effective_device="cpu",
282
+ fallback_reason="gpu_engine_unavailable",
283
+ fallback_detail={"backend": "vulkan"},
284
+ pool="system",
285
+ )
286
+ return DeviceDecision(
287
+ requested_device="gpu",
288
+ effective_device="vulkan",
289
+ fallback_reason=None,
290
+ pool="vulkan:0",
291
+ verify_on_start=True,
292
+ )
293
+
294
+
295
+ def decide_speech_device(
296
+ model: SpeechModelSpec | str,
297
+ use_gpu: bool,
298
+ facts: HostFacts | None = None,
299
+ *,
300
+ reserved_by_pool: Mapping[str, int] | None = None,
301
+ llm_pools: set[str] | None = None,
302
+ engine_lock_path: Path | None = None,
303
+ require_engine_build: bool = True,
304
+ ) -> DeviceDecision:
305
+ """Decide whether ``model`` runs on GPU or falls back to CPU without crowding any local LLM."""
306
+ spec = _resolve_model(model)
307
+ if not use_gpu:
308
+ return DeviceDecision(
309
+ requested_device="cpu",
310
+ effective_device="cpu",
311
+ fallback_reason=None,
312
+ pool="system",
313
+ )
314
+ if spec.engine == "sherpa-onnx" and not spec.gpu_supported:
315
+ return DeviceDecision(
316
+ requested_device="gpu",
317
+ effective_device="cpu",
318
+ fallback_reason="cpu_optimal_for_int8",
319
+ pool="system",
320
+ )
321
+ host = _probe_local() if facts is None else facts
322
+ if spec.engine == "sherpa-onnx" and metal.supported(host):
323
+ return DeviceDecision(
324
+ requested_device="gpu",
325
+ effective_device="cpu",
326
+ fallback_reason="cpu_optimal_for_int8",
327
+ pool="system",
328
+ )
329
+ if not spec.gpu_supported:
330
+ return DeviceDecision(
331
+ requested_device="gpu",
332
+ effective_device="cpu",
333
+ fallback_reason="gpu_engine_unavailable",
334
+ pool="system",
335
+ )
336
+
337
+ reserved = (
338
+ in_flight_library_load_bytes() if reserved_by_pool is None else dict(reserved_by_pool)
339
+ )
340
+ if metal.supported(host):
341
+ return _decide_metal(spec, host, reserved)
342
+ if host.get("platform") == "darwin":
343
+ return DeviceDecision(
344
+ requested_device="gpu",
345
+ effective_device="cpu",
346
+ fallback_reason="gpu_unsupported_platform",
347
+ fallback_detail={"platform": "darwin", "arch": host.get("arch", "unknown")},
348
+ pool="system",
349
+ )
350
+
351
+ lock_path = (
352
+ engine_lock_path
353
+ if engine_lock_path is not None
354
+ else engines.engine_lock_path(spec.engine_tag)
355
+ )
356
+ visible = visible_cuda_indices(host)
357
+ nvidia = [
358
+ g
359
+ for g in (host.get("gpus") or [])
360
+ if g.get("vendor") == "nvidia"
361
+ and g.get("mig_mode") != "enabled"
362
+ and (visible is None or g["index"] in visible)
363
+ ]
364
+ if nvidia:
365
+ pools_with_llm = active_llm_pools() if llm_pools is None else llm_pools
366
+ return _decide_cuda(
367
+ spec,
368
+ host,
369
+ nvidia,
370
+ reserved,
371
+ pools_with_llm,
372
+ lock_path,
373
+ require_engine_build=require_engine_build,
374
+ )
375
+
376
+ vendor = host.get("gpu_vendor_class", "none")
377
+ if vendor in ("amd", "intel") and spec.engine == "whisper.cpp":
378
+ return _decide_vulkan(host, lock_path)
379
+
380
+ return DeviceDecision(
381
+ requested_device="gpu",
382
+ effective_device="cpu",
383
+ fallback_reason="no_supported_gpu",
384
+ pool="system",
385
+ )
386
+
387
+
388
+ def _runtime_holds_pool(rec: Mapping[str, object], pool_id: str) -> bool:
389
+ """Return True if ``runtime.json`` indicates speech currently holds VRAM/unified memory on ``pool_id``."""
390
+ if not rec.get("running", True):
391
+ return False
392
+ state = rec.get("state")
393
+ if state not in ("loaded", "loading"):
394
+ return False
395
+ eff = rec.get("effective_device")
396
+ if eff not in _GPU_EFFECTIVE_DEVICES:
397
+ return False
398
+ rec_pool = rec.get("pool")
399
+ if isinstance(rec_pool, str) and rec_pool:
400
+ return rec_pool == pool_id
401
+ if pool_id == "unified":
402
+ return eff == "metal"
403
+ if pool_id.startswith("gpu:"):
404
+ return eff in ("cuda", "vulkan", "directml")
405
+ return False
406
+
407
+
408
+ def demote_speech_if_holding_pool(
409
+ state_dir: Path | None,
410
+ pool_id: str,
411
+ *,
412
+ timeout: float = SPEECH_DEMOTE_TIMEOUT_S,
413
+ ) -> bool:
414
+ """Ask a running speech sidecar to demote to CPU if it currently holds memory on ``pool_id``.
415
+
416
+ Never raises: a missing, stopped, or unreachable speech sidecar returns ``False`` so local
417
+ LLM loading is never blocked.
418
+ """
419
+ if pool_id == "system":
420
+ return False
421
+ rec = speech_state.load_runtime_record(state_dir)
422
+ if rec is None or not _runtime_holds_pool(rec, pool_id):
423
+ return False
424
+ base_url = rec.get("base_url")
425
+ if not isinstance(base_url, str) or not base_url:
426
+ return False
427
+ key_file = rec.get("key_file")
428
+ key_path = key_file if isinstance(key_file, str) and key_file else None
429
+ response = speech_state.sidecar_request(
430
+ base_url,
431
+ "/v1/speech/demote-to-cpu",
432
+ method="POST",
433
+ key_file=key_path,
434
+ payload={"reason": "yielded_to_llm", "pool": pool_id},
435
+ timeout=timeout,
436
+ )
437
+ return response is not None
@@ -0,0 +1,170 @@
1
+ """Closed v1 local speech model catalog parsed from localmodels/catalog.json.
2
+
3
+ Keeps catalog.json as the single source of truth for speech model pins, sizes, engines,
4
+ and license disclosures, matching the frozen localmodels.speech-status/v1 contract.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Any, Literal, TypedDict, cast
13
+
14
+ from localmodels.catalog_recipes import CATALOG_PATH as CATALOG_PATH
15
+ from localmodels.contracts import decode
16
+
17
+ SpeechEngine = Literal["sherpa-onnx", "whisper.cpp"]
18
+ QualityRating = Literal["fast-cjk", "high-multilingual"]
19
+
20
+ V1_SPEECH_MODEL_IDS: tuple[str, ...] = ("sensevoice-small", "whisper-large-v3-turbo")
21
+
22
+
23
+ class _RawSpeechFile(TypedDict):
24
+ path: str
25
+ size_bytes: int
26
+ sha256: str
27
+
28
+
29
+ class _RawSpeechOptional(TypedDict, total=False):
30
+ engine: str
31
+ commercial_notice: str | None
32
+ opt_in_only: bool
33
+ note: str
34
+
35
+
36
+ class _RawSpeechComponent(_RawSpeechOptional):
37
+ id: str
38
+ display_name: str
39
+ task: str
40
+ runtime: str
41
+ version: str
42
+ repo: str
43
+ revision: str
44
+ license: str
45
+ license_url: str
46
+ status: str
47
+ languages: list[str]
48
+ language_count: int
49
+ quality_rating: str
50
+ gpu_supported: bool
51
+ memory_estimate_bytes: int
52
+ vram_estimate_bytes: int
53
+ files: list[_RawSpeechFile]
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class SpeechModelFile:
58
+ """One pinned weight or vocabulary file belonging to a local speech model."""
59
+
60
+ path: str
61
+ size_bytes: int
62
+ sha256: str
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class SpeechModelSpec:
67
+ """Catalog metadata and pinned artifacts for one v1 local speech model."""
68
+
69
+ id: str
70
+ name: str
71
+ engine: SpeechEngine
72
+ engine_tag: str | None
73
+ version: str
74
+ repo: str
75
+ revision: str
76
+ status: str
77
+ languages: tuple[str, ...]
78
+ language_count: int
79
+ quality_rating: QualityRating
80
+ license: str
81
+ license_url: str
82
+ commercial_notice: str | None
83
+ opt_in_only: bool
84
+ disk_size_bytes: int
85
+ vram_estimate_bytes: int
86
+ ram_estimate_bytes: int
87
+ gpu_supported: bool
88
+ files: tuple[SpeechModelFile, ...]
89
+
90
+ def status_fields(self) -> dict[str, Any]:
91
+ """Static model-row fields defined by localmodels.speech-status/v1."""
92
+ return {
93
+ "id": self.id,
94
+ "name": self.name,
95
+ "engine": self.engine,
96
+ "languages": list(self.languages),
97
+ "language_count": self.language_count,
98
+ "quality_rating": self.quality_rating,
99
+ "license": self.license,
100
+ "license_url": self.license_url,
101
+ "commercial_notice": self.commercial_notice,
102
+ "disk_size_bytes": self.disk_size_bytes,
103
+ "vram_estimate_bytes": self.vram_estimate_bytes,
104
+ "ram_estimate_bytes": self.ram_estimate_bytes,
105
+ "gpu_supported": self.gpu_supported,
106
+ }
107
+
108
+
109
+ def _parse_entry(raw: dict[str, Any]) -> SpeechModelSpec:
110
+ comp = decode(raw, _RawSpeechComponent)
111
+ runtime = comp["runtime"]
112
+ if runtime not in ("sherpa-onnx", "whisper.cpp"):
113
+ raise ValueError(f"unsupported speech runtime for {comp['id']}: {runtime}")
114
+ rating = comp["quality_rating"]
115
+ if rating not in ("fast-cjk", "high-multilingual"):
116
+ raise ValueError(f"unsupported speech quality_rating for {comp['id']}: {rating}")
117
+ files = tuple(
118
+ SpeechModelFile(
119
+ path=f["path"],
120
+ size_bytes=f["size_bytes"],
121
+ sha256=f["sha256"],
122
+ )
123
+ for f in comp["files"]
124
+ )
125
+ if not files:
126
+ raise ValueError(f"speech model {comp['id']} pins no files")
127
+ return SpeechModelSpec(
128
+ id=comp["id"],
129
+ name=comp["display_name"],
130
+ engine=cast(SpeechEngine, runtime),
131
+ engine_tag=comp.get("engine"),
132
+ version=comp["version"],
133
+ repo=comp["repo"],
134
+ revision=comp["revision"],
135
+ status=comp["status"],
136
+ languages=tuple(comp["languages"]),
137
+ language_count=comp["language_count"],
138
+ quality_rating=cast(QualityRating, rating),
139
+ license=comp["license"],
140
+ license_url=comp["license_url"],
141
+ commercial_notice=comp.get("commercial_notice"),
142
+ opt_in_only=bool(comp.get("opt_in_only", False)),
143
+ disk_size_bytes=sum(f.size_bytes for f in files),
144
+ vram_estimate_bytes=comp["vram_estimate_bytes"],
145
+ ram_estimate_bytes=comp["memory_estimate_bytes"],
146
+ gpu_supported=comp["gpu_supported"],
147
+ files=files,
148
+ )
149
+
150
+
151
+ def speech_models(catalog_path: Path = CATALOG_PATH) -> tuple[SpeechModelSpec, ...]:
152
+ """Return the closed v1 local speech catalog in contract order."""
153
+ doc = json.loads(catalog_path.read_text(encoding="utf-8"))
154
+ by_id = {
155
+ str(c["id"]): c
156
+ for c in doc.get("components", [])
157
+ if c.get("task") == "stt" and c.get("id") in V1_SPEECH_MODEL_IDS
158
+ }
159
+ missing = [model_id for model_id in V1_SPEECH_MODEL_IDS if model_id not in by_id]
160
+ if missing:
161
+ raise ValueError(f"catalog.json is missing v1 speech models: {', '.join(missing)}")
162
+ return tuple(_parse_entry(by_id[model_id]) for model_id in V1_SPEECH_MODEL_IDS)
163
+
164
+
165
+ def speech_model(model_id: str, catalog_path: Path = CATALOG_PATH) -> SpeechModelSpec:
166
+ """Return one v1 speech model spec by ID, raising KeyError if unknown."""
167
+ for entry in speech_models(catalog_path):
168
+ if entry.id == model_id:
169
+ return entry
170
+ raise KeyError(f"unknown speech model: {model_id}")