import { NextRequest } from "next/server"; export const dynamic = "force-dynamic"; export const runtime = "nodejs"; export const maxDuration = 120; /** * POST /api/tts/generate * * Proxies openedai-speech /v1/audio/speech endpoint. * * Body: { * model: 'tts-1' | 'tts-1-hd', * voice: string, * input: string, * response_format?: string, * speed?: number, * language?: string, // 'ru', 'en', etc. — passed to XTTSv2 for better quality * } * * For Russian text with tts-1-hd (XTTSv2): * - The voice_to_speaker.yaml should have language: ru set for the voice * - Or we pass it as a hint via extra_body (non-standard OpenAI extension) */ export async function POST(req: NextRequest) { const body = (await req.json()) as { model?: string; voice?: string; input?: string; response_format?: string; speed?: number; language?: string; }; if (!body.input || !body.voice) { return Response.json( { ok: false, error: "input and voice are required" }, { status: 400 } ); } // The OpenAI API doesn't support a language parameter, but openedai-speech // reads it from the voice_to_speaker.yaml config. If the user passes a // language, we include it in the payload — openedai-speech ignores unknown // fields in the API request, but the voice config should have language set. const payload: Record = { model: body.model || "tts-1-hd", voice: body.voice, input: body.input, response_format: body.response_format || "mp3", }; if (body.speed != null) payload.speed = body.speed; try { const res = await fetch("http://tts:8000/v1/audio/speech", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), signal: req.signal, }); if (!res.ok || !res.body) { const text = await res.text().catch(() => ""); return Response.json( { ok: false, error: `tts returned ${res.status}: ${text.slice(0, 500)}` }, { status: res.status } ); } const contentType = res.headers.get("content-type") || "audio/mpeg"; const format = body.response_format || "mp3"; const arrayBuffer = await res.arrayBuffer(); return new Response(arrayBuffer, { headers: { "Content-Type": contentType, "Content-Disposition": `attachment; filename="tts-output.${format}"`, "Content-Length": `${arrayBuffer.byteLength}`, }, }); } catch (err) { const msg = (err as Error).message; const hint = msg.includes("ECONNREFUSED") || msg.includes("fetch failed") ? "TTS container is not running. Start it from the TTS tab." : msg.includes("ENOTFOUND") ? "TTS container not found on Docker network." : msg; return Response.json( { ok: false, error: hint }, { status: 503 } ); } }