@simplexai/localmodels-darwin-x64 0.1.0-dev.59 → 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.
- package/bootstrap.identity +1 -1
- package/bootstrap.sha256 +126 -107
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +107 -44
- package/modules/localmodels/apple_sensors.py +431 -0
- package/modules/localmodels/auth_proxy.py +185 -19
- package/modules/localmodels/bifrost_admin.py +30 -0
- package/modules/localmodels/bifrost_checks.py +2 -2
- package/modules/localmodels/bifrost_config.py +132 -9
- package/modules/localmodels/bifrost_models.py +1 -1
- package/modules/localmodels/catalog.json +509 -54
- package/modules/localmodels/catalog.py +21 -4
- package/modules/localmodels/catalog_add.py +42 -11
- 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.py +983 -0
- package/modules/localmodels/custom_hub_http.py +579 -0
- package/modules/localmodels/custom_probe.py +451 -0
- package/modules/localmodels/debug_mode.py +13 -0
- package/modules/localmodels/debug_stub_server.py +156 -1
- package/modules/localmodels/deploy.py +38 -7
- package/modules/localmodels/deploy_steps.py +5 -0
- package/modules/localmodels/download-mirrors.json +20 -0
- package/modules/localmodels/engines-b12757-mix-ef2df21.json +26 -0
- package/modules/localmodels/engines-prism-b12178-03ec600.json +131 -0
- package/modules/localmodels/engines-strata-poly-0.2.20-poly.6.json +94 -0
- package/modules/localmodels/engines-whisper-b5454.json +120 -1
- package/modules/localmodels/engines.py +38 -8
- package/modules/localmodels/estimator.py +60 -7
- package/modules/localmodels/gateway.py +48 -3
- package/modules/localmodels/gateway_app_bifrost.py +18 -18
- package/modules/localmodels/gateway_bifrost.py +102 -16
- package/modules/localmodels/gateway_cli.py +14 -80
- package/modules/localmodels/gateway_server.py +88 -16
- package/modules/localmodels/gguf.py +6 -0
- 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/host_sensors.py +704 -0
- package/modules/localmodels/install.py +4 -4
- package/modules/localmodels/library_cli.py +181 -3
- package/modules/localmodels/library_custom.py +831 -0
- package/modules/localmodels/library_elastic.py +35 -7
- package/modules/localmodels/library_gateway.py +94 -32
- package/modules/localmodels/library_jobs.py +76 -11
- package/modules/localmodels/library_kept.py +50 -6
- package/modules/localmodels/library_model.py +254 -2
- package/modules/localmodels/library_pricing.py +83 -4
- package/modules/localmodels/library_serve.py +178 -60
- package/modules/localmodels/library_smoke.py +315 -0
- package/modules/localmodels/library_state.py +77 -1
- package/modules/localmodels/library_status.py +126 -4
- package/modules/localmodels/npm_transport.py +4 -58
- package/modules/localmodels/nvml_ctypes.py +431 -0
- package/modules/localmodels/plan_envelope.py +14 -6
- package/modules/localmodels/recommend_cli.py +2 -1
- package/modules/localmodels/records.py +1 -0
- package/modules/localmodels/remote_ops.py +120 -665
- package/modules/localmodels/remote_ops_common.py +729 -0
- package/modules/localmodels/remote_ops_download.py +396 -241
- package/modules/localmodels/remote_ops_mirrors.py +26 -65
- package/modules/localmodels/remote_ops_prepare.py +43 -35
- package/modules/localmodels/remote_ops_ranges.py +98 -65
- package/modules/localmodels/remote_ops_remove.py +30 -22
- package/modules/localmodels/remote_ops_service.py +103 -95
- package/modules/localmodels/remote_ops_verify.py +113 -65
- package/modules/localmodels/runtime-lock.json +19 -19
- package/modules/localmodels/runtime_cli.py +15 -5
- package/modules/localmodels/runtime_io.py +54 -1
- package/modules/localmodels/service_control.py +32 -1
- package/modules/localmodels/service_wiring.py +2 -3
- package/modules/localmodels/service_worker.py +6 -2
- package/modules/localmodels/services_cli.py +35 -27
- package/modules/localmodels/source_byok.py +3 -5
- 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 +772 -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_lifecycle.py +2 -2
- package/modules/localmodels/stack_memory.py +14 -3
- package/modules/localmodels/stack_suite.py +9 -10
- package/modules/localmodels/stack_summary.py +4 -4
- package/modules/localmodels/stack_view.py +77 -53
- package/modules/localmodels/stack_view_demo.py +36 -5
- package/modules/localmodels/stack_view_events.py +147 -12
- package/modules/localmodels/stack_view_gpu.py +97 -17
- package/modules/localmodels/stack_view_llm.py +16 -1
- package/modules/localmodels/stack_view_measure.py +4 -1
- package/modules/localmodels/stack_view_schema.py +54 -8
- package/modules/localmodels/stack_view_serve.py +40 -3
- package/modules/localmodels/stack_view_slots.py +89 -10
- package/modules/localmodels/stack_view_telemetry.py +163 -0
- package/modules/localmodels/stack_view_text.py +5 -2
- package/modules/localmodels/stack_view_tick.py +658 -0
- package/modules/localmodels/stack_view_words.py +4 -0
- package/modules/localmodels/{strata-poly-serve-0.2.20-poly.5.txt → strata-poly-serve-0.2.20-poly.6.txt} +1 -1
- package/modules/localmodels/suite.py +3 -1
- package/modules/localmodels/telemetry_math.py +538 -0
- package/modules/localmodels/transport.py +3 -2
- package/modules/localmodels/tui_views.py +2 -2
- package/modules/localmodels/web/view/view.js +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/RECORD +123 -104
- package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/licenses/NOTICE +9 -0
- package/package.json +1 -1
- package/tool.json +1 -1
- package/modules/localmodels/bifrost_datasheet.py +0 -53
- package/modules/localmodels/bifrost_provider.py +0 -88
- package/modules/localmodels/bifrost_unit.py +0 -99
- package/modules/localmodels/engines-strata-poly-0.2.20-poly.5.json +0 -94
- package/modules/localmodels/gateway_switch.py +0 -51
- package/modules/localmodels/library_floor.py +0 -78
- package/modules/localmodels/service_stop.py +0 -52
- /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev59.dist-info → simplex_localmodels-0.1.0.dev61.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -0,0 +1,783 @@
|
|
|
1
|
+
"""Isolated speech engine child supervision, multipart/WAV helpers, and worker RPC calls."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import http.client
|
|
7
|
+
import json
|
|
8
|
+
import math
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
import time
|
|
14
|
+
import urllib.error
|
|
15
|
+
import urllib.parse
|
|
16
|
+
import urllib.request
|
|
17
|
+
import uuid
|
|
18
|
+
from collections.abc import Callable
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any, cast
|
|
22
|
+
|
|
23
|
+
from localmodels import (
|
|
24
|
+
auth_proxy,
|
|
25
|
+
component,
|
|
26
|
+
debug_mode,
|
|
27
|
+
engines,
|
|
28
|
+
frontend,
|
|
29
|
+
http_local,
|
|
30
|
+
speech_admission,
|
|
31
|
+
speech_jobs,
|
|
32
|
+
speech_state,
|
|
33
|
+
speech_worker_sensevoice,
|
|
34
|
+
windows_job,
|
|
35
|
+
)
|
|
36
|
+
from localmodels.probe import HostFacts
|
|
37
|
+
from localmodels.speech_admission import DeviceDecision
|
|
38
|
+
from localmodels.speech_catalog import SpeechModelSpec
|
|
39
|
+
from localmodels.speech_model import EffectiveDevice, SpeechError
|
|
40
|
+
|
|
41
|
+
SENSEVOICE_REQUIREMENTS = "speech-sv.txt"
|
|
42
|
+
# Simplified-Chinese prompt injected ONLY when language == "zh" and speech is present.
|
|
43
|
+
ZH_SIMPLIFIED_PROMPT = "\u4ee5\u4e0b\u662f\u666e\u901a\u8bdd\u7684\u53e5\u5b50\u3002"
|
|
44
|
+
SILENCE_RMS_THRESHOLD = 150.0 # int16 RMS noise floor (~-46.8 dBFS)
|
|
45
|
+
WORKER_STOP_GRACE_S = 3.0 # whisper-server b5454 hangs on SIGTERM -> SIGKILL after 3s
|
|
46
|
+
WORKER_READY_TIMEOUT_S = 60.0
|
|
47
|
+
WORKER_REQUEST_TIMEOUT_S = 300.0
|
|
48
|
+
WINDOWS_CREATE_NO_WINDOW = 0x08000000
|
|
49
|
+
|
|
50
|
+
_POSIX_WATCHDOG_SH = (
|
|
51
|
+
'read _; kill -TERM "$0" 2>/dev/null; n=0; '
|
|
52
|
+
'while kill -0 "$0" 2>/dev/null && [ "$n" -lt 3 ]; do sleep 1; n=$((n+1)); done; '
|
|
53
|
+
'kill -KILL "$0" 2>/dev/null'
|
|
54
|
+
)
|
|
55
|
+
GPU_OOM_SIGNATURES: tuple[str, ...] = (
|
|
56
|
+
"oom",
|
|
57
|
+
"out of memory",
|
|
58
|
+
"cuda",
|
|
59
|
+
"cublas",
|
|
60
|
+
"metal",
|
|
61
|
+
"vulkan",
|
|
62
|
+
"vkresult",
|
|
63
|
+
"directml",
|
|
64
|
+
"failed to allocate",
|
|
65
|
+
"unable to allocate",
|
|
66
|
+
"not enough memory",
|
|
67
|
+
"insufficient memory",
|
|
68
|
+
"bad_alloc",
|
|
69
|
+
"kioreturnnomemory",
|
|
70
|
+
"newbufferwithlength",
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
_BOUNDARY_RE = re.compile(r'boundary=(?:"([^"]+)"|([^;\s]+))', re.IGNORECASE)
|
|
74
|
+
_DISPOSITION_PARAM_RE = re.compile(r'([a-zA-Z0-9_-]+)="([^"]*)"')
|
|
75
|
+
|
|
76
|
+
# Whisper verbose_json returns full English language names (e.g. "english", "chinese")
|
|
77
|
+
# rather than ISO-639-1 codes; normalize them to match localmodels speech-v1.
|
|
78
|
+
_WHISPER_LANGUAGE_TO_ISO: dict[str, str] = {
|
|
79
|
+
"afrikaans": "af",
|
|
80
|
+
"albanian": "sq",
|
|
81
|
+
"amharic": "am",
|
|
82
|
+
"arabic": "ar",
|
|
83
|
+
"armenian": "hy",
|
|
84
|
+
"assamese": "as",
|
|
85
|
+
"azerbaijani": "az",
|
|
86
|
+
"bashkir": "ba",
|
|
87
|
+
"basque": "eu",
|
|
88
|
+
"belarusian": "be",
|
|
89
|
+
"bengali": "bn",
|
|
90
|
+
"bosnian": "bs",
|
|
91
|
+
"breton": "br",
|
|
92
|
+
"bulgarian": "bg",
|
|
93
|
+
"burmese": "my",
|
|
94
|
+
"cantonese": "yue",
|
|
95
|
+
"castilian": "es",
|
|
96
|
+
"catalan": "ca",
|
|
97
|
+
"chinese": "zh",
|
|
98
|
+
"croatian": "hr",
|
|
99
|
+
"czech": "cs",
|
|
100
|
+
"danish": "da",
|
|
101
|
+
"dutch": "nl",
|
|
102
|
+
"english": "en",
|
|
103
|
+
"estonian": "et",
|
|
104
|
+
"faroese": "fo",
|
|
105
|
+
"finnish": "fi",
|
|
106
|
+
"flemish": "nl",
|
|
107
|
+
"french": "fr",
|
|
108
|
+
"galician": "gl",
|
|
109
|
+
"georgian": "ka",
|
|
110
|
+
"german": "de",
|
|
111
|
+
"greek": "el",
|
|
112
|
+
"gujarati": "gu",
|
|
113
|
+
"haitian": "ht",
|
|
114
|
+
"haitian creole": "ht",
|
|
115
|
+
"hausa": "ha",
|
|
116
|
+
"hawaiian": "haw",
|
|
117
|
+
"hebrew": "he",
|
|
118
|
+
"hindi": "hi",
|
|
119
|
+
"hungarian": "hu",
|
|
120
|
+
"icelandic": "is",
|
|
121
|
+
"indonesian": "id",
|
|
122
|
+
"italian": "it",
|
|
123
|
+
"japanese": "ja",
|
|
124
|
+
"javanese": "jw",
|
|
125
|
+
"kannada": "kn",
|
|
126
|
+
"kazakh": "kk",
|
|
127
|
+
"khmer": "km",
|
|
128
|
+
"korean": "ko",
|
|
129
|
+
"lao": "lo",
|
|
130
|
+
"latin": "la",
|
|
131
|
+
"latvian": "lv",
|
|
132
|
+
"letzeburgesch": "lb",
|
|
133
|
+
"lingala": "ln",
|
|
134
|
+
"lithuanian": "lt",
|
|
135
|
+
"luxembourgish": "lb",
|
|
136
|
+
"macedonian": "mk",
|
|
137
|
+
"malagasy": "mg",
|
|
138
|
+
"malay": "ms",
|
|
139
|
+
"malayalam": "ml",
|
|
140
|
+
"maltese": "mt",
|
|
141
|
+
"mandarin": "zh",
|
|
142
|
+
"maori": "mi",
|
|
143
|
+
"marathi": "mr",
|
|
144
|
+
"moldavian": "ro",
|
|
145
|
+
"moldovan": "ro",
|
|
146
|
+
"mongolian": "mn",
|
|
147
|
+
"myanmar": "my",
|
|
148
|
+
"nepali": "ne",
|
|
149
|
+
"norwegian": "no",
|
|
150
|
+
"nynorsk": "nn",
|
|
151
|
+
"occitan": "oc",
|
|
152
|
+
"panjabi": "pa",
|
|
153
|
+
"pashto": "ps",
|
|
154
|
+
"persian": "fa",
|
|
155
|
+
"polish": "pl",
|
|
156
|
+
"portuguese": "pt",
|
|
157
|
+
"punjabi": "pa",
|
|
158
|
+
"pushto": "ps",
|
|
159
|
+
"romanian": "ro",
|
|
160
|
+
"russian": "ru",
|
|
161
|
+
"sanskrit": "sa",
|
|
162
|
+
"serbian": "sr",
|
|
163
|
+
"shona": "sn",
|
|
164
|
+
"sindhi": "sd",
|
|
165
|
+
"sinhala": "si",
|
|
166
|
+
"sinhalese": "si",
|
|
167
|
+
"slovak": "sk",
|
|
168
|
+
"slovenian": "sl",
|
|
169
|
+
"somali": "so",
|
|
170
|
+
"spanish": "es",
|
|
171
|
+
"sundanese": "su",
|
|
172
|
+
"swahili": "sw",
|
|
173
|
+
"swedish": "sv",
|
|
174
|
+
"tagalog": "tl",
|
|
175
|
+
"tajik": "tg",
|
|
176
|
+
"tamil": "ta",
|
|
177
|
+
"tatar": "tt",
|
|
178
|
+
"telugu": "te",
|
|
179
|
+
"thai": "th",
|
|
180
|
+
"tibetan": "bo",
|
|
181
|
+
"turkish": "tr",
|
|
182
|
+
"turkmen": "tk",
|
|
183
|
+
"ukrainian": "uk",
|
|
184
|
+
"urdu": "ur",
|
|
185
|
+
"uzbek": "uz",
|
|
186
|
+
"valencian": "ca",
|
|
187
|
+
"vietnamese": "vi",
|
|
188
|
+
"welsh": "cy",
|
|
189
|
+
"yiddish": "yi",
|
|
190
|
+
"yoruba": "yo",
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def normalize_whisper_language(raw: str) -> str:
|
|
195
|
+
"""Normalize whisper-server ``verbose_json`` language names (e.g. ``'english'``) to ISO-639-1."""
|
|
196
|
+
cleaned = raw.strip().lower()
|
|
197
|
+
if not cleaned:
|
|
198
|
+
return ""
|
|
199
|
+
return _WHISPER_LANGUAGE_TO_ISO.get(cleaned, cleaned)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
class WorkerError(RuntimeError):
|
|
203
|
+
"""Raised when an isolated speech engine child fails to start or process audio."""
|
|
204
|
+
|
|
205
|
+
def __init__(self, message: str, *, detail: str = "") -> None:
|
|
206
|
+
super().__init__(message)
|
|
207
|
+
self.detail = detail or message
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def is_gpu_oom_error(message: str) -> bool:
|
|
211
|
+
"""Return True when ``message`` matches any known GPU or OOM failure signature."""
|
|
212
|
+
lowered = message.lower()
|
|
213
|
+
return any(sig in lowered for sig in GPU_OOM_SIGNATURES)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def validate_wav_and_rms(data: bytes) -> tuple[float, float]:
|
|
217
|
+
"""Validate 16-bit mono PCM WAV bytes and return ``(duration_seconds, int16_rms)``."""
|
|
218
|
+
samples, _rate, duration = speech_worker_sensevoice.read_pcm16_wav(data)
|
|
219
|
+
if not samples:
|
|
220
|
+
return duration, 0.0
|
|
221
|
+
mean_sq = sum(sample * sample for sample in samples) / len(samples)
|
|
222
|
+
return duration, math.sqrt(mean_sq) * 32768.0
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def parse_multipart_form(
|
|
226
|
+
content_type: str,
|
|
227
|
+
body: bytes,
|
|
228
|
+
) -> tuple[dict[str, str], dict[str, tuple[str, bytes]]]:
|
|
229
|
+
"""Parse ``multipart/form-data`` in stdlib Python into ``(fields, files)``."""
|
|
230
|
+
match = _BOUNDARY_RE.search(content_type)
|
|
231
|
+
if match is None:
|
|
232
|
+
raise ValueError("missing multipart boundary in Content-Type")
|
|
233
|
+
boundary = (match.group(1) or match.group(2) or "").encode("latin-1")
|
|
234
|
+
if not boundary:
|
|
235
|
+
raise ValueError("empty multipart boundary")
|
|
236
|
+
raw_parts = body.split(b"--" + boundary)
|
|
237
|
+
if len(raw_parts) < 3:
|
|
238
|
+
raise ValueError("malformed multipart body")
|
|
239
|
+
|
|
240
|
+
fields: dict[str, str] = {}
|
|
241
|
+
files: dict[str, tuple[str, bytes]] = {}
|
|
242
|
+
for raw_part in raw_parts[1:]:
|
|
243
|
+
if raw_part.startswith(b"--"):
|
|
244
|
+
break
|
|
245
|
+
part = raw_part[2:] if raw_part.startswith(b"\r\n") else raw_part.lstrip(b"\n")
|
|
246
|
+
sep = b"\r\n\r\n" if b"\r\n\r\n" in part else b"\n\n"
|
|
247
|
+
if sep not in part:
|
|
248
|
+
continue
|
|
249
|
+
head_bytes, content = part.split(sep, 1)
|
|
250
|
+
if content.endswith(b"\r\n"):
|
|
251
|
+
content = content[:-2]
|
|
252
|
+
elif content.endswith(b"\n"):
|
|
253
|
+
content = content[:-1]
|
|
254
|
+
disposition = ""
|
|
255
|
+
for line in head_bytes.decode("latin-1", errors="replace").splitlines():
|
|
256
|
+
key, colon, value = line.partition(":")
|
|
257
|
+
if colon and key.strip().lower() == "content-disposition":
|
|
258
|
+
disposition = value.strip()
|
|
259
|
+
break
|
|
260
|
+
params = dict(_DISPOSITION_PARAM_RE.findall(disposition))
|
|
261
|
+
name = params.get("name")
|
|
262
|
+
if not name:
|
|
263
|
+
continue
|
|
264
|
+
if "filename" in params or name == "file":
|
|
265
|
+
files[name] = (params.get("filename", "audio.wav"), content)
|
|
266
|
+
else:
|
|
267
|
+
fields[name] = content.decode("utf-8", errors="replace").strip()
|
|
268
|
+
return fields, files
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def build_multipart_body(
|
|
272
|
+
fields: list[tuple[str, str]],
|
|
273
|
+
file_name: str,
|
|
274
|
+
file_bytes: bytes,
|
|
275
|
+
) -> tuple[bytes, str]:
|
|
276
|
+
"""Encode a multipart/form-data upload payload and return ``(body, content_type)``."""
|
|
277
|
+
boundary = "localmodels-speech-" + uuid.uuid4().hex
|
|
278
|
+
chunks: list[bytes] = []
|
|
279
|
+
for name, value in fields:
|
|
280
|
+
chunks.append(
|
|
281
|
+
f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode()
|
|
282
|
+
)
|
|
283
|
+
safe_name = file_name.replace('"', "") or "audio.wav"
|
|
284
|
+
chunks.append(
|
|
285
|
+
(
|
|
286
|
+
f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '
|
|
287
|
+
f'filename="{safe_name}"\r\nContent-Type: audio/wav\r\n\r\n'
|
|
288
|
+
).encode()
|
|
289
|
+
)
|
|
290
|
+
chunks.append(file_bytes)
|
|
291
|
+
chunks.append(f"\r\n--{boundary}--\r\n".encode())
|
|
292
|
+
return b"".join(chunks), f"multipart/form-data; boundary={boundary}"
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def ensure_run_dir(state_dir: Path | None) -> Path:
|
|
296
|
+
"""Ensure ``$LOCALMODELS_STATE/speech/run`` exists with 0700 permissions."""
|
|
297
|
+
path = speech_state.run_dir(state_dir)
|
|
298
|
+
path.mkdir(parents=True, exist_ok=True)
|
|
299
|
+
if os.name != "nt":
|
|
300
|
+
with contextlib.suppress(OSError):
|
|
301
|
+
path.chmod(0o700)
|
|
302
|
+
return path
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def whisper_argv(
|
|
306
|
+
binary: str,
|
|
307
|
+
model_path: str,
|
|
308
|
+
port: int,
|
|
309
|
+
effective_device: EffectiveDevice,
|
|
310
|
+
*,
|
|
311
|
+
threads: int | None = None,
|
|
312
|
+
) -> list[str]:
|
|
313
|
+
"""Build ``whisper-server`` argv (no ``--convert``, ``-mc 0``, ``-ng`` on CPU, ``-fa`` on GPU)."""
|
|
314
|
+
num_threads = threads if threads is not None else min(4, max(1, os.cpu_count() or 1))
|
|
315
|
+
argv = [
|
|
316
|
+
binary,
|
|
317
|
+
"-m",
|
|
318
|
+
model_path,
|
|
319
|
+
"-t",
|
|
320
|
+
str(max(1, num_threads)),
|
|
321
|
+
"-p",
|
|
322
|
+
"1",
|
|
323
|
+
"-mc",
|
|
324
|
+
"0",
|
|
325
|
+
"--host",
|
|
326
|
+
"127.0.0.1",
|
|
327
|
+
"--port",
|
|
328
|
+
str(port),
|
|
329
|
+
"--inference-path",
|
|
330
|
+
"/v1/audio/transcriptions",
|
|
331
|
+
]
|
|
332
|
+
argv.append("-ng" if effective_device == "cpu" else "-fa")
|
|
333
|
+
return argv
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def sensevoice_argv(
|
|
337
|
+
python_bin: str,
|
|
338
|
+
model_path: str,
|
|
339
|
+
tokens_path: str,
|
|
340
|
+
port: int,
|
|
341
|
+
*,
|
|
342
|
+
threads: int | None = None,
|
|
343
|
+
) -> list[str]:
|
|
344
|
+
"""Build isolated ``speech_worker_sensevoice.py`` child worker argv."""
|
|
345
|
+
num_threads = threads if threads is not None else min(4, max(1, os.cpu_count() or 1))
|
|
346
|
+
script = str(Path(speech_worker_sensevoice.__file__).resolve())
|
|
347
|
+
return [
|
|
348
|
+
python_bin,
|
|
349
|
+
script,
|
|
350
|
+
"--model",
|
|
351
|
+
model_path,
|
|
352
|
+
"--tokens",
|
|
353
|
+
tokens_path,
|
|
354
|
+
"--host",
|
|
355
|
+
"127.0.0.1",
|
|
356
|
+
"--port",
|
|
357
|
+
str(port),
|
|
358
|
+
"--threads",
|
|
359
|
+
str(max(1, num_threads)),
|
|
360
|
+
]
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
class ChildWatchdog:
|
|
364
|
+
"""Binds a child worker's lifetime to this sidecar via POSIX pipe guard or Windows Job."""
|
|
365
|
+
|
|
366
|
+
def __init__(self, proc: subprocess.Popen[bytes]) -> None:
|
|
367
|
+
self._guard: subprocess.Popen[bytes] | None = None
|
|
368
|
+
self._write_fd: int | None = None
|
|
369
|
+
if sys.platform == "win32":
|
|
370
|
+
handle = getattr(proc, "_handle", None)
|
|
371
|
+
if isinstance(handle, int):
|
|
372
|
+
windows_job.end_with_this_process(handle)
|
|
373
|
+
return
|
|
374
|
+
if os.name == "posix":
|
|
375
|
+
read_fd, write_fd = os.pipe()
|
|
376
|
+
try:
|
|
377
|
+
self._guard = subprocess.Popen(
|
|
378
|
+
["/bin/sh", "-c", _POSIX_WATCHDOG_SH, str(proc.pid)],
|
|
379
|
+
stdin=read_fd,
|
|
380
|
+
stdout=subprocess.DEVNULL,
|
|
381
|
+
stderr=subprocess.DEVNULL,
|
|
382
|
+
)
|
|
383
|
+
self._write_fd = write_fd
|
|
384
|
+
except OSError:
|
|
385
|
+
os.close(write_fd)
|
|
386
|
+
finally:
|
|
387
|
+
os.close(read_fd)
|
|
388
|
+
|
|
389
|
+
def close(self) -> None:
|
|
390
|
+
"""Stop the POSIX watchdog before closing its pipe so it does not signal a reused PID."""
|
|
391
|
+
if self._guard is not None:
|
|
392
|
+
with contextlib.suppress(OSError):
|
|
393
|
+
self._guard.kill()
|
|
394
|
+
with contextlib.suppress(OSError, subprocess.TimeoutExpired):
|
|
395
|
+
self._guard.wait(timeout=2.0)
|
|
396
|
+
self._guard = None
|
|
397
|
+
if self._write_fd is not None:
|
|
398
|
+
with contextlib.suppress(OSError):
|
|
399
|
+
os.close(self._write_fd)
|
|
400
|
+
self._write_fd = None
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def stop_subprocess(
|
|
404
|
+
proc: subprocess.Popen[bytes],
|
|
405
|
+
watchdog: ChildWatchdog | None = None,
|
|
406
|
+
*,
|
|
407
|
+
grace_s: float = WORKER_STOP_GRACE_S,
|
|
408
|
+
) -> None:
|
|
409
|
+
"""Terminate ``proc`` with ``SIGTERM -> grace_s -> SIGKILL`` and release its watchdog."""
|
|
410
|
+
try:
|
|
411
|
+
if proc.poll() is None:
|
|
412
|
+
with contextlib.suppress(OSError):
|
|
413
|
+
proc.terminate()
|
|
414
|
+
try:
|
|
415
|
+
proc.wait(timeout=max(0.1, grace_s))
|
|
416
|
+
except subprocess.TimeoutExpired:
|
|
417
|
+
with contextlib.suppress(OSError):
|
|
418
|
+
proc.kill()
|
|
419
|
+
with contextlib.suppress(OSError, subprocess.TimeoutExpired):
|
|
420
|
+
proc.wait(timeout=5.0)
|
|
421
|
+
finally:
|
|
422
|
+
if watchdog is not None:
|
|
423
|
+
watchdog.close()
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
@dataclass
|
|
427
|
+
class WorkerHandle:
|
|
428
|
+
"""Live isolated engine child subprocess owned by ``SpeechSidecar``."""
|
|
429
|
+
|
|
430
|
+
model_id: str
|
|
431
|
+
engine: str
|
|
432
|
+
port: int
|
|
433
|
+
proc: subprocess.Popen[bytes]
|
|
434
|
+
watchdog: ChildWatchdog | None
|
|
435
|
+
stderr_path: Path
|
|
436
|
+
decision: DeviceDecision
|
|
437
|
+
ram_estimate_bytes: int
|
|
438
|
+
vram_estimate_bytes: int
|
|
439
|
+
|
|
440
|
+
def is_alive(self) -> bool:
|
|
441
|
+
return self.proc.poll() is None
|
|
442
|
+
|
|
443
|
+
def stderr_tail(self, limit: int = 2000) -> str:
|
|
444
|
+
try:
|
|
445
|
+
text = self.stderr_path.read_text(encoding="utf-8", errors="replace")
|
|
446
|
+
return text[-limit:].strip()
|
|
447
|
+
except OSError:
|
|
448
|
+
return ""
|
|
449
|
+
|
|
450
|
+
def stop(self, grace_s: float = WORKER_STOP_GRACE_S) -> None:
|
|
451
|
+
stop_subprocess(self.proc, self.watchdog, grace_s=grace_s)
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
WorkerFactory = Callable[[SpeechModelSpec, DeviceDecision, str, Path | None], WorkerHandle]
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def wait_worker_ready(
|
|
458
|
+
proc: subprocess.Popen[bytes],
|
|
459
|
+
port: int,
|
|
460
|
+
engine: str,
|
|
461
|
+
stderr_path: Path,
|
|
462
|
+
timeout_s: float = WORKER_READY_TIMEOUT_S,
|
|
463
|
+
) -> None:
|
|
464
|
+
"""Wait until the child engine answers loopback HTTP 200 or exits early."""
|
|
465
|
+
deadline = time.monotonic() + timeout_s
|
|
466
|
+
paths = ("/health", "/") if engine == "whisper.cpp" else ("/health",)
|
|
467
|
+
opener = http_local.no_proxy_opener(allow_redirects=False)
|
|
468
|
+
while time.monotonic() < deadline:
|
|
469
|
+
code = proc.poll()
|
|
470
|
+
if code is not None:
|
|
471
|
+
tail = ""
|
|
472
|
+
with contextlib.suppress(OSError):
|
|
473
|
+
tail = stderr_path.read_text(encoding="utf-8", errors="replace")[-1200:].strip()
|
|
474
|
+
raise WorkerError(
|
|
475
|
+
f"{engine} worker exited with status {code}",
|
|
476
|
+
detail=tail or f"exit code {code}",
|
|
477
|
+
)
|
|
478
|
+
for path in paths:
|
|
479
|
+
req = urllib.request.Request(
|
|
480
|
+
f"http://127.0.0.1:{port}{path}",
|
|
481
|
+
headers={"Connection": "close"},
|
|
482
|
+
method="GET",
|
|
483
|
+
)
|
|
484
|
+
try:
|
|
485
|
+
with opener.open(req, timeout=1.0) as resp:
|
|
486
|
+
if 200 <= getattr(resp, "status", 200) < 300:
|
|
487
|
+
return
|
|
488
|
+
except (urllib.error.URLError, OSError, http.client.HTTPException):
|
|
489
|
+
continue
|
|
490
|
+
time.sleep(0.1)
|
|
491
|
+
raise WorkerError(f"{engine} worker did not become ready within {timeout_s:.0f}s")
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def resolve_whisper_binary(
|
|
495
|
+
spec: SpeechModelSpec,
|
|
496
|
+
decision: DeviceDecision,
|
|
497
|
+
base_dir: str,
|
|
498
|
+
state_dir: Path | None,
|
|
499
|
+
) -> str:
|
|
500
|
+
"""Locate the installed ``whisper-server`` binary matching ``decision``."""
|
|
501
|
+
binary_name = "whisper-server.exe" if sys.platform == "win32" else "whisper-server"
|
|
502
|
+
rec = speech_state.load_record(spec.id, state_dir)
|
|
503
|
+
if rec is not None and (eng_dir := rec.get("engine_dir")):
|
|
504
|
+
candidate = Path(os.path.expanduser(eng_dir)) / binary_name
|
|
505
|
+
if candidate.is_file():
|
|
506
|
+
return str(candidate)
|
|
507
|
+
if spec.engine_tag:
|
|
508
|
+
lock_path = engines.engine_lock_path(spec.engine_tag)
|
|
509
|
+
if lock_path.is_file():
|
|
510
|
+
backends = (
|
|
511
|
+
[decision.effective_device, "cpu"]
|
|
512
|
+
if decision.effective_device != "cpu"
|
|
513
|
+
else ["cpu"]
|
|
514
|
+
)
|
|
515
|
+
for backend in backends:
|
|
516
|
+
eng_dir_path = (
|
|
517
|
+
Path(os.path.expanduser(base_dir)) / "engines" / f"{spec.engine_tag}-{backend}"
|
|
518
|
+
)
|
|
519
|
+
candidate = eng_dir_path / binary_name
|
|
520
|
+
if candidate.is_file():
|
|
521
|
+
return str(candidate)
|
|
522
|
+
raise WorkerError(
|
|
523
|
+
f"whisper-server binary not found for {spec.id}; run `localmodels speech download {spec.id}`"
|
|
524
|
+
)
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def resolve_sensevoice_python(base_dir: str) -> str:
|
|
528
|
+
"""Ensure the hash-locked ``sherpa-onnx`` venv exists and return its python path."""
|
|
529
|
+
venv = component.front_venv(base_dir, SENSEVOICE_REQUIREMENTS)
|
|
530
|
+
if not frontend.ready(base_dir, SENSEVOICE_REQUIREMENTS):
|
|
531
|
+
try:
|
|
532
|
+
frontend.install(base_dir, SENSEVOICE_REQUIREMENTS)
|
|
533
|
+
except frontend.FrontendError as exc:
|
|
534
|
+
raise WorkerError(f"cannot prepare SenseVoice runtime venv: {exc}") from None
|
|
535
|
+
return component.venv_python(venv)
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def _launch_worker_process(
|
|
539
|
+
spec: SpeechModelSpec,
|
|
540
|
+
decision: DeviceDecision,
|
|
541
|
+
argv: list[str],
|
|
542
|
+
env: dict[str, str],
|
|
543
|
+
port: int,
|
|
544
|
+
state_dir: Path | None,
|
|
545
|
+
) -> WorkerHandle:
|
|
546
|
+
"""Spawn, watchdog-bind, and health-check a worker child process."""
|
|
547
|
+
run_cwd = ensure_run_dir(state_dir)
|
|
548
|
+
stderr_path = run_cwd / f"worker-{spec.id}-{port}.stderr.log"
|
|
549
|
+
kwargs: dict[str, Any] = {"cwd": str(run_cwd), "env": env}
|
|
550
|
+
if sys.platform == "win32":
|
|
551
|
+
kwargs["creationflags"] = WINDOWS_CREATE_NO_WINDOW
|
|
552
|
+
|
|
553
|
+
with stderr_path.open("wb") as err_stream:
|
|
554
|
+
try:
|
|
555
|
+
proc = subprocess.Popen(
|
|
556
|
+
argv,
|
|
557
|
+
stdin=subprocess.DEVNULL,
|
|
558
|
+
stdout=subprocess.DEVNULL,
|
|
559
|
+
stderr=err_stream,
|
|
560
|
+
**kwargs,
|
|
561
|
+
)
|
|
562
|
+
except OSError as exc:
|
|
563
|
+
raise WorkerError(f"failed to launch {spec.engine} worker: {exc}") from None
|
|
564
|
+
|
|
565
|
+
watchdog = ChildWatchdog(proc)
|
|
566
|
+
try:
|
|
567
|
+
wait_worker_ready(proc, port, spec.engine, stderr_path)
|
|
568
|
+
except Exception:
|
|
569
|
+
stop_subprocess(proc, watchdog)
|
|
570
|
+
raise
|
|
571
|
+
|
|
572
|
+
return WorkerHandle(
|
|
573
|
+
model_id=spec.id,
|
|
574
|
+
engine=spec.engine,
|
|
575
|
+
port=port,
|
|
576
|
+
proc=proc,
|
|
577
|
+
watchdog=watchdog,
|
|
578
|
+
stderr_path=stderr_path,
|
|
579
|
+
decision=decision,
|
|
580
|
+
ram_estimate_bytes=spec.ram_estimate_bytes,
|
|
581
|
+
vram_estimate_bytes=spec.vram_estimate_bytes,
|
|
582
|
+
)
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
def decide_simulated_device(
|
|
586
|
+
spec: SpeechModelSpec,
|
|
587
|
+
use_gpu: bool,
|
|
588
|
+
facts: HostFacts | None = None,
|
|
589
|
+
) -> DeviceDecision:
|
|
590
|
+
"""Deterministic speech device admission for ``LOCALMODELS_DEBUG=simulate``."""
|
|
591
|
+
host = (
|
|
592
|
+
facts
|
|
593
|
+
if facts is not None
|
|
594
|
+
else cast(HostFacts, debug_mode.simulated_facts(debug_mode.current()))
|
|
595
|
+
)
|
|
596
|
+
return speech_admission.decide_speech_device(spec, use_gpu, host, require_engine_build=False)
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def spawn_simulated_worker(
|
|
600
|
+
spec: SpeechModelSpec,
|
|
601
|
+
decision: DeviceDecision,
|
|
602
|
+
base_dir: str,
|
|
603
|
+
state_dir: Path | None,
|
|
604
|
+
) -> WorkerHandle:
|
|
605
|
+
"""Spawn an isolated loopback ``debug_stub_server`` worker for ``LOCALMODELS_DEBUG=simulate``."""
|
|
606
|
+
if not speech_jobs.weights_installed(spec, base_dir):
|
|
607
|
+
raise SpeechError(
|
|
608
|
+
"INVALID_STATE",
|
|
609
|
+
f"speech model {spec.id} is not downloaded; run `localmodels speech download {spec.id}`",
|
|
610
|
+
)
|
|
611
|
+
cfg = debug_mode.current()
|
|
612
|
+
if reason := cfg.fail.get("load"):
|
|
613
|
+
raise WorkerError(reason, detail=reason)
|
|
614
|
+
if cfg.load_ms > 0:
|
|
615
|
+
time.sleep(min(cfg.load_ms, 5000) / 1000.0)
|
|
616
|
+
port = auth_proxy.free_port()
|
|
617
|
+
module_root = str(Path(__file__).resolve().parent.parent)
|
|
618
|
+
env = {
|
|
619
|
+
**os.environ,
|
|
620
|
+
"PYTHONPATH": module_root,
|
|
621
|
+
"PYTHONNOUSERSITE": "1",
|
|
622
|
+
"PYTHONDONTWRITEBYTECODE": "1",
|
|
623
|
+
}
|
|
624
|
+
mode = "speech-whisper" if spec.engine == "whisper.cpp" else "speech-sensevoice"
|
|
625
|
+
argv = [
|
|
626
|
+
sys.executable,
|
|
627
|
+
"-P",
|
|
628
|
+
"-s",
|
|
629
|
+
"-m",
|
|
630
|
+
"localmodels.debug_stub_server",
|
|
631
|
+
"--mode",
|
|
632
|
+
mode,
|
|
633
|
+
"--port",
|
|
634
|
+
str(port),
|
|
635
|
+
"--model",
|
|
636
|
+
spec.id,
|
|
637
|
+
]
|
|
638
|
+
return _launch_worker_process(spec, decision, argv, env, port, state_dir)
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
def spawn_real_worker(
|
|
642
|
+
spec: SpeechModelSpec,
|
|
643
|
+
decision: DeviceDecision,
|
|
644
|
+
base_dir: str,
|
|
645
|
+
state_dir: Path | None,
|
|
646
|
+
) -> WorkerHandle:
|
|
647
|
+
"""Spawn an isolated ``whisper-server`` or ``speech_worker_sensevoice`` child process."""
|
|
648
|
+
if not speech_jobs.weights_installed(spec, base_dir):
|
|
649
|
+
raise SpeechError(
|
|
650
|
+
"INVALID_STATE",
|
|
651
|
+
f"speech model {spec.id} is not downloaded; run `localmodels speech download {spec.id}`",
|
|
652
|
+
)
|
|
653
|
+
port = auth_proxy.free_port()
|
|
654
|
+
env = dict(os.environ)
|
|
655
|
+
if decision.effective_device == "cuda" and decision.gpu_index is not None:
|
|
656
|
+
env["CUDA_VISIBLE_DEVICES"] = str(decision.gpu_index)
|
|
657
|
+
elif decision.effective_device == "cpu":
|
|
658
|
+
env["CUDA_VISIBLE_DEVICES"] = ""
|
|
659
|
+
|
|
660
|
+
model_root = speech_jobs.model_dir(base_dir, spec.id)
|
|
661
|
+
if spec.engine == "whisper.cpp":
|
|
662
|
+
binary = resolve_whisper_binary(spec, decision, base_dir, state_dir)
|
|
663
|
+
model_file = str(model_root / Path(spec.files[0].path).name)
|
|
664
|
+
argv = whisper_argv(binary, model_file, port, decision.effective_device)
|
|
665
|
+
else:
|
|
666
|
+
python_bin = resolve_sensevoice_python(base_dir)
|
|
667
|
+
model_file = str(model_root / Path(spec.files[0].path).name)
|
|
668
|
+
tokens_file = str(model_root / Path(spec.files[1].path).name)
|
|
669
|
+
argv = sensevoice_argv(python_bin, model_file, tokens_file, port)
|
|
670
|
+
|
|
671
|
+
return _launch_worker_process(spec, decision, argv, env, port, state_dir)
|
|
672
|
+
|
|
673
|
+
|
|
674
|
+
def _normalize_segments(
|
|
675
|
+
raw_segments: object,
|
|
676
|
+
text: str,
|
|
677
|
+
duration: float,
|
|
678
|
+
) -> list[dict[str, object]]:
|
|
679
|
+
segments: list[dict[str, object]] = []
|
|
680
|
+
if isinstance(raw_segments, list):
|
|
681
|
+
for seg in raw_segments:
|
|
682
|
+
if not isinstance(seg, dict):
|
|
683
|
+
continue
|
|
684
|
+
seg_text = str(seg.get("text") or "").strip()
|
|
685
|
+
if not seg_text:
|
|
686
|
+
continue
|
|
687
|
+
try:
|
|
688
|
+
start = round(float(seg.get("start", 0.0)), 3)
|
|
689
|
+
end = round(float(seg.get("end", duration)), 3)
|
|
690
|
+
except (TypeError, ValueError):
|
|
691
|
+
start, end = 0.0, round(duration, 3)
|
|
692
|
+
segments.append({"start": start, "end": end, "text": seg_text})
|
|
693
|
+
if not segments and text:
|
|
694
|
+
segments.append({"start": 0.0, "end": round(duration, 3), "text": text})
|
|
695
|
+
return segments
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
def _post_worker(
|
|
699
|
+
url: str,
|
|
700
|
+
body: bytes,
|
|
701
|
+
content_type: str,
|
|
702
|
+
worker: WorkerHandle,
|
|
703
|
+
) -> dict[str, Any]:
|
|
704
|
+
"""Send a ``Connection: close`` loopback POST to an engine child and parse its JSON reply."""
|
|
705
|
+
req = urllib.request.Request(
|
|
706
|
+
url,
|
|
707
|
+
data=body,
|
|
708
|
+
headers={"Content-Type": content_type, "Connection": "close"},
|
|
709
|
+
method="POST",
|
|
710
|
+
)
|
|
711
|
+
opener = http_local.no_proxy_opener(allow_redirects=False)
|
|
712
|
+
try:
|
|
713
|
+
with opener.open(req, timeout=WORKER_REQUEST_TIMEOUT_S) as resp:
|
|
714
|
+
raw = resp.read(16 << 20).decode("utf-8", "replace")
|
|
715
|
+
parsed = json.loads(raw)
|
|
716
|
+
if not isinstance(parsed, dict):
|
|
717
|
+
raise WorkerError("worker returned non-object JSON")
|
|
718
|
+
return parsed
|
|
719
|
+
except urllib.error.HTTPError as exc:
|
|
720
|
+
err_body = ""
|
|
721
|
+
with contextlib.suppress(OSError):
|
|
722
|
+
err_body = exc.read(4096).decode("utf-8", "replace")
|
|
723
|
+
detail = f"HTTP {exc.code}: {err_body} {worker.stderr_tail()}".strip()
|
|
724
|
+
raise WorkerError(f"worker HTTP {exc.code}", detail=detail) from None
|
|
725
|
+
except (urllib.error.URLError, OSError, http.client.HTTPException, ValueError) as exc:
|
|
726
|
+
detail = f"{exc} {worker.stderr_tail()}".strip()
|
|
727
|
+
raise WorkerError(f"worker request failed: {exc}", detail=detail) from None
|
|
728
|
+
|
|
729
|
+
|
|
730
|
+
def call_whisper_worker(
|
|
731
|
+
worker: WorkerHandle,
|
|
732
|
+
wav_data: bytes,
|
|
733
|
+
*,
|
|
734
|
+
language: str,
|
|
735
|
+
duration: float,
|
|
736
|
+
rms: float,
|
|
737
|
+
response_format: str,
|
|
738
|
+
) -> dict[str, object]:
|
|
739
|
+
"""Forward a WAV transcription to ``whisper-server`` with hallucination & zh prompt guards."""
|
|
740
|
+
fields: list[tuple[str, str]] = [
|
|
741
|
+
("response_format", "verbose_json"),
|
|
742
|
+
("language", language),
|
|
743
|
+
("temperature", "0.0"),
|
|
744
|
+
("no_speech_thold", "0.6"),
|
|
745
|
+
("entropy_thold", "2.4"),
|
|
746
|
+
("logprob_thold", "-1.0"),
|
|
747
|
+
("suppress_nst", "true"),
|
|
748
|
+
("max_context", "0"),
|
|
749
|
+
]
|
|
750
|
+
if (language == "zh" or language.startswith("zh-")) and rms >= SILENCE_RMS_THRESHOLD:
|
|
751
|
+
fields.append(("prompt", ZH_SIMPLIFIED_PROMPT))
|
|
752
|
+
body, content_type = build_multipart_body(fields, "audio.wav", wav_data)
|
|
753
|
+
url = f"http://127.0.0.1:{worker.port}/v1/audio/transcriptions"
|
|
754
|
+
parsed = _post_worker(url, body, content_type, worker)
|
|
755
|
+
text = str(parsed.get("text") or "").strip()
|
|
756
|
+
detected = normalize_whisper_language(str(parsed.get("language") or ""))
|
|
757
|
+
lang_out = detected or ("" if language == "auto" else language)
|
|
758
|
+
dur_raw = parsed.get("duration")
|
|
759
|
+
dur_out = round(float(dur_raw), 3) if isinstance(dur_raw, int | float) else round(duration, 3)
|
|
760
|
+
segments = _normalize_segments(parsed.get("segments"), text, dur_out)
|
|
761
|
+
_ = response_format
|
|
762
|
+
return {"text": text, "language": lang_out, "duration": dur_out, "segments": segments}
|
|
763
|
+
|
|
764
|
+
|
|
765
|
+
def call_sensevoice_worker(
|
|
766
|
+
worker: WorkerHandle,
|
|
767
|
+
wav_data: bytes,
|
|
768
|
+
*,
|
|
769
|
+
language: str,
|
|
770
|
+
duration: float,
|
|
771
|
+
) -> dict[str, object]:
|
|
772
|
+
"""Forward a WAV transcription to ``speech_worker_sensevoice.py``."""
|
|
773
|
+
qs = urllib.parse.urlencode({"language": language})
|
|
774
|
+
url = f"http://127.0.0.1:{worker.port}/transcribe?{qs}"
|
|
775
|
+
parsed = _post_worker(url, wav_data, "audio/wav", worker)
|
|
776
|
+
raw_text = str(parsed.get("text") or "")
|
|
777
|
+
raw_lang = str(parsed.get("language") or "")
|
|
778
|
+
text, detected = speech_worker_sensevoice.parse_sensevoice_output(raw_text, raw_lang=raw_lang)
|
|
779
|
+
lang_out = detected or ("" if language == "auto" else language)
|
|
780
|
+
dur_raw = parsed.get("duration")
|
|
781
|
+
dur_out = round(float(dur_raw), 3) if isinstance(dur_raw, int | float) else round(duration, 3)
|
|
782
|
+
segments = _normalize_segments(parsed.get("segments"), text, dur_out)
|
|
783
|
+
return {"text": text, "language": lang_out, "duration": dur_out, "segments": segments}
|