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
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()
|
||||
Loading…
Add table
Add a link
Reference in a new issue