File size: 4,428 Bytes
daa9f5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Pre-renders the built-in sample (and a short preview per natural voice) with the REAL app and the local
// Kokoro model, in a headless Chrome, so the clips match the app's own sentence split exactly.
// Output: public/sample-audio/*.ogg (Opus, 24 kbps mono) + src/sample-audio.json (texts the clips belong to).
// Usage (needs a build served on BASE, e.g. `npx vite preview --outDir <dist> --port 4180`):
//   systemd-run --user --scope -p MemoryMax=5G -p MemorySwapMax=0 nice -n 19 node scripts/render-sample-audio.mjs
import { chromium } from '@playwright/test';
import { execFileSync, spawnSync } from 'node:child_process';
import { mkdirSync, writeFileSync, rmSync, readdirSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';

const BASE = process.env.BASE || 'http://localhost:4180/';
const ROOT = new URL('..', import.meta.url).pathname;
const OUT = join(ROOT, 'public/sample-audio');
const PREVIEW_TEXT = 'In another moment down went Alice after it.'; // a real line of the sample
const VOICES = ['af_heart', 'af_bella', 'am_michael', 'am_fenrir', 'bf_emma', 'bm_george'];

const b = await chromium.launch({ channel: 'chrome' });
const page = await b.newPage();
page.setDefaultTimeout(600_000);
await page.addInitScript(() => localStorage.setItem('earshelf.noWarm', '1'));
// generate everything fresh: the clips shipped in this build must never be reused (or prefetched) here
await page.route(/\/sample-audio\//, (r) => r.abort());
await page.goto(BASE);
await page.getByRole('button', { name: /Try a sample/ }).click();
await page.waitForFunction(() => window.__earshelf?.engine?.book);
const res = await page.evaluate(
  async ({ voices, previewText }) => {
    const e = window.__earshelf.engine;
    e.pause();
    e.preclip = undefined;
    e.clips.clear();
    e.voice = { kind: 'natural', id: 'af_heart' };
    e.ensureModel();
    while (e.model.s !== 'ready') {
      if (e.model.s === 'error') throw new Error('model failed to load');
      await new Promise((r) => setTimeout(r, 300));
    }
    const b64 = async (blob) => {
      const buf = new Uint8Array(await blob.arrayBuffer());
      let s = '';
      for (let i = 0; i < buf.length; i += 0x8000) s += String.fromCharCode(...buf.subarray(i, i + 0x8000));
      return btoa(s);
    };
    const chapters = [];
    for (let c = 0; c < e.book.chapters.length; c++) {
      e.gotoChapter(c);
      const texts = [...e.sentences];
      const wavs = [];
      for (let i = 0; i < texts.length; i++) wavs.push(await b64(await e.clip(i)));
      chapters.push({ texts, wavs });
    }
    const gen = (voice) =>
      new Promise((resolve, reject) => {
        const id = e.nextId++;
        e.pending.set(id, { key: `preview|${voice}`, resolve, reject });
        e.worker.postMessage({ type: 'gen', id, text: previewText, voice });
      });
    const previews = {};
    for (const v of voices) previews[v] = await b64(await gen(v));
    return { chapters, previews };
  },
  { voices: VOICES, previewText: PREVIEW_TEXT },
);
await b.close();

const tmp = join(tmpdir(), 'earshelf-render-' + process.pid);
mkdirSync(tmp, { recursive: true });
rmSync(OUT, { recursive: true, force: true });
mkdirSync(OUT, { recursive: true });
const enc = (b64, name) => {
  const wav = join(tmp, name + '.wav');
  writeFileSync(wav, Buffer.from(b64, 'base64'));
  execFileSync('ffmpeg', ['-v', 'error', '-y', '-i', wav, '-ac', '1', '-c:a', 'libopus', '-b:a', '24k', '-application', 'voip', join(OUT, name + '.ogg')]);
  // gate: a silent clip must never ship (Kokoro fp16 can return silence; the worker retries, this checks)
  const log = spawnSync('ffmpeg', ['-hide_banner', '-i', join(OUT, name + '.ogg'), '-af', 'volumedetect', '-f', 'null', '-'], { encoding: 'utf8' }).stderr; // volumedetect reports on stderr
  const m = /mean_volume: (-?[\d.]+) dB/.exec(log);
  if (!m || Number(m[1]) < -45) throw new Error(`${name}: silent clip (mean ${m?.[1]} dB)`);
};
res.chapters.forEach((ch, c) => ch.wavs.forEach((w, i) => enc(w, `s-${c}-${i}`)));
for (const [v, w] of Object.entries(res.previews)) enc(w, `voice-${v}`);
rmSync(tmp, { recursive: true, force: true });
writeFileSync(
  join(ROOT, 'src/sample-audio.json'),
  JSON.stringify({ voice: 'af_heart', previewText: PREVIEW_TEXT, voices: VOICES, chapters: res.chapters.map((c) => c.texts) }, null, 2) + '\n',
);
console.log(`wrote ${readdirSync(OUT).length} clips to ${OUT}`);