decklight 0.1.0 → 0.3.0

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 (139) hide show
  1. package/LICENSE +202 -21
  2. package/README.md +105 -183
  3. package/SPEC.md +861 -74
  4. package/cli/agents.mjs +206 -0
  5. package/cli/associate.mjs +279 -0
  6. package/cli/audit.mjs +424 -0
  7. package/cli/bundle.mjs +210 -45
  8. package/cli/deckfile.mjs +233 -0
  9. package/cli/decklight.mjs +216 -5
  10. package/cli/dev.mjs +455 -0
  11. package/cli/edit.mjs +733 -63
  12. package/cli/extension.mjs +108 -0
  13. package/cli/git.mjs +141 -0
  14. package/cli/import.mjs +398 -0
  15. package/cli/init.mjs +465 -121
  16. package/cli/loader.mjs +263 -0
  17. package/cli/marketplace.mjs +730 -0
  18. package/cli/pdf.mjs +156 -0
  19. package/cli/pkg.mjs +69 -0
  20. package/cli/plugin.mjs +646 -0
  21. package/cli/port-conflict.mjs +94 -0
  22. package/cli/present.mjs +560 -0
  23. package/cli/publish.mjs +342 -0
  24. package/cli/qr.mjs +334 -0
  25. package/cli/rec.mjs +12 -8
  26. package/cli/remote.mjs +149 -0
  27. package/cli/report-bug.mjs +97 -0
  28. package/cli/restore.mjs +174 -0
  29. package/cli/serve.mjs +247 -0
  30. package/cli/sign.mjs +216 -0
  31. package/cli/skill-content.mjs +222 -0
  32. package/cli/skills.mjs +338 -0
  33. package/cli/supervise.mjs +57 -0
  34. package/cli/theme.mjs +201 -0
  35. package/cli/units.mjs +488 -0
  36. package/cli/upgrade.mjs +250 -0
  37. package/cli/util.mjs +90 -0
  38. package/cli/wizard.mjs +432 -0
  39. package/cli/zip.mjs +121 -0
  40. package/dist/decklight.css +949 -72
  41. package/dist/decklight.js +220 -103
  42. package/dist/decklight.js.map +4 -4
  43. package/docs/architecture.svg +1 -1
  44. package/package.json +9 -6
  45. package/themes/README.md +6 -4
  46. package/themes/aurora.css +4 -1
  47. package/themes/berry.css +4 -1
  48. package/themes/carbon.css +4 -1
  49. package/themes/citrus.css +4 -1
  50. package/themes/coastal.css +4 -1
  51. package/themes/cosmos.css +4 -1
  52. package/themes/dune.css +4 -1
  53. package/themes/eclipse.css +4 -1
  54. package/themes/ember.css +4 -1
  55. package/themes/fjord.css +4 -1
  56. package/themes/gallery.html +3 -11
  57. package/themes/glacier.css +4 -1
  58. package/themes/graphite.css +4 -1
  59. package/themes/harvest.css +4 -1
  60. package/themes/ibm-modern.css +4 -1
  61. package/themes/ink.css +4 -1
  62. package/themes/latte.css +4 -1
  63. package/themes/linen.css +4 -1
  64. package/themes/meadow.css +4 -1
  65. package/themes/metropolis.css +4 -1
  66. package/themes/midnight.css +4 -1
  67. package/themes/mint.css +4 -1
  68. package/themes/moss.css +4 -1
  69. package/themes/obsidian.css +4 -1
  70. package/themes/orchid.css +4 -1
  71. package/themes/packs.json +4 -31
  72. package/themes/paper.css +4 -1
  73. package/themes/peony.css +4 -1
  74. package/themes/porcelain.css +4 -1
  75. package/themes/reveal-beige.css +4 -1
  76. package/themes/reveal-black.css +4 -1
  77. package/themes/reveal-blood.css +4 -1
  78. package/themes/reveal-dracula.css +4 -1
  79. package/themes/reveal-league.css +4 -1
  80. package/themes/reveal-moon.css +4 -1
  81. package/themes/reveal-night.css +4 -1
  82. package/themes/reveal-serif.css +4 -1
  83. package/themes/reveal-simple.css +4 -1
  84. package/themes/reveal-sky.css +4 -1
  85. package/themes/reveal-solarized.css +4 -1
  86. package/themes/reveal-white.css +4 -1
  87. package/themes/sepia.css +4 -1
  88. package/themes/seriph.css +4 -1
  89. package/themes/slate.css +4 -1
  90. package/themes/storm.css +4 -1
  91. package/themes/synthwave.css +4 -1
  92. package/themes/velvet.css +4 -1
  93. package/themes/yamabuki.css +120 -0
  94. package/tools/args.mjs +32 -0
  95. package/tools/bridge.mjs +30 -0
  96. package/tools/chrome.mjs +52 -0
  97. package/tools/color.mjs +110 -0
  98. package/tools/deck-html.mjs +138 -0
  99. package/tools/elevenlabs-tts.mjs +248 -0
  100. package/tools/escape.mjs +40 -0
  101. package/tools/extension-check-runner.mjs +41 -0
  102. package/tools/extension-check.mjs +266 -0
  103. package/tools/gemini-tts.mjs +44 -4
  104. package/tools/lipsync-engines.mjs +81 -0
  105. package/tools/lipsync-server.mjs +290 -0
  106. package/tools/lipsync.mjs +181 -0
  107. package/tools/local-voice.mjs +209 -0
  108. package/tools/ooxml.mjs +151 -0
  109. package/tools/pptx.mjs +320 -0
  110. package/tools/publish-site-voices.mjs +5 -1
  111. package/tools/publish-targets.mjs +143 -0
  112. package/tools/publish-voices.mjs +230 -0
  113. package/tools/shot.mjs +129 -0
  114. package/tools/theme-check.mjs +139 -0
  115. package/tools/tts-engines.mjs +455 -0
  116. package/tools/tts-setup.mjs +257 -0
  117. package/tools/veo.mjs +204 -0
  118. package/tools/video.mjs +316 -0
  119. package/tools/visemes.mjs +26 -0
  120. package/tools/voiceover-server.mjs +0 -0
  121. package/tools/voiceover.mjs +73 -39
  122. package/tools/zip.mjs +143 -0
  123. package/docs/demo.svg +0 -124
  124. package/themes/aliens.css +0 -84
  125. package/themes/apple2.css +0 -126
  126. package/themes/blade-runner.css +0 -83
  127. package/themes/c64.css +0 -85
  128. package/themes/friends.css +0 -82
  129. package/themes/gameboy.css +0 -118
  130. package/themes/genesis.css +0 -84
  131. package/themes/godfather.css +0 -82
  132. package/themes/ibm-oldschool.css +0 -84
  133. package/themes/miami-vice.css +0 -84
  134. package/themes/pulp-fiction.css +0 -84
  135. package/themes/severance.css +0 -82
  136. package/themes/snes.css +0 -82
  137. package/themes/star-wars.css +0 -85
  138. package/themes/stranger-things.css +0 -84
  139. package/themes/terminator.css +0 -84
@@ -0,0 +1,290 @@
1
+ #!/usr/bin/env node
2
+ // Lip-sync bridge: a tiny local HTTP server the player calls to turn
3
+ // narration audio into lip-sync data for the character overlay (SPEC PRESENTING).
4
+ // Everything runs on THIS machine — Rhubarb Lip Sync for viseme timelines,
5
+ // Wav2Lip / SadTalker (local python repos, your GPU) for talking-head video.
6
+ // No cloud service is involved; the browser just can't spawn native
7
+ // processes, so this bridge does, exactly like `decklight tts` holds the
8
+ // Google credentials the browser can't.
9
+ //
10
+ // GET /ping → { ok, engines: { viseme, video: [names] }, portraits }
11
+ // POST /viseme?text=<transcript> (body: audio/wav)
12
+ // → viseme timeline JSON v1 (tools/visemes.mjs)
13
+ // POST /video?engine=wav2lip&portrait=<name> (body: audio/wav)
14
+ // → video/mp4 (muted talking head)
15
+ //
16
+ // decklight lipsync [--port 8789] [--rhubarb <bin>]
17
+ // [--portrait <name=img.png>]… (first one is 'default')
18
+ // [--wav2lip-dir <repo> --wav2lip-ckpt <pth>]
19
+ // [--sadtalker-dir <repo>] [--python <bin>]
20
+ // [--cache-dir ~/.cache/decklight/lipsync]
21
+ //
22
+ // Rhubarb: https://github.com/DanielSWolf/rhubarb-lip-sync — one static
23
+ // binary, ~0.1× real-time. The transcript (?text=) markedly improves cue
24
+ // accuracy, so the player always sends it. Wav2Lip suits LIVE mode (static
25
+ // pose → seamless per-sentence cuts, near real-time on a decent GPU);
26
+ // SadTalker suits BATCH clips (tools/lipsync.mjs) — minutes per clip.
27
+ //
28
+ // CORS is wide open (decks run on file://, origin "null") — the server binds
29
+ // 127.0.0.1 only. Results are cached ON DISK keyed by a hash of (audio,
30
+ // route, params): restarts keep the cache, so a replayed deck costs nothing
31
+ // and the player's 10-sentence lookahead only ever pays for new sentences.
32
+
33
+ import { createServer } from 'node:http';
34
+ import { createHash } from 'node:crypto';
35
+ import { execFile } from 'node:child_process';
36
+ import { mkdirSync, existsSync, readFileSync, writeFileSync, rmSync, statSync, copyFileSync } from 'node:fs';
37
+ import { join, resolve, basename } from 'node:path';
38
+ import { homedir } from 'node:os';
39
+ import { promisify } from 'node:util';
40
+ import { createVeo, DEFAULT_PROMPT, VEO_MODELS } from './veo.mjs';
41
+ import { argReader, isMain } from './args.mjs';
42
+ import { runRhubarb, runWav2lip, runSadtalker, muteFaststart } from './lipsync-engines.mjs';
43
+ import { corsHeaders, readBody } from './bridge.mjs';
44
+
45
+ const run = promisify(execFile);
46
+
47
+ // width-limited job queue: rhubarb gets 2 lanes, the GPU exactly 1 — a burst
48
+ // of lookahead prefetches must never launch parallel model runs
49
+ function makeQueue(width) {
50
+ let active = 0;
51
+ const waiting = [];
52
+ const next = () => {
53
+ if (active >= width || !waiting.length) return;
54
+ active++;
55
+ const { fn, res, rej } = waiting.shift();
56
+ fn().then(res, rej).finally(() => { active--; next(); });
57
+ };
58
+ return (fn) => new Promise((res, rej) => { waiting.push({ fn, res, rej }); next(); });
59
+ }
60
+
61
+ export async function lipsyncMain(args) {
62
+ if (args.includes('--help')) {
63
+ console.log(`usage: decklight lipsync [--port 8789] [--rhubarb <bin>]
64
+ [--portrait <name=img.png>]... portraits offered for video mode (first = default)
65
+ [--wav2lip-dir <repo> --wav2lip-ckpt <checkpoint.pth>]
66
+ [--sadtalker-dir <repo>] [--python python3]
67
+ [--cache-dir ~/.cache/decklight/lipsync]
68
+ [--veo] [--veo-project <id>] [--veo-model veo-3.1-lite-generate-001]
69
+ [--veo-seconds 4|6|8] [--veo-prompt "..."] [--veo-location us-central1]
70
+ [--veo-face-y 0.12] where the square crop starts, as a fraction of height
71
+
72
+ Viseme timelines need rhubarb on PATH (or --rhubarb):
73
+ https://github.com/DanielSWolf/rhubarb-lip-sync
74
+ Talking-head video needs a local Wav2Lip and/or SadTalker checkout, a GPU,
75
+ and at least one --portrait. Everything runs offline on this machine.
76
+
77
+ --veo is the exception, and the only thing here that leaves the machine: it
78
+ animates each portrait ONCE through Veo on Vertex AI (head turns, blinks,
79
+ shoulders) and hands Wav2Lip that clip instead of the still, so the narrator
80
+ moves like a person instead of staring. One billed call per portrait, cached
81
+ in --cache-dir forever; the per-sentence lip-sync stays local on your GPU.
82
+ Give it a HEAD-AND-SHOULDERS portrait (3:4 or taller). The clip is cropped
83
+ square around the head for the deck's circular overlay, and a tight square
84
+ photo puts the face lower in Veo's 9:16 frame — chin off the bottom. Nudge
85
+ --veo-face-y up (~0.22) for such a portrait, or feed it one with headroom.`);
86
+ return;
87
+ }
88
+ const { opt, opts } = argReader(args);
89
+ const port = Number(opt('--port', 8789));
90
+ const rhubarb = opt('--rhubarb', 'rhubarb');
91
+ const python = opt('--python', 'python3');
92
+ const wav2lipDir = opt('--wav2lip-dir');
93
+ const wav2lipCkpt = opt('--wav2lip-ckpt');
94
+ const sadtalkerDir = opt('--sadtalker-dir');
95
+ const cacheDir = resolve(opt('--cache-dir', join(homedir(), '.cache', 'decklight', 'lipsync')));
96
+ mkdirSync(cacheDir, { recursive: true });
97
+
98
+ // Veo: the portrait's MOTION, bought once (tools/veo.mjs). Only wav2lip can
99
+ // use it — SadTalker animates the head itself and wants a still.
100
+ const veoOn = args.includes('--veo');
101
+ let veo = null;
102
+ if (veoOn) {
103
+ try {
104
+ veo = createVeo({
105
+ project: opt('--veo-project', process.env.GOOGLE_CLOUD_PROJECT),
106
+ location: opt('--veo-location', 'us-central1'),
107
+ model: opt('--veo-model', VEO_MODELS[0]),
108
+ seconds: Number(opt('--veo-seconds', 8)),
109
+ prompt: opt('--veo-prompt', DEFAULT_PROMPT),
110
+ faceY: Number(opt('--veo-face-y', 0.12)),
111
+ cacheDir,
112
+ });
113
+ } catch (e) {
114
+ // A misconfigured --veo must not cost you the whole bridge: visemes and
115
+ // still-portrait video still work, so say what broke and carry on.
116
+ console.error(`veo disabled — ${e.message}`);
117
+ veo = null;
118
+ }
119
+ }
120
+
121
+ // portraits: --portrait alice=face.png (or a bare path — named by basename)
122
+ const portraits = new Map();
123
+ for (const p of opts('--portrait')) {
124
+ if (!p) continue;
125
+ const eq = p.indexOf('=');
126
+ const name = eq > 0 ? p.slice(0, eq) : basename(p).replace(/\.[^.]+$/, '');
127
+ const file = resolve(eq > 0 ? p.slice(eq + 1) : p);
128
+ if (!existsSync(file)) { console.error(`portrait not found: ${file}`); process.exitCode = 1; return; }
129
+ if (!portraits.size) portraits.set('default', file); // first doubles as 'default'
130
+ portraits.set(name, file);
131
+ }
132
+
133
+ const has = async (bin, flags = ['--version']) => {
134
+ try { await run(bin, flags); return true; } catch (e) { return e?.code !== 'ENOENT'; }
135
+ };
136
+ const visemeOk = await has(rhubarb);
137
+ const ffmpegOk = await has('ffmpeg', ['-version']);
138
+ const videoEngines = [];
139
+ if (wav2lipDir && wav2lipCkpt && existsSync(join(wav2lipDir, 'inference.py')) && existsSync(wav2lipCkpt) && portraits.size) videoEngines.push('wav2lip');
140
+ if (sadtalkerDir && existsSync(join(sadtalkerDir, 'inference.py')) && portraits.size) videoEngines.push('sadtalker');
141
+ if (!visemeOk && !videoEngines.length) {
142
+ console.error(`neither engine is usable:
143
+ visemes — rhubarb not found (install it, or pass --rhubarb <bin>)
144
+ video — needs --wav2lip-dir/--wav2lip-ckpt or --sadtalker-dir, plus --portrait`);
145
+ process.exitCode = 1;
146
+ return;
147
+ }
148
+
149
+ const rhubarbQ = makeQueue(2);
150
+ const gpuQ = makeQueue(1);
151
+ const inflight = new Map(); // cache key → promise, dedups concurrent misses
152
+ const dedup = (key, fn) => {
153
+ if (!inflight.has(key)) {
154
+ const p = fn().finally(() => inflight.delete(key));
155
+ inflight.set(key, p);
156
+ }
157
+ return inflight.get(key);
158
+ };
159
+ const sha = (...parts) => {
160
+ const h = createHash('sha256');
161
+ for (const p of parts) h.update(p);
162
+ return h.digest('hex').slice(0, 32);
163
+ };
164
+
165
+ async function visemes(wav, text) {
166
+ const key = sha('viseme|', text, '|', wav);
167
+ const out = join(cacheDir, `${key}.json`);
168
+ if (existsSync(out)) return { body: readFileSync(out), cached: true };
169
+ await dedup(key, () => rhubarbQ(async () => {
170
+ if (existsSync(out)) return;
171
+ const tmpWav = join(cacheDir, `${key}.tmp.wav`);
172
+ const tmpTxt = join(cacheDir, `${key}.tmp.txt`);
173
+ const tmpOut = join(cacheDir, `${key}.tmp.json`);
174
+ writeFileSync(tmpWav, wav);
175
+ if (text.trim()) writeFileSync(tmpTxt, text);
176
+ try {
177
+ const t0 = Date.now();
178
+ const tl = await runRhubarb(rhubarb, { wav: tmpWav, dialogFile: text.trim() ? tmpTxt : undefined, out: tmpOut, timeout: 120000 });
179
+ writeFileSync(out, JSON.stringify(tl));
180
+ console.log(` viseme: ${(wav.length / 1024).toFixed(0)} KB wav → ${tl.cues.length} cues · ${((Date.now() - t0) / 1000).toFixed(1)}s`);
181
+ } finally {
182
+ for (const f of [tmpWav, tmpTxt, tmpOut]) rmSync(f, { force: true });
183
+ }
184
+ }));
185
+ return { body: readFileSync(out), cached: false };
186
+ }
187
+
188
+ async function video(wav, engine, portraitName) {
189
+ if (!videoEngines.includes(engine)) throw new Error(`engine '${engine}' not available`);
190
+ const still = portraits.get(portraitName);
191
+ if (!still) throw new Error(`unknown portrait '${portraitName}'`);
192
+ // With --veo, wav2lip's source is the portrait's motion clip rather than the
193
+ // portrait: same model, same per-sentence cost, but the head is alive under
194
+ // the new mouth. Bought once per portrait and cached (tools/veo.mjs), so
195
+ // this awaits a network call only the very first time. SadTalker is left
196
+ // alone — it makes its own head motion and needs the still.
197
+ const face = veo && engine === 'wav2lip' ? await veo.motionFor(still) : still;
198
+ // the key reads `face`, so a veo clip and a still can never share a cache
199
+ // entry — flip --veo off and yesterday's clips are still there, untouched
200
+ const key = sha('video|', engine, '|', readFileSync(face), '|', wav);
201
+ const out = join(cacheDir, `${key}.mp4`);
202
+ if (existsSync(out)) return { body: readFileSync(out), cached: true };
203
+ await dedup(key, () => gpuQ(async () => {
204
+ if (existsSync(out)) return;
205
+ const tmpWav = join(cacheDir, `${key}.tmp.wav`);
206
+ const tmpMp4 = join(cacheDir, `${key}.tmp.mp4`);
207
+ const tmpDir = join(cacheDir, `${key}.tmp.d`);
208
+ writeFileSync(tmpWav, wav);
209
+ try {
210
+ const t0 = Date.now();
211
+ process.stdout.write(` video ${engine} · ${portraitName}: ${(wav.length / 1024).toFixed(0)} KB wav … `);
212
+ if (engine === 'wav2lip') {
213
+ // A still is ONE frame to detect a face in; a --veo motion clip is a
214
+ // couple of hundred. Wav2Lip's face detector batches 16 frames by
215
+ // default, halving on CUDA OOM until it gives up at 1 with "Image too
216
+ // big to run face detection on GPU" — which it will do on an 8 GB card
217
+ // that a desktop is already using half of. Batch small instead: the
218
+ // clip is short, and the GPU queue is serial anyway.
219
+ await runWav2lip(python, { dir: wav2lipDir, checkpoint: wav2lipCkpt, face,
220
+ wav: tmpWav, out: tmpMp4, smallBatches: face !== still, timeout: 600000 });
221
+ } else {
222
+ // SadTalker writes <timestamp>/….mp4 into result_dir — runSadtalker
223
+ // takes the newest and moves it to tmpMp4.
224
+ await runSadtalker(python, { dir: sadtalkerDir, still: face,
225
+ wav: tmpWav, out: tmpMp4, resultDir: tmpDir, timeout: 1800000 });
226
+ }
227
+ // strip the audio track (playback is muted — narrAudio is the voice)
228
+ // and front-load the moov atom so the player can start instantly
229
+ if (ffmpegOk) await muteFaststart(tmpMp4, out, { timeout: 120000 });
230
+ else copyFileSync(tmpMp4, out);
231
+ console.log(`${((Date.now() - t0) / 1000).toFixed(1)}s → ${(statSync(out).size / 1024).toFixed(0)} KB`);
232
+ } finally {
233
+ for (const f of [tmpWav, tmpMp4]) rmSync(f, { force: true });
234
+ rmSync(tmpDir, { recursive: true, force: true });
235
+ }
236
+ }));
237
+ return { body: readFileSync(out), cached: false };
238
+ }
239
+
240
+ const CORS = corsHeaders('x-lipsync-cached');
241
+
242
+ const server = createServer(async (req, res) => {
243
+ if (req.method === 'OPTIONS') { res.writeHead(204, CORS); return res.end(); }
244
+ const url = new URL(req.url, 'http://localhost');
245
+ if (req.method === 'GET' && url.pathname === '/ping') {
246
+ res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
247
+ return res.end(JSON.stringify({
248
+ ok: true,
249
+ engines: { viseme: visemeOk, video: videoEngines },
250
+ // what the head is driven from: a veo motion clip, or the still photo
251
+ motion: veo ? { engine: 'veo', model: veo.model, seconds: veo.seconds } : null,
252
+ portraits: [...portraits.keys()],
253
+ }));
254
+ }
255
+ if (req.method === 'POST' && (url.pathname === '/viseme' || url.pathname === '/video')) {
256
+ try {
257
+ const wav = await readBody(req);
258
+ if (wav.length < 44) { res.writeHead(400, CORS); return res.end('no audio'); }
259
+ const out = url.pathname === '/viseme'
260
+ ? await visemes(wav, url.searchParams.get('text') ?? '')
261
+ : await video(wav, url.searchParams.get('engine') ?? 'wav2lip', url.searchParams.get('portrait') ?? 'default');
262
+ res.writeHead(200, {
263
+ ...CORS,
264
+ 'content-type': url.pathname === '/viseme' ? 'application/json' : 'video/mp4',
265
+ 'x-lipsync-cached': out.cached ? '1' : '0',
266
+ });
267
+ return res.end(out.body);
268
+ } catch (e) {
269
+ console.error(` ${url.pathname.slice(1)} error: ${String(e).slice(0, 160)}`);
270
+ if (!res.headersSent) res.writeHead(502, CORS);
271
+ return res.end(String(e));
272
+ }
273
+ }
274
+ res.writeHead(404, CORS);
275
+ res.end();
276
+ });
277
+
278
+ server.listen(port, '127.0.0.1', () => {
279
+ const what = [visemeOk && 'visemes (rhubarb)', ...videoEngines.map((e) => `video (${e})`)].filter(Boolean).join(' · ');
280
+ console.log(`decklight lipsync bridge on http://127.0.0.1:${port} — ${what} — Ctrl-C stops`);
281
+ if (veo) {
282
+ console.log(`veo: ${veo.model} · ${veo.seconds}s — each portrait is animated ONCE (billed), `
283
+ + 'then wav2lip re-syncs that clip locally for every sentence');
284
+ }
285
+ console.log(`cache: ${cacheDir}`);
286
+ });
287
+ return server;
288
+ }
289
+
290
+ if (isMain(import.meta.url)) lipsyncMain(process.argv.slice(2));
@@ -0,0 +1,181 @@
1
+ #!/usr/bin/env node
2
+ // Lip-sync generator for RECORDED narration: sidecar files for every
3
+ // slide-NN audio clip in a voiceover directory (tools/voiceover.mjs or a
4
+ // ⇧V-recorded set), so a deck plays back with an animated character and no
5
+ // bridge running. Fully offline, like everything else here.
6
+ //
7
+ // node tools/lipsync.mjs <voiceover-dir> [--visemes] [--video]
8
+ // [--rhubarb <bin>]
9
+ // [--engine sadtalker|wav2lip] [--portrait <img>]
10
+ // [--wav2lip-dir <repo> --wav2lip-ckpt <pth>]
11
+ // [--sadtalker-dir <repo>] [--python python3]
12
+ //
13
+ // Outputs, next to the audio they belong to (config: narration.files dir):
14
+ // --visemes (default) — slide-NN.visemes.json (timeline v1, via Rhubarb)
15
+ // --video — slide-NN.mp4 (muted talking head)
16
+ //
17
+ // Rhubarb wants WAV: slide-NN.wav is used when present (voiceover.mjs
18
+ // --keep-wav, or a ⇧V set); otherwise the .m4a is decoded on the fly with
19
+ // ffmpeg (afconvert fallback on macOS). The transcript slide-NN.txt, when
20
+ // present, markedly improves cue accuracy. For batch video SadTalker is the
21
+ // default engine — per-slide clips are long enough that its natural head
22
+ // motion beats Wav2Lip's static pose (live mode is the reverse).
23
+ //
24
+ // Incremental like voiceover.mjs: lipsync.json stores a hash of
25
+ // (audio bytes, tool, engine, portrait) per slide, persisted after every
26
+ // slide, so a rerun only regenerates what actually changed.
27
+
28
+ import { readFileSync, writeFileSync, existsSync, readdirSync, rmSync, renameSync } from 'node:fs';
29
+ import { createHash } from 'node:crypto';
30
+ import { execFileSync } from 'node:child_process';
31
+ import { resolve, join, basename } from 'node:path';
32
+ import { createVeo, DEFAULT_PROMPT, VEO_MODELS } from './veo.mjs';
33
+ import { argReader } from './args.mjs';
34
+ import { runRhubarb, runWav2lip, runSadtalker, muteFaststart } from './lipsync-engines.mjs';
35
+
36
+ const args = process.argv.slice(2);
37
+ const dirArg = args.find((a) => !a.startsWith('-'));
38
+ if (!dirArg || args.includes('--help')) {
39
+ console.error('usage: lipsync.mjs <voiceover-dir> [--visemes] [--video] [--rhubarb bin]\n'
40
+ + ' [--engine sadtalker|wav2lip] [--portrait img]\n'
41
+ + ' [--wav2lip-dir repo --wav2lip-ckpt pth] [--sadtalker-dir repo] [--python bin]');
42
+ process.exit(dirArg ? 0 : 1);
43
+ }
44
+ const dir = resolve(dirArg);
45
+ const { opt } = argReader(args);
46
+ const doVideo = args.includes('--video');
47
+ const doVisemes = args.includes('--visemes') || !doVideo; // visemes by default
48
+ const rhubarb = opt('--rhubarb', 'rhubarb');
49
+ const engine = opt('--engine', 'sadtalker');
50
+ const portrait = opt('--portrait') && resolve(opt('--portrait'));
51
+ const wav2lipDir = opt('--wav2lip-dir');
52
+ const wav2lipCkpt = opt('--wav2lip-ckpt');
53
+ const sadtalkerDir = opt('--sadtalker-dir');
54
+ const python = opt('--python', 'python3');
55
+ // --veo: animate the portrait ONCE through Vertex (tools/veo.mjs) and give
56
+ // wav2lip that clip instead of the still, so the recorded narrator moves
57
+ // instead of staring. One billed call per portrait, cached next to the audio.
58
+ const veoOn = args.includes('--veo');
59
+
60
+ const veo = veoOn ? createVeo({
61
+ project: opt('--veo-project', process.env.GOOGLE_CLOUD_PROJECT),
62
+ location: opt('--veo-location', 'us-central1'),
63
+ model: opt('--veo-model', VEO_MODELS[0]),
64
+ seconds: Number(opt('--veo-seconds', 8)),
65
+ prompt: opt('--veo-prompt', DEFAULT_PROMPT),
66
+ faceY: Number(opt('--veo-face-y', 0.12)),
67
+ cacheDir: dir,
68
+ }) : null;
69
+
70
+ const have = (bin, flags = ['--version']) => {
71
+ try { execFileSync(bin, flags, { stdio: 'ignore' }); return true; } catch (e) { return e?.code !== 'ENOENT'; }
72
+ };
73
+ if (doVisemes && !have(rhubarb)) {
74
+ console.error(`rhubarb not found — install https://github.com/DanielSWolf/rhubarb-lip-sync or pass --rhubarb <bin>`);
75
+ process.exit(1);
76
+ }
77
+ if (doVideo) {
78
+ if (!portrait || !existsSync(portrait)) { console.error('--video needs --portrait <image>'); process.exit(1); }
79
+ if (engine === 'wav2lip' && !(wav2lipDir && wav2lipCkpt)) { console.error('--engine wav2lip needs --wav2lip-dir and --wav2lip-ckpt'); process.exit(1); }
80
+ if (engine === 'sadtalker' && !sadtalkerDir) { console.error('--engine sadtalker needs --sadtalker-dir'); process.exit(1); }
81
+ }
82
+ const ffmpegOk = have('ffmpeg', ['-version']);
83
+
84
+ // every slide-NN with audio, wav preferred over m4a
85
+ const slides = [...new Set(readdirSync(dir)
86
+ .map((f) => f.match(/^slide-(\d+)\.(wav|m4a)$/)?.[1])
87
+ .filter(Boolean))].sort();
88
+ if (!slides.length) { console.error(`${dir}: no slide-NN.wav/.m4a files`); process.exit(1); }
89
+ console.log(`${basename(dir)}: ${slides.length} slides with audio`);
90
+
91
+ // incremental state — its own file so voiceover.mjs reruns can't clobber it
92
+ const statePath = join(dir, 'lipsync.json');
93
+ let state = {};
94
+ try { state = JSON.parse(readFileSync(statePath, 'utf8')); } catch { /* first run */ }
95
+
96
+ const sha = (...parts) => {
97
+ const h = createHash('sha256');
98
+ for (const p of parts) h.update(p);
99
+ return h.digest('hex').slice(0, 16);
100
+ };
101
+
102
+ function toWav(nn) {
103
+ const wav = join(dir, `slide-${nn}.wav`);
104
+ if (existsSync(wav)) return { path: wav, tmp: false };
105
+ const m4a = join(dir, `slide-${nn}.m4a`);
106
+ const tmp = join(dir, `slide-${nn}.tmp.wav`);
107
+ if (ffmpegOk) execFileSync('ffmpeg', ['-y', '-i', m4a, tmp], { stdio: 'ignore' });
108
+ else execFileSync('afconvert', ['-f', 'WAVE', '-d', 'LEI16', m4a, tmp]);
109
+ return { path: tmp, tmp: true };
110
+ }
111
+
112
+ // One portrait → one motion clip → every slide. Bought before the loop so the
113
+ // cost is one call, not one per slide, and so a failure stops us before any
114
+ // GPU time is spent.
115
+ const face = veo && engine === 'wav2lip' ? await veo.motionFor(portrait) : portrait;
116
+
117
+ let made = 0, kept = 0;
118
+ for (const nn of slides) {
119
+ const audioFile = ['wav', 'm4a'].map((e) => join(dir, `slide-${nn}.${e}`)).find(existsSync);
120
+ const audioBytes = readFileSync(audioFile);
121
+ const txtPath = join(dir, `slide-${nn}.txt`);
122
+ const text = existsSync(txtPath) ? readFileSync(txtPath, 'utf8').trim() : '';
123
+ const st = (state[nn] ??= {});
124
+ const jobs = [];
125
+ if (doVisemes) jobs.push('visemes');
126
+ if (doVideo) jobs.push('video');
127
+
128
+ for (const job of jobs) {
129
+ const outFile = join(dir, job === 'visemes' ? `slide-${nn}.visemes.json` : `slide-${nn}.mp4`);
130
+ const hash = job === 'visemes'
131
+ ? sha('visemes|', text, '|', audioBytes)
132
+ : sha('video|', engine, '|', readFileSync(face), '|', audioBytes); // `face`, so --veo re-renders
133
+ if (st[job] === hash && existsSync(outFile)) {
134
+ kept++;
135
+ console.log(` slide ${nn}: ${job} unchanged — kept`);
136
+ continue;
137
+ }
138
+ const wav = toWav(nn);
139
+ try {
140
+ const t0 = Date.now();
141
+ if (job === 'visemes') {
142
+ const tmpOut = join(dir, `slide-${nn}.tmp.visemes.json`);
143
+ let dialogFile;
144
+ if (text) { dialogFile = join(dir, `slide-${nn}.tmp.txt`); writeFileSync(dialogFile, text); }
145
+ const tl = await runRhubarb(rhubarb, { wav: wav.path, dialogFile, out: tmpOut });
146
+ writeFileSync(outFile, JSON.stringify(tl));
147
+ rmSync(tmpOut, { force: true });
148
+ rmSync(join(dir, `slide-${nn}.tmp.txt`), { force: true });
149
+ console.log(` slide ${nn}: ${tl.cues.length} cues → ${basename(outFile)} · ${((Date.now() - t0) / 1000).toFixed(1)}s`);
150
+ } else {
151
+ const tmpMp4 = join(dir, `slide-${nn}.tmp.mp4`);
152
+ if (engine === 'wav2lip') {
153
+ // a --veo clip is hundreds of frames to detect faces in, not one:
154
+ // batch small or an 8GB card dies with "Image too big to run face
155
+ // detection on GPU" (see lipsync-server.mjs)
156
+ await runWav2lip(python, { dir: wav2lipDir, checkpoint: wav2lipCkpt, face,
157
+ wav: wav.path, out: tmpMp4, smallBatches: face !== portrait, inherit: true });
158
+ } else {
159
+ const resDir = join(dir, `slide-${nn}.tmp.d`);
160
+ await runSadtalker(python, { dir: sadtalkerDir, still: portrait,
161
+ wav: wav.path, out: tmpMp4, resultDir: resDir, inherit: true });
162
+ rmSync(resDir, { recursive: true, force: true });
163
+ }
164
+ // mute + faststart: the player's audio always comes from narrAudio
165
+ if (ffmpegOk) {
166
+ await muteFaststart(tmpMp4, outFile);
167
+ rmSync(tmpMp4, { force: true });
168
+ } else renameSync(tmpMp4, outFile);
169
+ console.log(` slide ${nn}: ${engine} → ${basename(outFile)} · ${((Date.now() - t0) / 1000).toFixed(1)}s`);
170
+ }
171
+ st[job] = hash;
172
+ made++;
173
+ // crash-safe: persist progress after every slide (voiceover.mjs idiom)
174
+ writeFileSync(statePath, JSON.stringify(state, null, 1));
175
+ } finally {
176
+ if (wav.tmp) rmSync(wav.path, { force: true });
177
+ }
178
+ }
179
+ }
180
+ writeFileSync(statePath, JSON.stringify(state, null, 1));
181
+ console.log(`done → ${dir} (${made} generated${kept ? `, ${kept} unchanged` : ''})`);
@@ -0,0 +1,209 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // What can this machine say out loud, without a credential and without a
5
+ // download?
6
+ //
7
+ // Every desktop OS has shipped a speech synthesizer for twenty years, and on
8
+ // current ones they are neural and genuinely good — macOS's Premium and
9
+ // Personal Voices, Windows's mobile/neural SAPI voices. decklight already had
10
+ // a free offline engine (piper), but piper costs a toolchain install and a
11
+ // ~120 MB model download. The voice already on the machine costs nothing.
12
+ //
13
+ // So: look, and only propose piper when there is nothing to find. Everything
14
+ // here is pure over injected `exec`/`platform`, because the whole point is
15
+ // branching on an operating system that CI is not running.
16
+ //
17
+ // Android is detected and REFUSED, deliberately: Termux reports `android` and
18
+ // can run Node, but Android's TextToSpeech is an in-process Java API with no
19
+ // command line behind it, so there is nothing for a bridge to call. Saying so
20
+ // beats a bridge that starts and never speaks.
21
+
22
+ const PIPER_SUGGEST = 'piper is the free offline voice — install it with '
23
+ + '`uv tool install piper-tts`, then run `decklight tts --engine piper`';
24
+
25
+ /** `say -v '?'` on macOS: one voice per line, name, locale, sample sentence. */
26
+ export const SAY_LIST = ['-v', '?'];
27
+
28
+ /**
29
+ * PowerShell, because SAPI is a .NET API and there is no speech CLI on Windows.
30
+ * `-NoProfile` so a slow user profile cannot hang the probe.
31
+ */
32
+ export const SAPI_LIST = [
33
+ '-NoProfile', '-NonInteractive', '-Command',
34
+ 'Add-Type -AssemblyName System.Speech; '
35
+ + '(New-Object System.Speech.Synthesis.SpeechSynthesizer).GetInstalledVoices() '
36
+ + '| ForEach-Object { $_.VoiceInfo.Name }',
37
+ ];
38
+
39
+ /**
40
+ * Rank a macOS voice by how good it is likely to sound.
41
+ *
42
+ * The roster mixes twenty years of engines — 1990s formant voices sit in the
43
+ * same list as this year's neural ones — and picking the first alphabetically
44
+ * means picking Agnes. The parenthesised tier is macOS's own label, and a
45
+ * Personal Voice (the one the user recorded themselves, Apple's
46
+ * accessibility/Apple-Intelligence-era feature) outranks everything.
47
+ */
48
+ export function sayTier(name) {
49
+ if (/\(Personal Voice\)/i.test(name)) return 0;
50
+ if (/\(Premium\)/i.test(name)) return 1;
51
+ if (/\(Neural\)|\(Siri\)/i.test(name)) return 1;
52
+ if (/\(Enhanced\)/i.test(name)) return 2;
53
+ return 3;
54
+ }
55
+
56
+ const TIER_LABEL = ['personal voice', 'premium', 'enhanced', 'built-in'];
57
+
58
+ /**
59
+ * Parse `say -v '?'`.
60
+ *
61
+ * A voice NAME may contain spaces and a parenthesised tier, so the locale — the
62
+ * one token that always looks like `en_US` and always precedes the `#` — is the
63
+ * anchor, not a column position.
64
+ */
65
+ export function parseSayVoices(stdout, { lang } = {}) {
66
+ const out = [];
67
+ for (const line of String(stdout ?? '').split('\n')) {
68
+ const m = /^(.*?)\s{2,}([a-z]{2}(?:[-_][A-Za-z0-9]{2,8})*)\s*#/.exec(line)
69
+ ?? /^(.*?)\s+([a-z]{2}[-_][A-Z]{2})\s+#/.exec(line);
70
+ if (!m) continue;
71
+ const name = m[1].trim();
72
+ if (!name) continue;
73
+ out.push({ name, locale: m[2].replace('-', '_'), tier: sayTier(name) });
74
+ }
75
+ const want = (lang ?? 'en').slice(0, 2).toLowerCase();
76
+ // English (or the asked-for language) first, then by tier: a machine whose
77
+ // best voice speaks Italian should not narrate an English deck with it
78
+ return out.sort((a, b) =>
79
+ (a.locale.startsWith(want) ? 0 : 1) - (b.locale.startsWith(want) ? 0 : 1)
80
+ || a.tier - b.tier
81
+ || a.name.localeCompare(b.name));
82
+ }
83
+
84
+ /** Parse the PowerShell voice list — one name per line. */
85
+ export function parseSapiVoices(stdout) {
86
+ return String(stdout ?? '').split('\n').map((l) => l.trim()).filter(Boolean)
87
+ .map((name) => ({
88
+ name,
89
+ locale: /\b(en|fr|de|es|it|ja|zh|pt|nl|ko|ru)\b/i.exec(name)?.[1]?.toLowerCase() ?? '',
90
+ // Windows names its newer voices "Microsoft Aria Online (Natural)"
91
+ tier: /\bNatural\b/i.test(name) ? 1 : 3,
92
+ }))
93
+ .sort((a, b) => a.tier - b.tier || a.name.localeCompare(b.name));
94
+ }
95
+
96
+ /** The argv that makes macOS speak a line into a WAV file. */
97
+ export const sayArgs = (text, voice, file) => [
98
+ ...(voice ? ['-v', voice] : []),
99
+ // LEI16@24000 is little-endian 16-bit PCM at 24 kHz — the same shape every
100
+ // other engine hands the bridge, so nothing downstream has to care
101
+ '--data-format=LEI16@24000', '-o', file, '--', text,
102
+ ];
103
+
104
+ /** The PowerShell that makes Windows speak a line into a WAV file. */
105
+ export function sapiArgs(text, voice, file) {
106
+ const q = (s) => `'${String(s).replace(/'/g, "''")}'`; // PowerShell escaping
107
+ return ['-NoProfile', '-NonInteractive', '-Command',
108
+ 'Add-Type -AssemblyName System.Speech; '
109
+ + '$s = New-Object System.Speech.Synthesis.SpeechSynthesizer; '
110
+ + (voice ? `$s.SelectVoice(${q(voice)}); ` : '')
111
+ + `$s.SetOutputToWaveFile(${q(file)}); `
112
+ + `$s.Speak(${q(text)}); $s.Dispose()`];
113
+ }
114
+
115
+ /**
116
+ * What this machine can speak with, if anything.
117
+ *
118
+ * Returns `{ engine, voices, label }` when a native synthesizer is available,
119
+ * or `{ engine: null, why, suggest }` when there is none — `why` being the
120
+ * reason THIS machine has none, which differs enough between an Android
121
+ * device, a bare Linux box and a Mac with a broken `say` to be worth saying.
122
+ */
123
+ export function detectLocalVoice({
124
+ platform = process.platform,
125
+ hasBin = () => false,
126
+ exec = () => '',
127
+ lang,
128
+ } = {}) {
129
+ if (platform === 'android') {
130
+ return {
131
+ engine: null,
132
+ why: 'Android has a system voice, but only as an in-app Java API — there is no '
133
+ + 'command line behind it, so nothing here can drive it',
134
+ suggest: 'record the narration on a desktop (decklight tts, then ⇧V) and ship the '
135
+ + 'audio with the deck — a recorded track needs no bridge at all',
136
+ };
137
+ }
138
+
139
+ if (platform === 'darwin' && hasBin('say')) {
140
+ let voices = [];
141
+ try { voices = parseSayVoices(exec('say', SAY_LIST), { lang }); } catch { /* treated as none */ }
142
+ if (voices.length) {
143
+ return {
144
+ engine: 'say', voices,
145
+ label: `macOS ${TIER_LABEL[voices[0].tier]}: ${voices[0].name}`,
146
+ };
147
+ }
148
+ return { engine: null, why: 'macOS `say` is installed but reported no voices', suggest: PIPER_SUGGEST };
149
+ }
150
+
151
+ if (platform === 'win32') {
152
+ const shell = ['powershell.exe', 'pwsh.exe'].find((b) => hasBin(b));
153
+ if (shell) {
154
+ let voices = [];
155
+ try { voices = parseSapiVoices(exec(shell, SAPI_LIST)); } catch { /* treated as none */ }
156
+ if (voices.length) {
157
+ return {
158
+ engine: 'sapi', shell, voices,
159
+ label: `Windows ${voices[0].tier === 1 ? 'natural' : 'built-in'} voice: ${voices[0].name}`,
160
+ };
161
+ }
162
+ }
163
+ return { engine: null, why: 'no SAPI voices are installed on this Windows machine', suggest: PIPER_SUGGEST };
164
+ }
165
+
166
+ return {
167
+ engine: null,
168
+ why: platform === 'linux'
169
+ ? 'Linux ships no system speech synthesizer'
170
+ : `no system speech synthesizer on ${platform}`,
171
+ suggest: PIPER_SUGGEST,
172
+ };
173
+ }
174
+
175
+ /**
176
+ * Ollama, which is not a speech engine and is the single most common thing a
177
+ * local-AI user expects to be one.
178
+ *
179
+ * It is probed only so the answer can be honest. Serving LLMs is not serving
180
+ * speech: there is no audio endpoint, and the models people name in this
181
+ * context (Kokoro, Orpheus) either are not Ollama models or need a separate
182
+ * audio decoder Ollama does not run.
183
+ */
184
+ export const OLLAMA_URL = 'http://127.0.0.1:11434/api/tags';
185
+
186
+ export async function ollamaRunning({ fetchImpl = fetch, timeoutMs = 300 } = {}) {
187
+ // A machine without Ollama must not pay for the question. The signal alone is
188
+ // not enough: it only helps if the implementation honors it, and a socket
189
+ // that hangs before the abort lands would stall dev's startup — which is the
190
+ // one thing this budget exists to prevent. So the timeout is RACED, and the
191
+ // abort is the courtesy that lets the request stop early.
192
+ const ac = new AbortController();
193
+ let timer;
194
+ const expired = new Promise((done) => {
195
+ timer = setTimeout(() => { ac.abort(); done(null); }, timeoutMs);
196
+ });
197
+ try {
198
+ const answered = Promise.resolve()
199
+ .then(() => fetchImpl(OLLAMA_URL, { signal: ac.signal }))
200
+ .catch(() => null);
201
+ const r = await Promise.race([answered, expired]);
202
+ return !!r?.ok;
203
+ } finally {
204
+ clearTimeout(timer);
205
+ }
206
+ }
207
+
208
+ export const OLLAMA_NOTE = 'Ollama is running, but it serves LLMs and cannot speak — '
209
+ + 'it has no speech endpoint';