@simplexai/localmodels-win32-x64 0.1.0-dev.102 → 0.1.0-dev.104
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/LICENSE +201 -0
- package/NOTICE +126 -0
- package/README.md +10 -0
- package/bootstrap.identity +1 -1
- package/bootstrap.sha256 +139 -121
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +3 -1
- package/modules/localmodels/catalog.json +435 -127
- package/modules/localmodels/catalog.py +7 -3
- package/modules/localmodels/catalog_recipes.py +3 -3
- package/modules/localmodels/cli_parser.py +7 -3
- package/modules/localmodels/component.py +1 -1
- package/modules/localmodels/console.py +1 -1
- package/modules/localmodels/context_policy.py +6 -5
- package/modules/localmodels/debug_cli.py +0 -12
- package/modules/localmodels/debug_mode.py +0 -6
- package/modules/localmodels/debug_stub_server.py +280 -7
- package/modules/localmodels/decode_calibration.json +3 -4
- package/modules/localmodels/decode_calibration.py +5 -2
- package/modules/localmodels/deployment_lifecycle.py +1 -1
- package/modules/localmodels/download-mirrors.json +77 -1
- package/modules/localmodels/engine_adapters/base.py +11 -1
- package/modules/localmodels/engine_adapters/strata_poly.py +65 -3
- package/modules/localmodels/engine_adapters/suite_plan.py +57 -20
- package/modules/localmodels/engines-b11583.json +6 -26
- package/modules/localmodels/engines-b12588-mix-c0c3de8.json +3 -15
- package/modules/localmodels/engines-b12757-mix-ef2df21.json +3 -15
- package/modules/localmodels/engines-prism-b12178-03ec600.json +3 -15
- package/modules/localmodels/engines-speechcpp-v0.11.3.json +68 -0
- package/modules/localmodels/engines-strata-0.1.47.json +1 -5
- package/modules/localmodels/engines-strata-0.1.49.2.json +1 -5
- package/modules/localmodels/engines-strata-0.1.59.1.json +1 -5
- package/modules/localmodels/engines-strata-poly-0.2.20-poly.1.json +6 -30
- package/modules/localmodels/engines-strata-poly-0.2.20-poly.9.json +129 -0
- package/modules/localmodels/engines-whisper-b5454.json +6 -30
- package/modules/localmodels/engines.json +13 -61
- package/modules/localmodels/estimator.py +10 -5
- package/modules/localmodels/gpu_specs.py +1 -1
- package/modules/localmodels/hosts.py +12 -16
- package/modules/localmodels/kokoro-tts-0.6.1.txt +1 -1
- package/modules/localmodels/library_elastic.py +135 -6
- package/modules/localmodels/library_kept.py +9 -1
- package/modules/localmodels/library_model.py +28 -1
- package/modules/localmodels/library_poly.py +109 -11
- package/modules/localmodels/library_pricing.py +12 -3
- package/modules/localmodels/library_serve.py +162 -75
- package/modules/localmodels/library_smoke.py +63 -5
- package/modules/localmodels/library_state.py +3 -2
- package/modules/localmodels/library_status.py +8 -1
- package/modules/localmodels/llm_rank.py +13 -8
- package/modules/localmodels/metal.py +1 -2
- package/modules/localmodels/plan_envelope.py +29 -11
- package/modules/localmodels/planning/budget.py +14 -12
- package/modules/localmodels/planning/memory_pools.py +7 -1
- package/modules/localmodels/privacy_acceptance.py +6 -5
- package/modules/localmodels/py.typed +0 -0
- package/modules/localmodels/quant_formats.py +1 -1
- package/modules/localmodels/recommend_cli.py +1 -1
- package/modules/localmodels/remote_ops_common.py +12 -2
- package/modules/localmodels/remote_ops_launchd.py +8 -1
- package/modules/localmodels/runtime_process.py +1 -1
- package/modules/localmodels/service_deployment.py +2 -4
- package/modules/localmodels/service_probe.py +59 -13
- package/modules/localmodels/setup_inspection.py +72 -70
- package/modules/localmodels/setup_text.py +7 -56
- package/modules/localmodels/sidecar_downloads.py +460 -0
- package/modules/localmodels/sidecar_http.py +452 -0
- package/modules/localmodels/sidecar_state.py +516 -0
- package/modules/localmodels/speech_admission.py +33 -4
- package/modules/localmodels/speech_catalog.py +23 -0
- package/modules/localmodels/speech_cli.py +10 -2
- package/modules/localmodels/speech_jobs.py +120 -384
- package/modules/localmodels/speech_server.py +187 -77
- package/modules/localmodels/speech_state.py +90 -454
- package/modules/localmodels/speech_workers.py +51 -162
- package/modules/localmodels/stack.py +18 -0
- package/modules/localmodels/stack_args.py +6 -6
- package/modules/localmodels/stack_auto.py +1 -1
- package/modules/localmodels/stack_aux_gpu.py +1 -1
- package/modules/localmodels/stack_cleanup.py +21 -18
- package/modules/localmodels/stack_cli.py +6 -2
- package/modules/localmodels/stack_compose.py +11 -4
- package/modules/localmodels/stack_debug.py +1 -2
- package/modules/localmodels/stack_decision.py +4 -4
- package/modules/localmodels/stack_doctor.py +2 -2
- package/modules/localmodels/stack_down.py +19 -14
- package/modules/localmodels/stack_events.py +1 -1
- package/modules/localmodels/stack_gpu_memory.py +1 -1
- package/modules/localmodels/stack_hardware.py +3 -3
- package/modules/localmodels/stack_mcp.py +1 -2
- package/modules/localmodels/stack_picks.py +1 -1
- package/modules/localmodels/stack_plan.py +9 -9
- package/modules/localmodels/stack_ports.py +32 -4
- package/modules/localmodels/stack_rollback.py +1 -1
- package/modules/localmodels/stack_run.py +1 -1
- package/modules/localmodels/stack_suite.py +61 -12
- package/modules/localmodels/stack_up.py +51 -1
- package/modules/localmodels/stack_view_agent.py +1 -1
- package/modules/localmodels/stack_view_serve.py +0 -2
- package/modules/localmodels/stack_view_words.py +2 -2
- package/modules/localmodels/stack_warm.py +2 -2
- package/modules/localmodels/stack_whatif.py +524 -41
- package/modules/localmodels/stack_whatif_html.py +903 -0
- package/modules/localmodels/startlux-decide-83fe6c7d.txt +2 -2
- package/modules/localmodels/{strata-poly-serve-0.2.20-poly.7.txt → strata-poly-serve-0.2.20-poly.9.txt} +1 -1
- package/modules/localmodels/strata_poly_server.py +251 -3
- package/modules/localmodels/suite.py +137 -5
- package/modules/localmodels/tts-moss.txt +321 -0
- package/modules/localmodels/tts_admission.py +381 -0
- package/modules/localmodels/tts_backend_speechcpp.py +487 -0
- package/modules/localmodels/tts_catalog.py +279 -0
- package/modules/localmodels/tts_cli.py +352 -0
- package/modules/localmodels/tts_http.py +623 -0
- package/modules/localmodels/tts_jobs.py +526 -0
- package/modules/localmodels/tts_model.py +591 -0
- package/modules/localmodels/tts_moss_presets.json +1 -0
- package/modules/localmodels/tts_serve.py +451 -0
- package/modules/localmodels/tts_server.py +1 -1
- package/modules/localmodels/tts_sidecar.py +788 -0
- package/modules/localmodels/tts_state.py +400 -0
- package/modules/localmodels/tts_worker_kokoro.py +463 -0
- package/modules/localmodels/tts_worker_moss.py +748 -0
- package/modules/localmodels/tts_workers.py +696 -0
- package/modules/localmodels/vision.py +5 -3
- package/modules/localmodels/web/view/ASSET-SOURCES.md +4 -7
- package/modules/localmodels/web/view/view.css +0 -1
- package/modules/localmodels/web/view/view.js +2 -5
- package/modules/localmodels/web/whatif/app.js +730 -0
- package/modules/localmodels/web/whatif/page.html +1172 -0
- package/modules/localmodels/web/whatif/sim.js +303 -0
- package/modules/localmodels/windows_job.py +179 -11
- package/modules/simplex_localmodels-0.1.0.dev104.dist-info/METADATA +14 -0
- package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev104.dist-info}/RECORD +132 -109
- package/modules/simplex_localmodels-0.1.0.dev104.dist-info/licenses/LICENSE +201 -0
- package/modules/simplex_localmodels-0.1.0.dev104.dist-info/licenses/NOTICE +126 -0
- package/package.json +11 -2
- package/tool.json +1 -1
- package/modules/localmodels/engines-strata-poly-0.2.20-poly.7.json +0 -94
- package/modules/localmodels/fixtures/stack-research-demo-plan.json +0 -1059
- package/modules/localmodels/stack_research.py +0 -716
- package/modules/localmodels/stack_research_demo.py +0 -125
- package/modules/localmodels/stack_research_plan.py +0 -146
- package/modules/localmodels/web/index.html +0 -2605
- package/modules/localmodels/web/sizecalc/app.js +0 -1306
- package/modules/localmodels/web/sizecalc/calc.js +0 -269
- package/modules/localmodels/web/sizecalc/page.html +0 -520
- package/modules/localmodels/web/view/logo-claude.svg +0 -3
- package/modules/localmodels/web/view/logo-codex.png +0 -0
- package/modules/simplex_localmodels-0.1.0.dev102.dist-info/METADATA +0 -9
- package/modules/simplex_localmodels-0.1.0.dev102.dist-info/licenses/NOTICE +0 -68
- /package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev104.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev104.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev104.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
"""Pluggable ``speech.cpp`` v0.11.3 backend for Qwen3-TTS CustomVoice models (Layer 5).
|
|
2
|
+
|
|
3
|
+
Supervises pinned ``speech serve`` on loopback, enforces the 9 official preset speakers (zero
|
|
4
|
+
cloning), streams PCM/WAV, and normalizes ZH/EN numbers. Never logs text, instructions, or audio.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import contextlib
|
|
10
|
+
import http.client
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import sys
|
|
15
|
+
from collections.abc import Iterator
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import TYPE_CHECKING, Any
|
|
18
|
+
|
|
19
|
+
from localmodels import (
|
|
20
|
+
app,
|
|
21
|
+
debug_mode,
|
|
22
|
+
engines,
|
|
23
|
+
hosts,
|
|
24
|
+
plan_envelope,
|
|
25
|
+
sidecar_downloads,
|
|
26
|
+
sidecar_http,
|
|
27
|
+
speech_admission,
|
|
28
|
+
tts_catalog,
|
|
29
|
+
tts_model,
|
|
30
|
+
tts_state,
|
|
31
|
+
)
|
|
32
|
+
from localmodels.probe import HostFacts
|
|
33
|
+
from localmodels.records import ReleaseEngine
|
|
34
|
+
from localmodels.sidecar_http import SidecarWorkerError, wrap_pcm16_wav
|
|
35
|
+
from localmodels.tts_admission import TtsDeviceDecision
|
|
36
|
+
from localmodels.tts_catalog import TtsEngine, TtsModelSpec
|
|
37
|
+
from localmodels.tts_model import TtsError, TtsSynthRequest, TtsSynthResult, TtsVoiceInfo
|
|
38
|
+
|
|
39
|
+
if TYPE_CHECKING:
|
|
40
|
+
from localmodels.tts_workers import TtsWorkerHandle
|
|
41
|
+
|
|
42
|
+
SPEECHCPP_REQUEST_TIMEOUT_S = 180.0
|
|
43
|
+
SPEECHCPP_STREAM_READ_BYTES = 4096
|
|
44
|
+
SPEECHCPP_MAX_CPU_THREADS = 4
|
|
45
|
+
|
|
46
|
+
_VOICE_BY_ID: dict[str, TtsVoiceInfo] = {
|
|
47
|
+
item["id"]: item for item in tts_model.QWEN3_CUSTOMVOICE_VOICES
|
|
48
|
+
}
|
|
49
|
+
_VOICE_IDS: tuple[str, ...] = tuple(_VOICE_BY_ID)
|
|
50
|
+
_INSTRUCTIONS_MODEL_IDS: frozenset[str] = frozenset(("qwen3-tts-1.7b-customvoice",))
|
|
51
|
+
|
|
52
|
+
# Pure-ASCII Unicode escapes keep source English-only for tests/test_stack_english.py.
|
|
53
|
+
_CJK_IDEOGRAPH_RE = re.compile(r"[\u4e00-\u9fff]")
|
|
54
|
+
_KANA_OR_HANGUL_RE = re.compile(r"[\u3040-\u30ff\uac00-\ud7af]")
|
|
55
|
+
_ZH_DIGITS = "\u96f6\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d"
|
|
56
|
+
_ZH_TEN, _ZH_HUNDRED, _ZH_THOUSAND = "\u5341", "\u767e", "\u5343"
|
|
57
|
+
_ZH_WAN, _ZH_YI, _ZH_DOT, _ZH_MINUS = "\u4e07", "\u4ebf", "\u70b9", "\u8d1f"
|
|
58
|
+
_ZH_PERCENT, _ZH_YEAR = "\u767e\u5206\u4e4b", "\u5e74"
|
|
59
|
+
|
|
60
|
+
_URL_SPAN_RE = re.compile(
|
|
61
|
+
r"(https?://[^\s\u3000\uff0c\u3002\uff01\uff1f\uff1b\u3001\uff09\u3011\u300b\u3009\u300d\u300f]+)"
|
|
62
|
+
)
|
|
63
|
+
_NUMBER_TOKEN_RE = re.compile(
|
|
64
|
+
r"(?<![A-Za-z0-9._/:=-])(-?)(\d{1,3}(?:,\d{3})+|\d+)(?:\.(\d+))?"
|
|
65
|
+
r"(?:(%|" + _ZH_YEAR + r")|(?![A-Za-z0-9_/-]|\.\d))"
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _digits_to_zh(digits: str) -> str:
|
|
70
|
+
return "".join(_ZH_DIGITS[int(ch)] for ch in digits)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _under_10000_to_zh(value: int, *, omit_leading_one_ten: bool) -> str:
|
|
74
|
+
if value <= 0:
|
|
75
|
+
return _ZH_DIGITS[0]
|
|
76
|
+
parts: list[str] = []
|
|
77
|
+
zero_pending = False
|
|
78
|
+
rem = value
|
|
79
|
+
for divisor, label in ((1000, _ZH_THOUSAND), (100, _ZH_HUNDRED), (10, _ZH_TEN), (1, "")):
|
|
80
|
+
digit, rem = divmod(rem, divisor)
|
|
81
|
+
if digit == 0:
|
|
82
|
+
if parts:
|
|
83
|
+
zero_pending = True
|
|
84
|
+
continue
|
|
85
|
+
if zero_pending:
|
|
86
|
+
parts.append(_ZH_DIGITS[0])
|
|
87
|
+
zero_pending = False
|
|
88
|
+
if divisor == 10 and digit == 1 and not parts and omit_leading_one_ten:
|
|
89
|
+
parts.append(_ZH_TEN)
|
|
90
|
+
else:
|
|
91
|
+
parts.append(_ZH_DIGITS[digit] + label)
|
|
92
|
+
return "".join(parts)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _int_to_zh(value: int) -> str:
|
|
96
|
+
if value == 0:
|
|
97
|
+
return _ZH_DIGITS[0]
|
|
98
|
+
if value >= 1_000_000_000_000:
|
|
99
|
+
return _digits_to_zh(str(value))
|
|
100
|
+
yi, rem_yi = divmod(value, 100_000_000)
|
|
101
|
+
wan, rem = divmod(rem_yi, 10_000)
|
|
102
|
+
parts: list[str] = []
|
|
103
|
+
if yi:
|
|
104
|
+
parts.append(_under_10000_to_zh(yi, omit_leading_one_ten=True) + _ZH_YI)
|
|
105
|
+
if wan:
|
|
106
|
+
if yi and wan < 1000:
|
|
107
|
+
parts.append(_ZH_DIGITS[0])
|
|
108
|
+
parts.append(_under_10000_to_zh(wan, omit_leading_one_ten=not yi) + _ZH_WAN)
|
|
109
|
+
if rem:
|
|
110
|
+
if (yi or wan) and rem < 1000:
|
|
111
|
+
parts.append(_ZH_DIGITS[0])
|
|
112
|
+
parts.append(_under_10000_to_zh(rem, omit_leading_one_ten=not (yi or wan)))
|
|
113
|
+
return "".join(parts)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _replace_zh_number(match: re.Match[str]) -> str:
|
|
117
|
+
sign, raw_int, raw_frac, suffix = match.groups()
|
|
118
|
+
digits = raw_int.replace(",", "")
|
|
119
|
+
if suffix == _ZH_YEAR and not sign and raw_frac is None and len(digits) == 4:
|
|
120
|
+
return _digits_to_zh(digits) + _ZH_YEAR
|
|
121
|
+
if (
|
|
122
|
+
(len(digits) > 1 and digits.startswith("0"))
|
|
123
|
+
or len(digits) > 12
|
|
124
|
+
or ("," not in raw_int and len(digits) > 10)
|
|
125
|
+
):
|
|
126
|
+
spoken = _digits_to_zh(digits)
|
|
127
|
+
else:
|
|
128
|
+
spoken = _int_to_zh(int(digits))
|
|
129
|
+
if raw_frac is not None:
|
|
130
|
+
spoken = f"{spoken}{_ZH_DOT}{_digits_to_zh(raw_frac)}"
|
|
131
|
+
if suffix == "%":
|
|
132
|
+
spoken = _ZH_PERCENT + spoken
|
|
133
|
+
return _ZH_MINUS + spoken if sign else spoken
|
|
134
|
+
if sign:
|
|
135
|
+
spoken = _ZH_MINUS + spoken
|
|
136
|
+
return spoken + (suffix or "")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def normalize_qwen3_text(text: str, *, language: str | None = None) -> str:
|
|
140
|
+
"""Convert standalone Arabic numbers to Chinese spoken form in Chinese/mixed ZH+EN text.
|
|
141
|
+
|
|
142
|
+
Leaves explicit non-Chinese languages, pure English, Japanese/Korean, URLs, ports/query
|
|
143
|
+
parameters, and identifiers such as ``Qwen3``, ``0.6B``, ``v0.11.3``, and ``2026-12-01``
|
|
144
|
+
untouched.
|
|
145
|
+
"""
|
|
146
|
+
if language and language.lower() != "auto" and not language.lower().startswith("zh"):
|
|
147
|
+
return text
|
|
148
|
+
if not _CJK_IDEOGRAPH_RE.search(text) or _KANA_OR_HANGUL_RE.search(text):
|
|
149
|
+
return text
|
|
150
|
+
parts = _URL_SPAN_RE.split(text)
|
|
151
|
+
return "".join(
|
|
152
|
+
part if idx % 2 else _NUMBER_TOKEN_RE.sub(_replace_zh_number, part)
|
|
153
|
+
for idx, part in enumerate(parts)
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def validate_qwen3_voice(voice: str) -> str:
|
|
158
|
+
"""Validate and canonicalize one of the 9 official CustomVoice preset speaker IDs."""
|
|
159
|
+
cleaned = voice.strip().lower()
|
|
160
|
+
if cleaned in _VOICE_BY_ID:
|
|
161
|
+
return cleaned
|
|
162
|
+
raise TtsError(
|
|
163
|
+
"VOICE_UNKNOWN",
|
|
164
|
+
f"unknown Qwen3-TTS voice {voice!r}; expected one of {', '.join(_VOICE_IDS)}",
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _host_has_discrete_gpu(host: HostFacts) -> bool:
|
|
169
|
+
if any(
|
|
170
|
+
g.get("vendor") == "nvidia" and g.get("mig_mode") != "enabled"
|
|
171
|
+
for g in (host.get("gpus") or [])
|
|
172
|
+
):
|
|
173
|
+
return True
|
|
174
|
+
return host.get("gpu_vendor_class") in ("nvidia", "amd", "intel")
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _candidate_backends(host: HostFacts, *, include_gpu: bool, is_sim: bool) -> list[str]:
|
|
178
|
+
plat = host.get("platform", "")
|
|
179
|
+
if plat == "darwin":
|
|
180
|
+
return ["metal"] if host.get("arch") == "arm64" else []
|
|
181
|
+
vulkan_ok = is_sim or speech_admission.vulkan_loader_available(host)
|
|
182
|
+
if plat == "win32":
|
|
183
|
+
return ["vulkan"] if vulkan_ok else []
|
|
184
|
+
if plat.startswith("linux"):
|
|
185
|
+
return (
|
|
186
|
+
["vulkan", "cpu"]
|
|
187
|
+
if (include_gpu and _host_has_discrete_gpu(host) and vulkan_ok)
|
|
188
|
+
else ["cpu"]
|
|
189
|
+
)
|
|
190
|
+
return []
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def resolve_speechcpp_engine(
|
|
194
|
+
spec: TtsModelSpec,
|
|
195
|
+
base_dir: str,
|
|
196
|
+
*,
|
|
197
|
+
include_gpu: bool,
|
|
198
|
+
facts: HostFacts | None = None,
|
|
199
|
+
) -> ReleaseEngine | None:
|
|
200
|
+
"""Resolve the pinned ``speech.cpp`` release build for this host."""
|
|
201
|
+
if spec.engine != "speech.cpp" or not spec.engine_tag:
|
|
202
|
+
return None
|
|
203
|
+
lock_path = engines.engine_lock_path(spec.engine_tag)
|
|
204
|
+
if not lock_path.is_file():
|
|
205
|
+
return None
|
|
206
|
+
host = app.probe(hosts.LOCAL_ID) if facts is None else facts
|
|
207
|
+
is_sim = debug_mode.current().mode == "simulate"
|
|
208
|
+
for backend in _candidate_backends(host, include_gpu=include_gpu, is_sim=is_sim):
|
|
209
|
+
try:
|
|
210
|
+
build = engines.select_engine_build(host, backend, lock_path)
|
|
211
|
+
except (engines.CudaDriverError, engines.EngineUnavailableError, plan_envelope.PlanError):
|
|
212
|
+
continue
|
|
213
|
+
return engines.release_engine(build, base_dir)
|
|
214
|
+
print(
|
|
215
|
+
f"localmodels tts: no prebuilt {spec.engine_tag} binary for "
|
|
216
|
+
f"{host.get('platform', '')}/{host.get('arch')}; downloading weights only",
|
|
217
|
+
file=sys.stderr,
|
|
218
|
+
)
|
|
219
|
+
return None
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _allowed_backends_for_device(effective_device: str, platform_name: str) -> tuple[str, ...]:
|
|
223
|
+
if effective_device in ("metal", "vulkan"):
|
|
224
|
+
return (effective_device,)
|
|
225
|
+
return (
|
|
226
|
+
("metal", "cpu")
|
|
227
|
+
if platform_name == "darwin"
|
|
228
|
+
else (("vulkan", "cpu") if platform_name == "win32" else ("cpu", "vulkan"))
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def resolve_speechcpp_binary(
|
|
233
|
+
spec: TtsModelSpec,
|
|
234
|
+
decision: TtsDeviceDecision,
|
|
235
|
+
base_dir: str,
|
|
236
|
+
state_dir: Path | None,
|
|
237
|
+
*,
|
|
238
|
+
platform_name: str | None = None,
|
|
239
|
+
) -> Path:
|
|
240
|
+
"""Locate the installed ``speech`` executable compatible with ``decision``."""
|
|
241
|
+
plat = sys.platform if platform_name is None else platform_name
|
|
242
|
+
binary_name = "speech.exe" if plat == "win32" else "speech"
|
|
243
|
+
allowed = _allowed_backends_for_device(decision.effective_device, plat)
|
|
244
|
+
|
|
245
|
+
rec = tts_state.load_record(spec.id, state_dir)
|
|
246
|
+
if rec is not None and (eng_dir := rec.get("engine_dir")):
|
|
247
|
+
if decision.effective_device == "cpu" or rec.get("engine_backend") in allowed:
|
|
248
|
+
candidate = (Path(os.path.expanduser(eng_dir)).resolve()) / binary_name
|
|
249
|
+
if candidate.is_file():
|
|
250
|
+
return candidate
|
|
251
|
+
|
|
252
|
+
if spec.engine_tag:
|
|
253
|
+
engines_root = Path(os.path.expanduser(base_dir)).resolve() / "engines"
|
|
254
|
+
for backend in allowed:
|
|
255
|
+
candidate = engines_root / f"{spec.engine_tag}-{backend}" / binary_name
|
|
256
|
+
if candidate.is_file():
|
|
257
|
+
return candidate
|
|
258
|
+
|
|
259
|
+
if decision.effective_device == "vulkan" and plat.startswith("linux"):
|
|
260
|
+
hint = f"run `localmodels tts download {spec.id} --include-gpu-engine`"
|
|
261
|
+
elif plat == "win32":
|
|
262
|
+
hint = f"install a Vulkan loader and run `localmodels tts download {spec.id}`"
|
|
263
|
+
else:
|
|
264
|
+
hint = f"run `localmodels tts download {spec.id}`"
|
|
265
|
+
raise SidecarWorkerError(
|
|
266
|
+
f"speech.cpp binary not found for {spec.id} ({decision.effective_device}); {hint}"
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def speechcpp_device_arg(decision: TtsDeviceDecision) -> str:
|
|
271
|
+
"""Map ``TtsDeviceDecision`` to a ``speech serve --device`` argument."""
|
|
272
|
+
if decision.effective_device == "cpu":
|
|
273
|
+
return "cpu"
|
|
274
|
+
if decision.effective_device == "vulkan" and decision.gpu_index is not None:
|
|
275
|
+
return f"Vulkan{decision.gpu_index}"
|
|
276
|
+
return "gpu"
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def speechcpp_env(
|
|
280
|
+
binary: Path,
|
|
281
|
+
threads: int,
|
|
282
|
+
*,
|
|
283
|
+
base_env: dict[str, str] | None = None,
|
|
284
|
+
platform_name: str | None = None,
|
|
285
|
+
) -> dict[str, str]:
|
|
286
|
+
"""Build cross-platform library search path and thread-cap env for ``speech serve``."""
|
|
287
|
+
plat = sys.platform if platform_name is None else platform_name
|
|
288
|
+
env = dict(os.environ if base_env is None else base_env)
|
|
289
|
+
bin_dir = str(binary.parent)
|
|
290
|
+
var, sep = (
|
|
291
|
+
("DYLD_LIBRARY_PATH", ":")
|
|
292
|
+
if plat == "darwin"
|
|
293
|
+
else (("PATH", ";") if plat == "win32" else ("LD_LIBRARY_PATH", ":"))
|
|
294
|
+
)
|
|
295
|
+
cur = env.get(var, "")
|
|
296
|
+
env[var] = f"{bin_dir}{sep}{cur}" if cur else bin_dir
|
|
297
|
+
cap = str(max(1, threads))
|
|
298
|
+
env["OMP_NUM_THREADS"] = env["OPENBLAS_NUM_THREADS"] = env["MKL_NUM_THREADS"] = cap
|
|
299
|
+
return env
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _supports_instructions(model_id: str) -> bool:
|
|
303
|
+
try:
|
|
304
|
+
return tts_catalog.tts_model(model_id).supports_instructions
|
|
305
|
+
except KeyError:
|
|
306
|
+
return model_id in _INSTRUCTIONS_MODEL_IDS
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _build_speech_payload(worker: TtsWorkerHandle, req: TtsSynthRequest) -> tuple[bytes, str]:
|
|
310
|
+
canonical_voice = validate_qwen3_voice(req.voice)
|
|
311
|
+
payload: dict[str, object] = {
|
|
312
|
+
"input": normalize_qwen3_text(req.text, language=req.language),
|
|
313
|
+
"voice": canonical_voice,
|
|
314
|
+
"response_format": "pcm",
|
|
315
|
+
}
|
|
316
|
+
if req.instructions and _supports_instructions(worker.model_id):
|
|
317
|
+
payload["instructions"] = req.instructions
|
|
318
|
+
if req.language and req.language != "auto":
|
|
319
|
+
payload["language"] = req.language
|
|
320
|
+
return json.dumps(payload, ensure_ascii=False).encode("utf-8"), canonical_voice
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _error_detail_from_body(raw: bytes) -> str:
|
|
324
|
+
text = raw[:500].decode("utf-8", errors="replace").strip()
|
|
325
|
+
if not text:
|
|
326
|
+
return ""
|
|
327
|
+
with contextlib.suppress(ValueError):
|
|
328
|
+
parsed = json.loads(text)
|
|
329
|
+
err = parsed.get("error") if isinstance(parsed, dict) else None
|
|
330
|
+
msg = err.get("message") if isinstance(err, dict) else None
|
|
331
|
+
if isinstance(msg, str):
|
|
332
|
+
return msg[:500]
|
|
333
|
+
return text
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _extract_raw_model_voices(parsed: dict[str, Any] | None) -> list[object]:
|
|
337
|
+
if not isinstance(parsed, dict) or not isinstance(parsed.get("data"), list):
|
|
338
|
+
raise SidecarWorkerError("speech.cpp worker did not return a valid /v1/models payload")
|
|
339
|
+
for item in parsed["data"]:
|
|
340
|
+
speech_meta = item.get("speech") if isinstance(item, dict) else None
|
|
341
|
+
voices = speech_meta.get("voices") if isinstance(speech_meta, dict) else None
|
|
342
|
+
if isinstance(voices, list):
|
|
343
|
+
return voices
|
|
344
|
+
return []
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _normalize_voice_language(raw_lang: object, fallback: str) -> str:
|
|
348
|
+
if not isinstance(raw_lang, str) or not raw_lang.strip():
|
|
349
|
+
return fallback
|
|
350
|
+
try:
|
|
351
|
+
return tts_model.validate_language(raw_lang)
|
|
352
|
+
except TtsError:
|
|
353
|
+
return fallback
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _parse_models_voices(parsed: dict[str, Any] | None) -> list[TtsVoiceInfo]:
|
|
357
|
+
by_id: dict[str, TtsVoiceInfo] = {}
|
|
358
|
+
for entry in _extract_raw_model_voices(parsed):
|
|
359
|
+
if not isinstance(entry, dict):
|
|
360
|
+
continue
|
|
361
|
+
vid = str(entry.get("name") or entry.get("id") or "").strip().lower()
|
|
362
|
+
base = _VOICE_BY_ID.get(vid)
|
|
363
|
+
if base is None:
|
|
364
|
+
continue
|
|
365
|
+
raw_gender = entry.get("gender")
|
|
366
|
+
gender = (
|
|
367
|
+
raw_gender.strip()
|
|
368
|
+
if isinstance(raw_gender, str) and raw_gender.strip()
|
|
369
|
+
else base["gender"]
|
|
370
|
+
)
|
|
371
|
+
by_id[vid] = {
|
|
372
|
+
"id": vid,
|
|
373
|
+
"name": base["name"],
|
|
374
|
+
"language": _normalize_voice_language(entry.get("language"), base["language"]),
|
|
375
|
+
"gender": gender,
|
|
376
|
+
}
|
|
377
|
+
if not by_id:
|
|
378
|
+
return tts_model.qwen3_voice_list()
|
|
379
|
+
return [by_id[vid] for vid in _VOICE_IDS if vid in by_id]
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _stream_speech_pcm(port: int, raw_body: bytes, rate: int) -> Iterator[tuple[bytes, int]]:
|
|
383
|
+
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=SPEECHCPP_REQUEST_TIMEOUT_S)
|
|
384
|
+
try:
|
|
385
|
+
conn.request(
|
|
386
|
+
"POST",
|
|
387
|
+
"/v1/audio/speech",
|
|
388
|
+
body=raw_body,
|
|
389
|
+
headers={"Content-Type": "application/json", "Connection": "close"},
|
|
390
|
+
)
|
|
391
|
+
resp = conn.getresponse()
|
|
392
|
+
if not (200 <= resp.status < 300):
|
|
393
|
+
detail = _error_detail_from_body(resp.read(2048))
|
|
394
|
+
if 400 <= resp.status < 500:
|
|
395
|
+
msg = detail or f"invalid synthesis request (HTTP {resp.status})"
|
|
396
|
+
raise TtsError("VOICE_UNKNOWN" if "voice" in msg.lower() else "INVALID_INPUT", msg)
|
|
397
|
+
raise SidecarWorkerError(
|
|
398
|
+
f"speech.cpp worker returned HTTP {resp.status}", detail=detail
|
|
399
|
+
)
|
|
400
|
+
carry = b""
|
|
401
|
+
read_fn = getattr(resp, "read1", resp.read)
|
|
402
|
+
while chunk := read_fn(SPEECHCPP_STREAM_READ_BYTES):
|
|
403
|
+
buf = carry + chunk
|
|
404
|
+
carry, out = (buf[-1:], buf[:-1]) if len(buf) % 2 else (b"", buf)
|
|
405
|
+
if out:
|
|
406
|
+
yield out, rate
|
|
407
|
+
except (http.client.HTTPException, OSError, ValueError) as exc:
|
|
408
|
+
raise SidecarWorkerError(
|
|
409
|
+
f"speech.cpp worker request failed: {exc}", detail=str(exc)
|
|
410
|
+
) from None
|
|
411
|
+
finally:
|
|
412
|
+
conn.close()
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
class SpeechCppBackend:
|
|
416
|
+
"""``TtsBackend`` implementation for Qwen3-TTS CustomVoice via ``speech.cpp`` v0.11.3."""
|
|
417
|
+
|
|
418
|
+
runtime: TtsEngine = "speech.cpp"
|
|
419
|
+
|
|
420
|
+
def resolve_engine(
|
|
421
|
+
self,
|
|
422
|
+
spec: TtsModelSpec,
|
|
423
|
+
base_dir: str,
|
|
424
|
+
*,
|
|
425
|
+
include_gpu: bool,
|
|
426
|
+
facts: HostFacts | None,
|
|
427
|
+
) -> ReleaseEngine | None:
|
|
428
|
+
return resolve_speechcpp_engine(spec, base_dir, include_gpu=include_gpu, facts=facts)
|
|
429
|
+
|
|
430
|
+
def build_launch(
|
|
431
|
+
self,
|
|
432
|
+
spec: TtsModelSpec,
|
|
433
|
+
decision: TtsDeviceDecision,
|
|
434
|
+
base_dir: str,
|
|
435
|
+
state_dir: Path | None,
|
|
436
|
+
port: int,
|
|
437
|
+
) -> tuple[list[str], dict[str, str]]:
|
|
438
|
+
binary = resolve_speechcpp_binary(spec, decision, base_dir, state_dir)
|
|
439
|
+
model_path = str(
|
|
440
|
+
sidecar_downloads.model_file_dest(base_dir, "tts", spec.id, spec.files[0].path)
|
|
441
|
+
)
|
|
442
|
+
num_threads = min(SPEECHCPP_MAX_CPU_THREADS, max(1, os.cpu_count() or 1))
|
|
443
|
+
argv = [
|
|
444
|
+
str(binary),
|
|
445
|
+
"serve",
|
|
446
|
+
model_path,
|
|
447
|
+
"--host",
|
|
448
|
+
"127.0.0.1",
|
|
449
|
+
"--port",
|
|
450
|
+
str(port),
|
|
451
|
+
"--device",
|
|
452
|
+
speechcpp_device_arg(decision),
|
|
453
|
+
"--threads",
|
|
454
|
+
str(num_threads),
|
|
455
|
+
"--no-warmup",
|
|
456
|
+
]
|
|
457
|
+
return argv, speechcpp_env(binary, num_threads)
|
|
458
|
+
|
|
459
|
+
def synthesize(self, worker: TtsWorkerHandle, req: TtsSynthRequest) -> TtsSynthResult:
|
|
460
|
+
raw_body, voice = _build_speech_payload(worker, req)
|
|
461
|
+
rate = worker.sample_rate or 24000
|
|
462
|
+
pcm_bytes = b"".join(chunk for chunk, _r in _stream_speech_pcm(worker.port, raw_body, rate))
|
|
463
|
+
duration = len(pcm_bytes) / float(2 * max(1, rate))
|
|
464
|
+
audio, ctype = (
|
|
465
|
+
(wrap_pcm16_wav(pcm_bytes, rate), "audio/wav")
|
|
466
|
+
if req.response_format == "wav"
|
|
467
|
+
else (pcm_bytes, "audio/pcm")
|
|
468
|
+
)
|
|
469
|
+
return TtsSynthResult(
|
|
470
|
+
audio_bytes=audio,
|
|
471
|
+
content_type=ctype,
|
|
472
|
+
sample_rate=rate,
|
|
473
|
+
duration_seconds=round(duration, 3),
|
|
474
|
+
voice=voice,
|
|
475
|
+
)
|
|
476
|
+
|
|
477
|
+
def synthesize_stream(
|
|
478
|
+
self, worker: TtsWorkerHandle, req: TtsSynthRequest
|
|
479
|
+
) -> Iterator[tuple[bytes, int]]:
|
|
480
|
+
raw_body, _voice = _build_speech_payload(worker, req)
|
|
481
|
+
return _stream_speech_pcm(worker.port, raw_body, worker.sample_rate or 24000)
|
|
482
|
+
|
|
483
|
+
def list_voices(self, worker: TtsWorkerHandle) -> list[TtsVoiceInfo]:
|
|
484
|
+
parsed = sidecar_http.sidecar_request(
|
|
485
|
+
f"http://127.0.0.1:{worker.port}", "/v1/models", timeout=5.0
|
|
486
|
+
)
|
|
487
|
+
return _parse_models_voices(parsed)
|