@simplexai/localmodels-win32-x64 0.1.0-dev.65 → 0.1.0-dev.68
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 +62 -61
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/auth_proxy.py +34 -2
- package/modules/localmodels/bifrost_config.py +11 -6
- package/modules/localmodels/catalog.json +500 -16
- package/modules/localmodels/custom_hub.py +54 -6
- package/modules/localmodels/custom_probe.py +28 -0
- package/modules/localmodels/debug_stub_server.py +34 -1
- package/modules/localmodels/deploy.py +33 -349
- package/modules/localmodels/download-mirrors.json +43 -3
- package/modules/localmodels/draft_spec.py +1 -1
- package/modules/localmodels/engine_adapters/__init__.py +4 -2
- package/modules/localmodels/engine_adapters/auxiliary.py +4 -1
- package/modules/localmodels/engine_adapters/llama_cpp.py +539 -0
- package/modules/localmodels/engines-b11583.json +9 -5
- package/modules/localmodels/engines-b12757-mix-ef2df21.json +85 -1
- package/modules/localmodels/engines.json +9 -5
- package/modules/localmodels/gateway_bifrost.py +2 -1
- package/modules/localmodels/harness_gateway.py +14 -3
- package/modules/localmodels/harness_probe.py +64 -3
- package/modules/localmodels/library_custom.py +9 -7
- package/modules/localmodels/library_elastic.py +5 -4
- package/modules/localmodels/library_jobs.py +138 -25
- package/modules/localmodels/library_model.py +22 -2
- package/modules/localmodels/library_order.py +1 -1
- package/modules/localmodels/library_serve.py +49 -11
- package/modules/localmodels/library_state.py +12 -0
- package/modules/localmodels/library_status.py +10 -0
- package/modules/localmodels/pi_profile.py +1 -1
- package/modules/localmodels/planning/budget.py +8 -3
- package/modules/localmodels/process_identity.py +73 -10
- package/modules/localmodels/remote_ops_mirrors.py +55 -19
- package/modules/localmodels/runtime_io.py +1 -0
- package/modules/localmodels/runtime_windows_acl.py +47 -17
- package/modules/localmodels/service_deployment.py +3 -3
- package/modules/localmodels/setup_inspection.py +28 -1
- package/modules/localmodels/setup_inspection_harness.py +4 -1
- package/modules/localmodels/setup_text.py +6 -0
- package/modules/localmodels/slot_cache.py +1 -3
- package/modules/localmodels/speech_admission.py +16 -4
- package/modules/localmodels/speech_catalog.py +5 -1
- package/modules/localmodels/speech_cli.py +5 -5
- package/modules/localmodels/speech_jobs.py +101 -19
- package/modules/localmodels/speech_server.py +2 -0
- package/modules/localmodels/speech_worker_sensevoice.py +194 -6
- package/modules/localmodels/speech_workers.py +74 -6
- package/modules/localmodels/stack.py +13 -1
- package/modules/localmodels/stack_auto.py +6 -0
- package/modules/localmodels/stack_capacity.py +3 -3
- package/modules/localmodels/stack_cli.py +3 -0
- package/modules/localmodels/stack_compose.py +7 -3
- package/modules/localmodels/stack_ports.py +58 -27
- package/modules/localmodels/stack_suite.py +7 -1
- package/modules/localmodels/suite.py +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev68.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev68.dist-info}/RECORD +59 -58
- package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev68.dist-info}/licenses/NOTICE +3 -0
- package/package.json +1 -1
- package/tool.json +1 -1
- /package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev68.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev68.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev65.dist-info → simplex_localmodels-0.1.0.dev68.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -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
|
-
|
|
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
|
-
|
|
160
|
-
|
|
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
|
-
|
|
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, ...] = (
|
|
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
|
|
24
|
-
"inspect status, download with resumable verification, cancel, remove, and
|
|
25
|
-
"preferences. Every command writes pure JSON or JSONL on stdout. Exit
|
|
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
|
-
"""
|
|
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
|
-
|
|
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":
|
|
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(
|
|
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
|
|
682
|
-
"""
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
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") ==
|
|
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":
|
|
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
|
-
|
|
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",
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
"""Isolated CPU child HTTP worker serving SenseVoice Small
|
|
1
|
+
"""Isolated CPU child HTTP worker serving sherpa-onnx ASR models (SenseVoice Small & Qwen3-ASR).
|
|
2
2
|
|
|
3
3
|
Run inside the hash-locked Python venv built from ``localmodels/speech-sv.txt``
|
|
4
4
|
(``<base_dir>/frontends/speech-sv/``) as a child of ``localmodels/speech_server.py``.
|
|
5
5
|
``sherpa_onnx`` is imported dynamically at startup so this module remains pure stdlib at
|
|
6
|
-
import time and its WAV framing and
|
|
6
|
+
import time and its WAV framing and output parsing stay unit-testable without
|
|
7
7
|
``sherpa-onnx`` installed.
|
|
8
8
|
"""
|
|
9
9
|
|
|
@@ -32,6 +32,83 @@ MAX_AUDIO_BYTES = 50 << 20 # 50 MiB bounded upload
|
|
|
32
32
|
SENSEVOICE_TAG_RE = re.compile(r"<\|([^|]+)\|>")
|
|
33
33
|
KNOWN_LANGUAGES = frozenset(("zh", "en", "ja", "ko", "yue"))
|
|
34
34
|
NO_SPEECH_TAGS = frozenset(("nospeech", "bgm"))
|
|
35
|
+
QWEN3_ASR_MAX_TOTAL_LEN = 512
|
|
36
|
+
QWEN3_ASR_MAX_NEW_TOKENS = 256
|
|
37
|
+
_LANGUAGE_TAG_RE = re.compile(r"^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$")
|
|
38
|
+
_QWEN3_LANG_PREFIX_RE = re.compile(
|
|
39
|
+
r"(?:^|\b)language\s+([A-Za-z][A-Za-z -]{0,30})\s*$", re.IGNORECASE
|
|
40
|
+
)
|
|
41
|
+
_LANGUAGE_NAME_TO_ISO: dict[str, str] = {
|
|
42
|
+
"arabic": "ar",
|
|
43
|
+
"cantonese": "yue",
|
|
44
|
+
"chinese": "zh",
|
|
45
|
+
"czech": "cs",
|
|
46
|
+
"danish": "da",
|
|
47
|
+
"dutch": "nl",
|
|
48
|
+
"english": "en",
|
|
49
|
+
"finnish": "fi",
|
|
50
|
+
"french": "fr",
|
|
51
|
+
"german": "de",
|
|
52
|
+
"greek": "el",
|
|
53
|
+
"hindi": "hi",
|
|
54
|
+
"hungarian": "hu",
|
|
55
|
+
"indonesian": "id",
|
|
56
|
+
"italian": "it",
|
|
57
|
+
"japanese": "ja",
|
|
58
|
+
"korean": "ko",
|
|
59
|
+
"macedonian": "mk",
|
|
60
|
+
"malay": "ms",
|
|
61
|
+
"mandarin": "zh",
|
|
62
|
+
"norwegian": "no",
|
|
63
|
+
"persian": "fa",
|
|
64
|
+
"polish": "pl",
|
|
65
|
+
"portuguese": "pt",
|
|
66
|
+
"romanian": "ro",
|
|
67
|
+
"russian": "ru",
|
|
68
|
+
"spanish": "es",
|
|
69
|
+
"swedish": "sv",
|
|
70
|
+
"thai": "th",
|
|
71
|
+
"turkish": "tr",
|
|
72
|
+
"ukrainian": "uk",
|
|
73
|
+
"vietnamese": "vi",
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def is_valid_language_tag(value: str) -> bool:
|
|
78
|
+
"""Return True when ``value`` conforms to the speech-v1 ISO-639-1 / BCP-47 tag pattern."""
|
|
79
|
+
return bool(_LANGUAGE_TAG_RE.fullmatch(value))
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def normalize_qwen3_language(raw: str) -> str:
|
|
83
|
+
"""Normalize a Qwen3-ASR language name (e.g. ``'Chinese'``) or code to ISO-639-1 / BCP-47."""
|
|
84
|
+
cleaned = raw.strip()
|
|
85
|
+
if not cleaned:
|
|
86
|
+
return ""
|
|
87
|
+
mapped = _LANGUAGE_NAME_TO_ISO.get(cleaned.lower())
|
|
88
|
+
if mapped is not None:
|
|
89
|
+
return mapped
|
|
90
|
+
parts = cleaned.split("-")
|
|
91
|
+
parts[0] = parts[0].lower()
|
|
92
|
+
candidate = "-".join(parts)
|
|
93
|
+
return candidate if is_valid_language_tag(candidate) else ""
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def parse_qwen3_asr_output(raw_text: str, *, raw_lang: str = "") -> tuple[str, str]:
|
|
97
|
+
"""Normalize Qwen3-ASR text and language into ``(clean_text, iso_language)``.
|
|
98
|
+
|
|
99
|
+
Strips any defensive ``language <Name><asr_text>`` prefix if present and normalizes
|
|
100
|
+
language names (such as ``"Chinese"`` or ``"English"``) to ISO-639-1 codes.
|
|
101
|
+
"""
|
|
102
|
+
lang_hint = raw_lang
|
|
103
|
+
body = raw_text
|
|
104
|
+
if "<asr_text>" in raw_text:
|
|
105
|
+
prefix, _, body = raw_text.partition("<asr_text>")
|
|
106
|
+
if not lang_hint:
|
|
107
|
+
match = _QWEN3_LANG_PREFIX_RE.search(prefix.strip())
|
|
108
|
+
if match is not None:
|
|
109
|
+
lang_hint = match.group(1)
|
|
110
|
+
cleaned = " ".join(body.split()).strip()
|
|
111
|
+
return cleaned, normalize_qwen3_language(lang_hint)
|
|
35
112
|
|
|
36
113
|
|
|
37
114
|
def parse_sensevoice_output(raw_text: str, *, raw_lang: str = "") -> tuple[str, str]:
|
|
@@ -186,6 +263,68 @@ class SenseVoiceRecognizer:
|
|
|
186
263
|
}
|
|
187
264
|
|
|
188
265
|
|
|
266
|
+
class Qwen3AsrRecognizer:
|
|
267
|
+
"""Thread-safe sherpa-onnx OfflineRecognizer wrapper for Qwen3-ASR (INT8)."""
|
|
268
|
+
|
|
269
|
+
def __init__(
|
|
270
|
+
self,
|
|
271
|
+
conv_frontend: Path,
|
|
272
|
+
encoder: Path,
|
|
273
|
+
decoder: Path,
|
|
274
|
+
tokenizer: Path,
|
|
275
|
+
*,
|
|
276
|
+
threads: int = 4,
|
|
277
|
+
max_total_len: int = QWEN3_ASR_MAX_TOTAL_LEN,
|
|
278
|
+
max_new_tokens: int = QWEN3_ASR_MAX_NEW_TOKENS,
|
|
279
|
+
) -> None:
|
|
280
|
+
_preload_windows_onnxruntime()
|
|
281
|
+
sherpa_onnx = importlib.import_module("sherpa_onnx")
|
|
282
|
+
self._recognizer: Any = sherpa_onnx.OfflineRecognizer.from_qwen3_asr(
|
|
283
|
+
conv_frontend=str(conv_frontend),
|
|
284
|
+
encoder=str(encoder),
|
|
285
|
+
decoder=str(decoder),
|
|
286
|
+
tokenizer=str(tokenizer),
|
|
287
|
+
num_threads=max(1, threads),
|
|
288
|
+
provider="cpu",
|
|
289
|
+
max_total_len=max(1, max_total_len),
|
|
290
|
+
max_new_tokens=max(1, max_new_tokens),
|
|
291
|
+
)
|
|
292
|
+
self._lock = threading.Lock()
|
|
293
|
+
|
|
294
|
+
def transcribe(
|
|
295
|
+
self,
|
|
296
|
+
samples: list[float],
|
|
297
|
+
sample_rate: int,
|
|
298
|
+
language: str = "auto",
|
|
299
|
+
) -> dict[str, object]:
|
|
300
|
+
duration = len(samples) / float(sample_rate) if sample_rate > 0 else 0.0
|
|
301
|
+
if not samples:
|
|
302
|
+
return {
|
|
303
|
+
"text": "",
|
|
304
|
+
"language": "" if language == "auto" else language,
|
|
305
|
+
"duration": 0.0,
|
|
306
|
+
"segments": [],
|
|
307
|
+
}
|
|
308
|
+
with self._lock:
|
|
309
|
+
stream = self._recognizer.create_stream()
|
|
310
|
+
stream.accept_waveform(sample_rate, samples)
|
|
311
|
+
self._recognizer.decode_stream(stream)
|
|
312
|
+
result = stream.result
|
|
313
|
+
raw_text = str(getattr(result, "text", "") or "")
|
|
314
|
+
raw_lang = str(getattr(result, "lang", "") or "")
|
|
315
|
+
text, detected = parse_qwen3_asr_output(raw_text, raw_lang=raw_lang)
|
|
316
|
+
lang_out = detected or ("" if language == "auto" else language)
|
|
317
|
+
segments: list[dict[str, object]] = (
|
|
318
|
+
[{"start": 0.0, "end": round(duration, 3), "text": text}] if text else []
|
|
319
|
+
)
|
|
320
|
+
return {
|
|
321
|
+
"text": text,
|
|
322
|
+
"language": lang_out,
|
|
323
|
+
"duration": round(duration, 3),
|
|
324
|
+
"segments": segments,
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
|
|
189
328
|
def send_json_response(
|
|
190
329
|
handler: BaseHTTPRequestHandler,
|
|
191
330
|
status: HTTPStatus,
|
|
@@ -265,15 +404,64 @@ def default_threads() -> int:
|
|
|
265
404
|
|
|
266
405
|
|
|
267
406
|
def main(argv: list[str] | None = None) -> int:
|
|
268
|
-
parser = argparse.ArgumentParser(description="
|
|
269
|
-
parser.add_argument(
|
|
270
|
-
|
|
407
|
+
parser = argparse.ArgumentParser(description="sherpa-onnx CPU speech loopback worker")
|
|
408
|
+
parser.add_argument(
|
|
409
|
+
"--arch",
|
|
410
|
+
choices=("sensevoice", "qwen3-asr"),
|
|
411
|
+
default="sensevoice",
|
|
412
|
+
help="sherpa-onnx model architecture (default: sensevoice)",
|
|
413
|
+
)
|
|
414
|
+
parser.add_argument("--model", help="path to SenseVoice model.int8.onnx")
|
|
415
|
+
parser.add_argument("--tokens", help="path to SenseVoice tokens.txt")
|
|
416
|
+
parser.add_argument("--conv-frontend", help="path to Qwen3-ASR conv_frontend.onnx")
|
|
417
|
+
parser.add_argument("--encoder", help="path to Qwen3-ASR encoder.int8.onnx")
|
|
418
|
+
parser.add_argument("--decoder", help="path to Qwen3-ASR decoder.int8.onnx")
|
|
419
|
+
parser.add_argument("--tokenizer", help="path to Qwen3-ASR tokenizer directory")
|
|
420
|
+
parser.add_argument(
|
|
421
|
+
"--max-total-len",
|
|
422
|
+
type=int,
|
|
423
|
+
default=QWEN3_ASR_MAX_TOTAL_LEN,
|
|
424
|
+
help="Qwen3-ASR KV cache sequence limit",
|
|
425
|
+
)
|
|
426
|
+
parser.add_argument(
|
|
427
|
+
"--max-new-tokens",
|
|
428
|
+
type=int,
|
|
429
|
+
default=QWEN3_ASR_MAX_NEW_TOKENS,
|
|
430
|
+
help="Qwen3-ASR max new tokens per utterance",
|
|
431
|
+
)
|
|
271
432
|
parser.add_argument("--host", default="127.0.0.1", help="loopback bind host")
|
|
272
433
|
parser.add_argument("--port", type=int, required=True, help="loopback bind port")
|
|
273
434
|
parser.add_argument("--threads", type=int, default=default_threads(), help="CPU thread count")
|
|
274
435
|
args = parser.parse_args(argv)
|
|
275
436
|
|
|
276
|
-
recognizer
|
|
437
|
+
recognizer: Recognizer
|
|
438
|
+
if args.arch == "qwen3-asr":
|
|
439
|
+
missing = [
|
|
440
|
+
flag
|
|
441
|
+
for flag, value in (
|
|
442
|
+
("--conv-frontend", args.conv_frontend),
|
|
443
|
+
("--encoder", args.encoder),
|
|
444
|
+
("--decoder", args.decoder),
|
|
445
|
+
("--tokenizer", args.tokenizer),
|
|
446
|
+
)
|
|
447
|
+
if not value
|
|
448
|
+
]
|
|
449
|
+
if missing:
|
|
450
|
+
parser.error(f"--arch qwen3-asr requires: {', '.join(missing)}")
|
|
451
|
+
recognizer = Qwen3AsrRecognizer(
|
|
452
|
+
Path(args.conv_frontend),
|
|
453
|
+
Path(args.encoder),
|
|
454
|
+
Path(args.decoder),
|
|
455
|
+
Path(args.tokenizer),
|
|
456
|
+
threads=args.threads,
|
|
457
|
+
max_total_len=args.max_total_len,
|
|
458
|
+
max_new_tokens=args.max_new_tokens,
|
|
459
|
+
)
|
|
460
|
+
else:
|
|
461
|
+
if not args.model or not args.tokens:
|
|
462
|
+
parser.error("--arch sensevoice requires: --model, --tokens")
|
|
463
|
+
recognizer = SenseVoiceRecognizer(Path(args.model), Path(args.tokens), threads=args.threads)
|
|
464
|
+
|
|
277
465
|
server = ThreadingHTTPServer((args.host, args.port), make_handler(recognizer))
|
|
278
466
|
server.daemon_threads = True
|
|
279
467
|
|
|
@@ -363,6 +363,59 @@ def sensevoice_argv(
|
|
|
363
363
|
]
|
|
364
364
|
|
|
365
365
|
|
|
366
|
+
def qwen3_asr_argv(
|
|
367
|
+
python_bin: str,
|
|
368
|
+
conv_frontend: str,
|
|
369
|
+
encoder: str,
|
|
370
|
+
decoder: str,
|
|
371
|
+
tokenizer_dir: str,
|
|
372
|
+
port: int,
|
|
373
|
+
*,
|
|
374
|
+
threads: int | None = None,
|
|
375
|
+
max_total_len: int = speech_worker_sensevoice.QWEN3_ASR_MAX_TOTAL_LEN,
|
|
376
|
+
max_new_tokens: int = speech_worker_sensevoice.QWEN3_ASR_MAX_NEW_TOKENS,
|
|
377
|
+
) -> list[str]:
|
|
378
|
+
"""Build isolated ``speech_worker_sensevoice.py`` child worker argv for Qwen3-ASR."""
|
|
379
|
+
num_threads = threads if threads is not None else min(4, max(1, os.cpu_count() or 1))
|
|
380
|
+
script = str(Path(speech_worker_sensevoice.__file__).resolve())
|
|
381
|
+
return [
|
|
382
|
+
python_bin,
|
|
383
|
+
script,
|
|
384
|
+
"--arch",
|
|
385
|
+
"qwen3-asr",
|
|
386
|
+
"--conv-frontend",
|
|
387
|
+
conv_frontend,
|
|
388
|
+
"--encoder",
|
|
389
|
+
encoder,
|
|
390
|
+
"--decoder",
|
|
391
|
+
decoder,
|
|
392
|
+
"--tokenizer",
|
|
393
|
+
tokenizer_dir,
|
|
394
|
+
"--max-total-len",
|
|
395
|
+
str(max(1, max_total_len)),
|
|
396
|
+
"--max-new-tokens",
|
|
397
|
+
str(max(1, max_new_tokens)),
|
|
398
|
+
"--host",
|
|
399
|
+
"127.0.0.1",
|
|
400
|
+
"--port",
|
|
401
|
+
str(port),
|
|
402
|
+
"--threads",
|
|
403
|
+
str(max(1, num_threads)),
|
|
404
|
+
]
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _resolve_qwen3_asr_paths(spec: SpeechModelSpec, base_dir: str) -> tuple[str, str, str, str]:
|
|
408
|
+
"""Locate ``(conv_frontend, encoder, decoder, tokenizer_dir)`` for a Qwen3-ASR model."""
|
|
409
|
+
dests = {f.path: speech_jobs.model_file_dest(base_dir, spec.id, f.path) for f in spec.files}
|
|
410
|
+
conv = next((p for rel, p in dests.items() if "conv_frontend" in rel), None)
|
|
411
|
+
enc = next((p for rel, p in dests.items() if "encoder" in rel), None)
|
|
412
|
+
dec = next((p for rel, p in dests.items() if "decoder" in rel), None)
|
|
413
|
+
vocab = next((p for rel, p in dests.items() if rel.endswith("vocab.json")), None)
|
|
414
|
+
if conv is None or enc is None or dec is None or vocab is None:
|
|
415
|
+
raise WorkerError(f"incomplete Qwen3-ASR file layout for {spec.id}")
|
|
416
|
+
return str(conv), str(enc), str(dec), str(vocab.parent)
|
|
417
|
+
|
|
418
|
+
|
|
366
419
|
class ChildWatchdog:
|
|
367
420
|
"""Binds a child worker's lifetime to this sidecar via POSIX pipe guard or Windows Job."""
|
|
368
421
|
|
|
@@ -625,7 +678,12 @@ def spawn_simulated_worker(
|
|
|
625
678
|
"PYTHONNOUSERSITE": "1",
|
|
626
679
|
"PYTHONDONTWRITEBYTECODE": "1",
|
|
627
680
|
}
|
|
628
|
-
|
|
681
|
+
if spec.engine == "whisper.cpp":
|
|
682
|
+
mode = "speech-whisper"
|
|
683
|
+
elif spec.id == "qwen3-asr-0.6b":
|
|
684
|
+
mode = "speech-qwen3-asr"
|
|
685
|
+
else:
|
|
686
|
+
mode = "speech-sensevoice"
|
|
629
687
|
argv = [
|
|
630
688
|
sys.executable,
|
|
631
689
|
"-P",
|
|
@@ -661,15 +719,18 @@ def spawn_real_worker(
|
|
|
661
719
|
elif decision.effective_device == "cpu":
|
|
662
720
|
env["CUDA_VISIBLE_DEVICES"] = ""
|
|
663
721
|
|
|
664
|
-
model_root = speech_jobs.model_dir(base_dir, spec.id)
|
|
665
722
|
if spec.engine == "whisper.cpp":
|
|
666
723
|
binary = resolve_whisper_binary(spec, decision, base_dir, state_dir)
|
|
667
|
-
model_file = str(
|
|
724
|
+
model_file = str(speech_jobs.model_file_dest(base_dir, spec.id, spec.files[0].path))
|
|
668
725
|
argv = whisper_argv(binary, model_file, port, decision.effective_device)
|
|
726
|
+
elif spec.id == "qwen3-asr-0.6b":
|
|
727
|
+
python_bin = resolve_sensevoice_python(base_dir)
|
|
728
|
+
conv_frontend, encoder, decoder, tokenizer_dir = _resolve_qwen3_asr_paths(spec, base_dir)
|
|
729
|
+
argv = qwen3_asr_argv(python_bin, conv_frontend, encoder, decoder, tokenizer_dir, port)
|
|
669
730
|
else:
|
|
670
731
|
python_bin = resolve_sensevoice_python(base_dir)
|
|
671
|
-
model_file = str(
|
|
672
|
-
tokens_file = str(
|
|
732
|
+
model_file = str(speech_jobs.model_file_dest(base_dir, spec.id, spec.files[0].path))
|
|
733
|
+
tokens_file = str(speech_jobs.model_file_dest(base_dir, spec.id, spec.files[1].path))
|
|
673
734
|
argv = sensevoice_argv(python_bin, model_file, tokens_file, port)
|
|
674
735
|
|
|
675
736
|
return _launch_worker_process(spec, decision, argv, env, port, state_dir)
|
|
@@ -779,7 +840,14 @@ def call_sensevoice_worker(
|
|
|
779
840
|
parsed = _post_worker(url, wav_data, "audio/wav", worker)
|
|
780
841
|
raw_text = str(parsed.get("text") or "")
|
|
781
842
|
raw_lang = str(parsed.get("language") or "")
|
|
782
|
-
|
|
843
|
+
if worker.model_id == "qwen3-asr-0.6b":
|
|
844
|
+
text, detected = speech_worker_sensevoice.parse_qwen3_asr_output(
|
|
845
|
+
raw_text, raw_lang=raw_lang
|
|
846
|
+
)
|
|
847
|
+
else:
|
|
848
|
+
text, detected = speech_worker_sensevoice.parse_sensevoice_output(
|
|
849
|
+
raw_text, raw_lang=raw_lang
|
|
850
|
+
)
|
|
783
851
|
lang_out = detected or ("" if language == "auto" else language)
|
|
784
852
|
dur_raw = parsed.get("duration")
|
|
785
853
|
dur_out = round(float(dur_raw), 3) if isinstance(dur_raw, int | float) else round(duration, 3)
|