Files
Live_RC/src/tts_settings_view.js
T
larssandandClaude Opus 5.5 ebd0f74f40 feat(audio): add downloadable extra Piper voices with accents
Adds Alma (sv), Alan, Northern English, Cori, Alba (British/Scottish)
and Joe, John, Norman (American) as optional voices downloaded one at
a time from Settings, with gender (measured pitch) and accent shown in
the voice lists. The standard install is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 21:58:08 +02:00

148 lines
8.0 KiB
JavaScript

// "Voice engine" panel in Settings -> Audio: choose browser voices or the local Piper
// voices, install Piper + Swedish/English voices once, and pre-generate fixed phrases and
// driver names so race day never waits on generation.
import { speakWithPiper } from "./piper_speech.js";
const LANGUAGES = ["sv", "en"];
// Fixed per language on purpose - the sample must be in the voice being tested, not the UI language.
const SAMPLES = { sv: "Heat ett startar om tio sekunder. Nytt varvrekord för Alex Karlsson.", en: "Heat one starts in ten seconds. New lap record for Alex Karlsson." };
async function getStatus() {
return fetch("/api/tts/status").then((res) => res.json()).catch(() => null);
}
const voiceSettingKey = (language) => (language === "sv" ? "ttsVoiceSv" : "ttsVoiceEn");
async function buildPregenerateItems(state) {
const manifest = await fetch("/race-sounds/sound_manifest.json").then((res) => res.json()).catch(() => ({}));
const items = [];
LANGUAGES.forEach((language) => {
const voice = state.settings[voiceSettingKey(language)] || "";
Object.values(manifest?.voice_events?.[language] || {})
.filter((text) => typeof text === "string" && text && !text.includes("{"))
.forEach((text) => items.push({ text, language, voice }));
(state.drivers || []).forEach((driver) => {
const name = String(driver.speechName || driver.name || "").trim();
if (name) items.push({ text: name, language, voice });
});
});
return items;
}
export async function mountTtsSettings(container, deps) {
if (!container) return;
const { state, t, escapeHtml, saveState, speakText } = deps;
const status = await getStatus();
if (!container.isConnected) return;
const remount = () => mountTtsSettings(container, deps);
const voicesFor = (language) => (status?.voices || []).filter((voice) => voice.language === language);
const hasLanguage = (language) => voicesFor(language).length > 0;
// Complete = a male and a female voice installed for every language.
const complete = LANGUAGES.every((language) => ["male", "female"].every((gender) => voicesFor(language).some((voice) => voice.gender === gender)));
const voiceLabel = (voice) => {
const details = [voice.gender ? t(voice.gender === "male" ? "tts.gender_male" : "tts.gender_female") : "", voice.accent ? t(`tts.accent_${voice.accent}`) : ""].filter(Boolean);
return details.length ? `${voice.label} (${details.join(", ")})` : voice.label;
};
const downloadable = status?.downloadable || [];
const voiceSelect = (language) => {
const chosen = state.settings[voiceSettingKey(language)] || "";
const automatic = voicesFor(language).find((voice) => voice.isDefault) || voicesFor(language)[0];
return `
<div class="tts-voice-row">
<label><span>${escapeHtml(t(language === "sv" ? "tts.voice_sv" : "tts.voice_en"))}</span>
<select data-tts-voice="${language}" ${hasLanguage(language) ? "" : "disabled"}>
<option value="">${escapeHtml(t("tts.voice_auto"))}${automatic ? ` - ${escapeHtml(voiceLabel(automatic))}` : ""}</option>
${voicesFor(language).map((voice) => `<option value="${escapeHtml(voice.name)}" ${chosen === voice.name ? "selected" : ""}>${escapeHtml(voiceLabel(voice))}</option>`).join("")}
</select>
</label>
<button class="btn" type="button" data-tts-test="${language}" ${hasLanguage(language) ? "" : "disabled"}>${escapeHtml(t("tts.test"))}</button>
</div>`;
};
const engine = state.settings.ttsEngine === "piper" ? "piper" : "browser";
const install = status?.install || {};
const pregen = status?.pregenerate || {};
const busy = install.running || pregen.running;
container.innerHTML = `
<p class="hint">${escapeHtml(t("tts.hint"))}</p>
<div class="form-grid cols-2">
<label><span>${escapeHtml(t("tts.engine"))}</span>
<select id="ttsEngine">
<option value="browser" ${engine === "browser" ? "selected" : ""}>${escapeHtml(t("tts.engine_browser"))}</option>
<option value="piper" ${engine === "piper" ? "selected" : ""}>${escapeHtml(t("tts.engine_piper"))}</option>
</select>
</label>
<div>
<p><strong>${escapeHtml(status?.available ? t("tts.status_ready") : t("tts.status_missing"))}</strong></p>
<p class="hint">${LANGUAGES.map((language) => `${language === "sv" ? "Svenska" : "English"}: ${hasLanguage(language) ? "✓" : "✗"}`).join(" · ")} · ${escapeHtml(t("tts.cached", { count: status?.cachedLines || 0 }))}</p>
</div>
</div>
<div class="actions">
<button class="btn" type="button" id="ttsInstall" ${busy ? "disabled" : ""}>${escapeHtml(t(status?.available && complete ? "tts.reinstall" : "tts.install"))}</button>
<button class="btn" type="button" id="ttsPregenerate" ${busy || !status?.available ? "disabled" : ""}>${escapeHtml(t("tts.pregenerate"))}</button>
</div>
<div class="form-grid cols-2 mt-16">
${voiceSelect("sv")}
${voiceSelect("en")}
</div>
<p class="error" id="ttsTestError" hidden></p>
${downloadable.length ? `
<h4 class="mt-16">${escapeHtml(t("tts.more_voices"))}</h4>
<p class="hint">${escapeHtml(t("tts.more_voices_hint"))}</p>
<div class="tts-download-list">
${downloadable.map((voice) => `
<div class="tts-download-row">
<span>${voice.language === "sv" ? "Svenska" : "English"} · <strong>${escapeHtml(voiceLabel(voice))}</strong></span>
<button class="btn btn-mini" type="button" data-tts-download="${escapeHtml(voice.name)}" ${busy ? "disabled" : ""}>${escapeHtml(install.running && install.voice === voice.name ? t("tts.downloading") : t("tts.download"))}</button>
</div>`).join("")}
</div>` : ""}
${install.running || install.log?.length ? `<pre class="log-box">${escapeHtml((install.log || []).join("\n"))}${install.error ? `\n${escapeHtml(install.error)}` : ""}</pre>` : ""}
${pregen.total ? `<p class="hint">${escapeHtml(t("tts.pregenerate_progress", { done: pregen.done, total: pregen.total, failed: pregen.failed }))}</p>` : ""}`;
container.querySelector("#ttsEngine").addEventListener("change", (event) => {
state.settings.ttsEngine = event.target.value === "piper" ? "piper" : "browser";
saveState();
});
container.querySelector("#ttsInstall").addEventListener("click", async () => {
await fetch("/api/tts/install", { method: "POST" });
remount();
});
container.querySelectorAll("[data-tts-download]").forEach((button) => {
button.addEventListener("click", async () => {
await fetch("/api/tts/install", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ voice: button.dataset.ttsDownload }) });
remount();
});
});
container.querySelector("#ttsPregenerate").addEventListener("click", async () => {
await fetch("/api/tts/pregenerate", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ items: await buildPregenerateItems(state) }) });
remount();
});
container.querySelectorAll("[data-tts-voice]").forEach((select) => {
select.addEventListener("change", () => {
state.settings[voiceSettingKey(select.dataset.ttsVoice)] = select.value;
saveState();
});
});
// Always tests the Piper voice itself (no browser fallback), whatever engine is active,
// so picking a voice and hearing it are never confused with the browser's voice.
container.querySelectorAll("[data-tts-test]").forEach((button) => {
button.addEventListener("click", () => {
const language = button.dataset.ttsTest;
const error = container.querySelector("#ttsTestError");
error.hidden = true;
speakWithPiper(SAMPLES[language], {
language,
voice: state.settings[voiceSettingKey(language)] || "",
interrupt: true,
fallback: () => {
error.textContent = t("tts.test_failed");
error.hidden = false;
return true;
},
});
});
});
// Keep polling while a background install/pre-generation is running.
if (busy) setTimeout(() => { if (container.isConnected) remount(); }, 1500);
}