/** * @license * Copyright 2026 aphrody-code * SPDX-License-Identifier: Apache-2.0 */ import type { DetectionV2Item, DetectLanguageV2Response } from "./types.ts"; const STOPWORDS: Record = { fr: ["le", "la", "les", "de", "des", "un", "une", "et", "en", "du", "je", "tu", "il", "elle", "nous", "vous", "ils", "elles", "est", "sont", "qui", "que", "pour", "dans", "ce", "cette", "bonjour", "merci"], en: ["the", "be", "to", "of", "and", "a", "in", "that", "have", "i", "it", "for", "not", "on", "with", "he", "as", "you", "do", "at", "this", "but", "his", "by", "from", "they", "hello", "world"], es: ["el", "la", "de", "que", "y", "en", "un", "se", "no", "haber", "por", "con", "su", "para", "como", "estar", "tener", "le", "lo", "todo", "pero", "mas", "hola", "mundo"], de: ["das", "ist", "du", "ich", "nicht", "die", "es", "und", "der", "wir", "sie", "von", "ein", "eine", "fuer", "auf", "mit", "dem", "den", "im", "hallo", "welt"], it: ["il", "la", "di", "e", "che", "in", "un", "per", "una", "sono", "mi", "si", "ho", "ma", "non", "lo", "ciao", "mondo"], pt: ["de", "a", "o", "que", "e", "do", "da", "em", "um", "para", "com", "nao", "uma", "os", "no", "se", "na", "por", "mais", "ola", "mundo"], nl: ["de", "van", "ik", "te", "dat", "die", "in", "een", "hij", "het", "niet", "zijn", "is", "was", "op", "aan", "met", "als", "voor"], }; function lexicalDetect(text: string): { lang: string; confidence: number } | null { const words = text.toLowerCase().replace(/[^a-zA-ZÀ-ſ\s]/g, " ").split(/\s+/).filter(w => w.length > 0); if (words.length === 0) return null; const scores: Record = {}; for (const [lang, list] of Object.entries(STOPWORDS)) { scores[lang] = 0; for (const w of words) { if (list.includes(w)) scores[lang]++; } } let bestLang = "en"; let maxScore = 0; for (const [lang, score] of Object.entries(scores)) { if (score > maxScore) { maxScore = score; bestLang = lang; } } if (maxScore > 0) { const conf = Math.min(0.99, 0.65 + (maxScore / words.length) * 0.35); return { lang: bestLang, confidence: Number(conf.toFixed(2)) }; } return null; } function scriptDetect(text: string): { lang: string; confidence: number } | null { if (/[぀-ゟ゠-ヿ]/.test(text)) return { lang: "ja", confidence: 0.99 }; if (/[가-힯ᄀ-ᇿ]/.test(text)) return { lang: "ko", confidence: 0.99 }; if (/[一-鿿]/.test(text)) return { lang: "zh", confidence: 0.95 }; if (/[Ѐ-ӿ]/.test(text)) return { lang: "ru", confidence: 0.95 }; if (/[؀-ۿ]/.test(text)) return { lang: "ar", confidence: 0.95 }; if (/[Ͱ-Ͽ]/.test(text)) return { lang: "el", confidence: 0.95 }; if (/[֐-׿]/.test(text)) return { lang: "he", confidence: 0.95 }; if (/[ऀ-ॿ]/.test(text)) return { lang: "hi", confidence: 0.95 }; if (/[฀-๿]/.test(text)) return { lang: "th", confidence: 0.95 }; return null; } export async function detectSingle(text: string): Promise { const trimmed = text.trim(); if (!trimmed) { return { language: "und", confidence: 0, isReliable: false }; } const script = scriptDetect(trimmed); if (script) { return { language: script.lang, confidence: script.confidence, isReliable: true }; } const lexical = lexicalDetect(trimmed); if (lexical && lexical.confidence >= 0.7) { return { language: lexical.lang, confidence: lexical.confidence, isReliable: true }; } // Fallback to Gemini LLM for complex/short snippets try { const { defaultGeminiToolbox } = await import("../../gemini/index.ts"); const prompt = "Detect the ISO 639-1 two-letter language code of the following text. Reply ONLY with the 2-letter code (e.g. en, fr, de, es):\n\n" + trimmed; const res = await defaultGeminiToolbox.ask(prompt, { model: "flash-lite" }); const code = res.text.trim().toLowerCase().slice(0, 5); if (/^[a-z]{2}(-[a-z]{2,4})?$/.test(code)) { return { language: code, confidence: 0.95, isReliable: true }; } } catch {} return { language: lexical?.lang || "en", confidence: 0.6, isReliable: false }; } export async function detectLanguages(input: string | string[]): Promise { const items = Array.isArray(input) ? input : [input]; const detections: DetectionV2Item[][] = []; for (const it of items) { const det = await detectSingle(it); detections.push([det]); } return { data: { detections, }, }; } export class GoogleLanguageDetector { async detect(text: string): Promise { return detectSingle(text); } async detectBatch(input: string | string[]): Promise { return detectLanguages(input); } } export const defaultLanguageDetector = new GoogleLanguageDetector();