Merge pull request 'fix: TTS voices cleanup — filter placeholders, auto-model switch, entrypoint always writes config + v0.9.3' (#25) from fix/tts-voices-cleanup into master

This commit was merged in pull request #25.
This commit is contained in:
2026-10-29 23:51:58 +00:00
6 changed files with 137 additions and 176 deletions

View File

@@ -120,7 +120,7 @@ export async function GET() {
ok: envError === null, ok: envError === null,
error: envError, error: envError,
}, },
version: "0.9.2", version: "0.9.3",
timestamp: new Date().toISOString(), timestamp: new Date().toISOString(),
}); });
} }

View File

@@ -1,5 +1,5 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import { promises as fs, existsSync } from "node:fs"; import { promises as fs } from "node:fs";
import path from "node:path"; import path from "node:path";
import { PROJECT_DIR } from "@/lib/docker"; import { PROJECT_DIR } from "@/lib/docker";
@@ -7,21 +7,14 @@ export const dynamic = "force-dynamic";
export const runtime = "nodejs"; export const runtime = "nodejs";
const TTS_VOICES_DIR = path.join(PROJECT_DIR, "gpu", "tts", "voices"); const TTS_VOICES_DIR = path.join(PROJECT_DIR, "gpu", "tts", "voices");
const TTS_CONFIG_DIR = path.join(PROJECT_DIR, "gpu", "tts", "config");
const VOICE_CONFIG_PATH = path.join(TTS_CONFIG_DIR, "voice_to_speaker.yaml");
/** /**
* POST /api/tts/upload-voice * POST /api/tts/upload-voice
* *
* Uploads a custom voice sample (WAV file) for XTTSv2 voice cloning. * Uploads a custom voice sample (WAV file) for XTTSv2 voice cloning.
* The file is saved to gpu/tts/voices/ AND the voice_to_speaker.yaml config * The file is saved to gpu/tts/voices/. The custom entrypoint.sh automatically
* is updated so openedai-speech picks it up after restart. * scans this directory on startup and adds .wav files as XTTS voices.
* * No config file modification needed — restart TTS to pick up new voices.
* For XTTS voice samples:
* - Mono (single channel) 22050 Hz WAV file
* - 6-30 seconds long
* - Low noise, no background sounds
* - Even speaking pace
*/ */
export async function POST(req: NextRequest) { export async function POST(req: NextRequest) {
const contentType = req.headers.get("content-type") || ""; const contentType = req.headers.get("content-type") || "";
@@ -36,7 +29,6 @@ export async function POST(req: NextRequest) {
const form = await req.formData(); const form = await req.formData();
const file = form.get("file"); const file = form.get("file");
const name = form.get("name") as string | null; const name = form.get("name") as string | null;
const language = (form.get("language") as string) || null;
if (!file || !(file instanceof File)) { if (!file || !(file instanceof File)) {
return NextResponse.json( return NextResponse.json(
@@ -45,7 +37,6 @@ export async function POST(req: NextRequest) {
); );
} }
// Voice name — use provided name or derive from filename
let voiceName: string; let voiceName: string;
if (name) { if (name) {
voiceName = name.replace(/[^\w\-]/g, "_"); voiceName = name.replace(/[^\w\-]/g, "_");
@@ -53,28 +44,20 @@ export async function POST(req: NextRequest) {
voiceName = path.parse(file.name).name.replace(/[^\w\-]/g, "_"); voiceName = path.parse(file.name).name.replace(/[^\w\-]/g, "_");
} }
// Ensure .wav extension for XTTS voices
const filename = `${voiceName}.wav`; const filename = `${voiceName}.wav`;
const dest = path.join(TTS_VOICES_DIR, filename); const dest = path.join(TTS_VOICES_DIR, filename);
// Create directories if they don't exist
await fs.mkdir(TTS_VOICES_DIR, { recursive: true }); await fs.mkdir(TTS_VOICES_DIR, { recursive: true });
await fs.mkdir(TTS_CONFIG_DIR, { recursive: true });
const buffer = Buffer.from(await file.arrayBuffer()); const buffer = Buffer.from(await file.arrayBuffer());
await fs.writeFile(dest, buffer); await fs.writeFile(dest, buffer);
// Now update voice_to_speaker.yaml to include the new voice
// openedai-speech reads this config at startup — without it, the voice
// won't appear in the voices list even though the WAV file exists.
await updateVoiceConfig(voiceName, filename, language);
return NextResponse.json({ return NextResponse.json({
ok: true, ok: true,
voice: voiceName, voice: voiceName,
path: filename, path: filename,
size: buffer.length, size: buffer.length,
hint: "Voice uploaded and config updated. Restart TTS container to apply.", hint: "Voice uploaded. Restart TTS — the entrypoint will auto-detect and add it to the config.",
}); });
} catch (err) { } catch (err) {
return NextResponse.json( return NextResponse.json(
@@ -86,8 +69,7 @@ export async function POST(req: NextRequest) {
/** /**
* GET /api/tts/upload-voice * GET /api/tts/upload-voice
* * Lists voice files on disk.
* Lists voice files on disk (in gpu/tts/voices/).
*/ */
export async function GET() { export async function GET() {
try { try {
@@ -100,100 +82,3 @@ export async function GET() {
return NextResponse.json({ ok: true, voices: [] }); return NextResponse.json({ ok: true, voices: [] });
} }
} }
/**
* Update voice_to_speaker.yaml to add a new voice entry.
* If the file doesn't exist, create it with the default built-in voices
* plus the new custom voice.
*/
async function updateVoiceConfig(
voiceName: string,
filename: string,
language: string | null
): Promise<void> {
let existing = "";
try {
existing = await fs.readFile(VOICE_CONFIG_PATH, "utf-8");
} catch {
// File doesn't exist — create from scratch with default voices
existing = createDefaultVoiceConfig();
}
// Check if voice already exists in config
if (existing.includes(` ${voiceName}:`)) {
// Voice already in config — update the speaker file path
existing = existing.replace(
new RegExp(
` ${voiceName}:\\n(?: [^\\n]+\\n)*`,
"m"
),
formatVoiceEntry(voiceName, filename, language)
);
} else {
// Add new voice under tts-1-hd section
// Find the tts-1-hd: section and append
if (existing.includes("tts-1-hd:")) {
existing = existing.replace(
/(tts-1-hd:\n)/,
`$1${formatVoiceEntry(voiceName, filename, language)}`
);
} else {
// No tts-1-hd section — add it
existing += `\ntts-1-hd:\n${formatVoiceEntry(voiceName, filename, language)}`;
}
}
await fs.writeFile(VOICE_CONFIG_PATH, existing, "utf-8");
}
function formatVoiceEntry(
name: string,
filename: string,
language: string | null
): string {
let entry = ` ${name}:\n model: xtts\n speaker: voices/${filename}\n`;
if (language) {
entry += ` language: ${language}\n`;
}
return entry;
}
function createDefaultVoiceConfig(): string {
return `# voice_to_speaker.yaml — openedai-speech voice configuration
# Custom voices are added here. Restart TTS container after changes.
tts-1:
alloy:
model: voices/en_US-amy-medium.onnx
echo:
model: voices/en_US-libritts-high.onnx
fable:
model: voices/en_US-ryan-high.onnx
onyx:
model: voices/en_US-daniel-low.onnx
nova:
model: voices/en_US-lessac-medium.onnx
shimmer:
model: voices/en_US-nora-medium.onnx
tts-1-hd:
alloy:
model: xtts
speaker: voices/alloy.wav
echo:
model: xtts
speaker: voices/echo.wav
fable:
model: xtts
speaker: voices/fable.wav
onyx:
model: xtts
speaker: voices/onyx.wav
nova:
model: xtts
speaker: voices/nova.wav
shimmer:
model: xtts
speaker: voices/shimmer.wav
`;
}

View File

@@ -10,18 +10,46 @@ const TTS_VOICES_DIR = path.join(PROJECT_DIR, "gpu", "tts", "voices");
const TTS_CONFIG_DIR = path.join(PROJECT_DIR, "gpu", "tts", "config"); const TTS_CONFIG_DIR = path.join(PROJECT_DIR, "gpu", "tts", "config");
const VOICE_CONFIG_PATH = path.join(TTS_CONFIG_DIR, "voice_to_speaker.yaml"); const VOICE_CONFIG_PATH = path.join(TTS_CONFIG_DIR, "voice_to_speaker.yaml");
// Voices to filter out (placeholders from openedai-speech defaults)
const PLACEHOLDER_VOICES = new Set([
"some_other_voice_you_want",
"your_voice",
"custom",
"example",
"test",
]);
interface VoiceInfo {
voice_id: string;
model: "tts-1" | "tts-1-hd" | "both";
}
/** /**
* GET /api/tts/voices * GET /api/tts/voices
* *
* Returns available TTS voices. Tries two sources: * Returns available TTS voices with model info.
* 1. openedai-speech /v1/audio/voices API (if TTS is running) * Sources: TTS API + voice_to_speaker.yaml + directory scan.
* 2. Falls back to reading voice_to_speaker.yaml + scanning voices/ dir
* (so voices show up even when TTS is stopped)
*/ */
export async function GET() { export async function GET() {
const voices: string[] = []; const voiceMap = new Map<string, VoiceInfo>();
// Source 1: Try the TTS API // Helper to add/update a voice
const addVoice = (name: string, model: "tts-1" | "tts-1-hd" | "both") => {
const lower = name.toLowerCase();
if (PLACEHOLDER_VOICES.has(lower)) return;
if (lower.includes("some_other") || lower.includes("your_voice")) return;
const existing = voiceMap.get(name);
if (existing) {
if (existing.model !== model) {
existing.model = "both";
}
} else {
voiceMap.set(name, { voice_id: name, model });
}
};
// Source 1: TTS API
try { try {
const res = await fetch("http://tts:8000/v1/audio/voices", { const res = await fetch("http://tts:8000/v1/audio/voices", {
cache: "no-store", cache: "no-store",
@@ -32,56 +60,64 @@ export async function GET() {
if (data.voices && Array.isArray(data.voices)) { if (data.voices && Array.isArray(data.voices)) {
for (const v of data.voices) { for (const v of data.voices) {
const id = v.voice_id || v.name; const id = v.voice_id || v.name;
if (id && !voices.includes(id)) voices.push(id); if (id) addVoice(id, "both"); // API doesn't tell us which model
} }
} }
} }
} catch { } catch {
/* TTS not running — fall through to file scan */ /* TTS not running */
} }
// Source 2: Read voice_to_speaker.yaml (always available, even when TTS is off) // Source 2: Parse voice_to_speaker.yaml
try { try {
const yaml = await fs.readFile(VOICE_CONFIG_PATH, "utf-8"); const yaml = await fs.readFile(VOICE_CONFIG_PATH, "utf-8");
// Parse voice names — they're indented under "tts-1:" and "tts-1-hd:" const lines = yaml.split("\n");
// Format: " voicename:\n model: ..." let currentSection: "tts-1" | "tts-1-hd" | null = null;
const matches = yaml.matchAll(/^\s{2}(\w[\w\-]*):/gm); for (const line of lines) {
for (const m of matches) { // Section header: "tts-1:" or "tts-1-hd:"
const name = m[1]; const sectionMatch = line.match(/^(tts-1|tts-1-hd):\s*$/);
if (!voices.includes(name)) voices.push(name); if (sectionMatch) {
currentSection = sectionMatch[1] as "tts-1" | "tts-1-hd";
continue;
}
// Voice entry: " voicename:" (2 spaces indent)
const voiceMatch = line.match(/^ ([a-zA-Z][\w\-]*):\s*$/);
if (voiceMatch && currentSection) {
addVoice(voiceMatch[1], currentSection);
}
} }
} catch { } catch {
/* config doesn't exist yet */ /* config doesn't exist */
} }
// Source 3: Scan voices/ directory for .onnx files (Piper voices) // Source 3: Scan voices/ directory
try { try {
const entries = await fs.readdir(TTS_VOICES_DIR); const entries = await fs.readdir(TTS_VOICES_DIR);
for (const f of entries) { for (const f of entries) {
if (f.endsWith(".onnx")) { if (f.endsWith(".onnx")) {
// e.g. ru_RU-irina-medium.onnx → irina // Piper voice: ru_RU-irina-medium.onnx → irina
const match = f.match(/^[a-z]{2}_([A-Z]{2})-([a-z]+)-/i); const match = f.match(/^[a-z]{2}_[A-Z]{2}-([a-z]+)-/i);
if (match) { if (match) addVoice(match[1], "tts-1");
const name = match[2];
if (!voices.includes(name)) voices.push(name);
}
} }
if (f.endsWith(".wav")) { if (f.endsWith(".wav")) {
const name = f.replace(/\.wav$/, ""); const name = f.replace(/\.wav$/, "");
if (!voices.includes(name)) voices.push(name); // Don't add built-in XTTS voices again (they're already in config)
if (!["alloy", "echo", "fable", "onyx", "nova", "shimmer"].includes(name)) {
addVoice(name, "tts-1-hd");
}
} }
} }
} catch { } catch {
/* dir doesn't exist */ /* dir doesn't exist */
} }
// Always include defaults so the dropdown isn't empty // Always include defaults
for (const d of ["alloy", "echo", "fable", "onyx", "nova", "shimmer"]) { for (const d of ["alloy", "echo", "fable", "onyx", "nova", "shimmer"]) {
if (!voices.includes(d)) voices.push(d); if (!voiceMap.has(d)) {
addVoice(d, "both");
}
} }
return NextResponse.json({ const voices = Array.from(voiceMap.values());
ok: true, return NextResponse.json({ ok: true, voices });
voices: voices.map((v) => ({ voice_id: v })),
});
} }

View File

@@ -4427,8 +4427,13 @@ function TTSTab({
busy: string | null; busy: string | null;
onServiceAction: (role: string, action: "start" | "stop" | "restart" | "remove") => void; onServiceAction: (role: string, action: "start" | "stop" | "restart" | "remove") => void;
}) { }) {
const [voices, setVoices] = React.useState<string[]>([ const [voices, setVoices] = React.useState<{ voice_id: string; model: string }[]>([
"alloy", "echo", "fable", "onyx", "nova", "shimmer" { voice_id: "alloy", model: "both" },
{ voice_id: "echo", model: "both" },
{ voice_id: "fable", model: "both" },
{ voice_id: "onyx", model: "both" },
{ voice_id: "nova", model: "both" },
{ voice_id: "shimmer", model: "both" },
]); ]);
const [selectedVoice, setSelectedVoice] = React.useState("alloy"); const [selectedVoice, setSelectedVoice] = React.useState("alloy");
const [model, setModel] = React.useState<"tts-1" | "tts-1-hd">("tts-1-hd"); const [model, setModel] = React.useState<"tts-1" | "tts-1-hd">("tts-1-hd");
@@ -4447,22 +4452,32 @@ function TTSTab({
const res = await fetch("/api/tts/voices", { cache: "no-store" }); const res = await fetch("/api/tts/voices", { cache: "no-store" });
if (!res.ok) return; if (!res.ok) return;
const data = await res.json(); const data = await res.json();
if (data.ok && data.voices) { if (data.ok && data.voices && data.voices.length > 0) {
const voiceIds = data.voices.map((v: { voice_id?: string; name?: string }) => v.voice_id || v.name).filter(Boolean); setVoices(data.voices);
if (voiceIds.length > 0) {
setVoices(voiceIds);
}
} }
} catch { } catch {
/* keep defaults */ /* keep defaults */
} }
}, []); }, []);
// Refresh voices on mount (even if TTS is not running — we read config + files) // Refresh voices on mount
React.useEffect(() => { React.useEffect(() => {
refreshVoices(); refreshVoices();
}, [refreshVoices]); }, [refreshVoices]);
// When voice changes, auto-switch model if needed
function handleVoiceChange(v: string) {
setSelectedVoice(v);
const voiceInfo = voices.find((x) => x.voice_id === v);
if (voiceInfo) {
if (voiceInfo.model === "tts-1" && model !== "tts-1") {
setModel("tts-1");
} else if (voiceInfo.model === "tts-1-hd" && model !== "tts-1-hd") {
setModel("tts-1-hd");
}
}
}
async function handleGenerate() { async function handleGenerate() {
if (!input.trim() || !ttsRunning || generating) return; if (!input.trim() || !ttsRunning || generating) return;
setGenerating(true); setGenerating(true);
@@ -4610,14 +4625,17 @@ function TTSTab({
</div> </div>
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label>Voice</Label> <Label>Voice</Label>
<Select value={selectedVoice} onValueChange={setSelectedVoice}> <Select value={selectedVoice} onValueChange={handleVoiceChange}>
<SelectTrigger> <SelectTrigger>
<SelectValue /> <SelectValue />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
{voices.map((v) => ( {voices.map((v) => (
<SelectItem key={v} value={v}> <SelectItem key={v.voice_id} value={v.voice_id}>
{v} <span className="font-mono">{v.voice_id}</span>
<span className="ml-2 text-[10px] text-muted-foreground">
{v.model === "tts-1" ? "(Piper)" : v.model === "tts-1-hd" ? "(XTTS)" : "(both)"}
</span>
</SelectItem> </SelectItem>
))} ))}
</SelectContent> </SelectContent>

View File

@@ -4,7 +4,7 @@
* Displayed in the footer and available via /api/debug so the user can * Displayed in the footer and available via /api/debug so the user can
* verify the update actually took effect. * verify the update actually took effect.
*/ */
export const DASHBOARD_VERSION = "0.9.2"; export const DASHBOARD_VERSION = "0.9.3";
/** /**
* Build timestamp — set at build time by Next.js. * Build timestamp — set at build time by Next.js.

View File

@@ -2,18 +2,19 @@
set -e set -e
# Custom entrypoint for openedai-speech # Custom entrypoint for openedai-speech
# On first run, creates voice_to_speaker.yaml in /app/config/ with: # 1. Writes base voice_to_speaker.yaml (Piper + XTTS built-in voices)
# - Piper English voices (alloy, echo, fable, onyx, nova, shimmer) # 2. Scans /app/voices/ for custom .wav files not in the base config
# - Piper Russian voices (irina, denis) ← for natural Russian # 3. Appends custom voices under tts-1-hd section
# - XTTS voices (alloy, echo, fable, onyx, nova, shimmer) # 4. Starts openedai-speech
# Then launches the original startup script.
CONFIG_DIR="/app/config" CONFIG_DIR="/app/config"
VOICES_DIR="/app/voices"
# If config dir is empty (first run), create default config mkdir -p "$CONFIG_DIR"
if [ ! -f "$CONFIG_DIR/voice_to_speaker.yaml" ]; then
echo "[entrypoint] First run: creating voice_to_speaker.yaml..." # Write base config
cat > "$CONFIG_DIR/voice_to_speaker.yaml" << 'YAML' echo "[entrypoint] Writing voice_to_speaker.yaml..."
cat > "$CONFIG_DIR/voice_to_speaker.yaml" << 'YAML'
tts-1: tts-1:
alloy: alloy:
model: voices/en_US-amy-medium.onnx model: voices/en_US-amy-medium.onnx
@@ -56,7 +57,30 @@ tts-1-hd:
model: xtts model: xtts
speaker: voices/shimmer.wav speaker: voices/shimmer.wav
YAML YAML
echo "[entrypoint] Created voice_to_speaker.yaml with Russian Piper voices (irina, denis, dmitri, ruslan)"
# Scan for custom .wav voices not in the base config
BASE_VOICES="alloy echo fable onyx nova shimmer"
if [ -d "$VOICES_DIR" ]; then
for wav_file in "$VOICES_DIR"/*.wav; do
[ -f "$wav_file" ] || continue
voice_name=$(basename "$wav_file" .wav)
# Skip if it's a base voice (alloy.wav, nova.wav, etc.)
is_base=0
for base in $BASE_VOICES; do
if [ "$voice_name" = "$base" ]; then
is_base=1
break
fi
done
if [ "$is_base" -eq 1 ]; then
continue
fi
echo "[entrypoint] Adding custom voice: $voice_name"
echo " ${voice_name}:" >> "$CONFIG_DIR/voice_to_speaker.yaml"
echo " model: xtts" >> "$CONFIG_DIR/voice_to_speaker.yaml"
echo " speaker: voices/${voice_name}.wav" >> "$CONFIG_DIR/voice_to_speaker.yaml"
echo " language: ru" >> "$CONFIG_DIR/voice_to_speaker.yaml"
done
fi fi
# If pre_process_map.yaml doesn't exist, create an empty one # If pre_process_map.yaml doesn't exist, create an empty one
@@ -65,6 +89,4 @@ if [ ! -f "$CONFIG_DIR/pre_process_map.yaml" ]; then
fi fi
echo "[entrypoint] Config ready. Starting openedai-speech..." echo "[entrypoint] Config ready. Starting openedai-speech..."
# Run the original startup script (openedai-speech uses: bash startup.sh)
exec bash /app/startup.sh exec bash /app/startup.sh