/** * One-time ElevenLabs narration generation, run on your own computer or server. * Node.js with built-in fetch and --env-file support (for example Node 22+). * No dependencies. No network request without the explicit --generate flag. * * Dry run: * node --env-file=.env.local snippets/generate-narration.mjs scripts/narration.ru.txt public/audio/narration-ru.mp3 * Paid generation after checking the script, model and account quota: * node --env-file=.env.local snippets/generate-narration.mjs scripts/narration.ru.txt public/audio/narration-ru.mp3 --generate * * Environment: * ELEVENLABS_API_KEY Secret; never use a public/VITE_/NEXT_PUBLIC_ variable. * ELEVENLABS_VOICE_ID Copy the selected voice ID from the current account. * ELEVENLABS_MODEL_ID Explicitly choose a currently supported TTS model. * NARRATION_MAX_CHARS Optional project spending guard, defaults to 3000. * * This script has no automatic retry: a repeated generation may be billed again. * It refuses to overwrite an existing target to prevent an accidental duplicate. */ import { access, mkdir, readFile, rename, writeFile } from 'node:fs/promises'; import { constants } from 'node:fs'; import { dirname, resolve } from 'node:path'; const args = process.argv.slice(2); const shouldGenerate = args.includes('--generate'); const unknownFlags = args.filter((arg) => arg.startsWith('--') && arg !== '--generate'); const positional = args.filter((arg) => !arg.startsWith('--')); function fail(message) { throw new Error(message); } async function targetExists(path) { try { await access(path, constants.F_OK); return true; } catch (error) { if (error.code === 'ENOENT') return false; throw error; } } async function main() { if (unknownFlags.length || positional.length !== 2) { fail('Usage: node generate-narration.mjs SCRIPT.txt OUTPUT.mp3 [--generate]'); } const [inputName, outputName] = positional; const inputPath = resolve(inputName); const outputPath = resolve(outputName); if (!outputPath.toLowerCase().endsWith('.mp3')) fail('OUTPUT must end with .mp3.'); if (inputPath === outputPath) fail('Input and output must be different files.'); const text = (await readFile(inputPath, 'utf8')).trim(); const characters = Array.from(text).length; const maxCharacters = Number(process.env.NARRATION_MAX_CHARS || 3000); if (!Number.isInteger(maxCharacters) || maxCharacters < 1) { fail('NARRATION_MAX_CHARS must be a positive integer.'); } if (!characters) fail('The narration script is empty.'); if (characters > maxCharacters) { fail(`Script has ${characters} characters; local project guard is ${maxCharacters}. This is not the provider model limit.`); } const modelId = process.env.ELEVENLABS_MODEL_ID?.trim(); const voiceId = process.env.ELEVENLABS_VOICE_ID?.trim(); const apiKey = process.env.ELEVENLABS_API_KEY?.trim(); const outputFormat = 'mp3_44100_128'; console.log(JSON.stringify({ mode: shouldGenerate ? 'one-paid-generation' : 'dry-run-no-network', input: inputPath, output: outputPath, characters, model: modelId || 'NOT_CONFIGURED', voiceConfigured: Boolean(voiceId), keyConfigured: Boolean(apiKey), outputFormat, automaticRetries: 0, }, null, 2)); if (!shouldGenerate) { console.log('No API request made. Add --generate only after reviewing script, voice, model and current quota.'); return; } if (!apiKey || !voiceId || !modelId) { fail('Set ELEVENLABS_API_KEY, ELEVENLABS_VOICE_ID and ELEVENLABS_MODEL_ID in the server environment.'); } if (await targetExists(outputPath)) { fail('Target file already exists. Reuse it or deliberately choose a new versioned filename. No request made.'); } const url = new URL(`https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(voiceId)}`); url.searchParams.set('output_format', outputFormat); const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'audio/mpeg', 'xi-api-key': apiKey, }, body: JSON.stringify({ text, model_id: modelId }), signal: AbortSignal.timeout(180_000), }); if (!response.ok) { // Do not dump headers, account details or response bodies into public logs. const requestId = response.headers.get('request-id') || response.headers.get('x-request-id'); const retryAfter = response.headers.get('retry-after'); console.error(JSON.stringify({ httpStatus: response.status, requestId: requestId || undefined, retryAfter: retryAfter || undefined, })); fail('Generation was not saved. Check the account history and API error details before another request.'); } const contentType = response.headers.get('content-type') || ''; if (contentType.includes('json') || contentType.includes('text/html')) { fail('The response is not an audio file. Check the request in the account before generating again.'); } const bytes = Buffer.from(await response.arrayBuffer()); if (!bytes.length) fail('Empty response. Check account history before generating again.'); await mkdir(dirname(outputPath), { recursive: true }); const temporaryPath = `${outputPath}.${process.pid}.partial`; await writeFile(temporaryPath, bytes, { flag: 'wx' }); if (await targetExists(outputPath)) { fail(`Target appeared while generating. Audio remains at ${temporaryPath}; inspect it before retrying.`); } // Preserve the completed temporary file if a filesystem error prevents renaming. await rename(temporaryPath, outputPath); console.log(`Saved ${bytes.length} bytes to ${outputPath}. Listen to it and measure its actual duration before publishing.`); } main().catch((error) => { if (error.name === 'TimeoutError' || error.name === 'AbortError') { console.error('The request timed out. It may have completed on the provider side. Check History before starting another generation.'); } else { console.error(error.message); } process.exitCode = 1; });