// Paradee text-to-speech from the command line, on the web bundle (Node 20+, no dependencies):
//   node say.mjs "Hello there." hello.wav [v2f_lite | v2f | v2g]
// Expects the unzipped bundle next to it in ./paradee-web-v2. Optional: `npm i phonemizer` (eSpeak NG, GPL-3.0) to read words
// outside misaki's lexicon (mostly rare names); without it such a sentence raises an error.
import { writeFileSync } from "node:fs";
import { loadParadee } from "./paradee-web-v2/paradee.mjs";

const [text = "Hello from Paradee.", out = "out.wav", model = "v2f_lite"] = process.argv.slice(2);
const tts = await loadParadee({ model });
const t0 = performance.now();
const y = await tts.synth(text);
const ms = performance.now() - t0;

const wav = Buffer.alloc(44 + 2 * y.length);
wav.write("RIFF", 0); wav.writeUInt32LE(36 + 2 * y.length, 4); wav.write("WAVE", 8);
wav.write("fmt ", 12); wav.writeUInt32LE(16, 16); wav.writeUInt16LE(1, 20); wav.writeUInt16LE(1, 22);
wav.writeUInt32LE(tts.sampleRate, 24); wav.writeUInt32LE(2 * tts.sampleRate, 28); wav.writeUInt16LE(2, 32); wav.writeUInt16LE(16, 34);
wav.write("data", 36); wav.writeUInt32LE(2 * y.length, 40);
y.forEach((v, i) => wav.writeInt16LE(Math.round(Math.max(-1, Math.min(1, v)) * 32767), 44 + 2 * i));
writeFileSync(out, wav);
console.log(`${out}: ${(y.length / tts.sampleRate).toFixed(1)} s of audio in ${ms.toFixed(0)} ms (${model}, pdn ${tts.info.build})`);
process.exit(0);
