@gobing-ai/knowledge-kit 0.1.22 → 0.1.23

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 (59) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/index.js +165 -91
  3. package/package.json +1 -1
  4. package/plugins/generations/gemini-tts/dist/index.js +47 -7
  5. package/plugins/generations/gemini-tts/src/gemini-client.ts +34 -6
  6. package/plugins/generations/music-gen/README.md +2 -2
  7. package/plugins/generations/music-gen/dist/index.js +46 -10
  8. package/plugins/generations/music-gen/presets/formats/song.yaml +6 -1
  9. package/plugins/generations/music-gen/presets/themes/synthwave.yaml +6 -1
  10. package/plugins/generations/music-gen/src/adapter/instance.ts +34 -11
  11. package/plugins/generations/music-gen/src/presets.ts +36 -3
  12. package/plugins/generations/omni-voice-gen/uv.toml +5 -0
  13. package/plugins/generations/vibe-voice-tts/README.md +64 -0
  14. package/plugins/generations/vibe-voice-tts/dist/index.js +14259 -0
  15. package/plugins/generations/vibe-voice-tts/package.json +16 -0
  16. package/plugins/generations/vibe-voice-tts/plugin.json +6 -0
  17. package/plugins/generations/vibe-voice-tts/profiles.json +10 -0
  18. package/plugins/generations/vibe-voice-tts/pyproject.toml +9 -0
  19. package/plugins/generations/vibe-voice-tts/python/worker.py +566 -0
  20. package/plugins/generations/vibe-voice-tts/src/index.ts +88 -0
  21. package/plugins/generations/vibe-voice-tts/src/vibevoice-client.ts +828 -0
  22. package/plugins/generations/vibe-voice-tts/tsconfig.json +8 -0
  23. package/plugins/generations/vibe-voice-tts/uv.lock +1767 -0
  24. package/plugins/generations/vibe-voice-tts/uv.toml +4 -0
  25. package/plugins/generations/voice-gen/dist/index.js +31 -1
  26. package/plugins/generations/voice-gen/src/voicebox-client.ts +50 -1
  27. package/plugins/generations/voxcpm-tts/dist/index.js +81 -9
  28. package/plugins/generations/voxcpm-tts/python/worker.py +9 -0
  29. package/plugins/generations/voxcpm-tts/src/index.ts +41 -0
  30. package/plugins/generations/voxcpm-tts/src/voxcpm-client.ts +32 -11
  31. package/plugins/generations/voxcpm-tts/uv.toml +5 -0
  32. package/plugins/kk/README.md +21 -0
  33. package/plugins/kk/decisions/kk-safety.yaml +5 -2
  34. package/plugins/kk/plugin.json +1 -1
  35. package/plugins/kk/schedules/kk-serve.launchd.plist.tmpl +12 -1
  36. package/plugins/kk/scripts/daily-stages.ts +274 -40
  37. package/plugins/kk/scripts/kk-workflow-stages.ts +74 -11
  38. package/plugins/kk/scripts/safety-artifact-check.ts +28 -5
  39. package/plugins/kk/workflows/kk-daily-ai-voice.yaml +4 -3
  40. package/plugins/kk/workflows/kk-daily-ai-voice2.yaml +6 -5
  41. package/plugins/kk/workflows/kk-daily-safety.yaml +12 -10
  42. package/plugins/kk/workflows/kk-music.yaml +20 -16
  43. package/plugins/kk/workflows/kk-news-generate.yaml +23 -3
  44. package/plugins/kk/workflows/kk-publish.yaml +4 -1
  45. package/plugins/publishings/linkedin-pub/dist/index.js +51 -9
  46. package/plugins/publishings/linkedin-pub/dist/profile-check.js +5 -0
  47. package/plugins/publishings/linkedin-pub/src/index.ts +99 -12
  48. package/plugins/publishings/surfdash-pub/dist/index.js +8 -4
  49. package/plugins/publishings/surfdash-pub/src/index.ts +7 -1
  50. package/plugins/publishings/surfdash-pub/src/patch.ts +21 -3
  51. package/plugins/publishings/threads-pub/dist/index.js +47 -5
  52. package/plugins/publishings/threads-pub/dist/profile-check.js +7 -1
  53. package/plugins/publishings/threads-pub/src/post-rail.ts +101 -4
  54. package/plugins/publishings/wechatmp-pub/dist/index.js +94 -34
  55. package/plugins/publishings/wechatmp-pub/src/cgi-draft.ts +87 -53
  56. package/plugins/publishings/wechatmp-pub/src/enrich.ts +61 -3
  57. package/plugins/publishings/wechatmp-pub/src/flow.ts +28 -0
  58. package/plugins/publishings/x-pub/dist/index.js +84 -9
  59. package/plugins/publishings/x-pub/src/post-rail.ts +154 -12
@@ -0,0 +1,16 @@
1
+ {
2
+ "name": "@gobing-ai/vibe-voice-tts",
3
+ "type": "module",
4
+ "private": true,
5
+ "scripts": {
6
+ "typecheck": "tsc --noEmit"
7
+ },
8
+ "dependencies": {
9
+ "@gobing-ai/ts-utils": "catalog:",
10
+ "@gobing-ai/voice-gen": "workspace:*"
11
+ },
12
+ "devDependencies": {
13
+ "@gobing-ai/kk-core": "workspace:*",
14
+ "@types/bun": "1.4.3"
15
+ }
16
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "vibe-voice-tts",
3
+ "kind": "generator",
4
+ "entry": "./dist/index.js",
5
+ "version": "1.0.0"
6
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "profiles": [
3
+ {
4
+ "id": "robin-news",
5
+ "name": "robin-news",
6
+ "mode": "instruct",
7
+ "instruct": "清晰、自然、沉稳的中文新闻播报,语速适中。"
8
+ }
9
+ ]
10
+ }
@@ -0,0 +1,9 @@
1
+ [project]
2
+ name = "vibe-voice-tts"
3
+ version = "1.0.0"
4
+ description = "VibeVoice-backed voice generator worker for knowledge-kit (independent uv project)"
5
+ requires-python = "==3.12.*"
6
+ dependencies = ["vibevoice==0.0.1"]
7
+
8
+ [dependency-groups]
9
+ dev = ["pytest"]
@@ -0,0 +1,566 @@
1
+ """VibeVoice inference worker for the kk `vibe-voice-tts` generator plugin.
2
+
3
+ A private, invocation-scoped NDJSON worker the TypeScript adapter spawns through `uv run
4
+ --locked`. One model load per process; sequential integer-id health/render requests on stdin;
5
+ one JSON response per line on stdout. At startup fd 1 is pointed at stderr and the protocol
6
+ writes to the saved original fd, so library stdout stays clean at the fd level too — not just
7
+ the Python `sys.stdout` object (ADR-055 / docs/design/vibe-voice-driver.md).
8
+
9
+ Backend: independently published ``vibevoice==0.0.1`` on Python 3.12. `vendors/` is reference-only
10
+ — every model/cache/profile/import path is canonicalized and refused if it routes into `vendors/`.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import contextlib
16
+ import copy
17
+ import io
18
+ import json
19
+ import os
20
+ import re
21
+ import struct
22
+ import sys
23
+ from pathlib import Path
24
+
25
+ LINE_MAX_BYTES = 1_048_576
26
+ DEFAULT_MODEL = "microsoft/VibeVoice-1.5B"
27
+ DEFAULT_SAMPLE_RATE = 24_000
28
+ DEFAULT_CFG_SCALE = 1.5
29
+ DEFAULT_DDPM_STEPS = 10
30
+ DEFAULT_STREAMING_DDPM_STEPS = 5
31
+ _VENDOR_SEGMENT = "vendors"
32
+ _ENV_PATH_KEYS = (
33
+ "PYTHONPATH",
34
+ "PYTHONHOME",
35
+ "VIRTUAL_ENV",
36
+ "UV_PROJECT_ENVIRONMENT",
37
+ "UV_CACHE_DIR",
38
+ "HF_HOME",
39
+ "HF_HUB_CACHE",
40
+ "XDG_CACHE_HOME",
41
+ "TRANSFORMERS_CACHE",
42
+ "HF_DATASETS_CACHE",
43
+ )
44
+
45
+
46
+ class WorkerError(Exception):
47
+ """An actionable worker failure surfaced to the adapter as `{ok:false, error}`."""
48
+
49
+
50
+ def _canonical(path: str) -> str:
51
+ return str(Path(path).expanduser().resolve())
52
+
53
+
54
+ def vendor_blocked(path: str) -> bool:
55
+ """True when the canonical path (or any symlink target) contains a `vendors` segment."""
56
+ resolved = Path(path).expanduser()
57
+ try:
58
+ resolved = resolved.resolve()
59
+ except OSError:
60
+ resolved = resolved.absolute()
61
+ if _VENDOR_SEGMENT in resolved.parts:
62
+ return True
63
+ if resolved.exists():
64
+ real = Path(os.path.realpath(resolved))
65
+ if _VENDOR_SEGMENT in real.parts:
66
+ return True
67
+ return False
68
+
69
+
70
+ def assert_no_vendor(path: str, label: str) -> str:
71
+ if vendor_blocked(path):
72
+ raise WorkerError(f"{label} must not reference vendors/ (reference-only): {path}")
73
+ return _canonical(path)
74
+
75
+
76
+ def assert_env_paths_safe(environ: dict[str, str]) -> None:
77
+ for key in _ENV_PATH_KEYS:
78
+ raw = environ.get(key)
79
+ if not raw:
80
+ continue
81
+ for part in raw.split(os.pathsep):
82
+ if part:
83
+ assert_no_vendor(part, key)
84
+
85
+
86
+ def parse_registry(raw: object, registry_dir: str) -> list[dict]:
87
+ if not isinstance(raw, dict) or not isinstance(raw.get("profiles"), list):
88
+ raise WorkerError('profile registry must be an object with a "profiles" array')
89
+ seen_ids: set[str] = set()
90
+ seen_names: set[str] = set()
91
+ profiles: list[dict] = []
92
+ for index, entry in enumerate(raw["profiles"]):
93
+ if not isinstance(entry, dict):
94
+ raise WorkerError(f"profile entry {index} is not an object")
95
+ pid = str(entry.get("id", "")).strip()
96
+ name = str(entry.get("name", "")).strip()
97
+ if not pid or not name:
98
+ raise WorkerError(f"profile entry {index} needs nonempty id and name")
99
+ if pid in seen_ids or name in seen_names:
100
+ raise WorkerError(f"duplicate profile id/name {pid!r}")
101
+ if "prompt" in entry or "serialized_prompt" in entry:
102
+ raise WorkerError(f"profile {pid!r} carries a serialized OmniVoice prompt")
103
+ seen_ids.add(pid)
104
+ seen_names.add(name)
105
+ mode = entry.get("mode")
106
+ if mode not in ("instruct", "reference", "cached_prompt"):
107
+ raise WorkerError(f"profile {pid!r} has unsupported mode {mode!r}")
108
+ resolved = dict(entry)
109
+ for key in ("reference_wav_path", "prompt_pt_path"):
110
+ value = entry.get(key)
111
+ if value is None:
112
+ continue
113
+ if not isinstance(value, str) or not value.strip():
114
+ raise WorkerError(f"profile {pid!r} field {key} must be a nonempty string")
115
+ path = value if os.path.isabs(value) else os.path.join(registry_dir, value)
116
+ resolved[key] = assert_no_vendor(path, f"profile {pid!r} {key}")
117
+ mixed = (
118
+ [resolved.get("reference_wav_path"), resolved.get("prompt_pt_path")]
119
+ if mode == "instruct"
120
+ else [resolved.get("prompt_pt_path")]
121
+ if mode == "reference"
122
+ else [resolved.get("reference_wav_path")]
123
+ )
124
+ if any(value is not None for value in mixed):
125
+ raise WorkerError(f"profile {pid!r} mixes mode {mode!r} with fields from another mode")
126
+ if mode == "instruct" and not str(entry.get("instruct", "")).strip():
127
+ raise WorkerError(f"instruct profile {pid!r} needs a nonempty instruct")
128
+ if mode == "reference" and not resolved.get("reference_wav_path"):
129
+ raise WorkerError(f"reference profile {pid!r} needs reference_wav_path")
130
+ if mode == "cached_prompt" and not resolved.get("prompt_pt_path"):
131
+ raise WorkerError(f"cached_prompt profile {pid!r} needs prompt_pt_path")
132
+ profiles.append(resolved)
133
+ return profiles
134
+
135
+
136
+ def load_registry(environ: dict[str, str]) -> list[dict]:
137
+ path = environ.get("VIBEVOICE_PROFILES_PATH")
138
+ if not path:
139
+ raise WorkerError("VIBEVOICE_PROFILES_PATH is not set")
140
+ assert_no_vendor(path, "VIBEVOICE_PROFILES_PATH")
141
+ try:
142
+ raw = json.loads(Path(path).read_text(encoding="utf-8"))
143
+ except FileNotFoundError as err:
144
+ raise WorkerError(f"profile registry not found: {path}") from err
145
+ except json.JSONDecodeError as err:
146
+ raise WorkerError(f"profile registry is not valid JSON: {err}") from err
147
+ return parse_registry(raw, str(Path(path).parent))
148
+
149
+
150
+ def format_speaker_script(text: str) -> str:
151
+ """Normalize arbitrary VoiceScript segment text into a single-line VibeVoice `Speaker 1:` line."""
152
+ normalized = text.replace("\u2019", "'")
153
+ collapsed = re.sub(r"\s+", " ", normalized).strip()
154
+ if not collapsed:
155
+ raise WorkerError("render text must be a nonempty string")
156
+ return f"Speaker 1: {collapsed}"
157
+
158
+
159
+ def resolve_device(requested: str, torch_mod: object) -> str:
160
+ if requested not in ("auto", "cpu", "cuda", "mps"):
161
+ raise WorkerError(f"unsupported VIBEVOICE_DEVICE {requested!r} (allowed: auto, cpu, cuda, mps)")
162
+ cuda_mod = getattr(torch_mod, "cuda", None)
163
+ cuda_ok = bool(cuda_mod and cuda_mod.is_available())
164
+ backends_mod = getattr(torch_mod, "backends", None)
165
+ mps_mod = getattr(backends_mod, "mps", None)
166
+ mps_ok = bool(mps_mod and mps_mod.is_available())
167
+ if requested == "cuda":
168
+ if not cuda_ok:
169
+ raise WorkerError("VIBEVOICE_DEVICE='cuda' requested, but PyTorch CUDA backend is unavailable (refusing CPU fallback)")
170
+ return "cuda"
171
+ if requested == "mps":
172
+ if not mps_ok:
173
+ raise WorkerError("VIBEVOICE_DEVICE='mps' requested, but PyTorch MPS backend is unavailable (refusing CPU fallback)")
174
+ return "mps"
175
+ if requested == "cpu":
176
+ return "cpu"
177
+ if cuda_ok:
178
+ return "cuda"
179
+ if mps_ok:
180
+ return "mps"
181
+ return "cpu"
182
+
183
+
184
+ def is_streaming_checkpoint(model_id: str, local_dir: str) -> bool:
185
+ config_path = Path(local_dir) / "config.json"
186
+ if config_path.is_file():
187
+ try:
188
+ cfg = json.loads(config_path.read_text(encoding="utf-8"))
189
+ if isinstance(cfg, dict):
190
+ model_type = str(cfg.get("model_type", "")).lower()
191
+ archs = " ".join(str(a).lower() for a in cfg.get("architectures", []))
192
+ if "streaming" in model_type or "streaming" in archs:
193
+ return True
194
+ except (OSError, json.JSONDecodeError):
195
+ pass
196
+ lower_id = model_id.lower()
197
+ return "realtime" in lower_id or "streaming" in lower_id
198
+
199
+
200
+ def extract_waveform(outputs: object) -> object:
201
+ speech_outputs = getattr(outputs, "speech_outputs", None)
202
+ if not speech_outputs or speech_outputs[0] is None:
203
+ raise WorkerError("model returned no audio output")
204
+ sample = speech_outputs[0]
205
+ detach = getattr(sample, "detach", None)
206
+ if callable(detach):
207
+ sample = detach().cpu().float().numpy()
208
+ return sample
209
+
210
+
211
+ def to_pcm16(waveform: object) -> bytes:
212
+ import numpy as np # imported lazily so helper tests need no torch/numpy
213
+
214
+ array = np.asarray(waveform, dtype="float32").reshape(-1)
215
+ if array.size == 0:
216
+ raise WorkerError("model returned an empty waveform")
217
+ if not np.all(np.isfinite(array)):
218
+ raise WorkerError("model returned a non-finite waveform")
219
+ clipped = np.clip(array, -1.0, 1.0)
220
+ return (clipped * 32767.0).astype("<i2").tobytes()
221
+
222
+
223
+ def write_pcm16_wav(path: str, pcm: bytes, sample_rate: int, channels: int = 1) -> None:
224
+ if channels != 1:
225
+ raise WorkerError(f"refusing to write {channels}-channel audio; VibeVoice output must be mono")
226
+ if not isinstance(sample_rate, int) or sample_rate <= 0:
227
+ raise WorkerError(f"invalid sample rate {sample_rate}")
228
+ block_align = channels * 2
229
+ byte_rate = sample_rate * block_align
230
+ header = b"RIFF" + struct.pack("<I", 36 + len(pcm)) + b"WAVE"
231
+ header += b"fmt " + struct.pack("<IHHIIHH", 16, 1, channels, sample_rate, byte_rate, block_align, 16)
232
+ header += b"data" + struct.pack("<I", len(pcm))
233
+ Path(path).parent.mkdir(parents=True, exist_ok=True)
234
+ with open(path, "wb") as handle:
235
+ handle.write(header)
236
+ handle.write(pcm)
237
+
238
+
239
+ def _snapshot_revision(model_id: str, local_dir: str) -> str:
240
+ del local_dir
241
+ try:
242
+ from huggingface_hub import scan_cache_dir # type: ignore
243
+
244
+ for repo in scan_cache_dir().repos:
245
+ if repo.repo_id == model_id:
246
+ return repo.repo_path.name
247
+ except Exception: # noqa: BLE001 - provenance is best-effort, never fatal
248
+ return "unknown"
249
+ return "unknown"
250
+
251
+
252
+ def _load_cached_prompt(prompt_pt_path: str, device: str, torch_mod: object) -> object:
253
+ safe_classes: list[object] = []
254
+ try:
255
+ from transformers.modeling_outputs import BaseModelOutputWithPast # type: ignore
256
+
257
+ safe_classes.append(BaseModelOutputWithPast)
258
+ except Exception: # noqa: BLE001
259
+ pass
260
+ try:
261
+ from transformers.cache_utils import DynamicCache # type: ignore
262
+
263
+ safe_classes.append(DynamicCache)
264
+ except Exception: # noqa: BLE001
265
+ pass
266
+
267
+ serialization = getattr(torch_mod, "serialization", None)
268
+ safe_globals = getattr(serialization, "safe_globals", None)
269
+ if callable(safe_globals) and safe_classes:
270
+ with safe_globals(safe_classes):
271
+ return torch_mod.load(prompt_pt_path, map_location=device, weights_only=True)
272
+ return torch_mod.load(prompt_pt_path, map_location=device, weights_only=True)
273
+
274
+
275
+ def load_backend(environ: dict[str, str]) -> dict:
276
+ """Resolve the local snapshot, load the processor & model once, and report provenance."""
277
+ assert_env_paths_safe(environ)
278
+ model_id = environ.get("VIBEVOICE_MODEL", DEFAULT_MODEL)
279
+ requested_device = environ.get("VIBEVOICE_DEVICE", "auto")
280
+
281
+ with contextlib.redirect_stdout(sys.stderr):
282
+ import torch # type: ignore
283
+
284
+ device = resolve_device(requested_device, torch)
285
+
286
+ with contextlib.redirect_stdout(sys.stderr):
287
+ import vibevoice # type: ignore
288
+ from huggingface_hub import snapshot_download # type: ignore
289
+
290
+ if os.path.isdir(model_id):
291
+ local = assert_no_vendor(model_id, "VIBEVOICE_MODEL")
292
+ revision = "unknown"
293
+ else:
294
+ assert_no_vendor(model_id, "VIBEVOICE_MODEL")
295
+ with contextlib.redirect_stdout(sys.stderr):
296
+ local = snapshot_download(repo_id=model_id)
297
+ local = assert_no_vendor(local, "model snapshot")
298
+ revision = _snapshot_revision(model_id, local)
299
+
300
+ streaming = is_streaming_checkpoint(model_id, local)
301
+ if streaming:
302
+ try:
303
+ with contextlib.redirect_stdout(sys.stderr):
304
+ from vibevoice.modular.modeling_vibevoice_streaming_inference import ( # type: ignore
305
+ VibeVoiceStreamingForConditionalGenerationInference,
306
+ )
307
+ from vibevoice.processor.vibevoice_streaming_processor import ( # type: ignore
308
+ VibeVoiceStreamingProcessor,
309
+ )
310
+ except ImportError as err:
311
+ raise WorkerError(
312
+ f"streaming checkpoint {model_id!r} requires streaming inference classes "
313
+ "(VibeVoiceStreamingProcessor / VibeVoiceStreamingForConditionalGenerationInference), "
314
+ f"which are unavailable in installed vibevoice: {err}"
315
+ ) from err
316
+ processor_cls = VibeVoiceStreamingProcessor
317
+ model_cls = VibeVoiceStreamingForConditionalGenerationInference
318
+ else:
319
+ with contextlib.redirect_stdout(sys.stderr):
320
+ from vibevoice.modular.modeling_vibevoice_inference import ( # type: ignore
321
+ VibeVoiceForConditionalGenerationInference,
322
+ )
323
+ from vibevoice.processor.vibevoice_processor import VibeVoiceProcessor # type: ignore
324
+
325
+ processor_cls = VibeVoiceProcessor
326
+ model_cls = VibeVoiceForConditionalGenerationInference
327
+
328
+ if device == "cuda":
329
+ load_dtype = torch.bfloat16
330
+ attn_impl = "flash_attention_2"
331
+ device_map: str | None = "cuda"
332
+ else:
333
+ load_dtype = torch.float32
334
+ attn_impl = "sdpa"
335
+ device_map = None if device == "mps" else "cpu"
336
+
337
+ with contextlib.redirect_stdout(sys.stderr):
338
+ processor = processor_cls.from_pretrained(local)
339
+ try:
340
+ model = model_cls.from_pretrained(
341
+ local,
342
+ torch_dtype=load_dtype,
343
+ attn_implementation=attn_impl,
344
+ device_map=device_map,
345
+ )
346
+ if device == "mps":
347
+ model.to("mps")
348
+ except Exception: # noqa: BLE001 - match VibeVoice fallback when flash_attention_2 is absent on CUDA
349
+ if attn_impl != "flash_attention_2":
350
+ raise
351
+ model = model_cls.from_pretrained(
352
+ local,
353
+ torch_dtype=load_dtype,
354
+ attn_implementation="sdpa",
355
+ device_map=device_map,
356
+ )
357
+ model.eval()
358
+
359
+ package_version = getattr(vibevoice, "__version__", "unknown")
360
+ audio_processor = getattr(processor, "audio_processor", None)
361
+ sample_rate = int(getattr(audio_processor, "sampling_rate", DEFAULT_SAMPLE_RATE))
362
+ if sample_rate <= 0:
363
+ raise WorkerError(f"processor reported a non-positive sample rate {sample_rate}")
364
+ return {
365
+ "model": model,
366
+ "processor": processor,
367
+ "streaming": streaming,
368
+ "device": device,
369
+ "path": local,
370
+ "revision": revision,
371
+ "package": package_version,
372
+ "sample_rate": sample_rate,
373
+ }
374
+
375
+
376
+ def _move_tensors_to_device(inputs: dict, device: str, torch_mod: object) -> dict:
377
+ moved = dict(inputs)
378
+ is_tensor = getattr(torch_mod, "is_tensor", None)
379
+ for key, value in moved.items():
380
+ if callable(is_tensor) and is_tensor(value) and hasattr(value, "to"):
381
+ moved[key] = value.to(device)
382
+ return moved
383
+
384
+
385
+ def _render(state: dict, request: dict) -> dict:
386
+ text = request.get("text")
387
+ if not isinstance(text, str) or not text.strip():
388
+ raise WorkerError("render text must be a nonempty string")
389
+ dest = request.get("dest")
390
+ if not isinstance(dest, str) or not os.path.isabs(dest):
391
+ raise WorkerError("render destination must be an absolute path")
392
+ assert_no_vendor(dest, "render destination")
393
+
394
+ profile = request.get("profile") or {}
395
+ mode = profile.get("mode")
396
+ if mode not in ("instruct", "reference", "cached_prompt"):
397
+ raise WorkerError(f"unsupported profile mode {mode!r}")
398
+
399
+ streaming = bool(state.get("streaming", False))
400
+ if mode == "cached_prompt" and not streaming:
401
+ raise WorkerError("cached_prompt profile requires a streaming VibeVoice checkpoint (e.g. VibeVoice-Realtime-0.5B)")
402
+ if mode in ("reference", "instruct") and streaming:
403
+ raise WorkerError(f"{mode} profile requires a non-streaming VibeVoice checkpoint (e.g. microsoft/VibeVoice-1.5B)")
404
+
405
+ cfg_scale = float(profile.get("cfg_scale", DEFAULT_CFG_SCALE))
406
+ default_steps = DEFAULT_STREAMING_DDPM_STEPS if mode == "cached_prompt" else DEFAULT_DDPM_STEPS
407
+ ddpm_steps = int(profile.get("ddpm_steps", default_steps))
408
+
409
+ with contextlib.redirect_stdout(sys.stderr):
410
+ import torch # type: ignore
411
+
412
+ seed = request.get("seed")
413
+ if seed is not None:
414
+ torch.manual_seed(int(seed))
415
+
416
+ model = state["model"]
417
+ processor = state["processor"]
418
+ device = state.get("device", "cpu")
419
+
420
+ if hasattr(model, "set_ddpm_inference_steps"):
421
+ model.set_ddpm_inference_steps(num_steps=ddpm_steps)
422
+
423
+ extra_generate_kwargs: dict = {}
424
+ if mode == "reference":
425
+ ref_path = profile.get("reference_wav_path")
426
+ if not isinstance(ref_path, str) or not ref_path.strip():
427
+ raise WorkerError("reference profile requires reference_wav_path")
428
+ ref_wav = assert_no_vendor(ref_path, "reference_wav_path")
429
+ if not os.path.isfile(ref_wav):
430
+ raise WorkerError(f"reference audio file not found: {ref_wav}")
431
+ script = format_speaker_script(text)
432
+ raw_inputs = processor(
433
+ text=[script],
434
+ voice_samples=[[ref_wav]],
435
+ padding=True,
436
+ return_tensors="pt",
437
+ return_attention_mask=True,
438
+ )
439
+ elif mode == "cached_prompt":
440
+ pt_path_raw = profile.get("prompt_pt_path")
441
+ if not isinstance(pt_path_raw, str) or not pt_path_raw.strip():
442
+ raise WorkerError("cached_prompt profile requires prompt_pt_path")
443
+ pt_path = assert_no_vendor(pt_path_raw, "prompt_pt_path")
444
+ if not os.path.isfile(pt_path):
445
+ raise WorkerError(f"cached prompt .pt file not found: {pt_path}")
446
+ clean_text = text.replace("\u2019", "'").strip()
447
+ cached_prompt = _load_cached_prompt(pt_path, device, torch)
448
+ raw_inputs = processor.process_input_with_cached_prompt(
449
+ text=clean_text,
450
+ cached_prompt=cached_prompt,
451
+ padding=True,
452
+ return_tensors="pt",
453
+ return_attention_mask=True,
454
+ )
455
+ extra_generate_kwargs["all_prefilled_outputs"] = copy.deepcopy(cached_prompt)
456
+ else:
457
+ script = format_speaker_script(text)
458
+ raw_inputs = processor(
459
+ text=[script],
460
+ voice_samples=None,
461
+ padding=True,
462
+ return_tensors="pt",
463
+ return_attention_mask=True,
464
+ )
465
+
466
+ inputs = _move_tensors_to_device(dict(raw_inputs), device, torch)
467
+ with contextlib.redirect_stdout(sys.stderr):
468
+ outputs = model.generate(
469
+ **inputs,
470
+ max_new_tokens=None,
471
+ cfg_scale=cfg_scale,
472
+ tokenizer=processor.tokenizer,
473
+ generation_config={"do_sample": False},
474
+ **extra_generate_kwargs,
475
+ )
476
+
477
+ waveform = extract_waveform(outputs)
478
+ pcm = to_pcm16(waveform)
479
+ sample_rate = state["sample_rate"]
480
+ write_pcm16_wav(dest, pcm, sample_rate)
481
+ duration = len(pcm) / 2 / sample_rate
482
+ return {
483
+ "ok": True,
484
+ "duration": duration,
485
+ "wav_path": dest,
486
+ "sample_rate": sample_rate,
487
+ "model": {"path": state["path"], "revision": state["revision"], "package": state["package"]},
488
+ }
489
+
490
+
491
+ def _respond(stdout: io.TextIOBase, request_id: object, payload: dict) -> None:
492
+ message = {"id": request_id, **payload}
493
+ stdout.write(json.dumps(message) + "\n")
494
+ stdout.flush()
495
+
496
+
497
+ def _handle(state: dict, environ: dict[str, str], request: dict) -> dict:
498
+ op = request.get("op")
499
+ if op == "health":
500
+ backend = state.get("backend")
501
+ if backend is None:
502
+ load_registry(environ)
503
+ backend = load_backend(environ)
504
+ state["backend"] = backend
505
+ return {
506
+ "ok": True,
507
+ "sample_rate": backend["sample_rate"],
508
+ "model": {
509
+ "path": backend["path"],
510
+ "revision": backend["revision"],
511
+ "package": backend["package"],
512
+ },
513
+ }
514
+ if op == "render":
515
+ backend = state.get("backend")
516
+ if backend is None:
517
+ raise WorkerError("render before health; the model is not loaded")
518
+ return _render(backend, request)
519
+ raise WorkerError(f"unsupported op {op!r}")
520
+
521
+
522
+ def isolate_protocol_stdout() -> io.TextIOBase:
523
+ """Point fd 1 at stderr so a native library writing to fd 1 cannot corrupt the NDJSON
524
+ channel, and return the real protocol stream (the saved original fd 1)."""
525
+ saved = os.dup(1)
526
+ os.dup2(2, 1)
527
+ return os.fdopen(saved, "w", encoding="utf-8", newline="\n")
528
+
529
+
530
+ def main(
531
+ argv: list[str] | None = None,
532
+ environ: dict[str, str] | None = None,
533
+ protocol_stdout: io.TextIOBase | None = None,
534
+ ) -> int:
535
+ del argv
536
+ env = environ if environ is not None else dict(os.environ)
537
+ stdout = protocol_stdout if protocol_stdout is not None else sys.stdout
538
+ state: dict = {}
539
+ for raw in sys.stdin:
540
+ line = raw.rstrip("\n")
541
+ if not line.strip():
542
+ continue
543
+ if len(line.encode("utf-8")) > LINE_MAX_BYTES:
544
+ _respond(stdout, None, {"ok": False, "error": "request frame exceeds 1 MiB"})
545
+ return 1
546
+ try:
547
+ request = json.loads(line)
548
+ if not isinstance(request, dict) or not isinstance(request.get("id"), int):
549
+ raise WorkerError("request must carry an integer id")
550
+ except (json.JSONDecodeError, WorkerError) as err:
551
+ _respond(stdout, None, {"ok": False, "error": f"malformed request: {err}"})
552
+ continue
553
+ try:
554
+ payload = _handle(state, env, request)
555
+ except WorkerError as err:
556
+ _respond(stdout, request.get("id"), {"ok": False, "error": str(err)})
557
+ continue
558
+ except Exception as err: # noqa: BLE001 - surface any backend failure actionably
559
+ _respond(stdout, request.get("id"), {"ok": False, "error": f"{type(err).__name__}: {err}"})
560
+ continue
561
+ _respond(stdout, request.get("id"), payload)
562
+ return 0
563
+
564
+
565
+ if __name__ == "__main__":
566
+ raise SystemExit(main(protocol_stdout=isolate_protocol_stdout()))