/** * @license * Copyright 2026 aphrody-code * SPDX-License-Identifier: Apache-2.0 */ import { defaultTranslationCache, TranslationCache } from "./cache.ts"; import { detectSingle } from "./detect.ts"; import { defaultTTS, GoogleTranslateTTS } from "./tts.ts"; import { loadCookieJar } from "../../cookies/cookie-loader.ts"; import { buildCookieHeader } from "../../cookies/cookie-injector.ts"; import type { TranslateV2Request, TranslateV2Response, DetailedTranslationV2Item, DetailedTranslateV2Response, TranslateEngineOptions, DictionaryEntry, DefinitionEntry, AutoCorrection, TTSOptions, TTSResult, } from "./types.ts"; const USER_AGENTS = [ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36", ]; const RPC_CLIENTS = ["dict-chrome-ex", "dict-chrome-ex", "webapp"]; const GOOGLE_TRANSLATE_HOSTS = [ "https://translate.google.com", "https://translate.google.fr", "https://translate.google.co.uk", "https://translate.google.de", "https://translate.google.co.jp", ]; let hostRotator = 0; function getNextTranslateHost(): string { const host = GOOGLE_TRANSLATE_HOSTS[hostRotator % GOOGLE_TRANSLATE_HOSTS.length]; hostRotator++; return host; } export class GoogleTranslateEngine { private cache: TranslationCache; private ttsEngine: GoogleTranslateTTS; constructor(cache?: TranslationCache, tts?: GoogleTranslateTTS) { this.cache = cache || defaultTranslationCache; this.ttsEngine = tts || defaultTTS; } private getRandomUserAgent(): string { return USER_AGENTS[Math.floor(Math.random() * USER_AGENTS.length)]; } private getRandomClient(): string { return RPC_CLIENTS[Math.floor(Math.random() * RPC_CLIENTS.length)]; } /** * Parse rich RPC response arrays (dt=rm, bd, md, at, qc). */ private parseRichRpcData(data: any): { pronunciation?: string; sourcePronunciation?: string; correction?: AutoCorrection; dictionary?: DictionaryEntry[]; definitions?: DefinitionEntry[]; possibleTranslations?: string[]; } { const res: ReturnType = {}; if (!Array.isArray(data)) return res; // Pronunciation & Transliteration (from data[0]) if (Array.isArray(data[0])) { for (const item of data[0]) { if (Array.isArray(item)) { // Romanization/Pinyin (often at index 2 or 3 of pronunciation item) if (item[0] === null && typeof item[2] === "string" && item[2]) { res.pronunciation = item[2]; } else if (item[0] === null && typeof item[3] === "string" && item[3]) { res.pronunciation = item[3]; } else if (typeof item[2] === "string" && item[2] && !res.pronunciation) { res.pronunciation = item[2]; } else if (typeof item[3] === "string" && item[3] && !res.sourcePronunciation) { res.sourcePronunciation = item[3]; } } } } // Bilingual dictionary entries (from data[1]) if (Array.isArray(data[1])) { const dictEntries: DictionaryEntry[] = []; for (const group of data[1]) { if (Array.isArray(group) && typeof group[0] === "string") { const partOfSpeech = group[0]; const terms = Array.isArray(group[1]) ? group[1].map(String) : []; const details: any[] = []; if (Array.isArray(group[2])) { for (const d of group[2]) { if (Array.isArray(d) && typeof d[0] === "string") { details.push({ word: d[0], reverseTranslations: Array.isArray(d[1]) ? d[1].map(String) : [], score: typeof d[3] === "number" ? d[3] : undefined, article: typeof d[4] === "string" ? d[4] : undefined, }); } } } dictEntries.push({ partOfSpeech, terms, details, }); } } if (dictEntries.length > 0) { res.dictionary = dictEntries; } } // Alternative translations (from data[5]) if (Array.isArray(data[5])) { const alternatives: string[] = []; for (const block of data[5]) { if (Array.isArray(block) && Array.isArray(block[2])) { for (const cand of block[2]) { if (Array.isArray(cand) && typeof cand[0] === "string") { if (!alternatives.includes(cand[0])) { alternatives.push(cand[0]); } } } } } if (alternatives.length > 0) { res.possibleTranslations = alternatives; } } // Auto-correction / Did-you-mean (from data[7]) if (Array.isArray(data[7]) && data[7].length >= 2) { const htmlSnippet = typeof data[7][0] === "string" ? data[7][0] : undefined; const correctedText = typeof data[7][1] === "string" ? data[7][1] : undefined; if (correctedText) { res.correction = { didYouMean: true, autoCorrected: false, originalText: "", correctedText, htmlSnippet, }; } } // Definitions (from data[12]) if (Array.isArray(data[12])) { const defEntries: DefinitionEntry[] = []; for (const group of data[12]) { if (Array.isArray(group) && typeof group[0] === "string") { const partOfSpeech = group[0]; const defs: any[] = []; if (Array.isArray(group[1])) { for (const item of group[1]) { if (Array.isArray(item) && typeof item[0] === "string") { defs.push({ definition: item[0], label: typeof item[1] === "string" ? item[1] : undefined, example: typeof item[2] === "string" ? item[2] : undefined, }); } } } if (defs.length > 0) { defEntries.push({ partOfSpeech, definitions: defs, }); } } } if (defEntries.length > 0) { res.definitions = defEntries; } } return res; } /** * Translates a single text with optional detailed rich outputs. */ async translateSingle( text: string, target: string, source?: string, format: "text" | "html" = "text", opts: TranslateEngineOptions = {} ): Promise { const trimmed = text.trim(); if (!trimmed) { return { translatedText: text, detectedSourceLanguage: source || "und" }; } // 1. Cache lookup if (!opts.noCache && !opts.detailed) { const cached = this.cache.get(trimmed, target, source, format); if (cached) { return { translatedText: cached.translatedText, detectedSourceLanguage: cached.detectedSourceLanguage || source, model: "cache", }; } } let resultText: string | null = null; let detectedLang = source; let richData: ReturnType = {}; let rawRpc: any = undefined; // Load available Google session cookies for rate-limit evasion let cookieHeader = ""; try { const cookies = await loadCookieJar("google"); cookieHeader = buildCookieHeader(cookies, "https://translate.google.com") || ""; } catch {} // 2. Try Google Web RPC with rotating hosts and client profiles (2 attempts) if (opts.strategy !== "gemini" && opts.strategy !== "web") { const maxRpcAttempts = 2; for (let attempt = 0; attempt < maxRpcAttempts && !resultText; attempt++) { try { const host = getNextTranslateHost(); const client = attempt === 0 ? "dict-chrome-ex" : this.getRandomClient(); const url = new URL(host + "/translate_a/single"); url.searchParams.set("client", client); url.searchParams.set("sl", source || "auto"); url.searchParams.set("tl", target); url.searchParams.set("hl", target); url.searchParams.set("ie", "UTF-8"); url.searchParams.set("oe", "UTF-8"); url.searchParams.set("q", trimmed); // Request comprehensive rich fields for (const dt of ["t", "rm", "bd", "md", "at", "qc", "ex", "ss"]) { url.searchParams.append("dt", dt); } const headers: Record = { "User-Agent": this.getRandomUserAgent(), Accept: "*/*", Referer: host + "/", }; if (cookieHeader) headers["Cookie"] = cookieHeader; const resp = await fetch(url.toString(), { headers, signal: AbortSignal.timeout(opts.timeoutMs || 8000), }); if (resp.ok) { const data = await resp.json(); rawRpc = data; if (data && Array.isArray(data) && data[0]) { const parts: string[] = []; for (const item of data[0]) { if (item && Array.isArray(item) && typeof item[0] === "string") { parts.push(item[0]); } } if (parts.length > 0) { resultText = parts.join(""); if (!detectedLang && typeof data[2] === "string") { detectedLang = data[2]; } richData = this.parseRichRpcData(data); if (richData.correction) { richData.correction.originalText = trimmed; } break; } } } } catch {} } } // 3. Fallback: Authenticated mobile endpoint (with cookies from .bxc) if (!resultText && opts.strategy !== "rpc") { try { const mobileUrl = "https://translate.google.com/m?sl=" + encodeURIComponent(source || "auto") + "&tl=" + encodeURIComponent(target) + "&q=" + encodeURIComponent(trimmed); const headers: Record = { "User-Agent": this.getRandomUserAgent(), }; if (cookieHeader) headers["Cookie"] = cookieHeader; const resp = await fetch(mobileUrl, { headers, signal: AbortSignal.timeout(opts.timeoutMs || 8000), }); if (resp.ok) { const html = await resp.text(); const match = html.match(/
([^<]+)<\/div>/); if (match && match[1]) { resultText = match[1].trim(); } } } catch {} } // 4. Fallback: High-Intelligence Gemini LLM Translation (Preserves HTML, nuances, context) if (!resultText) { try { const { defaultGeminiToolbox } = await import("../../gemini/index.ts"); const prompt = format === "html" ? "Translate the following HTML into " + target + " language. Strictly preserve all HTML tags, attributes, entities and structure without adding any markdown or commentary:\n\n" + trimmed : "Translate the following text into " + target + " language. Output ONLY the raw translated text with zero commentary, formatting or preamble:\n\n" + trimmed; const res = await defaultGeminiToolbox.ask(prompt, { model: "flash" }); if (res.text) { resultText = res.text.trim(); } } catch {} } // 5. Fallback: Direct gcloud ADC Token if present if (!resultText) { try { const proc = Bun.spawnSync(["gcloud", "auth", "print-access-token"]); if (proc.exitCode === 0) { const token = proc.stdout.toString().trim(); const resp = await fetch("https://translation.googleapis.com/language/translate/v2", { method: "POST", headers: { Authorization: "Bearer " + token, "Content-Type": "application/json", "X-Goog-User-Project": "aphrody", }, body: JSON.stringify({ q: [trimmed], target, source, format, }), }); if (resp.ok) { const data = await resp.json(); const item = data?.data?.translations?.[0]; if (item) { resultText = item.translatedText; detectedLang = item.detectedSourceLanguage || detectedLang; } } } } catch {} } if (!resultText) { throw new Error("Translation failed for target " + target + ": all 5 engine layers exhausted or rate-limited."); } const finalResultText: string = resultText; // Auto-detect source if missing if (!detectedLang) { const det = await detectSingle(trimmed); detectedLang = det.language; } // Save to cache if (!opts.noCache) { this.cache.set(trimmed, finalResultText, target, detectedLang, format); } const item: DetailedTranslationV2Item = { translatedText: finalResultText, detectedSourceLanguage: detectedLang, model: "nmt", }; if (opts.detailed) { if (richData.pronunciation) item.pronunciation = richData.pronunciation; if (richData.sourcePronunciation) item.sourcePronunciation = richData.sourcePronunciation; if (richData.correction) item.correction = richData.correction; if (richData.dictionary) item.dictionary = richData.dictionary; if (richData.definitions) item.definitions = richData.definitions; if (richData.possibleTranslations) item.possibleTranslations = richData.possibleTranslations; item.raw = rawRpc; } return item; } /** * Main Google Cloud Translation API v2 compatible translate method. */ async translate( request: TranslateV2Request, opts: TranslateEngineOptions = {} ): Promise { const inputs = Array.isArray(request.q) ? request.q : [request.q]; const format = request.format || "text"; const target = request.target; const source = request.source; const concurrency = opts.concurrency || 8; const results = Array(inputs.length); for (let i = 0; i < inputs.length; i += concurrency) { const chunk = inputs.slice(i, i + concurrency); const promises = chunk.map((text, idx) => this.translateSingle(text, target, source, format, opts).then((res) => { results[i + idx] = res; }) ); await Promise.all(promises); } return { data: { translations: results, }, }; } /** * Translates with full details (pronunciation, dictionary, definitions, spell correction). */ async translateDetailed( request: TranslateV2Request, opts: TranslateEngineOptions = {} ): Promise { const res = await this.translate(request, { ...opts, detailed: true }); return res as DetailedTranslateV2Response; } /** * Synthesize text-to-speech audio via official Google Translate TTS endpoint. */ async tts(opts: TTSOptions): Promise { return this.ttsEngine.synthesize(opts); } /** * Save text-to-speech audio directly to a file. */ async saveTtsToFile(opts: TTSOptions, outputPath: string): Promise { return this.ttsEngine.saveToFile(opts, outputPath); } } export const defaultTranslateEngine = new GoogleTranslateEngine();