@simplexai/localmodels-darwin-x64 0.1.0-dev.65 → 0.1.0-dev.66

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 -55
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/auth_proxy.py +34 -2
  5. package/modules/localmodels/catalog.json +500 -16
  6. package/modules/localmodels/custom_hub.py +54 -6
  7. package/modules/localmodels/custom_probe.py +28 -0
  8. package/modules/localmodels/debug_stub_server.py +34 -1
  9. package/modules/localmodels/deploy.py +33 -349
  10. package/modules/localmodels/download-mirrors.json +43 -3
  11. package/modules/localmodels/draft_spec.py +1 -1
  12. package/modules/localmodels/engine_adapters/__init__.py +4 -2
  13. package/modules/localmodels/engine_adapters/auxiliary.py +4 -1
  14. package/modules/localmodels/engine_adapters/llama_cpp.py +539 -0
  15. package/modules/localmodels/engines-b11583.json +9 -5
  16. package/modules/localmodels/engines-b12757-mix-ef2df21.json +85 -1
  17. package/modules/localmodels/engines.json +9 -5
  18. package/modules/localmodels/harness_gateway.py +14 -3
  19. package/modules/localmodels/harness_probe.py +64 -3
  20. package/modules/localmodels/library_custom.py +9 -7
  21. package/modules/localmodels/library_elastic.py +5 -4
  22. package/modules/localmodels/library_jobs.py +138 -25
  23. package/modules/localmodels/library_model.py +22 -2
  24. package/modules/localmodels/library_order.py +1 -1
  25. package/modules/localmodels/library_serve.py +11 -4
  26. package/modules/localmodels/library_state.py +12 -0
  27. package/modules/localmodels/library_status.py +10 -0
  28. package/modules/localmodels/planning/budget.py +8 -3
  29. package/modules/localmodels/remote_ops_mirrors.py +55 -19
  30. package/modules/localmodels/service_deployment.py +3 -3
  31. package/modules/localmodels/setup_inspection.py +28 -1
  32. package/modules/localmodels/setup_inspection_harness.py +4 -1
  33. package/modules/localmodels/setup_text.py +6 -0
  34. package/modules/localmodels/slot_cache.py +1 -3
  35. package/modules/localmodels/speech_admission.py +16 -4
  36. package/modules/localmodels/speech_catalog.py +5 -1
  37. package/modules/localmodels/speech_cli.py +5 -5
  38. package/modules/localmodels/speech_jobs.py +101 -19
  39. package/modules/localmodels/speech_server.py +2 -0
  40. package/modules/localmodels/speech_worker_sensevoice.py +194 -6
  41. package/modules/localmodels/speech_workers.py +74 -6
  42. package/modules/localmodels/stack.py +13 -1
  43. package/modules/localmodels/stack_auto.py +6 -0
  44. package/modules/localmodels/stack_capacity.py +3 -3
  45. package/modules/localmodels/stack_cli.py +3 -0
  46. package/modules/localmodels/stack_compose.py +7 -3
  47. package/modules/localmodels/stack_ports.py +58 -27
  48. package/modules/localmodels/stack_suite.py +7 -1
  49. package/modules/localmodels/suite.py +1 -1
  50. package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/METADATA +1 -1
  51. package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/RECORD +53 -52
  52. package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/licenses/NOTICE +3 -0
  53. package/package.json +1 -1
  54. package/tool.json +1 -1
  55. /package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/WHEEL +0 -0
  56. /package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/entry_points.txt +0 -0
  57. /package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev66.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -152,6 +152,8 @@ class _JobSince20261113(TypedDict, total=False):
152
152
  connections: int # active parallel download connections
153
153
  shard_index: int # 1-based active shard index for multi-shard downloads
154
154
  shard_count: int # total shard count for multi-shard downloads
155
+ engine_done: int # engine archive bytes inside done while the engine downloads too
156
+ engine_total: int # engine archive bytes inside total (first install only)
155
157
  load_step: str # load sub-step: prepare | start | load | warm
156
158
  error: Problem # a download that stopped cleanly: status shows why; cancel discards it
157
159
  custom: CustomMeta # custom hub metadata while download is in progress
@@ -350,6 +352,8 @@ class JobHandle:
350
352
  load_step: str | None = None,
351
353
  shard_index: int | None = None,
352
354
  shard_count: int | None = None,
355
+ engine_done: int | None = None,
356
+ engine_total: int | None = None,
353
357
  ) -> None:
354
358
  import time
355
359
 
@@ -360,6 +364,7 @@ class JobHandle:
360
364
  self.job.get("total"),
361
365
  self.job.get("shard_index"),
362
366
  self.job.get("shard_count"),
367
+ self.job.get("done", 0) > 0, # the first bytes moving: status leaves 0 at once
363
368
  )
364
369
  self.job["phase"], self.job["done"], self.job["total"] = phase, done, total
365
370
  self.job["bytes_per_second"] = bytes_per_second
@@ -385,6 +390,12 @@ class JobHandle:
385
390
  self.job.pop("connections", None)
386
391
  self.job.pop("shard_index", None)
387
392
  self.job.pop("shard_count", None)
393
+ if phase in ("download", "verify") and engine_total is not None and engine_total > 0:
394
+ self.job["engine_total"] = engine_total
395
+ self.job["engine_done"] = max(0, min(engine_done or 0, engine_total))
396
+ else:
397
+ self.job.pop("engine_total", None)
398
+ self.job.pop("engine_done", None)
388
399
  if phase in ("load", "warm") and load_step is not None:
389
400
  self.job["load_step"] = load_step
390
401
  else:
@@ -396,6 +407,7 @@ class JobHandle:
396
407
  self.job.get("total"),
397
408
  self.job.get("shard_index"),
398
409
  self.job.get("shard_count"),
410
+ self.job.get("done", 0) > 0,
399
411
  ) != prev
400
412
  now = time.monotonic()
401
413
  if changed or now - self._written >= JOB_WRITE_EVERY_S or done >= total:
@@ -432,6 +432,16 @@ def _downloading(job: Job) -> Download:
432
432
  s_cnt = job.get("shard_count")
433
433
  if isinstance(s_cnt, int) and not isinstance(s_cnt, bool) and s_cnt >= 1:
434
434
  dl["shard_count"] = s_cnt
435
+ e_total, e_done = job.get("engine_total"), job.get("engine_done")
436
+ if (
437
+ isinstance(e_total, int)
438
+ and not isinstance(e_total, bool)
439
+ and e_total > 0
440
+ and isinstance(e_done, int)
441
+ and not isinstance(e_done, bool)
442
+ ):
443
+ dl["engine_total_bytes"] = min(e_total, dl["total_bytes"])
444
+ dl["engine_done_bytes"] = max(0, min(e_done, dl["engine_total_bytes"]))
435
445
  return dl
436
446
 
437
447
 
@@ -22,6 +22,7 @@ from __future__ import annotations
22
22
 
23
23
  import re
24
24
  from dataclasses import dataclass, replace
25
+ from typing import Literal
25
26
 
26
27
  from localmodels import gpu_specs, metal
27
28
  from localmodels.context_policy import RUNTIME_OVERHEAD_BYTES
@@ -61,6 +62,10 @@ _SERVING_PROCESS_RE = re.compile(
61
62
  )
62
63
 
63
64
 
65
+ # The device a placement runs on; engine_adapters.llama_cpp.backend_for keys its hooks on it.
66
+ Backend = Literal["cuda", "metal", "cpu"]
67
+
68
+
64
69
  @dataclass(frozen=True)
65
70
  class Placement:
66
71
  """Where one model would run: one card, every card split by layer, or the host's unified pool."""
@@ -69,7 +74,7 @@ class Placement:
69
74
  label: str
70
75
  gpu_indices: tuple[int, ...]
71
76
  budget: HardwareBudget
72
- backend: str # cuda | metal | cpu
77
+ backend: Backend
73
78
  pooled: bool = False # multi-card split: our extension, not calibrated
74
79
  busy: bool = False # another process already holds part of a selected card
75
80
  conflicts: tuple[str, ...] = () # foreign serving work on the selected cards (gpu_conflicts)
@@ -391,7 +396,7 @@ def placements(facts: HostFacts, *, planning: bool = True) -> list[Placement]:
391
396
  # Metal, integrated or unknown GPUs, CPU: RAM as unified memory. AMD/Intel discrete cards
392
397
  # need the engine's device probe, which runs only after an engine is installed.
393
398
  cls = facts.get("gpu_vendor_class", "unknown")
394
- backend = "metal" if facts.get("platform") == "darwin" else "cpu"
399
+ backend: Backend = "metal" if facts.get("platform") == "darwin" else "cpu"
395
400
  metal_info = metal.reading(facts) if backend == "metal" else None
396
401
  metal_name = str(metal_info.get("name") or "") if metal_info else ""
397
402
  budget = _uma(
@@ -562,7 +567,7 @@ class AdmissionBudget:
562
567
  """
563
568
 
564
569
  pool: str
565
- backend: str # metal | cuda | cpu
570
+ backend: Backend
566
571
  soft_budget_bytes: int
567
572
  hard_ceiling_bytes: int
568
573
  reserve_bytes: int
@@ -208,6 +208,35 @@ discard = remote_ops_common.discard
208
208
  clear_link = remote_ops_common.clear_link
209
209
 
210
210
 
211
+ def _lock_once(lock: object, *, block: bool = False) -> bool:
212
+ """Take the engines-root lock on an open lock file: one attempt, or (POSIX ``block``) wait
213
+ for it. Windows has no blocking form; its callers poll."""
214
+ try:
215
+ if os.name == "nt":
216
+ import msvcrt
217
+
218
+ lock.seek(0) # type: ignore[attr-defined]
219
+ msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1) # type: ignore[attr-defined]
220
+ else:
221
+ import fcntl
222
+
223
+ flags = fcntl.LOCK_EX if block else fcntl.LOCK_EX | fcntl.LOCK_NB
224
+ fcntl.flock(lock, flags) # type: ignore[arg-type]
225
+ except OSError:
226
+ return False
227
+ return True
228
+
229
+
230
+ def _unlock(lock: object) -> None:
231
+ if os.name == "nt":
232
+ import msvcrt
233
+
234
+ with contextlib.suppress(OSError):
235
+ lock.seek(0) # type: ignore[attr-defined]
236
+ msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1) # type: ignore[attr-defined]
237
+ # POSIX: closing the file releases the flock.
238
+
239
+
211
240
  @contextlib.contextmanager
212
241
  def engine_lock(directory: str) -> Iterator[None]:
213
242
  """Serialize concurrent engine fetches and unpacks under the same engines root so parallel
@@ -216,27 +245,34 @@ def engine_lock(directory: str) -> Iterator[None]:
216
245
  os.makedirs(parent, exist_ok=True)
217
246
  lock_path = os.path.join(parent, ".engine.lock")
218
247
  with open(lock_path, "a+") as lock:
219
- if os.name == "nt":
220
- import msvcrt
248
+ while not _lock_once(lock, block=True):
249
+ time.sleep(0.1)
250
+ try:
251
+ yield
252
+ finally:
253
+ _unlock(lock)
221
254
 
222
- lock.seek(0)
223
- while True:
224
- try:
225
- msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1) # type: ignore[attr-defined]
226
- break
227
- except OSError:
228
- time.sleep(0.1)
229
- try:
230
- yield
231
- finally:
232
- with contextlib.suppress(OSError):
233
- lock.seek(0)
234
- msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1) # type: ignore[attr-defined]
235
- else:
236
- import fcntl
237
255
 
238
- fcntl.flock(lock, fcntl.LOCK_EX)
239
- yield
256
+ @contextlib.contextmanager
257
+ def try_engine_lock(directory: str, wait_s: float = 0.0) -> Iterator[bool]:
258
+ """``engine_lock`` that gives up after ``wait_s``: yields whether it holds the lock. A
259
+ cleanup that must not touch another download's ``.archives/*.part`` uses it."""
260
+ parent = os.path.dirname(directory) or "."
261
+ if not os.path.isdir(parent):
262
+ yield False
263
+ return
264
+ lock_path = os.path.join(parent, ".engine.lock")
265
+ with open(lock_path, "a+") as lock:
266
+ deadline = time.monotonic() + max(0.0, wait_s)
267
+ held = _lock_once(lock)
268
+ while not held and time.monotonic() < deadline:
269
+ time.sleep(0.1)
270
+ held = _lock_once(lock)
271
+ try:
272
+ yield held
273
+ finally:
274
+ if held:
275
+ _unlock(lock)
240
276
 
241
277
 
242
278
  def npm_transfer(
@@ -75,7 +75,7 @@ def plan_component(
75
75
  options = {**stack.default_options(), "base_dir": str(root)}
76
76
  try:
77
77
  return decision.gpu_plans(facts, options, choice, card)
78
- except stack_ports.PortUnavailableError as exc:
78
+ except (stack_ports.PortUnavailableError, stack_ports.PortProbeError) as exc:
79
79
  raise WaitingForResourcesError("port") from exc
80
80
  raise WaitingForResourcesError("gpu")
81
81
  if role not in ("embedding", "reranker"):
@@ -85,7 +85,7 @@ def plan_component(
85
85
  port = stack_ports.default_port(
86
86
  facts, stack_ports.AUXILIARY_PORTS[role], stack_ports.loopback_listening
87
87
  )
88
- except PlanError as exc:
88
+ except (PlanError, stack_ports.PortProbeError) as exc:
89
89
  raise WaitingForResourcesError("port") from exc
90
90
  built = suite_plan.build_plan(
91
91
  "local",
@@ -394,7 +394,7 @@ class Deployment:
394
394
  offset=component.FRONT_OFFSET if template_front is not None else 0,
395
395
  reserved=(main["llm"]["service"]["port"],),
396
396
  )
397
- except PlanError as exc:
397
+ except (PlanError, stack_ports.PortProbeError) as exc:
398
398
  raise WaitingForResourcesError("port") from exc
399
399
  built, front = _decision_endpoint(template, template_front, port)
400
400
  else:
@@ -23,6 +23,7 @@ from localmodels import (
23
23
  stack,
24
24
  stack_binding,
25
25
  stack_hardware,
26
+ stack_ports,
26
27
  stack_review,
27
28
  )
28
29
  from localmodels.contracts import decode
@@ -237,12 +238,35 @@ def _harness_availability(
237
238
  }
238
239
 
239
240
 
241
+ def _port_check_availability(
242
+ options: StackOptions, facts: HostFacts, exc: StackError, lang: Lang
243
+ ) -> StackAvailability:
244
+ """No port of a range could be confirmed free (stack_ports.PortProbeError): blocked now and
245
+ retryable, never a reason to recommend another runtime when the hardware fits."""
246
+ capable = setup_inspection_harness.hardware_capable_without_harness(options, facts)
247
+ return {
248
+ "available": False,
249
+ "reasons": [
250
+ {
251
+ "code": "port-check-failed",
252
+ "message": text("port-check-failed", lang, detail=str(exc))
253
+ if capable
254
+ else str(exc),
255
+ }
256
+ ],
257
+ "plan": None,
258
+ "hardwareCapable": capable,
259
+ }
260
+
261
+
240
262
  def _plan_stack(
241
263
  options: StackOptions, facts: HostFacts, share_gpu: bool, lang: Lang
242
264
  ) -> StackAvailability:
243
265
  try:
244
266
  try:
245
267
  plan = stack.build(options, facts=facts)
268
+ except stack_ports.PortProbeError as exc:
269
+ return _port_check_availability(options, facts, exc, lang)
246
270
  except (PlanError, stack.StackError) as exc:
247
271
  last_error: PlanError | StackError | None = exc
248
272
  last_options = options
@@ -518,7 +542,7 @@ INSPECT = (
518
542
  INSPECT_REASONS = (
519
543
  "unsupported-platform · facts-unavailable · plan-unavailable · gpu-sharing-required\n"
520
544
  "cuda-driver-update-required · cuda-driver-version-unknown · gateway-port-in-use · "
521
- "harness-unavailable\n"
545
+ "harness-unavailable · port-check-failed\n"
522
546
  "(gpu-sharing-required: a plan fits only beside other GPU work, its owner known or not; ask, "
523
547
  "then rerun with --share-gpu, which plans by the free VRAM)\n"
524
548
  "cuda-driver-update-required / cuda-driver-version-unknown (stack.state is blocked-now, "
@@ -528,6 +552,9 @@ INSPECT_REASONS = (
528
552
  "gateway-port-in-use / harness-unavailable (stack.state is blocked-now with "
529
553
  "hardwareCapable true when the hardware fits, but the gateway port is held or tool checks "
530
554
  "failed; free the port or fix the tool issue and check again)\n"
555
+ "port-check-failed (stack.state is blocked-now with hardwareCapable true when the hardware "
556
+ "fits: no port of a range the stack needs could be confirmed free right now, because the "
557
+ "loopback check could not tell; check again)\n"
531
558
  "gpu-memory-required (stack.state is blocked-now, stack.basis is capacity: other programs "
532
559
  "or another inference app/GPU workload use the GPU memory the plan needs; close them and "
533
560
  "check again; gpuIndex, freeBytes and requiredBytes give the card and its free and needed "
@@ -45,7 +45,10 @@ class Reason(_ReasonOptional):
45
45
  message: str
46
46
 
47
47
 
48
- HARNESS_CODES = frozenset({"gateway-port-in-use", "harness-unavailable"})
48
+ # Blocked-now reasons about the gateway, its tools or loopback ports, not the hardware.
49
+ # port-check-failed: the loopback probe could not tell whether any port of a range is free
50
+ # (stack_ports.PortProbeError, or the Magpie address); checking again may pass.
51
+ HARNESS_CODES = frozenset({"gateway-port-in-use", "harness-unavailable", "port-check-failed"})
49
52
  _PORT_CONFLICT_HINTS = (
50
53
  "is held by",
51
54
  "ports 3425..3456 are all in use",
@@ -106,6 +106,12 @@ MESSAGES: dict[str, tuple[str, str]] = {
106
106
  "This computer's hardware can run local models, but the gateway port is currently in use "
107
107
  "({detail}). Stop that program or set another gateway address, then check again.",
108
108
  ),
109
+ "port-check-failed": (
110
+ "这台电脑的硬件可以运行本地模型,但暂时无法确认本地端口是否空闲({detail})。"
111
+ "请稍后重新检查。",
112
+ "This computer's hardware can run local models, but whether a local port is free could "
113
+ "not be confirmed right now ({detail}). Check again in a moment.",
114
+ ),
109
115
  "harness-unavailable": (
110
116
  "这台电脑的硬件可以运行本地模型,但网关或工具环境检查未通过({detail})。"
111
117
  "请先处理该问题后重新检查。",
@@ -424,9 +424,7 @@ def main(argv: list[str]) -> int:
424
424
  tally = Tally(slot_dir)
425
425
  if not (slot_dir / PREFIX_FILE).exists():
426
426
  tally.kept = None # write the leading prefix again
427
- proxy = http.server.ThreadingHTTPServer(
428
- (host, int(port)), handler(upstream, slot_dir, tally, key)
429
- )
427
+ proxy = auth_proxy.bind_server((host, int(port)), handler(upstream, slot_dir, tally, key))
430
428
  proxy.daemon_threads = True
431
429
  child = subprocess.Popen(inner)
432
430
  guard = end_with_me(child.pid)
@@ -137,6 +137,7 @@ def _decide_metal(
137
137
  spec: SpeechModelSpec,
138
138
  facts: HostFacts,
139
139
  reserved: Mapping[str, int],
140
+ llm_pools: set[str],
140
141
  ) -> DeviceDecision:
141
142
  adm = budget.admission_budget(facts, "unified", delta_bytes=reserved.get("unified", 0))
142
143
  if adm is None or adm.critical_pressure:
@@ -147,7 +148,13 @@ def _decide_metal(
147
148
  fallback_detail={"pool": "unified", "memory_pressure": "critical"},
148
149
  pool="system",
149
150
  )
150
- if adm.pressure_level == metal.PRESSURE_WARN:
151
+ # On Apple Silicon unified memory, running Whisper on CPU consumes roughly the same ~1.4 GB
152
+ # RAM as Metal while degrading 3s transcription from ~0.5s to ~15-19s. Everyday 16 GB Macs
153
+ # routinely sit at PRESSURE_WARN (level 2), so only yield Metal on PRESSURE_WARN / soft-budget
154
+ # tightness when a local LLM (RANK = 0) is active or loading on the unified pool; otherwise
155
+ # admit Metal whenever wired headroom (hard_ceiling_bytes) fits, relying on runtime_oom_fallback.
156
+ llm_on_unified = "unified" in llm_pools or reserved.get("unified", 0) > 0
157
+ if llm_on_unified and adm.pressure_level == metal.PRESSURE_WARN:
151
158
  return DeviceDecision(
152
159
  requested_device="gpu",
153
160
  effective_device="cpu",
@@ -156,8 +163,12 @@ def _decide_metal(
156
163
  pool="system",
157
164
  )
158
165
  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:
166
+ if adm.hard_ceiling_bytes < need or (llm_on_unified and adm.soft_budget_bytes < need):
167
+ free_avail = (
168
+ min(adm.soft_budget_bytes, adm.hard_ceiling_bytes)
169
+ if llm_on_unified
170
+ else adm.hard_ceiling_bytes
171
+ )
161
172
  return DeviceDecision(
162
173
  requested_device="gpu",
163
174
  effective_device="cpu",
@@ -338,7 +349,8 @@ def decide_speech_device(
338
349
  in_flight_library_load_bytes() if reserved_by_pool is None else dict(reserved_by_pool)
339
350
  )
340
351
  if metal.supported(host):
341
- return _decide_metal(spec, host, reserved)
352
+ pools_with_llm = active_llm_pools() if llm_pools is None else llm_pools
353
+ return _decide_metal(spec, host, reserved, pools_with_llm)
342
354
  if host.get("platform") == "darwin":
343
355
  return DeviceDecision(
344
356
  requested_device="gpu",
@@ -17,7 +17,11 @@ from localmodels.contracts import decode
17
17
  SpeechEngine = Literal["sherpa-onnx", "whisper.cpp"]
18
18
  QualityRating = Literal["fast-cjk", "high-multilingual"]
19
19
 
20
- V1_SPEECH_MODEL_IDS: tuple[str, ...] = ("sensevoice-small", "whisper-large-v3-turbo")
20
+ V1_SPEECH_MODEL_IDS: tuple[str, ...] = (
21
+ "qwen3-asr-0.6b",
22
+ "sensevoice-small",
23
+ "whisper-large-v3-turbo",
24
+ )
21
25
 
22
26
 
23
27
  class _RawSpeechFile(TypedDict):
@@ -20,10 +20,10 @@ from localmodels.speech_model import (
20
20
  )
21
21
 
22
22
  DESCRIPTION = (
23
- "Manage local speech-to-text models (Whisper Large v3 Turbo and opt-in SenseVoice Small): "
24
- "inspect status, download with resumable verification, cancel, remove, and configure runtime "
25
- "preferences. Every command writes pure JSON or JSONL on stdout. Exit status: 0 ok, 1 failed, "
26
- "2 refused, 130 cancelled."
23
+ "Manage local speech-to-text models (Whisper Large v3 Turbo, Qwen3-ASR 0.6B, and opt-in "
24
+ "SenseVoice Small): inspect status, download with resumable verification, cancel, remove, and "
25
+ "configure runtime preferences. Every command writes pure JSON or JSONL on stdout. Exit "
26
+ "status: 0 ok, 1 failed, 2 refused, 130 cancelled."
27
27
  )
28
28
 
29
29
  _FALLBACK_CODE = {
@@ -51,7 +51,7 @@ def _add_model_arg(parser: argparse.ArgumentParser) -> None:
51
51
  parser.add_argument(
52
52
  "model",
53
53
  metavar="MODEL",
54
- help="speech model id (whisper-large-v3-turbo or sensevoice-small)",
54
+ help="speech model id (whisper-large-v3-turbo, qwen3-asr-0.6b, or sensevoice-small)",
55
55
  )
56
56
 
57
57
 
@@ -7,6 +7,8 @@ HF/hf-mirror/ModelScope selection, and SHA-256 verification before atomic replac
7
7
 
8
8
  from __future__ import annotations
9
9
 
10
+ import contextlib
11
+ import io
10
12
  import os
11
13
  import shutil
12
14
  import sys
@@ -61,10 +63,26 @@ KEEP_FAILED_CODES = frozenset(("DOWNLOAD_FAILED", "NETWORK_UNAVAILABLE", "DISK_I
61
63
 
62
64
 
63
65
  def model_dir(base_dir: str, model_id: str) -> Path:
64
- """Short, flat directory holding one speech model's weight files."""
66
+ """Directory holding one speech model's weight and tokenizer files."""
65
67
  return Path(os.path.expanduser(base_dir)).resolve() / "speech" / model_id
66
68
 
67
69
 
70
+ def _relative_file_path(file_path: str) -> Path:
71
+ """Validate and preserve relative subdirectories (e.g. ``tokenizer/vocab.json``)."""
72
+ normalized = file_path.replace("\\", "/")
73
+ if not normalized or normalized.startswith("/") or ":" in normalized.split("/", 1)[0]:
74
+ raise ValueError(f"unsafe relative speech file path: {file_path!r}")
75
+ parts = [part for part in normalized.split("/") if part not in ("", ".")]
76
+ if not parts or any(part == ".." for part in parts):
77
+ raise ValueError(f"unsafe relative speech file path: {file_path!r}")
78
+ return Path(*parts)
79
+
80
+
81
+ def model_file_dest(base_dir: str, model_id: str, file_path: str) -> Path:
82
+ """Destination path for one pinned file of ``model_id``, preserving relative subdirs."""
83
+ return model_dir(base_dir, model_id) / _relative_file_path(file_path)
84
+
85
+
68
86
  def _file_spec(
69
87
  spec: SpeechModelSpec,
70
88
  base_dir: str,
@@ -73,7 +91,8 @@ def _file_spec(
73
91
  sha256: str,
74
92
  hf_endpoint: str,
75
93
  ) -> ReusableFile:
76
- dest = str(model_dir(base_dir, spec.id) / Path(file_path).name)
94
+ rel = _relative_file_path(file_path)
95
+ dest = str(model_dir(base_dir, spec.id) / rel)
77
96
  url = plan_envelope.hub_url(hf_endpoint, spec.repo, spec.revision, file_path)
78
97
  entry: ReusableFile = {
79
98
  "repo": spec.repo,
@@ -81,7 +100,7 @@ def _file_spec(
81
100
  "revision": spec.revision,
82
101
  "size_bytes": size_bytes,
83
102
  "sha256": sha256,
84
- "local_name": Path(file_path).name,
103
+ "local_name": rel.as_posix(),
85
104
  "dest": dest,
86
105
  "url": url,
87
106
  }
@@ -122,6 +141,7 @@ def _build_model_row(
122
141
  runtime: SpeechRuntime,
123
142
  record: SpeechModelRecord | None,
124
143
  job_info: tuple[SpeechJob, bool] | None,
144
+ engine_bytes: int = 0,
125
145
  ) -> SpeechModelRow:
126
146
  active = runtime["running"] and runtime["active_model"] == spec.id
127
147
  download_info: SpeechDownloadProgress | None = None
@@ -171,7 +191,7 @@ def _build_model_row(
171
191
  "license": str(static["license"]),
172
192
  "license_url": str(static["license_url"]),
173
193
  "commercial_notice": static["commercial_notice"],
174
- "disk_size_bytes": int(static["disk_size_bytes"]),
194
+ "disk_size_bytes": int(static["disk_size_bytes"]) + engine_bytes,
175
195
  "vram_estimate_bytes": int(static["vram_estimate_bytes"]),
176
196
  "ram_estimate_bytes": int(static["ram_estimate_bytes"]),
177
197
  "gpu_supported": bool(static["gpu_supported"]),
@@ -188,8 +208,21 @@ def status(base_dir: str, *, state_dir: Path | None = None) -> SpeechStatusDocum
188
208
  runtime = speech_state.probe_live_runtime(cfg, state_dir)
189
209
  by_record = {rec["id"]: rec for rec in speech_state.records(state_dir)}
190
210
  by_job = speech_state.jobs(state_dir)
211
+ debug = debug_mode.current()
212
+ facts = (
213
+ cast(HostFacts, debug_mode.simulated_facts(debug))
214
+ if debug.mode == "simulate"
215
+ else hosts.load_facts(hosts.LOCAL_ID)
216
+ )
191
217
  rows = [
192
- _build_model_row(spec, base_dir, runtime, by_record.get(spec.id), by_job.get(spec.id))
218
+ _build_model_row(
219
+ spec,
220
+ base_dir,
221
+ runtime,
222
+ by_record.get(spec.id),
223
+ by_job.get(spec.id),
224
+ _engine_bytes(spec, base_dir, use_gpu=bool(cfg.get("use_gpu")), facts=facts),
225
+ )
193
226
  for spec in speech_catalog.speech_models()
194
227
  ]
195
228
  return {
@@ -202,6 +235,22 @@ def status(base_dir: str, *, state_dir: Path | None = None) -> SpeechStatusDocum
202
235
  }
203
236
 
204
237
 
238
+ def _engine_bytes(
239
+ spec: SpeechModelSpec, base_dir: str, *, use_gpu: bool, facts: HostFacts | None
240
+ ) -> int:
241
+ """Archive bytes of the engine build a download of ``spec`` fetches on this host with the
242
+ configured GPU preference, so a row's size is what the model takes with its engine (the
243
+ CUDA whisper.cpp build is larger than the weights). Uses the facts the last probe saved; a
244
+ host never probed counts the weights only, since a status read must not probe."""
245
+ if spec.engine != "whisper.cpp" or facts is None:
246
+ return 0
247
+ with contextlib.redirect_stderr(io.StringIO()):
248
+ engine = _select_whisper_engine(spec, base_dir, include_gpu_engine=use_gpu, facts=facts)
249
+ if engine is None:
250
+ return 0
251
+ return sum(int(asset["size_bytes"]) for asset in engine.get("assets") or ())
252
+
253
+
205
254
  def model_row(model_id: str, base_dir: str, *, state_dir: Path | None = None) -> SpeechModelRow:
206
255
  """Return the current ``SpeechModelRow`` for ``model_id``."""
207
256
  doc = status(base_dir, state_dir=state_dir)
@@ -561,6 +610,7 @@ def download(
561
610
  with speech_state.held_job(claims, state_dir):
562
611
  handle = SpeechJobHandle(job, state_dir)
563
612
  try:
613
+ _unload_stale_if_active(spec, base_dir, state_dir)
564
614
  with _watch_cancel(job, state_dir):
565
615
  _run_fetch(spec, files, engine, handle, runner)
566
616
  except KeyboardInterrupt:
@@ -678,15 +728,36 @@ def _engine_in_use_elsewhere(
678
728
  return False
679
729
 
680
730
 
681
- def remove(model_id: str, base_dir: str, *, state_dir: Path | None = None) -> SpeechModelRow:
682
- """Unload if active, remove weight files idempotently, and preserve shared engines."""
683
- spec = _lookup_model(model_id)
684
- with speech_state.locked(state_dir):
685
- if speech_state.job_alive(spec.id, state_dir):
686
- raise SpeechError("INVALID_STATE", f"{spec.id} is downloading; cancel it first")
731
+ def _prune_empty_model_dirs(target_dir: Path, files: list[str]) -> None:
732
+ """Remove now-empty subdirectories under ``target_dir`` and then ``target_dir`` itself."""
733
+ if not target_dir.is_dir():
734
+ return
735
+ resolved_root = target_dir.resolve()
736
+ subdirs: set[Path] = set()
737
+ for file_path in files:
738
+ parent = Path(os.path.expanduser(file_path)).parent
739
+ try:
740
+ resolved_parent = parent.resolve()
741
+ except OSError:
742
+ continue
743
+ while resolved_parent != resolved_root and resolved_parent.is_relative_to(resolved_root):
744
+ subdirs.add(resolved_parent)
745
+ resolved_parent = resolved_parent.parent
746
+ for subdir in sorted(subdirs, key=lambda p: len(p.parts), reverse=True):
747
+ try:
748
+ subdir.rmdir()
749
+ except OSError:
750
+ pass
751
+ try:
752
+ target_dir.rmdir()
753
+ except OSError:
754
+ pass
755
+
687
756
 
757
+ def _unload_if_active(model_id: str, state_dir: Path | None) -> None:
758
+ """Best-effort unload ``model_id`` from a running sidecar before replacing or deleting weights."""
688
759
  rec_rt = speech_state.load_runtime_record(state_dir)
689
- if rec_rt is not None and rec_rt.get("active_model") == spec.id:
760
+ if rec_rt is not None and rec_rt.get("active_model") == model_id:
690
761
  rt_url = rec_rt.get("base_url")
691
762
  if isinstance(rt_url, str) and rt_url:
692
763
  key_file = rec_rt.get("key_file")
@@ -695,10 +766,26 @@ def remove(model_id: str, base_dir: str, *, state_dir: Path | None = None) -> Sp
695
766
  "/v1/speech/unload",
696
767
  method="POST",
697
768
  key_file=key_file if isinstance(key_file, str) else None,
698
- payload={"model_id": spec.id},
769
+ payload={"model_id": model_id},
699
770
  timeout=3.0,
700
771
  )
701
772
 
773
+
774
+ def _unload_stale_if_active(spec: SpeechModelSpec, base_dir: str, state_dir: Path | None) -> None:
775
+ """Unload a running worker before overwriting stale/mismatched weights."""
776
+ if not weights_installed(spec, base_dir):
777
+ _unload_if_active(spec.id, state_dir)
778
+
779
+
780
+ def remove(model_id: str, base_dir: str, *, state_dir: Path | None = None) -> SpeechModelRow:
781
+ """Unload if active, remove weight files idempotently, and preserve shared engines."""
782
+ spec = _lookup_model(model_id)
783
+ with speech_state.locked(state_dir):
784
+ if speech_state.job_alive(spec.id, state_dir):
785
+ raise SpeechError("INVALID_STATE", f"{spec.id} is downloading; cancel it first")
786
+
787
+ _unload_if_active(spec.id, state_dir)
788
+
702
789
  with speech_state.locked(state_dir):
703
790
  record = speech_state.load_record(spec.id, state_dir)
704
791
  files = [f["dest"] for f in model_file_specs(spec, base_dir)]
@@ -712,12 +799,7 @@ def remove(model_id: str, base_dir: str, *, state_dir: Path | None = None) -> Sp
712
799
  os.remove(candidate)
713
800
  except FileNotFoundError:
714
801
  pass
715
- target_dir = model_dir(base_dir, spec.id)
716
- if target_dir.is_dir():
717
- try:
718
- target_dir.rmdir()
719
- except OSError:
720
- pass
802
+ _prune_empty_model_dirs(model_dir(base_dir, spec.id), files)
721
803
  engine_dir = record.get("engine_dir") if record is not None else None
722
804
  if engine_dir and not _engine_in_use_elsewhere(engine_dir, spec.id, state_dir):
723
805
  eng_path = Path(os.path.expanduser(engine_dir))
@@ -69,6 +69,7 @@ from localmodels.speech_workers import (
69
69
  ensure_run_dir,
70
70
  is_gpu_oom_error,
71
71
  parse_multipart_form,
72
+ qwen3_asr_argv,
72
73
  resolve_sensevoice_python,
73
74
  resolve_whisper_binary,
74
75
  sensevoice_argv,
@@ -99,6 +100,7 @@ __all__ = [
99
100
  "main",
100
101
  "make_handler",
101
102
  "parse_multipart_form",
103
+ "qwen3_asr_argv",
102
104
  "resolve_sensevoice_python",
103
105
  "resolve_whisper_binary",
104
106
  "sensevoice_argv",