Add TTS voice builder (/tts): Piper + espeak, layers, effects
- src/tts.js: synth(config, text) -> cached mp3 in public/tts; up to 3 layers (engine, voice, speaker, speed, pitch, volume, delay) mixed with ffmpeg, 8 effects (stadium, echo, 8-bit, radio, robot, choir, warp, shaky), loudnorm; config is clamped and voice/speaker names are restricted to plain names - tools/tts/worker.py: long-running Python worker (JSON lines), Piper models kept loaded (LRU of 4), espeak-ng via libespeak-ng + ctypes - tools/tts/setup.sh: venv + piper-tts + default voice set - /tts page: presets, layers, effects, test playback, save/load/delete named voices (tts_voices table); TTS link in the nav - public/tts, tools/tts/venv and tools/tts/voices are gitignored Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
463c6580f4
commit
b5a81bdb15
10 changed files with 780 additions and 0 deletions
5
.gitignore
vendored
5
.gitignore
vendored
|
|
@ -13,3 +13,8 @@ node_modules/
|
||||||
*.db-wal
|
*.db-wal
|
||||||
public/media/*
|
public/media/*
|
||||||
!public/media/.gitkeep
|
!public/media/.gitkeep
|
||||||
|
|
||||||
|
# TTS: generated audio, Piper install and voice models (tools/tts/setup.sh)
|
||||||
|
public/tts/
|
||||||
|
tools/tts/venv/
|
||||||
|
tools/tts/voices/
|
||||||
|
|
|
||||||
16
CLAUDE.md
16
CLAUDE.md
|
|
@ -135,6 +135,22 @@ Chat (`?parts=chat`) is `public/chat/chat.css` + `public/chat/chat.js` (window.H
|
||||||
- Moderation: deleted messages, timeouts, bans and /clear remove the matching slips at once.
|
- Moderation: deleted messages, timeouts, bans and /clear remove the matching slips at once.
|
||||||
- Design preview with other styles: `~/Desktop/Stream/chat/index.html` (not in the repo).
|
- Design preview with other styles: `~/Desktop/Stream/chat/index.html` (not in the repo).
|
||||||
|
|
||||||
|
## TTS voices (/tts)
|
||||||
|
|
||||||
|
Builder page to make named TTS voices; redeems do not use them yet.
|
||||||
|
- `src/tts.js`: `synth(config, text)` -> cached mp3 in `public/tts/<sha1>.mp3` (gitignored, newest 300 kept).
|
||||||
|
Config = up to 3 `layers` (engine `piper`|`espeak`, voice, speaker, speed, pitch in semitones, volume, delay ms)
|
||||||
|
+ `effects` {stadium, echo, crush, radio, robot, chorus, flanger, tremolo: 0..1}. `normalize()` clamps everything
|
||||||
|
and only accepts plain voice/speaker names (no paths). Pitch = asetrate+atempo (formants shift too: the demon sound).
|
||||||
|
ffmpeg: per-layer pitch/volume/delay -> amix -> effects -> loudnorm -> mono mp3.
|
||||||
|
- `tools/tts/worker.py`: long-running Python process (JSON lines over stdin/stdout), started on first use. Piper
|
||||||
|
models stay loaded (LRU, `TTS_MAX_LOADED`=4, ~100 MB each); espeak-ng via libespeak-ng + ctypes (no binary needed).
|
||||||
|
- Setup (server): `sudo apt install python3-venv ffmpeg espeak-ng`, then `tools/tts/setup.sh` (venv + default voices
|
||||||
|
into `tools/tts/voices/`, both gitignored). Extra voices: `tools/tts/setup.sh en_US-amy-medium ...`.
|
||||||
|
Env overrides: `TTS_PYTHON`, `TTS_VOICES_DIR`.
|
||||||
|
- Table `tts_voices` (name, config JSON). Routes: GET `/tts`, POST `/tts/preview`, POST `/tts/voices`, POST `/tts/voices/:id/delete`.
|
||||||
|
- SAM (C64 voice) was left out on purpose: the only JS port has no licence (abandonware).
|
||||||
|
|
||||||
## Gap / new-message audio
|
## Gap / new-message audio
|
||||||
|
|
||||||
Configured in `settings`. When a chat message arrives in the overlay, tmi.js checks:
|
Configured in `settings`. When a chat message arrives in the overlay, tmi.js checks:
|
||||||
|
|
|
||||||
|
|
@ -56,6 +56,7 @@ app.use('/media', requireAuth, require('./routers/media'));
|
||||||
app.use('/settings', requireAuth, require('./routers/settings'));
|
app.use('/settings', requireAuth, require('./routers/settings'));
|
||||||
app.use('/alerts', requireAuth, require('./routers/alerts'));
|
app.use('/alerts', requireAuth, require('./routers/alerts'));
|
||||||
app.use('/redeems', requireAuth, require('./routers/redeems'));
|
app.use('/redeems', requireAuth, require('./routers/redeems'));
|
||||||
|
app.use('/tts', requireAuth, require('./routers/tts'));
|
||||||
app.use('/', requireAuth, require('./routers/dashboard'));
|
app.use('/', requireAuth, require('./routers/dashboard'));
|
||||||
|
|
||||||
module.exports = app;
|
module.exports = app;
|
||||||
|
|
|
||||||
33
src/db.js
33
src/db.js
|
|
@ -86,6 +86,14 @@ function createSchema() {
|
||||||
|
|
||||||
-- Channel point rewards / built-in rewards / bits Power-ups: each trigger has variations,
|
-- Channel point rewards / built-in rewards / bits Power-ups: each trigger has variations,
|
||||||
-- one is picked at random weighted by rarity (like Twitch alert variations).
|
-- one is picked at random weighted by rarity (like Twitch alert variations).
|
||||||
|
-- TTS voices built on the /tts page: config is JSON (layers + effects, see src/tts.js normalize()).
|
||||||
|
CREATE TABLE IF NOT EXISTS tts_voices (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
config TEXT NOT NULL,
|
||||||
|
created_at TEXT DEFAULT (datetime('now'))
|
||||||
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS reward_variations (
|
CREATE TABLE IF NOT EXISTS reward_variations (
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
kind TEXT NOT NULL, -- reward | auto_reward | power_up
|
kind TEXT NOT NULL, -- reward | auto_reward | power_up
|
||||||
|
|
@ -268,6 +276,30 @@ function deleteVariation(id) {
|
||||||
db.prepare('DELETE FROM reward_variations WHERE id = ?').run(id);
|
db.prepare('DELETE FROM reward_variations WHERE id = ?').run(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TTS voices (config is stored as JSON text, returned parsed)
|
||||||
|
const ttsRow = r => r && { ...r, config: JSON.parse(r.config) };
|
||||||
|
|
||||||
|
function getAllTtsVoices() {
|
||||||
|
return db.prepare('SELECT * FROM tts_voices ORDER BY name COLLATE NOCASE, id').all().map(ttsRow);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getTtsVoice(id) {
|
||||||
|
return ttsRow(db.prepare('SELECT * FROM tts_voices WHERE id = ?').get(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
function createTtsVoice(name, config) {
|
||||||
|
const r = db.prepare('INSERT INTO tts_voices (name, config) VALUES (?, ?)').run(name, JSON.stringify(config));
|
||||||
|
return getTtsVoice(r.lastInsertRowid);
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateTtsVoice(id, name, config) {
|
||||||
|
db.prepare('UPDATE tts_voices SET name = ?, config = ? WHERE id = ?').run(name, JSON.stringify(config), id);
|
||||||
|
}
|
||||||
|
|
||||||
|
function deleteTtsVoice(id) {
|
||||||
|
db.prepare('DELETE FROM tts_voices WHERE id = ?').run(id);
|
||||||
|
}
|
||||||
|
|
||||||
// Activity log
|
// Activity log
|
||||||
function logActivity(eventType, eventDetail, username, data, actionsFired) {
|
function logActivity(eventType, eventDetail, username, data, actionsFired) {
|
||||||
db.prepare(`
|
db.prepare(`
|
||||||
|
|
@ -293,5 +325,6 @@ module.exports = {
|
||||||
getAllMedia, getMediaFile, createMedia, deleteMedia,
|
getAllMedia, getMediaFile, createMedia, deleteMedia,
|
||||||
getAllActions, getAction, createAction, toggleAction, deleteAction, getMatchingActions,
|
getAllActions, getAction, createAction, toggleAction, deleteAction, getMatchingActions,
|
||||||
getAllVariations, getVariationsFor, getVariation, createVariation, updateVariation, renameTrigger, deleteVariation,
|
getAllVariations, getVariationsFor, getVariation, createVariation, updateVariation, renameTrigger, deleteVariation,
|
||||||
|
getAllTtsVoices, getTtsVoice, createTtsVoice, updateTtsVoice, deleteTtsVoice,
|
||||||
logActivity, getActivityLog,
|
logActivity, getActivityLog,
|
||||||
};
|
};
|
||||||
|
|
|
||||||
48
src/routers/tts.js
Normal file
48
src/routers/tts.js
Normal file
|
|
@ -0,0 +1,48 @@
|
||||||
|
// /tts — TTS voice builder: combine engines, voices, pitch/speed, layers and effects, test, save as named voices.
|
||||||
|
const express = require('express');
|
||||||
|
const router = express.Router();
|
||||||
|
const db = require('../db');
|
||||||
|
const tts = require('../tts');
|
||||||
|
|
||||||
|
router.get('/', async (req, res) => {
|
||||||
|
let voices = null, error = null;
|
||||||
|
try { voices = await tts.voices(); }
|
||||||
|
catch (e) { error = e.message; }
|
||||||
|
res.render('tts', {
|
||||||
|
voices, error, saved: db.getAllTtsVoices(),
|
||||||
|
effects: Object.fromEntries(Object.entries(tts.EFFECTS).map(([k, e]) => [k, { label: e.label, hint: e.hint }])),
|
||||||
|
limits: tts.LIMITS, defaults: tts.DEFAULT_CONFIG, maxChars: tts.MAX_CHARS,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// play: { config, text } -> { url, ms, cached }
|
||||||
|
router.post('/preview', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const out = await tts.synth(req.body.config, req.body.text);
|
||||||
|
res.json({ ok: true, url: out.url, ms: out.ms, cached: out.cached });
|
||||||
|
} catch (e) {
|
||||||
|
res.status(400).json({ ok: false, error: e.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// save: { id?, name, config } -> { voice }
|
||||||
|
router.post('/voices', (req, res) => {
|
||||||
|
try {
|
||||||
|
const name = String(req.body.name || '').trim().slice(0, 60);
|
||||||
|
if (!name) throw new Error('give the voice a name');
|
||||||
|
const config = tts.normalize(req.body.config);
|
||||||
|
const id = parseInt(req.body.id, 10);
|
||||||
|
if (!isNaN(id) && db.getTtsVoice(id)) db.updateTtsVoice(id, name, config);
|
||||||
|
const voice = !isNaN(id) && db.getTtsVoice(id) ? db.getTtsVoice(id) : db.createTtsVoice(name, config);
|
||||||
|
res.json({ ok: true, voice });
|
||||||
|
} catch (e) {
|
||||||
|
res.status(400).json({ ok: false, error: e.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post('/voices/:id/delete', (req, res) => {
|
||||||
|
db.deleteTtsVoice(req.params.id);
|
||||||
|
res.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
197
src/tts.js
Normal file
197
src/tts.js
Normal file
|
|
@ -0,0 +1,197 @@
|
||||||
|
// Text-to-speech: engines (Piper, espeak-ng) via the Python worker in tools/tts/worker.py, then ffmpeg for
|
||||||
|
// pitch/speed per layer, mixing up to 3 layers, effects and loudness. Output: cached mp3 in public/tts/.
|
||||||
|
//
|
||||||
|
// A voice config (stored in tts_voices.config, edited on the /tts page):
|
||||||
|
// { layers: [ { engine: 'piper'|'espeak', voice, speaker, speed, pitch, volume, delay } ... up to 3 ],
|
||||||
|
// effects: { stadium: 0..1, echo: 0..1, crush: 0..1, radio: 0..1, robot: 0..1, chorus: 0..1, flanger: 0..1, tremolo: 0..1 } }
|
||||||
|
// pitch is in semitones (changes the voice's character, like the "deep demon"), speed 1 = normal.
|
||||||
|
//
|
||||||
|
// Env: TTS_PYTHON (python with piper-tts, default tools/tts/venv/bin/python), TTS_VOICES_DIR (Piper models,
|
||||||
|
// default tools/tts/voices). See tools/tts/setup.sh.
|
||||||
|
const { spawn, execFile } = require('child_process');
|
||||||
|
const crypto = require('crypto');
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const ROOT = path.join(__dirname, '..');
|
||||||
|
const PY = process.env.TTS_PYTHON || path.join(ROOT, 'tools/tts/venv/bin/python');
|
||||||
|
const WORKER = path.join(ROOT, 'tools/tts/worker.py');
|
||||||
|
const VOICES_DIR = process.env.TTS_VOICES_DIR || path.join(ROOT, 'tools/tts/voices');
|
||||||
|
const OUT_DIR = path.join(ROOT, 'public/tts');
|
||||||
|
const TMP_DIR = path.join(OUT_DIR, 'tmp');
|
||||||
|
const KEEP_FILES = 300; // cached mp3s kept in public/tts (oldest deleted first)
|
||||||
|
const MAX_CHARS = 300;
|
||||||
|
const SR = 44100;
|
||||||
|
|
||||||
|
const LIMITS = {
|
||||||
|
layers: 3,
|
||||||
|
speed: [0.5, 2], pitch: [-12, 12], volume: [0, 1.5], delay: [0, 1000],
|
||||||
|
};
|
||||||
|
|
||||||
|
// effect key -> label, hint and the ffmpeg filter for amount a (0 < a <= 1)
|
||||||
|
const EFFECTS = {
|
||||||
|
stadium: { label: 'Stadium', hint: 'big hall: long double echo',
|
||||||
|
f: a => `aecho=0.8:0.9:${r(60 + 60 * a)}|${r(120 + 120 * a)}:${n(0.25 + 0.25 * a)}|${n(0.15 + 0.2 * a)}` },
|
||||||
|
echo: { label: 'Echo', hint: 'short cave echo (the demon uses this)',
|
||||||
|
f: a => `aecho=0.8:0.85:${r(40 + 60 * a)}:${n(0.15 + 0.35 * a)}` },
|
||||||
|
crush: { label: '8-bit', hint: 'bit-crushed, glitchy',
|
||||||
|
f: a => `acrusher=bits=${r(8 - 5 * a)}:samples=${r(1 + 6 * a)}:mix=${n(0.4 + 0.5 * a)}` },
|
||||||
|
radio: { label: 'Radio', hint: 'thin, crackly walkie-talkie',
|
||||||
|
f: a => `highpass=f=${r(300 + 300 * a)},lowpass=f=${r(3500 - 1200 * a)},acrusher=bits=8:mix=${n(0.1 + 0.3 * a)},volume=1.5` },
|
||||||
|
robot: { label: 'Robot', hint: 'metallic ring modulation',
|
||||||
|
f: a => `aeval='val(0)*(${n(1 - a)}+${n(a)}*sin(2*PI*${r(30 + 30 * a)}*t))':c=same` },
|
||||||
|
chorus: { label: 'Choir', hint: 'several voices at once',
|
||||||
|
f: a => `chorus=0.6:0.9:50|60|40:${n(0.4 * a)}|${n(0.32 * a)}|${n(0.3 * a)}:0.25|0.4|0.3:2|2.3|1.3` },
|
||||||
|
flanger: { label: 'Warp', hint: 'swooshy jet flanger',
|
||||||
|
f: a => `flanger=delay=${n(2 * a)}:depth=${n(2 + 6 * a)}` },
|
||||||
|
tremolo: { label: 'Shaky', hint: 'wobbling volume',
|
||||||
|
f: a => `tremolo=f=${n(4 + 6 * a)}:d=${n(0.2 + 0.6 * a)}` },
|
||||||
|
};
|
||||||
|
function r(x) { return Math.round(x); }
|
||||||
|
function n(x) { return Number(x.toFixed(3)); }
|
||||||
|
|
||||||
|
const DEFAULT_CONFIG = {
|
||||||
|
layers: [{ engine: 'piper', voice: 'en_GB-alan-medium', speaker: '', speed: 1, pitch: 0, volume: 1, delay: 0 }],
|
||||||
|
effects: {},
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------- validation ----------
|
||||||
|
const SAFE_NAME = /^[A-Za-z0-9_+-][A-Za-z0-9_.+-]{0,119}$/;
|
||||||
|
const clamp = (v, [lo, hi], d) => { const x = parseFloat(v); return isNaN(x) ? d : Math.max(lo, Math.min(hi, x)); };
|
||||||
|
|
||||||
|
function normalize(input) {
|
||||||
|
const c = typeof input === 'string' ? JSON.parse(input) : (input || {});
|
||||||
|
const layers = (Array.isArray(c.layers) ? c.layers : []).slice(0, LIMITS.layers).map(l => ({
|
||||||
|
engine: l.engine === 'espeak' ? 'espeak' : 'piper',
|
||||||
|
voice: SAFE_NAME.test(l.voice || '') ? l.voice : '', // plain names only: no paths
|
||||||
|
speaker: SAFE_NAME.test(l.speaker ?? '') ? String(l.speaker) : '',
|
||||||
|
speed: clamp(l.speed, LIMITS.speed, 1),
|
||||||
|
pitch: clamp(l.pitch, LIMITS.pitch, 0),
|
||||||
|
volume: clamp(l.volume, LIMITS.volume, 1),
|
||||||
|
delay: Math.round(clamp(l.delay, LIMITS.delay, 0)),
|
||||||
|
})).filter(l => l.voice);
|
||||||
|
if (!layers.length) throw new Error('a voice needs at least one layer');
|
||||||
|
const effects = {};
|
||||||
|
for (const k of Object.keys(EFFECTS)) {
|
||||||
|
const a = clamp(c.effects?.[k], [0, 1], 0);
|
||||||
|
if (a > 0) effects[k] = n(a);
|
||||||
|
}
|
||||||
|
return { layers, effects };
|
||||||
|
}
|
||||||
|
|
||||||
|
function cleanText(text) {
|
||||||
|
return String(text || '').replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, MAX_CHARS);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- worker ----------
|
||||||
|
let proc = null, outBuf = '', nextId = 1;
|
||||||
|
const pending = new Map();
|
||||||
|
|
||||||
|
function failAll(err) {
|
||||||
|
for (const p of pending.values()) { clearTimeout(p.timer); p.reject(err); }
|
||||||
|
pending.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
function worker() {
|
||||||
|
if (proc) return proc;
|
||||||
|
proc = spawn(PY, [WORKER], { env: { ...process.env, TTS_VOICES_DIR: VOICES_DIR }, stdio: ['pipe', 'pipe', 'pipe'] });
|
||||||
|
outBuf = '';
|
||||||
|
proc.stdout.on('data', d => {
|
||||||
|
outBuf += d;
|
||||||
|
let i;
|
||||||
|
while ((i = outBuf.indexOf('\n')) >= 0) {
|
||||||
|
const line = outBuf.slice(0, i); outBuf = outBuf.slice(i + 1);
|
||||||
|
let msg; try { msg = JSON.parse(line); } catch { continue; } // ignore stray library output
|
||||||
|
const p = pending.get(msg.id);
|
||||||
|
if (!p) continue;
|
||||||
|
pending.delete(msg.id); clearTimeout(p.timer);
|
||||||
|
msg.ok ? p.resolve(msg) : p.reject(new Error(msg.error || 'TTS failed'));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
proc.stderr.on('data', d => { const s = String(d).trim(); if (s) console.log('[tts-worker]', s.slice(0, 500)); });
|
||||||
|
proc.on('error', e => { console.error('[tts] worker failed to start:', e.message, `(TTS_PYTHON=${PY})`); proc = null; failAll(e); });
|
||||||
|
proc.on('exit', code => { if (proc) console.log(`[tts] worker exited (${code})`); proc = null; failAll(new Error('TTS worker exited')); });
|
||||||
|
return proc;
|
||||||
|
}
|
||||||
|
|
||||||
|
function call(req, timeoutMs = 30000) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const id = nextId++;
|
||||||
|
const timer = setTimeout(() => { pending.delete(id); reject(new Error('TTS worker timed out')); }, timeoutMs);
|
||||||
|
pending.set(id, { resolve, reject, timer });
|
||||||
|
try { worker().stdin.write(JSON.stringify({ ...req, id }) + '\n'); }
|
||||||
|
catch (e) { pending.delete(id); clearTimeout(timer); reject(e); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let voiceCache = null, voiceCacheAt = 0;
|
||||||
|
async function voices() {
|
||||||
|
if (voiceCache && Date.now() - voiceCacheAt < 60000) return voiceCache;
|
||||||
|
const v = await call({ op: 'voices' }, 60000);
|
||||||
|
voiceCache = { piper: v.piper || [], espeak: v.espeak || [] };
|
||||||
|
voiceCacheAt = Date.now();
|
||||||
|
return voiceCache;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- synthesis ----------
|
||||||
|
function ffmpeg(args) {
|
||||||
|
return new Promise((resolve, reject) => execFile('ffmpeg', args, { timeout: 60000 }, (err, _o, stderr) =>
|
||||||
|
err ? reject(new Error('ffmpeg: ' + String(stderr || err.message).trim().split('\n').slice(-3).join(' '))) : resolve()));
|
||||||
|
}
|
||||||
|
|
||||||
|
function layerFilter(l, i) {
|
||||||
|
const f = [`aresample=${SR}`];
|
||||||
|
if (l.pitch) {
|
||||||
|
const k = Math.pow(2, l.pitch / 12); // shift pitch + formants, keep the length
|
||||||
|
f.push(`asetrate=${r(SR * k)}`, `aresample=${SR}`, `atempo=${n(1 / k)}`);
|
||||||
|
}
|
||||||
|
if (l.volume !== 1) f.push(`volume=${l.volume}`);
|
||||||
|
if (l.delay) f.push(`adelay=${l.delay}|${l.delay}`);
|
||||||
|
return `[${i}:a]${f.join(',')}[l${i}]`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function prune() {
|
||||||
|
try {
|
||||||
|
const files = fs.readdirSync(OUT_DIR).filter(f => f.endsWith('.mp3'))
|
||||||
|
.map(f => ({ f, t: fs.statSync(path.join(OUT_DIR, f)).mtimeMs })).sort((a, b) => b.t - a.t);
|
||||||
|
for (const x of files.slice(KEEP_FILES)) fs.unlinkSync(path.join(OUT_DIR, x.f));
|
||||||
|
} catch (e) { console.warn('[tts] prune:', e.message); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returns { url, file, cached, ms }. Same config + text = same file (cached).
|
||||||
|
async function synth(configIn, textIn) {
|
||||||
|
const config = normalize(configIn);
|
||||||
|
const text = cleanText(textIn);
|
||||||
|
if (!text) throw new Error('nothing to say');
|
||||||
|
const hash = crypto.createHash('sha1').update(JSON.stringify([config, text])).digest('hex').slice(0, 20);
|
||||||
|
const file = path.join(OUT_DIR, `${hash}.mp3`);
|
||||||
|
const url = `/tts/${hash}.mp3`;
|
||||||
|
if (fs.existsSync(file)) return { url, file, cached: true, ms: 0 };
|
||||||
|
|
||||||
|
const t0 = Date.now();
|
||||||
|
fs.mkdirSync(TMP_DIR, { recursive: true });
|
||||||
|
const wavs = config.layers.map((_, i) => path.join(TMP_DIR, `${hash}-${i}.wav`));
|
||||||
|
try {
|
||||||
|
await Promise.all(config.layers.map((l, i) => call(l.engine === 'piper'
|
||||||
|
? { op: 'say', engine: 'piper', voice: l.voice, speaker: l.speaker || null, length_scale: n(1 / l.speed), text, out: wavs[i] }
|
||||||
|
: { op: 'say', engine: 'espeak', voice: l.voice, rate: r(160 * l.speed), text, out: wavs[i] })));
|
||||||
|
|
||||||
|
const parts = config.layers.map(layerFilter);
|
||||||
|
const mixIn = config.layers.map((_, i) => `[l${i}]`).join('');
|
||||||
|
const fx = Object.entries(config.effects).map(([k, a]) => EFFECTS[k].f(a));
|
||||||
|
const chain = [
|
||||||
|
config.layers.length > 1 ? `${mixIn}amix=inputs=${config.layers.length}:duration=longest:normalize=0` : `[l0]anull`,
|
||||||
|
...fx,
|
||||||
|
'loudnorm=I=-16:TP=-1.5',
|
||||||
|
].join(',');
|
||||||
|
await ffmpeg(['-loglevel', 'error', '-y', ...wavs.flatMap(w => ['-i', w]),
|
||||||
|
'-filter_complex', `${parts.join(';')};${chain}[out]`, '-map', '[out]',
|
||||||
|
'-ac', '1', '-ar', String(SR), '-codec:a', 'libmp3lame', '-q:a', '3', file]);
|
||||||
|
} finally {
|
||||||
|
for (const w of wavs) fs.rm(w, { force: true }, () => {});
|
||||||
|
}
|
||||||
|
prune();
|
||||||
|
return { url, file, cached: false, ms: Date.now() - t0 };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { voices, synth, normalize, cleanText, EFFECTS, LIMITS, DEFAULT_CONFIG, MAX_CHARS };
|
||||||
26
tools/tts/setup.sh
Executable file
26
tools/tts/setup.sh
Executable file
|
|
@ -0,0 +1,26 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
# One-time TTS setup for HeyStreamer. Run on the server (or dev PC) from anywhere:
|
||||||
|
# tools/tts/setup.sh -> installs Piper into tools/tts/venv and downloads the default voices
|
||||||
|
# tools/tts/setup.sh en_US-amy-medium ... -> downloads extra voices (names: https://huggingface.co/rhasspy/piper-voices)
|
||||||
|
# Needs: python3-venv, ffmpeg, espeak-ng (sudo apt install python3-venv ffmpeg espeak-ng). Restart HeyStreamer afterwards.
|
||||||
|
set -euo pipefail
|
||||||
|
cd "$(dirname "$0")"
|
||||||
|
|
||||||
|
missing=()
|
||||||
|
command -v ffmpeg >/dev/null || missing+=(ffmpeg)
|
||||||
|
ldconfig -p 2>/dev/null | grep -q libespeak-ng || missing+=(espeak-ng)
|
||||||
|
python3 -c 'import venv, ensurepip' 2>/dev/null || missing+=(python3-venv)
|
||||||
|
if ((${#missing[@]})); then echo "First install: sudo apt install ${missing[*]}"; exit 1; fi
|
||||||
|
|
||||||
|
[ -x venv/bin/python ] || python3 -m venv venv
|
||||||
|
venv/bin/pip install -q --upgrade pip piper-tts
|
||||||
|
|
||||||
|
# default set (~65 MB each): male-heavy English picks + a few female voices
|
||||||
|
DEFAULT=(
|
||||||
|
en_GB-alan-medium en_GB-northern_english_male-medium en_GB-semaine-medium en_GB-vctk-medium
|
||||||
|
en_US-ryan-high en_US-joe-medium en_US-john-medium en_US-norman-medium en_US-bryce-medium
|
||||||
|
en_US-kusal-medium en_US-mike-medium en_US-hfc_male-medium en_US-arctic-medium
|
||||||
|
en_US-lessac-medium en_US-kristin-medium en_GB-cori-medium
|
||||||
|
)
|
||||||
|
venv/bin/python -m piper.download_voices --download-dir voices "${@:-${DEFAULT[@]}}"
|
||||||
|
echo "Voices in $(pwd)/voices:"; ls voices/*.onnx | sed 's|.*/||; s|\.onnx$||'
|
||||||
171
tools/tts/worker.py
Normal file
171
tools/tts/worker.py
Normal file
|
|
@ -0,0 +1,171 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
"""HeyStreamer TTS worker: one long-running process, started by src/tts.js.
|
||||||
|
|
||||||
|
Reads one JSON request per line on stdin, writes one JSON reply per line on stdout.
|
||||||
|
{"id": 1, "op": "voices"} -> {"id": 1, "ok": true, "piper": [...], "espeak": [...]}
|
||||||
|
{"id": 2, "op": "say", "engine": "piper", "voice": "en_GB-alan-medium", "speaker": null,
|
||||||
|
"length_scale": 1.0, "text": "...", "out": "/path/x.wav"} -> {"id": 2, "ok": true}
|
||||||
|
{"id": 3, "op": "say", "engine": "espeak", "voice": "en-us+klatt", "rate": 160, "pitch": 50,
|
||||||
|
"text": "...", "out": "/path/y.wav"} -> {"id": 3, "ok": true}
|
||||||
|
Errors come back as {"id": n, "ok": false, "error": "..."}.
|
||||||
|
|
||||||
|
Piper: `pip install piper-tts` in this script's venv; voice models (*.onnx + *.onnx.json) in the voices dir.
|
||||||
|
espeak: uses libespeak-ng through ctypes (`apt install espeak-ng`), so no espeak binary is needed.
|
||||||
|
"""
|
||||||
|
import ctypes
|
||||||
|
import ctypes.util
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import wave
|
||||||
|
import array
|
||||||
|
import re
|
||||||
|
|
||||||
|
SAFE_NAME = re.compile(r'^[A-Za-z0-9_+-][A-Za-z0-9_.+-]{0,119}$') # plain names only: no paths
|
||||||
|
|
||||||
|
VOICES_DIR = os.environ.get('TTS_VOICES_DIR') or os.path.join(os.path.dirname(os.path.abspath(__file__)), 'voices')
|
||||||
|
|
||||||
|
# ---------- piper ----------
|
||||||
|
_piper = {} # model -> PiperVoice, most recently used last
|
||||||
|
MAX_LOADED = int(os.environ.get('TTS_MAX_LOADED', '4')) # each model is ~100 MB of RAM
|
||||||
|
|
||||||
|
|
||||||
|
def piper_voice(model):
|
||||||
|
if model in _piper:
|
||||||
|
_piper[model] = _piper.pop(model) # mark as recently used
|
||||||
|
return _piper[model]
|
||||||
|
from piper import PiperVoice # imported lazily so espeak works without piper installed
|
||||||
|
if not SAFE_NAME.match(model or ''):
|
||||||
|
raise ValueError('bad voice name')
|
||||||
|
path = os.path.join(VOICES_DIR, model + '.onnx')
|
||||||
|
if not os.path.isfile(path):
|
||||||
|
raise ValueError('unknown piper voice: ' + model)
|
||||||
|
while len(_piper) >= MAX_LOADED:
|
||||||
|
_piper.pop(next(iter(_piper)))
|
||||||
|
_piper[model] = PiperVoice.load(path)
|
||||||
|
return _piper[model]
|
||||||
|
|
||||||
|
|
||||||
|
def piper_list():
|
||||||
|
out = []
|
||||||
|
try:
|
||||||
|
names = sorted(f for f in os.listdir(VOICES_DIR) if f.endswith('.onnx'))
|
||||||
|
except FileNotFoundError:
|
||||||
|
return out
|
||||||
|
for f in names:
|
||||||
|
model = f[:-5]
|
||||||
|
try:
|
||||||
|
with open(os.path.join(VOICES_DIR, f + '.json'), encoding='utf-8') as fh:
|
||||||
|
cfg = json.load(fh)
|
||||||
|
except (OSError, ValueError):
|
||||||
|
continue
|
||||||
|
out.append({
|
||||||
|
'model': model,
|
||||||
|
'language': (cfg.get('language') or {}).get('code') or model.split('-')[0],
|
||||||
|
'quality': (cfg.get('audio') or {}).get('quality') or model.rsplit('-', 1)[-1],
|
||||||
|
'speakers': sorted(cfg.get('speaker_id_map') or {}, key=lambda k: cfg['speaker_id_map'][k]),
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def piper_say(req):
|
||||||
|
from piper import SynthesisConfig
|
||||||
|
v = piper_voice(req['voice'])
|
||||||
|
sid = None
|
||||||
|
spk = req.get('speaker')
|
||||||
|
if spk not in (None, ''):
|
||||||
|
sid = v.config.speaker_id_map.get(spk)
|
||||||
|
if sid is None:
|
||||||
|
raise ValueError('unknown speaker: %s' % spk)
|
||||||
|
cfg = SynthesisConfig(speaker_id=sid, length_scale=float(req.get('length_scale') or 1.0))
|
||||||
|
with wave.open(req['out'], 'wb') as w:
|
||||||
|
v.synthesize_wav(req['text'], w, syn_config=cfg)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- espeak-ng (libespeak-ng via ctypes) ----------
|
||||||
|
_es = {'lib': None, 'rate': 0, 'buf': None, 'cb': None}
|
||||||
|
CALLBACK = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.POINTER(ctypes.c_short), ctypes.c_int, ctypes.c_void_p)
|
||||||
|
|
||||||
|
|
||||||
|
def espeak_lib():
|
||||||
|
if _es['lib'] is None:
|
||||||
|
name = ctypes.util.find_library('espeak-ng') or 'libespeak-ng.so.1'
|
||||||
|
lib = ctypes.CDLL(name)
|
||||||
|
_es['rate'] = lib.espeak_Initialize(2, 0, None, 0) # AUDIO_OUTPUT_SYNCHRONOUS
|
||||||
|
|
||||||
|
def cb(wav, n, _ev):
|
||||||
|
if wav and n > 0:
|
||||||
|
_es['buf'].extend(wav[:n])
|
||||||
|
return 0
|
||||||
|
_es['cb'] = CALLBACK(cb) # keep a reference, or it gets garbage collected
|
||||||
|
lib.espeak_SetSynthCallback(_es['cb'])
|
||||||
|
_es['lib'] = lib
|
||||||
|
return _es['lib']
|
||||||
|
|
||||||
|
|
||||||
|
def espeak_list():
|
||||||
|
"""English voice + the variant files (klatt, Demonic, croak...), as 'en-us+variant' names."""
|
||||||
|
try:
|
||||||
|
espeak_lib()
|
||||||
|
except OSError:
|
||||||
|
return []
|
||||||
|
variants = []
|
||||||
|
for base in ('/usr/lib/x86_64-linux-gnu/espeak-ng-data/voices/!v', '/usr/lib/aarch64-linux-gnu/espeak-ng-data/voices/!v',
|
||||||
|
'/usr/share/espeak-ng-data/voices/!v', '/usr/lib/espeak-ng-data/voices/!v'):
|
||||||
|
if os.path.isdir(base):
|
||||||
|
variants = sorted(os.listdir(base), key=str.lower)
|
||||||
|
break
|
||||||
|
return ['en-us', 'en'] + ['en-us+' + v for v in variants]
|
||||||
|
|
||||||
|
|
||||||
|
def espeak_say(req):
|
||||||
|
lib = espeak_lib()
|
||||||
|
if not SAFE_NAME.match(str(req.get('voice') or '')):
|
||||||
|
raise ValueError('bad voice name')
|
||||||
|
if lib.espeak_SetVoiceByName(str(req['voice']).encode()) != 0:
|
||||||
|
raise ValueError('unknown espeak voice: %s' % req['voice'])
|
||||||
|
lib.espeak_SetParameter(1, int(req.get('rate') or 160), 0) # espeakRATE (words per minute)
|
||||||
|
lib.espeak_SetParameter(3, int(req.get('pitch') or 50), 0) # espeakPITCH (0-100)
|
||||||
|
_es['buf'] = array.array('h')
|
||||||
|
t = req['text'].encode('utf-8') + b'\0'
|
||||||
|
lib.espeak_Synth(t, len(t), 0, 1, 0, 0, None, None)
|
||||||
|
lib.espeak_Synchronize()
|
||||||
|
with wave.open(req['out'], 'wb') as w:
|
||||||
|
w.setnchannels(1)
|
||||||
|
w.setsampwidth(2)
|
||||||
|
w.setframerate(_es['rate'])
|
||||||
|
w.writeframes(_es['buf'].tobytes())
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- loop ----------
|
||||||
|
def handle(req):
|
||||||
|
op = req.get('op')
|
||||||
|
if op == 'voices':
|
||||||
|
return {'piper': piper_list(), 'espeak': espeak_list()}
|
||||||
|
if op == 'say':
|
||||||
|
if not req.get('text') or not req.get('out'):
|
||||||
|
raise ValueError('text and out are required')
|
||||||
|
{'piper': piper_say, 'espeak': espeak_say}[req['engine']](req)
|
||||||
|
return {}
|
||||||
|
raise ValueError('unknown op: %s' % op)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
for line in sys.stdin:
|
||||||
|
line = line.strip()
|
||||||
|
if not line:
|
||||||
|
continue
|
||||||
|
rid = None
|
||||||
|
try:
|
||||||
|
req = json.loads(line)
|
||||||
|
rid = req.get('id')
|
||||||
|
reply = {'id': rid, 'ok': True}
|
||||||
|
reply.update(handle(req))
|
||||||
|
except Exception as e: # one bad request must not kill the worker
|
||||||
|
reply = {'id': rid, 'ok': False, 'error': '%s: %s' % (type(e).__name__, e)}
|
||||||
|
sys.stdout.write(json.dumps(reply) + '\n')
|
||||||
|
sys.stdout.flush()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|
@ -24,6 +24,7 @@
|
||||||
<ul>
|
<ul>
|
||||||
<li><a href="/">Dashboard</a></li>
|
<li><a href="/">Dashboard</a></li>
|
||||||
<li><a href="/redeems">Redeems</a></li>
|
<li><a href="/redeems">Redeems</a></li>
|
||||||
|
<li><a href="/tts">TTS</a></li>
|
||||||
<li><a href="/actions">Actions</a></li>
|
<li><a href="/actions">Actions</a></li>
|
||||||
<li><a href="/media">Media</a></li>
|
<li><a href="/media">Media</a></li>
|
||||||
<li><a href="/settings">Settings</a></li>
|
<li><a href="/settings">Settings</a></li>
|
||||||
|
|
|
||||||
282
views/tts.ejs
Normal file
282
views/tts.ejs
Normal file
|
|
@ -0,0 +1,282 @@
|
||||||
|
<% const J = x => JSON.stringify(x).replace(/</g, '\\u003c'); %>
|
||||||
|
<style>
|
||||||
|
.tts { display:grid; grid-template-columns: minmax(0, 1.6fr) minmax(0, 1fr); gap:1.4rem; align-items:start; }
|
||||||
|
@media (max-width: 900px) { .tts { grid-template-columns: 1fr; } }
|
||||||
|
.card { border:1px solid var(--pico-muted-border-color); border-radius:10px; padding:.8rem 1rem; margin-bottom:1rem; }
|
||||||
|
.card h4 { margin:0 0 .6rem; font-size:1rem; display:flex; align-items:center; gap:.6rem; }
|
||||||
|
.card h4 .sp { flex:1; }
|
||||||
|
.grid2 { display:grid; grid-template-columns: 1fr 1fr; gap:.3rem .8rem; }
|
||||||
|
.tts label { font-size:.78rem; margin:0 0 .15rem; color:var(--pico-muted-color); display:flex; justify-content:space-between; }
|
||||||
|
.tts label b { color:var(--pico-color); font-weight:600; }
|
||||||
|
.tts select, .tts input:not([type=range]), .tts textarea { margin:0 0 .5rem; padding:.3rem .5rem; font-size:.88rem; height:auto; }
|
||||||
|
.tts input[type=range] { margin:0 0 .55rem; }
|
||||||
|
.btn-sm { margin:0; padding:.25rem .7rem; font-size:.8rem; width:auto; }
|
||||||
|
.row { display:flex; gap:.5rem; flex-wrap:wrap; align-items:center; }
|
||||||
|
.presets button { margin:0; padding:.25rem .65rem; font-size:.8rem; width:auto; }
|
||||||
|
.fx { display:grid; grid-template-columns: 1fr 1fr; gap:0 .9rem; }
|
||||||
|
.fx .off label b { color:var(--pico-muted-color); font-weight:400; }
|
||||||
|
.status { font-size:.85rem; color:var(--pico-muted-color); min-height:1.3em; }
|
||||||
|
.status.err { color:#f88; }
|
||||||
|
.saved { list-style:none; padding:0; margin:0; }
|
||||||
|
.saved li { display:flex; gap:.4rem; align-items:center; padding:.4rem 0; border-top:1px dashed var(--pico-muted-border-color); list-style:none; }
|
||||||
|
.saved li .nm { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||||
|
.saved li.cur .nm { color:var(--pico-primary); font-weight:600; }
|
||||||
|
.danger { color:#f88; border-color:#f88; }
|
||||||
|
.tts [data-tooltip]:not(a, button, input) { border-bottom:none; text-decoration:none; }
|
||||||
|
</style>
|
||||||
|
|
||||||
|
<h2>TTS voices</h2>
|
||||||
|
<% if (error) { %>
|
||||||
|
<article>
|
||||||
|
<strong>The TTS engine is not running.</strong>
|
||||||
|
<p class="status err"><%= error %></p>
|
||||||
|
<p>Set it up once with <code>tools/tts/setup.sh</code> (installs Piper and downloads voices), then reload this page.</p>
|
||||||
|
</article>
|
||||||
|
<% } else { %>
|
||||||
|
<div class="tts">
|
||||||
|
<div>
|
||||||
|
<div class="card">
|
||||||
|
<h4>Quick start</h4>
|
||||||
|
<div class="row presets" id="presets"></div>
|
||||||
|
</div>
|
||||||
|
<div id="layers"></div>
|
||||||
|
<div class="row" style="margin:-.4rem 0 1rem;">
|
||||||
|
<button type="button" class="outline btn-sm" id="addLayer"
|
||||||
|
data-tooltip="Layers speak the same text at once, mixed together (e.g. a normal and a deep copy = 'possessed')">+ Add layer</button>
|
||||||
|
</div>
|
||||||
|
<div class="card">
|
||||||
|
<h4>Effects <span class="sp"></span>
|
||||||
|
<button type="button" class="outline secondary btn-sm" id="fxOff">All off</button></h4>
|
||||||
|
<div class="fx" id="fx"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<div class="card">
|
||||||
|
<h4>Test</h4>
|
||||||
|
<textarea id="text" rows="3" maxlength="<%= maxChars %>">Streamer! Hydrate check. Also, nice shot. I was totally not camping that container.</textarea>
|
||||||
|
<div class="row">
|
||||||
|
<button type="button" id="play" class="btn-sm">▶ Play</button>
|
||||||
|
<button type="button" id="stop" class="outline secondary btn-sm">■ Stop</button>
|
||||||
|
<span class="status" id="status"></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="card">
|
||||||
|
<h4>Save</h4>
|
||||||
|
<input id="name" placeholder="Voice name, e.g. Alan demon" maxlength="60">
|
||||||
|
<div class="row">
|
||||||
|
<button type="button" id="saveNew" class="btn-sm" data-tooltip="Save the current settings as a new voice">Save as new</button>
|
||||||
|
<button type="button" id="saveCur" class="outline btn-sm" disabled data-tooltip="Overwrite the voice you loaded">Update</button>
|
||||||
|
<span class="status" id="saveStatus"></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="card">
|
||||||
|
<h4>Saved voices</h4>
|
||||||
|
<ul class="saved" id="saved"></ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
(() => {
|
||||||
|
const VOICES = <%- J(voices) %>, EFFECTS = <%- J(effects) %>, LIMITS = <%- J(limits) %>, DEFAULTS = <%- J(defaults) %>;
|
||||||
|
let saved = <%- J(saved) %>;
|
||||||
|
let cfg = JSON.parse(JSON.stringify(DEFAULTS)), currentId = null;
|
||||||
|
const $ = s => document.querySelector(s);
|
||||||
|
const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&':'&','<':'<','>':'>','"':'"',"'":''' }[c]));
|
||||||
|
|
||||||
|
// ---------- voice lists ----------
|
||||||
|
const pretty = m => { // en_GB-alan-medium -> Alan (GB, medium)
|
||||||
|
const [lang, name, q] = m.split('-');
|
||||||
|
const nm = (name || m).split('_').map(w => w[0].toUpperCase() + w.slice(1)).join(' ');
|
||||||
|
return `${nm} (${(lang.split('_')[1] || lang)}, ${q || ''})`;
|
||||||
|
};
|
||||||
|
const piperByModel = Object.fromEntries(VOICES.piper.map(v => [v.model, v]));
|
||||||
|
function voiceOptions(engine, sel) {
|
||||||
|
if (engine === 'espeak') return VOICES.espeak.map(v => `<option value="${esc(v)}"${v === sel ? ' selected' : ''}>${esc(v.replace('en-us+', ''))}</option>`).join('');
|
||||||
|
const groups = {};
|
||||||
|
for (const v of VOICES.piper) (groups[v.language] ||= []).push(v);
|
||||||
|
return Object.entries(groups).sort().map(([lang, list]) => `<optgroup label="${esc(lang)}">` +
|
||||||
|
list.map(v => `<option value="${esc(v.model)}"${v.model === sel ? ' selected' : ''}>${esc(pretty(v.model))}${v.speakers.length ? ` · ${v.speakers.length} speakers` : ''}</option>`).join('') +
|
||||||
|
'</optgroup>').join('');
|
||||||
|
}
|
||||||
|
const firstVoice = engine => engine === 'espeak' ? (VOICES.espeak.find(v => /klatt$/.test(v)) || VOICES.espeak[0]) : (piperByModel['en_GB-alan-medium'] ? 'en_GB-alan-medium' : VOICES.piper[0]?.model);
|
||||||
|
|
||||||
|
// ---------- layers ----------
|
||||||
|
const slider = (key, label, min, max, step, val, fmt, tip) =>
|
||||||
|
`<div${tip ? ` data-tooltip="${esc(tip)}"` : ''}><label>${label} <b data-out="${key}">${fmt(val)}</b></label>
|
||||||
|
<input type="range" data-k="${key}" min="${min}" max="${max}" step="${step}" value="${val}"></div>`;
|
||||||
|
const FMT = {
|
||||||
|
speed: v => `${(+v).toFixed(2)}×`, pitch: v => `${v > 0 ? '+' : ''}${v} st`,
|
||||||
|
volume: v => `${Math.round(v * 100)}%`, delay: v => `${v} ms`,
|
||||||
|
};
|
||||||
|
|
||||||
|
function renderLayers() {
|
||||||
|
$('#layers').innerHTML = cfg.layers.map((l, i) => {
|
||||||
|
const pv = l.engine === 'piper' ? piperByModel[l.voice] : null;
|
||||||
|
const speakers = pv && pv.speakers.length
|
||||||
|
? `<div><label>Speaker</label><select data-k="speaker">${pv.speakers.map(s => `<option${s === l.speaker ? ' selected' : ''}>${esc(s)}</option>`).join('')}</select></div>` : '';
|
||||||
|
return `<div class="card" data-i="${i}">
|
||||||
|
<h4>${i ? `Layer ${i + 1}` : 'Voice'}<span class="sp"></span>
|
||||||
|
${i ? `<button type="button" class="outline secondary btn-sm" data-remove>Remove</button>` : ''}</h4>
|
||||||
|
<div class="grid2">
|
||||||
|
<div><label>Engine</label><select data-k="engine">
|
||||||
|
<option value="piper"${l.engine === 'piper' ? ' selected' : ''}>Piper (natural)</option>
|
||||||
|
<option value="espeak"${l.engine === 'espeak' ? ' selected' : ''}>espeak (robot / retro)</option></select></div>
|
||||||
|
<div><label>Voice</label><select data-k="voice">${voiceOptions(l.engine, l.voice)}</select></div>
|
||||||
|
${speakers}
|
||||||
|
</div>
|
||||||
|
<div class="grid2">
|
||||||
|
${slider('speed', 'Speed', LIMITS.speed[0], LIMITS.speed[1], 0.05, l.speed, FMT.speed)}
|
||||||
|
${slider('pitch', 'Pitch', LIMITS.pitch[0], LIMITS.pitch[1], 1, l.pitch, FMT.pitch, 'Semitones. Down = deeper, demon-like; up = chipmunk')}
|
||||||
|
${i ? slider('volume', 'Volume', 0, LIMITS.volume[1], 0.05, l.volume, FMT.volume) : ''}
|
||||||
|
${i ? slider('delay', 'Delay', 0, LIMITS.delay[1], 10, l.delay, FMT.delay, 'Start this layer a bit later, for an echo-y double') : ''}
|
||||||
|
</div></div>`;
|
||||||
|
}).join('');
|
||||||
|
$('#addLayer').disabled = cfg.layers.length >= LIMITS.layers;
|
||||||
|
}
|
||||||
|
|
||||||
|
$('#layers').addEventListener('input', e => {
|
||||||
|
const k = e.target.dataset.k, card = e.target.closest('[data-i]');
|
||||||
|
if (!k || !card) return;
|
||||||
|
const l = cfg.layers[+card.dataset.i];
|
||||||
|
if (e.target.type === 'range') {
|
||||||
|
l[k] = +e.target.value;
|
||||||
|
card.querySelector(`[data-out="${k}"]`).textContent = FMT[k](l[k]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
l[k] = e.target.value;
|
||||||
|
if (k === 'engine') { l.voice = firstVoice(l.engine); l.speaker = ''; }
|
||||||
|
if (k === 'engine' || k === 'voice') {
|
||||||
|
const pv = l.engine === 'piper' ? piperByModel[l.voice] : null;
|
||||||
|
l.speaker = pv && pv.speakers.length ? (pv.speakers.includes(l.speaker) ? l.speaker : pv.speakers[0]) : '';
|
||||||
|
renderLayers();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
$('#layers').addEventListener('click', e => {
|
||||||
|
if (!e.target.matches('[data-remove]')) return;
|
||||||
|
cfg.layers.splice(+e.target.closest('[data-i]').dataset.i, 1);
|
||||||
|
renderLayers();
|
||||||
|
});
|
||||||
|
$('#addLayer').onclick = () => {
|
||||||
|
const base = cfg.layers[0];
|
||||||
|
cfg.layers.push({ ...base, pitch: base.pitch - 7, volume: 0.7, delay: 0 });
|
||||||
|
renderLayers();
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------- effects ----------
|
||||||
|
function renderFx() {
|
||||||
|
$('#fx').innerHTML = Object.entries(EFFECTS).map(([k, e]) => {
|
||||||
|
const v = cfg.effects[k] || 0;
|
||||||
|
return `<div class="${v ? '' : 'off'}" data-tooltip="${esc(e.hint)}"><label>${esc(e.label)} <b data-fxout="${k}">${v ? Math.round(v * 100) + '%' : 'off'}</b></label>
|
||||||
|
<input type="range" data-fx="${k}" min="0" max="1" step="0.05" value="${v}"></div>`;
|
||||||
|
}).join('');
|
||||||
|
}
|
||||||
|
$('#fx').addEventListener('input', e => {
|
||||||
|
const k = e.target.dataset.fx; if (!k) return;
|
||||||
|
const v = +e.target.value;
|
||||||
|
if (v) cfg.effects[k] = v; else delete cfg.effects[k];
|
||||||
|
e.target.parentElement.classList.toggle('off', !v);
|
||||||
|
$(`[data-fxout="${k}"]`).textContent = v ? Math.round(v * 100) + '%' : 'off';
|
||||||
|
});
|
||||||
|
$('#fxOff').onclick = () => { cfg.effects = {}; renderFx(); };
|
||||||
|
|
||||||
|
// ---------- quick presets (keep the current voice, change the rest) ----------
|
||||||
|
const PRESETS = {
|
||||||
|
'Plain': l => ({ layers: [{ ...l, speed: 1, pitch: 0 }], effects: {} }),
|
||||||
|
'Deep demon': l => ({ layers: [{ ...l, pitch: -6, speed: 1 }], effects: { echo: 0.5 } }),
|
||||||
|
'Stadium': l => ({ layers: [{ ...l, pitch: 0, speed: 0.92 }], effects: { stadium: 0.7 } }),
|
||||||
|
'8-bit': l => ({ layers: [{ ...l, pitch: 0, speed: 1 }], effects: { crush: 1 } }),
|
||||||
|
'Chipmunk': l => ({ layers: [{ ...l, pitch: 7, speed: 1.1 }], effects: {} }),
|
||||||
|
'Radio': l => ({ layers: [{ ...l, pitch: 0, speed: 1 }], effects: { radio: 0.7 } }),
|
||||||
|
'Robot': l => ({ layers: [{ ...l, pitch: 0, speed: 1 }], effects: { robot: 0.8 } }),
|
||||||
|
'Possessed': l => ({ layers: [{ ...l, pitch: 0, speed: 1 }, { ...l, pitch: -8, speed: 1, volume: 0.8, delay: 30 }], effects: { echo: 0.4 } }),
|
||||||
|
'Choir': l => ({ layers: [{ ...l, pitch: 0, speed: 1 }, { ...l, pitch: 5, speed: 1, volume: 0.6, delay: 15 }, { ...l, pitch: -5, speed: 1, volume: 0.6, delay: 25 }], effects: { chorus: 0.6, stadium: 0.3 } }),
|
||||||
|
};
|
||||||
|
$('#presets').innerHTML = Object.keys(PRESETS).map(p => `<button type="button" class="outline btn-sm" data-preset="${esc(p)}">${esc(p)}</button>`).join('');
|
||||||
|
$('#presets').onclick = e => {
|
||||||
|
const p = e.target.dataset.preset; if (!p) return;
|
||||||
|
const l = { volume: 1, delay: 0, ...cfg.layers[0] };
|
||||||
|
cfg = PRESETS[p](l);
|
||||||
|
renderLayers(); renderFx(); play();
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------- play ----------
|
||||||
|
const audio = new Audio();
|
||||||
|
async function post(url, body) {
|
||||||
|
const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
||||||
|
const j = await r.json().catch(() => ({ ok: false, error: `HTTP ${r.status}` }));
|
||||||
|
if (!j.ok) throw new Error(j.error || 'failed');
|
||||||
|
return j;
|
||||||
|
}
|
||||||
|
async function play() {
|
||||||
|
const st = $('#status'); st.className = 'status'; st.textContent = 'Generating…';
|
||||||
|
$('#play').setAttribute('aria-busy', 'true');
|
||||||
|
try {
|
||||||
|
const j = await post('/tts/preview', { config: cfg, text: $('#text').value });
|
||||||
|
audio.src = j.url; await audio.play();
|
||||||
|
st.textContent = j.cached ? 'Playing (cached)' : `Playing · made in ${(j.ms / 1000).toFixed(1)} s`;
|
||||||
|
} catch (e) { st.className = 'status err'; st.textContent = e.message; }
|
||||||
|
$('#play').removeAttribute('aria-busy');
|
||||||
|
}
|
||||||
|
$('#play').onclick = play;
|
||||||
|
$('#stop').onclick = () => audio.pause();
|
||||||
|
$('#text').addEventListener('keydown', e => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); play(); } });
|
||||||
|
|
||||||
|
// ---------- save / load / delete ----------
|
||||||
|
function renderSaved() {
|
||||||
|
$('#saved').innerHTML = saved.length ? saved.map(v => `<li class="${v.id === currentId ? 'cur' : ''}" data-id="${v.id}">
|
||||||
|
<span class="nm">${esc(v.name)}</span>
|
||||||
|
<button type="button" class="outline btn-sm" data-act="play" data-tooltip="Play the test text with this voice">▶</button>
|
||||||
|
<button type="button" class="outline btn-sm" data-act="load">Load</button>
|
||||||
|
<button type="button" class="outline secondary btn-sm" data-act="del">Delete</button></li>`).join('')
|
||||||
|
: '<li><span class="nm status">Nothing saved yet.</span></li>';
|
||||||
|
$('#saveCur').disabled = !currentId;
|
||||||
|
}
|
||||||
|
async function save(asNew) {
|
||||||
|
const st = $('#saveStatus'); st.className = 'status';
|
||||||
|
try {
|
||||||
|
const j = await post('/tts/voices', { id: asNew ? null : currentId, name: $('#name').value, config: cfg });
|
||||||
|
saved = saved.filter(v => v.id !== j.voice.id).concat(j.voice).sort((a, b) => a.name.localeCompare(b.name));
|
||||||
|
currentId = j.voice.id; st.textContent = 'Saved'; renderSaved();
|
||||||
|
} catch (e) { st.className = 'status err'; st.textContent = e.message; }
|
||||||
|
}
|
||||||
|
$('#saveNew').onclick = () => save(true);
|
||||||
|
$('#saveCur').onclick = () => save(false);
|
||||||
|
|
||||||
|
let armed = null; // two-click delete, no browser dialog
|
||||||
|
$('#saved').onclick = async e => {
|
||||||
|
const act = e.target.dataset.act, li = e.target.closest('[data-id]');
|
||||||
|
if (!act || !li) return;
|
||||||
|
const v = saved.find(x => x.id === +li.dataset.id);
|
||||||
|
if (act === 'load' || act === 'play') {
|
||||||
|
cfg = JSON.parse(JSON.stringify(v.config));
|
||||||
|
for (const l of cfg.layers) { l.volume ??= 1; l.delay ??= 0; }
|
||||||
|
cfg.effects ||= {};
|
||||||
|
if (act === 'load') { currentId = v.id; $('#name').value = v.name; renderSaved(); }
|
||||||
|
renderLayers(); renderFx();
|
||||||
|
if (act === 'play') play();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (act === 'del') {
|
||||||
|
if (armed !== e.target) {
|
||||||
|
if (armed) armed.textContent = 'Delete';
|
||||||
|
armed = e.target; e.target.textContent = 'Really?'; e.target.classList.add('danger');
|
||||||
|
setTimeout(() => { if (armed === e.target) { e.target.textContent = 'Delete'; e.target.classList.remove('danger'); armed = null; } }, 3000);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
armed = null;
|
||||||
|
try {
|
||||||
|
await post(`/tts/voices/${v.id}/delete`, {});
|
||||||
|
saved = saved.filter(x => x.id !== v.id);
|
||||||
|
if (currentId === v.id) currentId = null;
|
||||||
|
renderSaved();
|
||||||
|
} catch (err) { $('#saveStatus').className = 'status err'; $('#saveStatus').textContent = err.message; }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!piperByModel[cfg.layers[0].voice]) cfg.layers[0] = { ...cfg.layers[0], voice: firstVoice(VOICES.piper.length ? 'piper' : 'espeak'), engine: VOICES.piper.length ? 'piper' : 'espeak' };
|
||||||
|
renderLayers(); renderFx(); renderSaved();
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
<% } %>
|
||||||
Loading…
Add table
Add a link
Reference in a new issue