decklight 0.7.0 → 0.8.1

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.
@@ -48,8 +48,10 @@ import { execFileSync } from 'node:child_process';
48
48
  import { resolve, join, basename } from 'node:path';
49
49
  import { homedir } from 'node:os';
50
50
  import { createEngine } from './tts-engines.mjs';
51
+ import { clipKey, createTtsCache, extFor } from './tts-cache.mjs';
51
52
  import { argReader } from './args.mjs';
52
- import { sectionBodies, NOTES_ASIDE, cleanNotes, notesSegments } from './deck-html.mjs';
53
+ import { sectionBodies, NOTES_ASIDE, cleanNotes, notesSegments, isHiddenSection } from './deck-html.mjs';
54
+ import { run, PROBE_MS, CODEC_MS } from './exec.mjs';
53
55
 
54
56
  const args = process.argv.slice(2);
55
57
 
@@ -58,8 +60,9 @@ const HELP = `decklight voiceover — batch-synthesize a deck's narration into a
58
60
  Usage:
59
61
  decklight voiceover <deck.html> [-o <dir>] [--engine piper|chirp|gemini|elevenlabs]
60
62
  [--voice <name>] [--no-llm] [--reuse-text] [--keep-wav]
63
+ [--no-cache]
61
64
 
62
- The headless counterpart of the deck's \u21e7V: it reads each slide's speaker
65
+ The headless counterpart of the deck's V \u2192 Record this deck\u2026: it reads each slide's speaker
63
66
  notes and writes one slide-NN.m4a per slide (plus a file per \u27e8CLICK\u27e9 beat)
64
67
  and a manifest.json into <dir>, so a deck can point at it with
65
68
  narration: { files: [{ label, dir, segments: true }] }.
@@ -72,6 +75,12 @@ narration: { files: [{ label, dir, segments: true }] }.
72
75
  --reuse-text re-voice the existing slide-NN.txt without re-rolling the text
73
76
  — switch voices or engines without a new narration pass
74
77
  --keep-wav keep the lossless WAVs (tools/lipsync.mjs consumes them)
78
+ --no-cache re-synthesize every slide, ignoring the shared clip cache
79
+
80
+ Synthesis is cached on disk (~/.cache/decklight/tts) under a key made of
81
+ (engine, model, format, voice, style, text) — the SAME key the live bridge
82
+ uses, so a sentence you previewed in the deck is recorded here for free
83
+ instead of being billed a second time.
75
84
 
76
85
  Cloud engines need --project or $GOOGLE_CLOUD_PROJECT and application-default
77
86
  credentials; elevenlabs needs $ELEVENLABS_API_KEY. Audio is a build artifact.`;
@@ -95,6 +104,7 @@ const model = opt('--model', 'qwen3:30b-a3b');
95
104
  const useLlm = !args.includes('--no-llm');
96
105
  const reuseText = args.includes('--reuse-text');
97
106
  const keepWav = args.includes('--keep-wav');
107
+ const useCache = !args.includes('--no-cache');
98
108
 
99
109
  // one factory, three engines — the same ones the live bridge speaks with
100
110
  let tts;
@@ -113,21 +123,22 @@ try {
113
123
  // macOS — probing in that order keeps this working off a Mac (as tools/lipsync.mjs
114
124
  // already does), and both engines' output goes through here.
115
125
  const have = (bin, flags = ['-version']) => {
116
- try { execFileSync(bin, flags, { stdio: 'ignore' }); return true; } catch (e) { return e?.code !== 'ENOENT'; }
126
+ try { run(bin, flags, { stdio: 'ignore', timeout: PROBE_MS }); return true; } catch (e) { return e?.code !== 'ENOENT'; }
117
127
  };
118
128
  const encoder = have('ffmpeg') ? 'ffmpeg' : have('afconvert') ? 'afconvert' : null;
119
129
  if (!encoder) {
120
130
  console.error('no AAC encoder — install ffmpeg (apt install ffmpeg / brew install ffmpeg)');
121
131
  process.exit(1);
122
132
  }
123
- const toAac = (wav, m4a) => execFileSync(encoder, encoder === 'ffmpeg'
133
+ const toAac = (wav, m4a) => run(encoder, encoder === 'ffmpeg'
124
134
  ? ['-y', '-i', wav, '-c:a', 'aac', '-b:a', '128k', m4a]
125
- : ['-f', 'm4af', '-d', 'aac', wav, m4a], { stdio: 'ignore' });
135
+ : ['-f', 'm4af', '-d', 'aac', wav, m4a], { stdio: 'ignore', timeout: CODEC_MS, why: 'the encoder is stuck on this file — check it plays, then retry' });
126
136
 
127
137
  // ── extract per-slide narration text ─────────────────────────────────────────
128
138
  const html = readFileSync(deckPath, 'utf8');
129
139
  const sections = sectionBodies(html);
130
140
  const raw = sections.map((sec) => {
141
+ if (isHiddenSection(sec)) return ''; // no file for a hidden slide; the numbering stays
131
142
  const aside = sec.match(NOTES_ASIDE);
132
143
  if (aside) return aside[1];
133
144
  const md = sec.match(/^Note:\s*$([\s\S]*?)(?=^Rehearse:\s*$|<\/script>)/m);
@@ -174,12 +185,71 @@ function narrate(text, slideNo) {
174
185
  }
175
186
 
176
187
  // ── synthesize ────────────────────────────────────────────────────────────────
177
- // Incremental: the manifest stores a hash of (engine, voice, style, text) per
178
- // slide, so a rerun only synthesizes slides whose narration actually changed.
188
+ // TWO layers of reuse, and they answer different questions.
189
+ //
190
+ // The MANIFEST answers "is this folder already correct?" — a hash per slide,
191
+ // so a rerun re-synthesizes only the slides whose narration actually changed
192
+ // and leaves the rest of the .m4a files alone.
193
+ //
194
+ // The CLIP CACHE (tools/tts-cache.mjs) answers "has anyone, ever, paid for
195
+ // these exact words?" — it is keyed by content rather than by folder, so it
196
+ // survives a different -o, a deleted manifest, and above all the process
197
+ // boundary: the live bridge fills the same cache while you preview the deck,
198
+ // and this run collects it. An ElevenLabs deck used to be billed twice for
199
+ // that, once in the browser and once here.
200
+ //
201
+ // Both keys carry the same fields, and the reason is one bug rather than two:
202
+ // anything that changes the AUDIO must change the key. `model` is in them
203
+ // because `--tts-model eleven_v3` is a different voice performance of the same
204
+ // words, and a hash without it skipped the slide and kept the old take. STYLE
205
+ // is in them only when the engine can act on it — every engine but gemini and
206
+ // ElevenLabs v3 ignores the instruction entirely, and letting a style the
207
+ // engine never read change the hash would miss the bridge's own clip for no
208
+ // audible reason.
179
209
  mkdirSync(outDir, { recursive: true });
180
210
  let totalCost = 0;
181
- const slideHash = (text) =>
182
- createHash('sha256').update(`${engine}|${voice}|${style}|${text}`).digest('hex').slice(0, 16);
211
+ const audioExt = extFor(tts.synth.mimeType ?? 'audio/wav');
212
+ const clips = createTtsCache({ enabled: useCache });
213
+ clips.prune();
214
+ // `--voice` omitted on ElevenLabs means "the first of your voices", and the
215
+ // deck's picker offers that same roster in that same order — so the name is
216
+ // resolved HERE, for the key. Left undefined it would hash differently from
217
+ // the identical sentence the bridge just synthesized, and the cross-process
218
+ // reuse this cache exists for would silently never hit.
219
+ let keyVoice = voice;
220
+ if (!keyVoice && tts.listVoices) {
221
+ try { keyVoice = (await tts.listVoices())[0]?.name; } catch { /* keep it undefined */ }
222
+ }
223
+
224
+ /** `tts.synth`, but a sentence anyone has already paid for is free. */
225
+ async function synth(text) {
226
+ const key = clipKey(tts, { voice: keyVoice, style, text });
227
+ const hit = clips.read(key, audioExt);
228
+ if (hit) return { wav: hit, usage: { chars: 0, cost: 0 }, cached: true };
229
+ const out = await tts.synth(text, { voice, style });
230
+ clips.write(key, out.wav, audioExt);
231
+ return { ...out, cached: false };
232
+ }
233
+ // The manifest hash is the CLIP KEY, shortened: one definition of "the same
234
+ // audio", so the folder-level skip and the content-level cache can never
235
+ // disagree about whether a slide changed.
236
+ const slideHash = (text) => clipKey(tts, { voice: keyVoice, style, text }).slice(0, 16);
237
+ // ONE-TIME MIGRATION. The hash above gained `model` and lost the style no
238
+ // engine reads, so every folder recorded before this change hashes differently
239
+ // — and a folder that hashes differently is re-synthesized in full. That audio
240
+ // is not stale; it is exactly what today's key describes, and re-rolling it
241
+ // would hand an ElevenLabs user a bill for clips already on their disk.
242
+ //
243
+ // So a slide matching the OLD formula is accepted once and re-stamped. The
244
+ // gate is `prev.model === undefined`: only a manifest written before this
245
+ // change lacks that field, so the allowance cannot be claimed twice, and a
246
+ // later `--tts-model` switch is a genuine miss again. The one case it lets
247
+ // through is changing the model in the SAME run as the upgrade — narrow, and
248
+ // `--no-cache` is the way out of it.
249
+ const legacyHash = (text) => createHash('sha256')
250
+ .update(`${engine}|${voice}|${style}|${text}`).digest('hex').slice(0, 16);
251
+ const preDatesModel = (m) => m && m.model === undefined
252
+ && m.engine === engine && m.voice === voice && m.style === style;
183
253
  let prev = null;
184
254
  try {
185
255
  const m = JSON.parse(readFileSync(join(outDir, 'manifest.json'), 'utf8'));
@@ -201,7 +271,8 @@ for (let i = 0; i < slides.length; i++) {
201
271
  writeFileSync(txt, text);
202
272
  const hash = slideHash(text);
203
273
  manifest.push({ file: `slide-${n}.m4a`, hash });
204
- if (prev?.slides?.[i]?.hash === hash && existsSync(m4a)) {
274
+ const stamped = prev?.slides?.[i]?.hash;
275
+ if ((stamped === hash || (preDatesModel(prev) && stamped === legacyHash(text))) && existsSync(m4a)) {
205
276
  // Carry the segments across, or an unchanged slide loses its build sync on
206
277
  // the next rerun: the audio is still on disk and the manifest is the only
207
278
  // thing that knows it is there.
@@ -218,13 +289,15 @@ for (let i = 0; i < slides.length; i++) {
218
289
  // path, since its prior text is one script rather than segments.
219
290
  const segs = prior ? null : segmented[i];
220
291
  let usage = { cost: 0 };
292
+ let cachedBeats = 0;
221
293
  if (segs) {
222
294
  const parts = [];
223
295
  for (let k = 0; k < segs.length; k++) {
224
296
  const kk = String(k + 1).padStart(2, '0');
225
297
  const sWav = join(outDir, `slide-${n}-${kk}.wav`);
226
298
  const sM4a = join(outDir, `slide-${n}-${kk}.m4a`);
227
- const out = await tts.synth(segs[k], { voice, style });
299
+ const out = await synth(segs[k]);
300
+ if (out.cached) cachedBeats++;
228
301
  writeFileSync(sWav, out.wav);
229
302
  // The beat's own words, beside its own audio — tools/lipsync.mjs hands
230
303
  // this to Rhubarb as the dialog hint, and a hint for the whole slide
@@ -237,12 +310,13 @@ for (let i = 0; i < slides.length; i++) {
237
310
  }
238
311
  const list = join(outDir, `slide-${n}.concat`);
239
312
  writeFileSync(list, `${parts.map((p) => `file '${p.path.replaceAll("'", "'\\''")}'`).join('\n')}\n`);
240
- execFileSync('ffmpeg', ['-y', '-f', 'concat', '-safe', '0', '-i', list, '-c', 'copy', m4a],
313
+ run('ffmpeg', ['-y', '-f', 'concat', '-safe', '0', '-i', list, '-c', 'copy', m4a],
241
314
  { stdio: 'ignore' });
242
315
  rmSync(list, { force: true });
243
316
  manifest[i].segments = parts.map((p) => ({ file: p.file }));
244
317
  } else {
245
- const out = await tts.synth(text, { voice, style });
318
+ const out = await synth(text);
319
+ if (out.cached) cachedBeats++;
246
320
  writeFileSync(wav, out.wav);
247
321
  usage = out.usage ?? { cost: 0 };
248
322
  toAac(wav, m4a);
@@ -250,15 +324,20 @@ for (let i = 0; i < slides.length; i++) {
250
324
  }
251
325
  totalCost += usage.cost ?? 0;
252
326
  const costNote = usage.cost ? ` · ~$${usage.cost.toFixed(4)}` : '';
327
+ // "cached" is worth a word: on a paid engine it is the difference between a
328
+ // rerun that costs nothing and one that quietly re-bills the whole deck
329
+ const cacheNote = cachedBeats
330
+ ? ` · ${segs ? `${cachedBeats}/${segs.length} ` : ''}cached`
331
+ : '';
253
332
  console.log(` slide ${n}: ${text.length} chars → ${basename(m4a)}`
254
- + `${segs ? ` (${segs.length} ⟨CLICK⟩ segments)` : ''}${costNote}`);
333
+ + `${segs ? ` (${segs.length} ⟨CLICK⟩ segments)` : ''}${cacheNote}${costNote}`);
255
334
  // crash-safe: persist progress after every slide so an interrupted run
256
335
  // resumes incrementally instead of re-synthesizing everything
257
336
  writeFileSync(join(outDir, 'manifest.json'),
258
- JSON.stringify({ engine, voice, style, slides: manifest }, null, 1));
337
+ JSON.stringify({ engine, model: tts.model ?? null, voice, style, slides: manifest }, null, 1));
259
338
  }
260
339
  writeFileSync(join(outDir, 'manifest.json'),
261
- JSON.stringify({ engine, voice, style, slides: manifest }, null, 1));
340
+ JSON.stringify({ engine, model: tts.model ?? null, voice, style, slides: manifest }, null, 1));
262
341
  // piper is held resident (§ createPiper) — without this the tool prints `done`
263
342
  // and then hangs on the live child process
264
343
  tts.synth.close?.();