96 lines
2.6 KiB
TypeScript
96 lines
2.6 KiB
TypeScript
import { GoogleGenAI } from "@google/genai";
|
|
import { hash } from "bun";
|
|
import { PassThrough, Readable } from "stream";
|
|
import wav from "wav";
|
|
import z from "zod";
|
|
import { redis } from "@/lib/db/redis";
|
|
|
|
const { DONATE_WIDGET_KEY, GEMINI_TTS_API_KEY } = process.env as Record<
|
|
string,
|
|
string
|
|
>;
|
|
|
|
const API_KEYS = GEMINI_TTS_API_KEY.split(",")
|
|
.map((k) => k.trim())
|
|
.filter(Boolean);
|
|
|
|
const Schema = z.object({
|
|
message: z.string().max(1000),
|
|
key: z.literal(DONATE_WIDGET_KEY),
|
|
});
|
|
|
|
const voices = ["Zephyr", "Charon", "Fenrir", "Kore", "Sulafat"];
|
|
|
|
export async function GET(request: Request) {
|
|
const data = Schema.safeParse(
|
|
Object.fromEntries(new URL(request.url).searchParams.entries()),
|
|
);
|
|
if (data.error)
|
|
return new Response(z.prettifyError(data.error), { status: 400 });
|
|
const {
|
|
data: { message },
|
|
} = data;
|
|
|
|
const textHash = hash(message).toString(36);
|
|
const cached = await redis!.get(`tts:${textHash}`);
|
|
if (cached)
|
|
return new Response(pcmToWav(cached), {
|
|
headers: { "Content-Type": "audio/wav" },
|
|
});
|
|
|
|
let audioData: string | undefined;
|
|
|
|
for (const apiKey of API_KEYS) {
|
|
const client = new GoogleGenAI({ apiKey });
|
|
|
|
try {
|
|
const response = await client.models.generateContent({
|
|
model: "gemini-2.5-flash-preview-tts",
|
|
contents: [{ parts: [{ text: message }] }],
|
|
config: {
|
|
responseModalities: ["AUDIO"],
|
|
speechConfig: {
|
|
voiceConfig: {
|
|
prebuiltVoiceConfig: {
|
|
voiceName: voices[Math.floor(Math.random() * voices.length)],
|
|
},
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
audioData = response.candidates?.[0].content?.parts?.[0].inlineData?.data;
|
|
if (audioData) break;
|
|
} catch (e) {
|
|
console.error(`TTS API key failed: ${apiKey.slice(0, 8)}...`, e);
|
|
}
|
|
}
|
|
|
|
if (!audioData)
|
|
return Response.json({ error: "Response is empty" }, { status: 500 });
|
|
queueMicrotask(() => {
|
|
redis!.setex(`tts:${textHash}`, 604800, audioData);
|
|
});
|
|
return new Response(pcmToWav(audioData), {
|
|
headers: { "Content-Type": "audio/wav" },
|
|
});
|
|
}
|
|
|
|
function pcmToWav(audioData: string) {
|
|
const audioBuffer = Buffer.from(audioData, "base64");
|
|
const pcmStream = Readable.from([audioBuffer]);
|
|
const writer = new wav.Writer({
|
|
channels: 1,
|
|
sampleRate: 24000,
|
|
bitDepth: 16,
|
|
});
|
|
|
|
const out = new PassThrough();
|
|
|
|
pcmStream.pipe(writer);
|
|
writer.on("data", (chunk) => out.write(chunk));
|
|
writer.on("end", () => out.end());
|
|
writer.on("error", () => out.end());
|
|
return Readable.toWeb(out) as unknown as globalThis.ReadableStream;
|
|
}
|