Something went wrong. Try again.
fossabot clone for streamplace superbot.mmatt.net
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100import type { LanguageStrictness } from '../../../shared/schemas.ts'
interface Detection { language: string getScores(): Record<string, number> isReliable(): boolean}
let detector: { detect(text: string): Detection } | null = nulllet loading: Promise<void> | null = null
/** * Load the language detector (about 30 MB of n-gram data) on first use. The * language filter lets messages through until this has finished. */export function loadLanguageDetector(): Promise<void> { loading ??= import('eld/extrasmall') .then(({ eld }) => { detector = eld }) .catch((err) => { loading = null console.error('[language] could not load the language detector:', err) }) return loading}
/** * How far an allowed language's score may trail the best guess and still let * the message through. Lower is stricter. */const MARGIN: Record<LanguageStrictness, number> = { lenient: 0.25, balanced: 0.15, strict: 0.05 }
/** Chat shorthand and emote names that say nothing about the language a message is in. */const CHAT_NOISE = new Set( 'w l f gg ggs wp ez lol lmao lmfao rofl omg brb idk tbh ngl imo fr xd xdd pog poggers pogchamp pogu kekw lul lulw omegalul kappa monkas pepega sadge copium hopium catjam' .split(' ') .map((w) => squash(w)),)
function squash(word: string): string { return word.toLowerCase().replace(/[^\p{L}]/gu, '').replace(/(\p{L})\1+/gu, '$1')}
/** Strip links, mentions, emote codes, chat shorthand and repeats so only real words are left. */export function cleanForDetection(text: string): string { const seen = new Set<string>() const words: string[] = [] for (const word of text.split(/\s+/)) { if (!word) continue if (/^[@#]/.test(word) || word.includes('://') || /[\p{L}\d]\.\p{L}{2,}/u.test(word) || /^:[\w-]+:$/.test(word)) continue const key = word.toLowerCase().replace(/[^\p{L}]/gu, '') if (key && (CHAT_NOISE.has(squash(key)) || seen.has(key))) continue if (key) seen.add(key) words.push(word.replace(/(\p{L})\1{2,}/gu, '$1$1')) } return words.join(' ')}
const DENSE = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u
/** Letters in a message, where a Chinese, Japanese or Korean character counts as three. */export function letterCount(text: string): number { let n = 0 for (const ch of text) if (/\p{L}/u.test(ch)) n += DENSE.test(ch) ? 3 : 1 return n}
export interface LanguageCheck { allowedLanguages: string[] strictness: LanguageStrictness minLength: number}
/** * The language a message is written in when it's confidently none of the * allowed ones, or null to let it through. Short, ambiguous and undetectable * messages (emotes, kaomoji, "W chat") always pass. */export function detectForeignLanguage(text: string, check: LanguageCheck): string | null { if (!detector) { void loadLanguageDetector() return null } if (!check.allowedLanguages.length) return null const cleaned = cleanForDetection(text) if (letterCount(cleaned) < check.minLength) return null // A word or two ("happy birthday", "streamer chat") reads as half a dozen languages. if (!DENSE.test(cleaned) && cleaned.split(' ').filter((w) => /\p{L}/u.test(w)).length < 3) return null const result = detector.detect(cleaned) const top = result.language if (!top || check.allowedLanguages.includes(top)) return null const scores = result.getScores() const best = Math.max(0, ...check.allowedLanguages.map((code) => scores[code] ?? 0)) if (best >= (scores[top] ?? 0) - MARGIN[check.strictness]) return null // An unreliable guess still counts when no allowed language was even in the running, // e.g. Russian when only English is allowed (Russian, Bulgarian and Ukrainian score alike). return result.isReliable() || best === 0 ? top : null}