decklight 0.4.0 → 0.6.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.
@@ -38,7 +38,7 @@
38
38
  import { createServer } from 'node:http';
39
39
  import { createHash } from 'node:crypto';
40
40
  import { createInterface } from 'node:readline/promises';
41
- import { resolveEngine, ENGINES } from './tts-engines.mjs';
41
+ import { resolveEngine, engineBlocker, engineMenu, engineStatus, ENGINES } from './tts-engines.mjs';
42
42
  import { loadTtsConfig, runSetupWizard, ttsConfigPath } from './tts-setup.mjs';
43
43
  import { argReader, isMain } from './args.mjs';
44
44
  import { corsHeaders, readBody } from './bridge.mjs';
@@ -144,17 +144,44 @@ export async function ttsMain(args) {
144
144
  // made the name offerable, rather than in each engine — an engine that had to
145
145
  // know about the unit library would be an engine that could no longer be
146
146
  // tested without one.
147
- const refs = installedVoices(engine.name);
148
- const refIds = new Map(refs.map((r) => [r.label, r.voiceId]));
149
- if (refs.length) console.log(` voices: +${refs.length} installed (decklight voice list)`);
147
+ // Everything derived from the live engine, recomputed together — because the
148
+ // deck can now change which engine that is (SPEC `NARRATION`), and a roster
149
+ // or an id map left behind from the previous one would offer voices the
150
+ // current engine cannot say.
151
+ let refs = [];
152
+ let refIds = new Map();
153
+ const useEngine = (e) => {
154
+ engine = e;
155
+ refs = installedVoices(e.name);
156
+ refIds = new Map(refs.map((r) => [r.label, r.voiceId]));
157
+ if (refs.length) console.log(` voices: +${refs.length} installed (decklight voice list)`);
158
+ };
159
+ useEngine(engine);
150
160
 
151
161
  const voiceRoster = async () => [
152
162
  ...(engine.listVoices ? (await engine.listVoices()).map((v) => [v.name, v.flavor]) : engine.voices),
153
163
  ...refs.map((r) => [r.label, r.marketplace ?? 'installed']),
154
164
  ];
155
165
 
166
+ // The engine's NAME is part of every cache key, so a swap cannot serve one
167
+ // engine's audio under another's voice — the cache survives the switch, and
168
+ // switching back replays instantly rather than re-billing.
156
169
  const cache = new Map();
157
170
 
171
+ // What the bridge could become, and what stands in the way. The options the
172
+ // deck's picker draws (SPEC `NARRATION`).
173
+ //
174
+ // The blockers are all fixed in a TERMINAL and this route never collects
175
+ // one: a key or a project id typed into a web page — even one on loopback —
176
+ // is a different thing from one exported in a shell, and a deck under
177
+ // `--remote` is reachable from a phone. So the deck lists what is missing and
178
+ // says where to fix it; it never becomes the place you configure credentials.
179
+ const menuOpts = () => ({
180
+ env: process.env,
181
+ project: opt('--project') ?? process.env.GOOGLE_CLOUD_PROJECT ?? saved?.project,
182
+ voice: opt('--voice'), dataDir: opt('--data-dir'), lang: opt('--lang'),
183
+ });
184
+
158
185
  // the player reads the cost estimate for its debug window
159
186
  const CORS = corsHeaders('x-tts-cost, x-tts-tokens, x-tts-cached');
160
187
  let totalCost = 0;
@@ -178,6 +205,70 @@ export async function ttsMain(args) {
178
205
  voices, // piper speaks one voice, not the star roster
179
206
  }));
180
207
  }
208
+ // ── which engine is speaking, and what else could (SPEC `NARRATION`) ──
209
+ if (req.method === 'GET' && req.url === '/engines') {
210
+ // Ready or not, every engine is listed. Hiding the ones this machine
211
+ // cannot use would answer "where did ElevenLabs go?" with silence — the
212
+ // useful answer is that it is there and needs a key.
213
+ const opts = menuOpts();
214
+ const menu = engineMenu(opts).map((e) => ({ ...e, current: e.name === engine.name }));
215
+ // An engine the bridge was STARTED with is ready by definition — it is
216
+ // speaking. Detection can disagree (a marketplace engine is not one of
217
+ // the six, and a project passed by flag is invisible to a later probe),
218
+ // and a picker that greyed out the running engine would be absurd.
219
+ if (!menu.some((e) => e.current)) {
220
+ menu.unshift({ name: engine.name, ready: true, reason: 'ok', current: true, cost: engine.cost });
221
+ }
222
+ res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
223
+ return res.end(JSON.stringify({ ok: true, engine: engine.name, engines: menu }));
224
+ }
225
+ if (req.method === 'POST' && req.url === '/engine') {
226
+ let name;
227
+ try { ({ engine: name } = JSON.parse((await readBody(req)).toString())); }
228
+ catch { name = null; }
229
+ if (typeof name !== 'string' || !name) {
230
+ res.writeHead(400, { ...CORS, 'content-type': 'application/json' });
231
+ return res.end(JSON.stringify({ ok: false, error: 'name the engine' }));
232
+ }
233
+ if (name === engine.name) {
234
+ res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
235
+ return res.end(JSON.stringify({ ok: true, engine: engine.name, model: engine.model,
236
+ stylable: engine.stylable, voices: await voiceRoster().catch(() => []), changed: false }));
237
+ }
238
+ const opts = menuOpts();
239
+ // Checked BEFORE building, because two of the six build perfectly well
240
+ // and only fail on the first sentence — which mid-talk is a keypress into
241
+ // silence. A refusal here is recoverable; that one is not.
242
+ const status = engineStatus(name, opts);
243
+ if (ENGINES.includes(name) && !status.ready) {
244
+ // The blocker travels WITH the refusal. The deck's picker normally has
245
+ // it already (it came down with /engines), but a menu can be a minute
246
+ // stale — a key exported and un-exported, a model deleted — and a
247
+ // refusal the deck cannot put words to is a row that does nothing when
248
+ // clicked.
249
+ res.writeHead(409, { ...CORS, 'content-type': 'application/json' });
250
+ return res.end(JSON.stringify({
251
+ ok: false, error: status.reason, ...status, ...(engineBlocker(status, opts) ?? {}),
252
+ }));
253
+ }
254
+ let next;
255
+ try {
256
+ next = await resolveEngine({ ...opts, engine: name, model: undefined });
257
+ } catch (e) {
258
+ res.writeHead(409, { ...CORS, 'content-type': 'application/json' });
259
+ return res.end(JSON.stringify({ ok: false, error: String(e.message ?? e).slice(0, 200) }));
260
+ }
261
+ // Only now, once the new engine exists: a failed swap must leave the
262
+ // bridge speaking exactly as it was, not half-way between two engines.
263
+ const was = engine.name;
264
+ useEngine(next);
265
+ console.log(` engine: ${was} → ${engine.name} (asked for by the deck)`);
266
+ if (engine.caveat) console.log(` ${engine.caveat}`);
267
+ const voices = await voiceRoster().catch(() => []);
268
+ res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
269
+ return res.end(JSON.stringify({ ok: true, engine: engine.name, model: engine.model,
270
+ stylable: engine.stylable, cost: engine.cost, caveat: engine.caveat, voices, changed: true }));
271
+ }
181
272
  if (req.method === 'GET' && req.url === '/voices') {
182
273
  res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
183
274
  return res.end(JSON.stringify(await voiceRoster()));
@@ -49,7 +49,7 @@ import { resolve, join, basename } from 'node:path';
49
49
  import { homedir } from 'node:os';
50
50
  import { createEngine } from './tts-engines.mjs';
51
51
  import { argReader } from './args.mjs';
52
- import { sectionBodies, NOTES_ASIDE } from './deck-html.mjs';
52
+ import { sectionBodies, NOTES_ASIDE, cleanNotes, notesSegments } from './deck-html.mjs';
53
53
 
54
54
  const args = process.argv.slice(2);
55
55
  const deckPath = args.find((a) => !a.startsWith('-'));
@@ -102,19 +102,32 @@ const toAac = (wav, m4a) => execFileSync(encoder, encoder === 'ffmpeg'
102
102
  // ── extract per-slide narration text ─────────────────────────────────────────
103
103
  const html = readFileSync(deckPath, 'utf8');
104
104
  const sections = sectionBodies(html);
105
- const clean = (s) => s
106
- .replace(/⟨CLICK⟩/g, ' ')
107
- .replace(/<[^>]+>/g, ' ')
108
- .replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&')
109
- .replace(/\s+/g, ' ')
110
- .trim();
111
- const slides = sections.map((sec, i) => {
105
+ const raw = sections.map((sec) => {
112
106
  const aside = sec.match(NOTES_ASIDE);
113
- if (aside) return clean(aside[1]);
107
+ if (aside) return aside[1];
114
108
  const md = sec.match(/^Note:\s*$([\s\S]*?)(?=^Rehearse:\s*$|<\/script>)/m);
115
- if (md) return clean(md[1]);
116
- return '';
109
+ return md ? md[1] : '';
117
110
  });
111
+ const slides = raw.map(cleanNotes);
112
+ /**
113
+ * A slide's ⟨CLICK⟩ segments, or null when there is only one.
114
+ *
115
+ * These are the author's own build cues, and the sync rule they carry already
116
+ * ships: src/core/narration.js speaks segment k over build step k in live
117
+ * playback, and captions, rehearse mode and the notes editor all read the same
118
+ * segmentation. Recording them separately is what lets a rendered mp4 mirror
119
+ * that (SPEC PRESENTING). An empty segment is dropped rather than synthesised
120
+ * as silence — a ⟨CLICK⟩ at the very start or end of a note is punctuation,
121
+ * not a beat.
122
+ */
123
+ // Segmenting needs ffmpeg specifically: the per-slide file is CONCATENATED from
124
+ // the segments, and afconvert (Core Audio, macOS-only) has no concat demuxer.
125
+ // Without it the slide is synthesised whole, exactly as before.
126
+ const canSegment = encoder === 'ffmpeg';
127
+ const segmented = raw.map((r) => (canSegment ? notesSegments(r) : null));
128
+ if (!canSegment && raw.some((r) => notesSegments(r))) {
129
+ console.log(' note: ⟨CLICK⟩ segments need ffmpeg to concatenate — narrating each slide whole');
130
+ }
118
131
  console.log(`${basename(deckPath)}: ${slides.length} slides, ${slides.filter(Boolean).length} with notes`);
119
132
 
120
133
  // ── optional narration pass through a local model ────────────────────────────
@@ -164,17 +177,52 @@ for (let i = 0; i < slides.length; i++) {
164
177
  const hash = slideHash(text);
165
178
  manifest.push({ file: `slide-${n}.m4a`, hash });
166
179
  if (prev?.slides?.[i]?.hash === hash && existsSync(m4a)) {
180
+ // Carry the segments across, or an unchanged slide loses its build sync on
181
+ // the next rerun: the audio is still on disk and the manifest is the only
182
+ // thing that knows it is there.
183
+ const kept = prev.slides[i].segments;
184
+ if (kept?.every((sg) => existsSync(join(outDir, sg.file)))) manifest[i].segments = kept;
167
185
  skipped++;
168
- console.log(` slide ${n}: unchanged — kept`);
186
+ console.log(` slide ${n}: unchanged — kept${manifest[i].segments ? ` (${manifest[i].segments.length} segments)` : ''}`);
169
187
  continue;
170
188
  }
171
- const { wav: buf, usage } = await tts.synth(text, { voice, style });
172
- writeFileSync(wav, buf);
173
- totalCost += usage.cost;
189
+ // A segmented slide is synthesised segment by segment, and the per-slide file
190
+ // is CONCATENATED from those — one synthesis, both shapes. TTS is billed per
191
+ // character; asking for the same words twice to get the same audio cut two
192
+ // ways would be a bill nobody agreed to. --reuse-text takes the whole-slide
193
+ // path, since its prior text is one script rather than segments.
194
+ const segs = prior ? null : segmented[i];
195
+ let usage = { cost: 0 };
196
+ if (segs) {
197
+ const parts = [];
198
+ for (let k = 0; k < segs.length; k++) {
199
+ const kk = String(k + 1).padStart(2, '0');
200
+ const sWav = join(outDir, `slide-${n}-${kk}.wav`);
201
+ const sM4a = join(outDir, `slide-${n}-${kk}.m4a`);
202
+ const out = await tts.synth(segs[k], { voice, style });
203
+ writeFileSync(sWav, out.wav);
204
+ usage = { cost: usage.cost + (out.usage?.cost ?? 0) };
205
+ toAac(sWav, sM4a);
206
+ if (!keepWav) rmSync(sWav);
207
+ parts.push({ file: `slide-${n}-${kk}.m4a`, path: sM4a });
208
+ }
209
+ const list = join(outDir, `slide-${n}.concat`);
210
+ writeFileSync(list, `${parts.map((p) => `file '${p.path.replaceAll("'", "'\\''")}'`).join('\n')}\n`);
211
+ execFileSync('ffmpeg', ['-y', '-f', 'concat', '-safe', '0', '-i', list, '-c', 'copy', m4a],
212
+ { stdio: 'ignore' });
213
+ rmSync(list, { force: true });
214
+ manifest[i].segments = parts.map((p) => ({ file: p.file }));
215
+ } else {
216
+ const out = await tts.synth(text, { voice, style });
217
+ writeFileSync(wav, out.wav);
218
+ usage = out.usage ?? { cost: 0 };
219
+ toAac(wav, m4a);
220
+ if (!keepWav) rmSync(wav);
221
+ }
222
+ totalCost += usage.cost ?? 0;
174
223
  const costNote = usage.cost ? ` · ~$${usage.cost.toFixed(4)}` : '';
175
- toAac(wav, m4a);
176
- if (!keepWav) rmSync(wav);
177
- console.log(` slide ${n}: ${text.length} chars → ${basename(m4a)}${costNote}`);
224
+ console.log(` slide ${n}: ${text.length} chars → ${basename(m4a)}`
225
+ + `${segs ? ` (${segs.length} ⟨CLICK⟩ segments)` : ''}${costNote}`);
178
226
  // crash-safe: persist progress after every slide so an interrupted run
179
227
  // resumes incrementally instead of re-synthesizing everything
180
228
  writeFileSync(join(outDir, 'manifest.json'),