From b5a81bdb15363455a991c1ec3b9a784814954cf3 Mon Sep 17 00:00:00 2001 From: Bashy Date: Sat, 21 Nov 2026 13:06:32 +0200 Subject: [PATCH] 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 --- .gitignore | 5 + CLAUDE.md | 16 +++ src/app.js | 1 + src/db.js | 33 ++++++ src/routers/tts.js | 48 ++++++++ src/tts.js | 197 +++++++++++++++++++++++++++++++ tools/tts/setup.sh | 26 ++++ tools/tts/worker.py | 171 +++++++++++++++++++++++++++ views/layout.ejs | 1 + views/tts.ejs | 282 ++++++++++++++++++++++++++++++++++++++++++++ 10 files changed, 780 insertions(+) create mode 100644 src/routers/tts.js create mode 100644 src/tts.js create mode 100755 tools/tts/setup.sh create mode 100644 tools/tts/worker.py create mode 100644 views/tts.ejs diff --git a/.gitignore b/.gitignore index 962c904..5cde934 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,8 @@ node_modules/ *.db-wal public/media/* !public/media/.gitkeep + +# TTS: generated audio, Piper install and voice models (tools/tts/setup.sh) +public/tts/ +tools/tts/venv/ +tools/tts/voices/ diff --git a/CLAUDE.md b/CLAUDE.md index 02fbf22..36e7ef4 100644 --- a/CLAUDE.md +++ b/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. - 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/.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 Configured in `settings`. When a chat message arrives in the overlay, tmi.js checks: diff --git a/src/app.js b/src/app.js index 0c40d91..86564c2 100644 --- a/src/app.js +++ b/src/app.js @@ -56,6 +56,7 @@ app.use('/media', requireAuth, require('./routers/media')); app.use('/settings', requireAuth, require('./routers/settings')); app.use('/alerts', requireAuth, require('./routers/alerts')); app.use('/redeems', requireAuth, require('./routers/redeems')); +app.use('/tts', requireAuth, require('./routers/tts')); app.use('/', requireAuth, require('./routers/dashboard')); module.exports = app; diff --git a/src/db.js b/src/db.js index 7c09d81..fcc8ed6 100644 --- a/src/db.js +++ b/src/db.js @@ -86,6 +86,14 @@ function createSchema() { -- 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). + -- 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 ( id INTEGER PRIMARY KEY AUTOINCREMENT, 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); } +// 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 function logActivity(eventType, eventDetail, username, data, actionsFired) { db.prepare(` @@ -293,5 +325,6 @@ module.exports = { getAllMedia, getMediaFile, createMedia, deleteMedia, getAllActions, getAction, createAction, toggleAction, deleteAction, getMatchingActions, getAllVariations, getVariationsFor, getVariation, createVariation, updateVariation, renameTrigger, deleteVariation, + getAllTtsVoices, getTtsVoice, createTtsVoice, updateTtsVoice, deleteTtsVoice, logActivity, getActivityLog, }; diff --git a/src/routers/tts.js b/src/routers/tts.js new file mode 100644 index 0000000..3b649b3 --- /dev/null +++ b/src/routers/tts.js @@ -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; diff --git a/src/tts.js b/src/tts.js new file mode 100644 index 0000000..2ece907 --- /dev/null +++ b/src/tts.js @@ -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 }; diff --git a/tools/tts/setup.sh b/tools/tts/setup.sh new file mode 100755 index 0000000..413e1c0 --- /dev/null +++ b/tools/tts/setup.sh @@ -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$||' diff --git a/tools/tts/worker.py b/tools/tts/worker.py new file mode 100644 index 0000000..306e6f3 --- /dev/null +++ b/tools/tts/worker.py @@ -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() diff --git a/views/layout.ejs b/views/layout.ejs index 4788dc0..c5e3a73 100644 --- a/views/layout.ejs +++ b/views/layout.ejs @@ -24,6 +24,7 @@
  • Dashboard
  • Redeems
  • +
  • TTS
  • Actions
  • Media
  • Settings
  • diff --git a/views/tts.ejs b/views/tts.ejs new file mode 100644 index 0000000..2556dcf --- /dev/null +++ b/views/tts.ejs @@ -0,0 +1,282 @@ +<% const J = x => JSON.stringify(x).replace(/ + + +

    TTS voices

    +<% if (error) { %> +
    + The TTS engine is not running. +

    <%= error %>

    +

    Set it up once with tools/tts/setup.sh (installs Piper and downloads voices), then reload this page.

    +
    +<% } else { %> +
    +
    +
    +

    Quick start

    +
    +
    +
    +
    + +
    +
    +

    Effects +

    +
    +
    +
    + +
    +
    +

    Test

    + +
    + + + +
    +
    +
    +

    Save

    + +
    + + + +
    +
    +
    +

    Saved voices

    +
      +
      +
      +
      + + +<% } %>