@simplexai/localmodels-linux-arm64 0.1.0-dev.102 → 0.1.0-dev.103

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +46 -27
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +3 -1
  5. package/modules/localmodels/catalog.json +306 -1
  6. package/modules/localmodels/cli_parser.py +4 -0
  7. package/modules/localmodels/debug_stub_server.py +280 -7
  8. package/modules/localmodels/download-mirrors.json +76 -0
  9. package/modules/localmodels/engines-speechcpp-v0.11.3.json +84 -0
  10. package/modules/localmodels/library_serve.py +46 -26
  11. package/modules/localmodels/remote_ops_common.py +12 -2
  12. package/modules/localmodels/sidecar_downloads.py +426 -0
  13. package/modules/localmodels/sidecar_http.py +396 -0
  14. package/modules/localmodels/sidecar_state.py +466 -0
  15. package/modules/localmodels/speech_admission.py +13 -0
  16. package/modules/localmodels/speech_jobs.py +81 -370
  17. package/modules/localmodels/speech_server.py +17 -8
  18. package/modules/localmodels/speech_state.py +87 -454
  19. package/modules/localmodels/speech_workers.py +41 -163
  20. package/modules/localmodels/stack.py +18 -0
  21. package/modules/localmodels/stack_down.py +19 -14
  22. package/modules/localmodels/stack_ports.py +1 -0
  23. package/modules/localmodels/stack_up.py +51 -1
  24. package/modules/localmodels/strata_poly_server.py +140 -3
  25. package/modules/localmodels/tts-moss.txt +321 -0
  26. package/modules/localmodels/tts_admission.py +396 -0
  27. package/modules/localmodels/tts_backend_speechcpp.py +487 -0
  28. package/modules/localmodels/tts_catalog.py +251 -0
  29. package/modules/localmodels/tts_cli.py +333 -0
  30. package/modules/localmodels/tts_http.py +617 -0
  31. package/modules/localmodels/tts_jobs.py +496 -0
  32. package/modules/localmodels/tts_model.py +591 -0
  33. package/modules/localmodels/tts_moss_presets.json +1 -0
  34. package/modules/localmodels/tts_serve.py +451 -0
  35. package/modules/localmodels/tts_sidecar.py +750 -0
  36. package/modules/localmodels/tts_state.py +395 -0
  37. package/modules/localmodels/tts_worker_kokoro.py +463 -0
  38. package/modules/localmodels/tts_worker_moss.py +748 -0
  39. package/modules/localmodels/tts_workers.py +696 -0
  40. package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/METADATA +1 -1
  41. package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/RECORD +43 -24
  42. package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/licenses/NOTICE +29 -0
  43. package/package.json +1 -1
  44. package/tool.json +1 -1
  45. /package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/WHEEL +0 -0
  46. /package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/entry_points.txt +0 -0
  47. /package/modules/{simplex_localmodels-0.1.0.dev102.dist-info → simplex_localmodels-0.1.0.dev103.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -0,0 +1,251 @@
1
+ """Closed v1 local TTS model catalog parsed from ``localmodels/catalog.json``.
2
+
3
+ Selects only standby-sidecar TTS entries (``task == "tts"`` without legacy ``"argv"``) so
4
+ the historical ``kokoro-82m`` ``stack plan --tts`` recipe stays completely untouched.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from dataclasses import dataclass
11
+ from pathlib import Path
12
+ from typing import Any, Literal, TypedDict, cast
13
+
14
+ from localmodels import tts_model as tts_model_mod
15
+ from localmodels import tts_worker_kokoro, tts_worker_moss
16
+ from localmodels.catalog_recipes import CATALOG_PATH as CATALOG_PATH
17
+ from localmodels.contracts import decode
18
+ from localmodels.tts_model import TTS_ENGINES, TtsVoiceInfo
19
+ from localmodels.tts_model import TtsEngine as TtsEngine
20
+
21
+ TtsQualityRating = Literal["fast-bilingual", "lightweight-streaming", "high-expressive"]
22
+
23
+ V1_TTS_MODEL_IDS: tuple[str, ...] = (
24
+ "kokoro-v1.1-zh",
25
+ "moss-tts-nano-100m",
26
+ "qwen3-tts-0.6b-customvoice",
27
+ "qwen3-tts-1.7b-customvoice",
28
+ )
29
+
30
+
31
+ class _RawTtsFileOptional(TypedDict, total=False):
32
+ repo: str
33
+ revision: str
34
+
35
+
36
+ class _RawTtsFile(_RawTtsFileOptional):
37
+ path: str
38
+ size_bytes: int
39
+ sha256: str
40
+
41
+
42
+ class _RawTtsOptional(TypedDict, total=False):
43
+ engine: str
44
+ commercial_notice: str | None
45
+ opt_in_only: bool
46
+ supports_streaming: bool
47
+ supports_instructions: bool
48
+ note: str
49
+
50
+
51
+ class _RawTtsComponent(_RawTtsOptional):
52
+ id: str
53
+ display_name: str
54
+ task: str
55
+ runtime: str
56
+ version: str
57
+ default_voice: str
58
+ voice_count: int
59
+ sample_rate: int
60
+ files: list[_RawTtsFile]
61
+ memory_estimate_bytes: int
62
+ vram_estimate_bytes: int
63
+ gpu_supported: bool
64
+ quality_rating: str
65
+ languages: list[str]
66
+ language_count: int
67
+ repo: str
68
+ revision: str
69
+ license: str
70
+ license_url: str
71
+ status: str
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class TtsModelFile:
76
+ """One pinned weight, lexicon, or FST file belonging to a local TTS model."""
77
+
78
+ path: str
79
+ size_bytes: int
80
+ sha256: str
81
+ repo: str | None = None
82
+ revision: str | None = None
83
+
84
+
85
+ @dataclass(frozen=True)
86
+ class TtsModelSpec:
87
+ """Catalog metadata and pinned artifacts for one v1 local TTS model."""
88
+
89
+ id: str
90
+ name: str
91
+ engine: TtsEngine
92
+ engine_tag: str | None
93
+ version: str
94
+ repo: str
95
+ revision: str
96
+ status: str
97
+ languages: tuple[str, ...]
98
+ language_count: int
99
+ quality_rating: TtsQualityRating
100
+ default_voice: str
101
+ voice_count: int
102
+ sample_rate: int
103
+ supports_streaming: bool
104
+ supports_instructions: bool
105
+ license: str
106
+ license_url: str
107
+ commercial_notice: str | None
108
+ opt_in_only: bool
109
+ disk_size_bytes: int
110
+ vram_estimate_bytes: int
111
+ ram_estimate_bytes: int
112
+ gpu_supported: bool
113
+ files: tuple[TtsModelFile, ...]
114
+
115
+ def status_fields(self) -> dict[str, Any]:
116
+ """Static model-row fields defined by ``localmodels.tts-status/v1``."""
117
+ return {
118
+ "id": self.id,
119
+ "name": self.name,
120
+ "engine": self.engine,
121
+ "languages": list(self.languages),
122
+ "language_count": self.language_count,
123
+ "quality_rating": self.quality_rating,
124
+ "default_voice": self.default_voice,
125
+ "voice_count": self.voice_count,
126
+ "sample_rate": self.sample_rate,
127
+ "supports_streaming": self.supports_streaming,
128
+ "supports_instructions": self.supports_instructions,
129
+ "license": self.license,
130
+ "license_url": self.license_url,
131
+ "commercial_notice": self.commercial_notice,
132
+ "opt_in_only": self.opt_in_only,
133
+ "disk_size_bytes": self.disk_size_bytes,
134
+ "vram_estimate_bytes": self.vram_estimate_bytes,
135
+ "ram_estimate_bytes": self.ram_estimate_bytes,
136
+ "gpu_supported": self.gpu_supported,
137
+ }
138
+
139
+
140
+ def _parse_entry(raw: dict[str, Any]) -> TtsModelSpec:
141
+ comp = decode(raw, _RawTtsComponent)
142
+ runtime = comp["runtime"]
143
+ if runtime not in TTS_ENGINES:
144
+ raise ValueError(f"unsupported tts runtime for {comp['id']}: {runtime}")
145
+ rating = comp["quality_rating"]
146
+ if rating not in ("fast-bilingual", "lightweight-streaming", "high-expressive"):
147
+ raise ValueError(f"unsupported tts quality_rating for {comp['id']}: {rating}")
148
+ files = tuple(
149
+ TtsModelFile(
150
+ path=f["path"],
151
+ size_bytes=f["size_bytes"],
152
+ sha256=f["sha256"],
153
+ repo=f.get("repo"),
154
+ revision=f.get("revision"),
155
+ )
156
+ for f in comp["files"]
157
+ )
158
+ if not files:
159
+ raise ValueError(f"tts model {comp['id']} pins no files")
160
+ return TtsModelSpec(
161
+ id=comp["id"],
162
+ name=comp["display_name"],
163
+ engine=cast(TtsEngine, runtime),
164
+ engine_tag=comp.get("engine"),
165
+ version=comp["version"],
166
+ default_voice=comp["default_voice"],
167
+ voice_count=comp["voice_count"],
168
+ sample_rate=comp["sample_rate"],
169
+ supports_streaming=bool(comp.get("supports_streaming", True)),
170
+ supports_instructions=bool(comp.get("supports_instructions", False)),
171
+ files=files,
172
+ disk_size_bytes=sum(f.size_bytes for f in files),
173
+ gpu_supported=comp["gpu_supported"],
174
+ ram_estimate_bytes=comp["memory_estimate_bytes"],
175
+ vram_estimate_bytes=comp["vram_estimate_bytes"],
176
+ quality_rating=cast(TtsQualityRating, rating),
177
+ languages=tuple(comp["languages"]),
178
+ language_count=comp["language_count"],
179
+ repo=comp["repo"],
180
+ revision=comp["revision"],
181
+ status=comp["status"],
182
+ license=comp["license"],
183
+ license_url=comp["license_url"],
184
+ commercial_notice=comp.get("commercial_notice"),
185
+ opt_in_only=bool(comp.get("opt_in_only", False)),
186
+ )
187
+
188
+
189
+ def tts_models(catalog_path: Path = CATALOG_PATH) -> tuple[TtsModelSpec, ...]:
190
+ """Return the closed v1 local TTS catalog in contract order."""
191
+ doc = json.loads(catalog_path.read_text(encoding="utf-8"))
192
+ by_id = {
193
+ str(c["id"]): c
194
+ for c in doc.get("components", [])
195
+ if c.get("task") == "tts" and "argv" not in c and c.get("id") in V1_TTS_MODEL_IDS
196
+ }
197
+ missing = [model_id for model_id in V1_TTS_MODEL_IDS if model_id not in by_id]
198
+ if missing:
199
+ raise ValueError(f"catalog.json is missing v1 tts models: {', '.join(missing)}")
200
+ return tuple(_parse_entry(by_id[model_id]) for model_id in V1_TTS_MODEL_IDS)
201
+
202
+
203
+ def tts_model(model_id: str, catalog_path: Path = CATALOG_PATH) -> TtsModelSpec:
204
+ """Return one v1 TTS model spec by ID, raising KeyError if unknown."""
205
+ for entry in tts_models(catalog_path):
206
+ if entry.id == model_id:
207
+ return entry
208
+ raise KeyError(f"unknown tts model: {model_id}")
209
+
210
+
211
+ def static_voices(model_id: str, catalog_path: Path = CATALOG_PATH) -> list[TtsVoiceInfo]:
212
+ """Return static voice metadata for ``model_id`` when no worker is running."""
213
+ spec = tts_model(model_id, catalog_path)
214
+ raw_list: list[dict[str, str]] | None = None
215
+ if spec.id == "kokoro-v1.1-zh":
216
+ raw_list = tts_worker_kokoro.kokoro_voice_list()
217
+ elif spec.id == "moss-tts-nano-100m":
218
+ raw_list = tts_worker_moss.moss_voice_list()
219
+ elif spec.engine == "speech.cpp":
220
+ return tts_model_mod.qwen3_voice_list()
221
+ if raw_list is not None:
222
+ return [
223
+ {
224
+ "id": item["id"],
225
+ "name": item["name"],
226
+ "language": item["language"],
227
+ "gender": item["gender"],
228
+ }
229
+ for item in raw_list
230
+ ]
231
+ return [
232
+ {
233
+ "id": spec.default_voice,
234
+ "name": spec.default_voice,
235
+ "language": spec.languages[0] if spec.languages else "auto",
236
+ "gender": "unspecified",
237
+ }
238
+ ]
239
+
240
+
241
+ def resolve_catalog_voice(
242
+ model_id: str, voice: str, catalog_path: Path = CATALOG_PATH
243
+ ) -> str | None:
244
+ """Return the canonical voice ID for ``model_id`` (case-insensitive), or None if unknown."""
245
+ cleaned = voice.strip().lower()
246
+ if not cleaned:
247
+ return None
248
+ for item in static_voices(model_id, catalog_path):
249
+ if item["id"].lower() == cleaned:
250
+ return item["id"]
251
+ return None
@@ -0,0 +1,333 @@
1
+ """``localmodels tts`` CLI surface conforming to ``tts-v1``.
2
+
3
+ Pure JSON / JSONL on stdout, diagnostics on stderr. Exit codes:
4
+ 0 ok, 1 failed, 2 refused / invalid input, 130 cancelled.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import sys
11
+ from pathlib import Path
12
+
13
+ from localmodels import cli_help, deploy, tts_jobs, tts_serve
14
+ from localmodels.tts_model import (
15
+ EXIT_FAILED,
16
+ TtsError,
17
+ emit_final,
18
+ error_event,
19
+ parse_bool_flag,
20
+ result_event,
21
+ )
22
+
23
+ DESCRIPTION = (
24
+ "Manage local text-to-speech models (Kokoro-82M v1.1-zh, MOSS-TTS-Nano-100M, Qwen3-TTS "
25
+ "CustomVoice via speech.cpp, and pluggable TTS backends): "
26
+ "inspect status, list models, download with resumable verification, cancel, remove, configure "
27
+ "preferences, control the standby-first sidecar, list voices, and synthesize audio. Every "
28
+ "command writes pure JSON or JSONL on stdout. Exit status: 0 ok, 1 failed, 2 refused, 130 "
29
+ "cancelled."
30
+ )
31
+
32
+ _FALLBACK_CODE = {
33
+ "status": "RUNTIME_ERROR",
34
+ "list": "RUNTIME_ERROR",
35
+ "download": "DOWNLOAD_FAILED",
36
+ "cancel": "INVALID_STATE",
37
+ "remove": "INVALID_STATE",
38
+ "configure": "INVALID_CONFIG",
39
+ "start": "RUNTIME_ERROR",
40
+ "load": "RUNTIME_ERROR",
41
+ "unload": "RUNTIME_ERROR",
42
+ "stop": "RUNTIME_ERROR",
43
+ "voices": "RUNTIME_ERROR",
44
+ "synthesize": "RUNTIME_ERROR",
45
+ }
46
+
47
+
48
+ def _add_base_dir(parser: argparse.ArgumentParser) -> None:
49
+ parser.add_argument(
50
+ "--base-dir",
51
+ default=deploy.DEFAULT_BASE_DIR,
52
+ metavar="DIR",
53
+ help="directory holding TTS model weights and runtimes",
54
+ )
55
+
56
+
57
+ def _add_model_arg(parser: argparse.ArgumentParser) -> None:
58
+ parser.add_argument("model", metavar="MODEL", help="TTS model id (e.g. kokoro-v1.1-zh)")
59
+
60
+
61
+ def _add_json_flag(parser: argparse.ArgumentParser) -> None:
62
+ parser.add_argument("--json", action="store_true", help="accepted; output is JSON")
63
+
64
+
65
+ def _add_manage_parsers(verbs: argparse._SubParsersAction[argparse.ArgumentParser]) -> None:
66
+ status_p = verbs.add_parser("status", help="report TTS config, runtime, and models (JSON)")
67
+ _add_base_dir(status_p)
68
+ _add_json_flag(status_p)
69
+ cli_help.document(
70
+ status_p,
71
+ "Print one localmodels.tts-status/v1 JSON document describing configuration, live "
72
+ "sidecar status, and all v1 TTS models with license disclosures. Read-only.",
73
+ examples=[("%(prog)s --base-dir /srv/models --json", "")],
74
+ )
75
+
76
+ list_p = verbs.add_parser("list", help="list available TTS models and states (JSON)")
77
+ _add_base_dir(list_p)
78
+ _add_json_flag(list_p)
79
+ cli_help.document(
80
+ list_p,
81
+ "Print one localmodels.tts-list/v1 JSON document listing v1 TTS models and install states.",
82
+ examples=[("%(prog)s --json", "")],
83
+ )
84
+
85
+ dl_p = verbs.add_parser("download", help="download and verify a TTS model (JSONL)")
86
+ _add_model_arg(dl_p)
87
+ _add_base_dir(dl_p)
88
+ dl_p.add_argument(
89
+ "--include-gpu-engine",
90
+ action="store_true",
91
+ help="also fetch a GPU engine build when pinned for this model and host",
92
+ )
93
+ dl_p.add_argument("--jsonl", action="store_true", help="accepted; output is JSONL")
94
+ cli_help.document(
95
+ dl_p,
96
+ "Download and SHA-256 verify a TTS model into <base-dir>/tts/<model>/ with resumable "
97
+ "byte ranges and region-aware mirrors. Emits localmodels.tts-event/v1 JSONL.",
98
+ examples=[("%(prog)s kokoro-v1.1-zh --jsonl", "")],
99
+ )
100
+
101
+ cancel_p = verbs.add_parser("cancel", help="cancel an active TTS download (JSON)")
102
+ _add_model_arg(cancel_p)
103
+ _add_base_dir(cancel_p)
104
+ _add_json_flag(cancel_p)
105
+ cli_help.document(cancel_p, "Stop an active TTS download and clean up partial files.")
106
+
107
+ rm_p = verbs.add_parser("remove", help="delete a TTS model's weights (JSON)")
108
+ _add_model_arg(rm_p)
109
+ _add_base_dir(rm_p)
110
+ _add_json_flag(rm_p)
111
+ cli_help.document(
112
+ rm_p, "Unload the model if active and delete its downloaded weights idempotently."
113
+ )
114
+
115
+ cfg_p = verbs.add_parser("configure", help="update persisted TTS preferences (JSON)")
116
+ _add_base_dir(cfg_p)
117
+ cfg_p.add_argument("--model", dest="model_id", metavar="MODEL", help="default TTS model id")
118
+ cfg_p.add_argument("--voice", dest="voice", metavar="VOICE", help="default voice id")
119
+ cfg_p.add_argument("--speed", dest="speed", type=float, metavar="FLOAT", help="speed 0.5..2.0")
120
+ cfg_p.add_argument(
121
+ "--response-format",
122
+ dest="response_format",
123
+ metavar="FMT",
124
+ help="default audio format ('wav' or 'pcm')",
125
+ )
126
+ cfg_p.add_argument(
127
+ "--use-gpu", dest="use_gpu", metavar="BOOL", help="prefer GPU ('true' or 'false')"
128
+ )
129
+ cfg_p.add_argument(
130
+ "--keep-loaded-seconds",
131
+ dest="keep_loaded_seconds",
132
+ type=int,
133
+ metavar="INT",
134
+ help="idle unload TTL in seconds (-1 never, 0 immediate, 1..86400 TTL)",
135
+ )
136
+ cfg_p.add_argument(
137
+ "--language", dest="language", metavar="LANG", help="language preference ('auto' or ISO)"
138
+ )
139
+ _add_json_flag(cfg_p)
140
+ cli_help.document(cfg_p, "Validate and persist TTS preferences under $LOCALMODELS_STATE/tts/.")
141
+
142
+
143
+ def _add_runtime_parsers(verbs: argparse._SubParsersAction[argparse.ArgumentParser]) -> None:
144
+ start_p = verbs.add_parser("start", help="start the local TTS sidecar (JSON)")
145
+ _add_base_dir(start_p)
146
+ start_p.add_argument(
147
+ "--standby",
148
+ action="store_true",
149
+ default=True,
150
+ help="start in zero-VRAM standby without loading a model (default)",
151
+ )
152
+ start_p.add_argument("--model", dest="model_id", metavar="MODEL", help="eagerly load model")
153
+ start_p.add_argument("--port", type=int, default=None, metavar="PORT", help="loopback port")
154
+ _add_json_flag(start_p)
155
+ cli_help.document(start_p, "Idempotently start the standby-first TTS loopback HTTP sidecar.")
156
+
157
+ load_p = verbs.add_parser("load", help="load a downloaded TTS model into the sidecar (JSONL)")
158
+ _add_model_arg(load_p)
159
+ _add_base_dir(load_p)
160
+ load_p.add_argument(
161
+ "--use-gpu", dest="use_gpu", metavar="BOOL", help="override GPU preference for this load"
162
+ )
163
+ load_p.add_argument("--jsonl", action="store_true", help="accepted; output is JSONL")
164
+ cli_help.document(load_p, "Load a downloaded TTS model with 4-step JSONL progress events.")
165
+
166
+ unload_p = verbs.add_parser("unload", help="unload the active TTS worker into standby (JSON)")
167
+ _add_base_dir(unload_p)
168
+ _add_json_flag(unload_p)
169
+ cli_help.document(
170
+ unload_p, "Terminate the active worker to reclaim RAM/VRAM while keeping standby."
171
+ )
172
+
173
+ stop_p = verbs.add_parser("stop", help="stop the local TTS sidecar cleanly (JSON)")
174
+ _add_base_dir(stop_p)
175
+ _add_json_flag(stop_p)
176
+ cli_help.document(stop_p, "Gracefully shut down the TTS sidecar and its worker.")
177
+
178
+ voices_p = verbs.add_parser("voices", help="list voices for a TTS model (JSON)")
179
+ _add_base_dir(voices_p)
180
+ voices_p.add_argument("--model", dest="model_id", metavar="MODEL", help="TTS model id")
181
+ _add_json_flag(voices_p)
182
+ cli_help.document(voices_p, "List available voices for the selected or default TTS model.")
183
+
184
+ synth_p = verbs.add_parser("synthesize", help="synthesize text to an audio file (JSON)")
185
+ _add_base_dir(synth_p)
186
+ text_grp = synth_p.add_mutually_exclusive_group(required=True)
187
+ text_grp.add_argument("--text", metavar="TEXT", help="text to synthesize")
188
+ text_grp.add_argument("--text-file", metavar="PATH", help="UTF-8 file containing text")
189
+ synth_p.add_argument("--out", required=True, metavar="PATH", help="output audio file path")
190
+ synth_p.add_argument("--model", dest="model_id", metavar="MODEL", help="TTS model id")
191
+ synth_p.add_argument("--voice", dest="voice", metavar="VOICE", help="voice id")
192
+ synth_p.add_argument(
193
+ "--speed", dest="speed", type=float, metavar="FLOAT", help="speed 0.5..2.0"
194
+ )
195
+ synth_p.add_argument(
196
+ "--response-format",
197
+ dest="response_format",
198
+ metavar="FMT",
199
+ help="audio format ('wav' or 'pcm')",
200
+ )
201
+ synth_p.add_argument(
202
+ "--instructions", dest="instructions", metavar="TEXT", help="optional style instructions"
203
+ )
204
+ _add_json_flag(synth_p)
205
+ cli_help.document(
206
+ synth_p, "Synthesize speech via the loopback TTS sidecar and write audio to --out."
207
+ )
208
+
209
+
210
+ def add_parser(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None:
211
+ """Register the ``localmodels tts`` command subtree."""
212
+ parser = sub.add_parser("tts", help="manage local text-to-speech models and runtime (JSON)")
213
+ verbs = parser.add_subparsers(dest="tts_command", required=True, metavar="COMMAND")
214
+ _add_manage_parsers(verbs)
215
+ _add_runtime_parsers(verbs)
216
+ cli_help.document(parser, DESCRIPTION)
217
+
218
+
219
+ def _read_text_input(args: argparse.Namespace) -> str:
220
+ if args.text is not None:
221
+ return str(args.text)
222
+ tf_path = Path(str(args.text_file))
223
+ try:
224
+ if tf_path.stat().st_size > 65536:
225
+ raise TtsError("INVALID_INPUT", "--text-file exceeds 64 KiB size limit")
226
+ return tf_path.read_text(encoding="utf-8")
227
+ except (OSError, UnicodeDecodeError) as exc:
228
+ raise TtsError("INVALID_INPUT", f"cannot read --text-file: {exc}") from None
229
+
230
+
231
+ def _dispatch(args: argparse.Namespace) -> dict[str, object]:
232
+ verb = str(args.tts_command)
233
+ base_dir = str(args.base_dir)
234
+ if verb == "status":
235
+ return dict(tts_jobs.status(base_dir))
236
+ if verb == "list":
237
+ return dict(tts_jobs.list_models(base_dir))
238
+ if verb == "download":
239
+ row = tts_jobs.download(
240
+ str(args.model),
241
+ base_dir,
242
+ include_gpu_engine=bool(getattr(args, "include_gpu_engine", False)),
243
+ )
244
+ return result_event(ok=True, model_id=str(args.model), detail="downloaded", row=row)
245
+ if verb == "cancel":
246
+ row = tts_jobs.cancel(str(args.model), base_dir)
247
+ return result_event(ok=True, model_id=str(args.model), detail="cancelled", row=row)
248
+ if verb == "remove":
249
+ row = tts_jobs.remove(str(args.model), base_dir)
250
+ return result_event(ok=True, model_id=str(args.model), detail="removed", row=row)
251
+ if verb == "configure":
252
+ use_gpu = (
253
+ parse_bool_flag(args.use_gpu, flag="--use-gpu") if args.use_gpu is not None else None
254
+ )
255
+ return dict(
256
+ tts_jobs.configure(
257
+ base_dir,
258
+ model_id=args.model_id,
259
+ voice=args.voice,
260
+ speed=args.speed,
261
+ response_format=args.response_format,
262
+ use_gpu=use_gpu,
263
+ keep_loaded_seconds=args.keep_loaded_seconds,
264
+ language=args.language,
265
+ )
266
+ )
267
+ if verb == "start":
268
+ return dict(
269
+ tts_serve.start(
270
+ base_dir,
271
+ standby=bool(getattr(args, "standby", True)) and args.model_id is None,
272
+ model_id=args.model_id,
273
+ port=args.port,
274
+ )
275
+ )
276
+ if verb == "load":
277
+ use_gpu = (
278
+ parse_bool_flag(args.use_gpu, flag="--use-gpu") if args.use_gpu is not None else None
279
+ )
280
+ doc = tts_serve.load(str(args.model), base_dir, use_gpu=use_gpu)
281
+ return result_event(
282
+ ok=True, model_id=str(args.model), detail="loaded", runtime=doc["runtime"]
283
+ )
284
+ if verb == "unload":
285
+ return dict(tts_serve.unload(base_dir))
286
+ if verb == "stop":
287
+ return dict(tts_serve.stop(base_dir))
288
+ if verb == "voices":
289
+ return dict(tts_serve.voices(args.model_id, base_dir))
290
+ if verb == "synthesize":
291
+ return dict(
292
+ tts_serve.synthesize(
293
+ _read_text_input(args),
294
+ str(args.out),
295
+ base_dir,
296
+ model_id=args.model_id,
297
+ voice=args.voice,
298
+ speed=args.speed,
299
+ response_format=args.response_format,
300
+ instructions=args.instructions,
301
+ )
302
+ )
303
+ raise TtsError("INVALID_CONFIG", f"unknown tts command: {verb}")
304
+
305
+
306
+ def cli(args: argparse.Namespace) -> int:
307
+ """Execute one ``localmodels tts`` verb, emitting pure JSON/JSONL on stdout."""
308
+ verb = str(getattr(args, "tts_command", ""))
309
+ model_id = getattr(args, "model", None) or getattr(args, "model_id", None)
310
+ try:
311
+ emit_final(_dispatch(args))
312
+ return 0
313
+ except TtsError as exc:
314
+ emit_final(error_event(exc, model_id=model_id if isinstance(model_id, str) else None))
315
+ return exc.exit_code
316
+ except KeyboardInterrupt:
317
+ emit_final(
318
+ error_event(
319
+ TtsError("CANCELLED", "tts command cancelled"),
320
+ model_id=model_id if isinstance(model_id, str) else None,
321
+ )
322
+ )
323
+ return 130
324
+ except Exception as exc: # noqa: BLE001
325
+ code = _FALLBACK_CODE.get(verb, "RUNTIME_ERROR")
326
+ print(f"localmodels tts {verb}: {exc}", file=sys.stderr)
327
+ emit_final(
328
+ error_event(
329
+ TtsError(code, str(exc), failed=True),
330
+ model_id=model_id if isinstance(model_id, str) else None,
331
+ )
332
+ )
333
+ return EXIT_FAILED