import { existsSync, mkdirSync } from "node:fs"; import { getBxcDir } from "../../utils/paths.ts"; import type { TTSOptions, TTSResult } from "./types.ts"; const GOOGLE_TTS_HOSTS = [ "https://translate.google.com", "https://translate.google.fr", "https://translate.google.de", "https://translate.google.co.uk", "https://translate.google.co.jp", ]; let hostIndex = 0; function getNextTtsHost(): string { const host = GOOGLE_TTS_HOSTS[hostIndex % GOOGLE_TTS_HOSTS.length]; hostIndex++; return host; } /** * Split long text into chunks <= maxLen characters, respecting word/sentence boundaries. */ function splitTextForTts(text: string, maxLen = 180): string[] { const trimmed = text.trim(); if (trimmed.length <= maxLen) return [trimmed]; const chunks: string[] = []; const sentences = trimmed.split(/(?<=[.?!;:\n\u3002\uFF01\uFF1F])/g); let current = ""; for (const s of sentences) { if ((current + s).length <= maxLen) { current += s; } else { if (current.trim()) chunks.push(current.trim()); if (s.length <= maxLen) { current = s; } else { const words = s.split(/\s+/); let wordChunk = ""; for (const w of words) { if ((wordChunk + " " + w).length <= maxLen) { wordChunk = wordChunk ? wordChunk + " " + w : w; } else { if (wordChunk.trim()) chunks.push(wordChunk.trim()); wordChunk = w; } } current = wordChunk; } } } if (current.trim()) chunks.push(current.trim()); return chunks.length > 0 ? chunks : [trimmed.slice(0, maxLen)]; } export class GoogleTranslateTTS { private cacheDir: string; constructor(customCacheDir?: string) { this.cacheDir = customCacheDir || (getBxcDir() + "/tts_cache"); if (!existsSync(this.cacheDir)) { try { mkdirSync(this.cacheDir, { recursive: true }); } catch {} } } private hashKey(text: string, lang: string, speed = 1): string { const hasher = new Bun.CryptoHasher("sha256"); hasher.update(lang + "::" + speed + "::" + text); return hasher.digest("hex"); } private async fetchChunk( chunk: string, lang: string, idx: number, total: number, speed = 1, timeoutMs = 10000 ): Promise { const host = getNextTtsHost(); const url = new URL(host + "/translate_tts"); url.searchParams.set("ie", "UTF-8"); url.searchParams.set("q", chunk); url.searchParams.set("tl", lang); url.searchParams.set("total", String(total)); url.searchParams.set("idx", String(idx)); url.searchParams.set("textlen", String(chunk.length)); url.searchParams.set("client", "tw-ob"); if (speed !== 1) { url.searchParams.set("ttsspeed", String(speed)); } const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs); try { const res = await fetch(url.toString(), { headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36", Referer: host + "/", Accept: "*/*", }, signal: controller.signal, }); if (!res.ok) { throw new Error("Google TTS failed with HTTP " + res.status + " (" + res.statusText + ")"); } const buf = await res.arrayBuffer(); return new Uint8Array(buf); } finally { clearTimeout(timer); } } async synthesize(opts: TTSOptions): Promise { const { text, lang, speed = 1, timeoutMs = 15000 } = opts; const cleanText = text.trim(); if (!cleanText) { return { audioBuffer: new Uint8Array(0), mimeType: "audio/mpeg", size: 0 }; } const key = this.hashKey(cleanText, lang, speed); const cachedFilePath = this.cacheDir + "/" + key + ".mp3"; const cachedFile = Bun.file(cachedFilePath); if (await cachedFile.exists()) { const buf = await cachedFile.arrayBuffer(); const audioBuffer = new Uint8Array(buf); return { audioBuffer, mimeType: "audio/mpeg", size: audioBuffer.byteLength, }; } const chunks = splitTextForTts(cleanText); const audioChunks: Uint8Array[] = []; for (let i = 0; i < chunks.length; i++) { const chunkAudio = await this.fetchChunk(chunks[i], lang, i, chunks.length, speed, timeoutMs); audioChunks.push(chunkAudio); } const totalLength = audioChunks.reduce((acc, c) => acc + c.byteLength, 0); const merged = new Uint8Array(totalLength); let offset = 0; for (const chunk of audioChunks) { merged.set(chunk, offset); offset += chunk.byteLength; } try { await Bun.write(cachedFilePath, merged); } catch {} return { audioBuffer: merged, mimeType: "audio/mpeg", size: merged.byteLength, }; } async saveToFile(opts: TTSOptions, outputPath: string): Promise { const res = await this.synthesize(opts); await Bun.write(outputPath, res.audioBuffer); return outputPath; } } export const defaultTTS = new GoogleTranslateTTS();