- 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>
282 lines
15 KiB
Text
282 lines
15 KiB
Text
<% 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>
|
||
<% } %>
|