Modern Apps git

← Modern-Apps.git

translate: Auto source now actually detects the language instead of assuming English

Commit
9960b327c836a948db2065cca377fcbdcb18bf16
Author
Vayun Mathur <[email protected]>
When
2026-12-01 08:17 UTC (5 days ago)
Parents
997a783
With the default Auto (detect) source, any non-English text
was encoded for NLLB with the English source token: the
ViewModel mapped Auto to from=null, NllbTranslator.
detectLanguage() unconditionally returned null (and nothing
called it), and translate() resolved the null through
AUTO_FALLBACK='en' — so 'Bonjour le monde...' was translated
as English into every target, in camera mode too, against
the picker's label and the engine contract ('null means
auto-detect').

A new pure domain/LanguageDetection detects conservatively
offline: unambiguous scripts first (kana, Hangul, Han with
Hans/Hant split, Hebrew, Greek, Thai, Arabic-script and
Cyrillic splits, Indic), then a stopword vote for Latin-
script en/fr/es/de/it/pt requiring a clear winner (with
signature-letter votes), returning null on no trusted
evidence so ambiguous text still falls back rather than
being guessed. translate() resolves Auto through detection
first, English only as the no-evidence fallback; explicit
sources are untouched. Ten detector tests plus the engine
contract test (which pinned detectLanguage -> null and now
pins 'fr') cover it. History, chunking, catalogue/token sync
and model state were audited and cleared. Verified:
:translate:testDevUnitTest 154 tests pass; lint errors are
pre-existing on untouched files.

Diff

translate/AGENTS.md
diff --git a/translate/AGENTS.md b/translate/AGENTS.mdindex 91ec1bc45a..b27b39fcd7 100644--- a/translate/AGENTS.md+++ b/translate/AGENTS.md@@ -13,7 +13,7 @@ _Install: ./install translate (dev by default)._ ## Overview **Purpose:** Fully offline translator (NLLB-200, 202 languages) with camera OCR overlay, speech input, TTS output, and selection-menu translation from any app. Internet only for one-time SHA-256-verified model downloads. **Key features:**-- Text translation over the on-device NLLB engine (`NllbTranslator` + `NllbModel`); language catalog + recents in `domain/`+- Text translation over the on-device NLLB engine (`NllbTranslator` + `NllbModel`); language catalog, recents, and Auto source-language detection (`detectLanguageCode`, English fallback when it finds no trusted evidence) in `domain/` - Camera mode: `CameraPreviewLayer` + `CameraOverlay` over `:library:ocr`; speech in via `SpeechRecognizerEngine`, spoken output via `TtsSpeaker` - History + persistent settings (`data/TranslateSettings`); translation available from the system selection menu **Architecture / data-flow:** `ui/` text/camera/language pages → `platform/TranslateViewModel` (+ `TranslateUiContract`) → `domain/TranslationEngine` → `platform/NllbTranslator` on the `:library:ml` runtime; models fetched once via `:library:downloadservice` and hash-verified before first use. Translator loading is a terminal state machine (`platform/TranslatorLoader` + `TranslatorLoadState`): the ViewModel is created before the download gate passes, so the text/camera/image pages re-attempt the load on entry, and every attempt ends in Ready or a Failed error with retry (Retry action / scaffold pull-to-refresh) — never an endless loading state.@@ -32,6 +32,7 @@ _Install: ./install translate (dev by default)._ - com/vayunmathur/translate/data/TranslateSettings.kt - com/vayunmathur/translate/domain/TranslationEngine.kt - com/vayunmathur/translate/domain/TranslationChunks.kt+- com/vayunmathur/translate/domain/LanguageDetection.kt - com/vayunmathur/translate/domain/Languages.kt - com/vayunmathur/translate/domain/RecentLanguages.kt ### platform/ — ViewModel, NLLB, speech, TTS
translate/src/main/java/com/vayunmathur/translate/domain/LanguageDetection.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/domain/LanguageDetection.kt b/translate/src/main/java/com/vayunmathur/translate/domain/LanguageDetection.ktnew file mode 100644index 0000000000..7f75552510--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/domain/LanguageDetection.kt@@ -0,0 +1,185 @@+package com.vayunmathur.translate.domain++/**+ * Conservative, offline source-language detection for the Auto source option.+ *+ * NLLB always needs an explicit source language token: it cannot detect the+ * language itself. Until this existed, the Auto option silently used the+ * English token for every text, so a French sentence picked up with Auto was+ * translated as if it were English. This detector is the missing step: it+ * names the source language when the evidence in the text is strong, and+ * returns null when it is not — the caller then keeps its documented English+ * fallback rather than running with a guessed language.+ *+ * Evidence, in order:+ *  - a writing system that maps to one language, or to a small family the+ *    letters themselves can split (kana → Japanese, Hangul → Korean,+ *    Ukrainian-only Cyrillic letters → Ukrainian, and so on);+ *  - for Latin-script text, a stopword vote between the major Latin-script+ *    languages: the winner must score at least [MIN_LATIN_SCORE] and beat+ *    every other candidate, so one shared word ("de", "la", …) never decides+ *    a text on its own. Distinctive letters (¿, ¡, ñ, ã, õ, ß) vote too.+ *+ * Only codes from [Languages.ALL] are returned, so the result can go straight+ * to `Languages.byCode(...).flores` for the NLLB source token.+ */+object LanguageDetection {+    /** How strongly a distinctive greeting ("bonjour", "hola", …) votes. */+    private const val STRONG_SCORE = 2++    /** Minimum winning score before a Latin-script vote is trusted. */+    private const val MIN_LATIN_SCORE = 2++    private val simplifiedHan = "们么这为国学汉语言车马龙书见门问时进远运达"+    private val traditionalHan = "們麼這為國學漢語言車馬龍書見門問時進遠運達"++    private val latinStopwords: Map<String, Set<String>> = mapOf(+        "en" to setOf(+            "the", "and", "is", "are", "you", "i", "am", "this", "that", "with",+            "for", "here", "world", "today",+        ),+        "fr" to setOf(+            "le", "la", "les", "de", "des", "et", "est", "je", "vous", "nous",+            "un", "une", "dans", "pour", "avec", "sur", "pas", "qui", "au", "aux",+        ),+        "es" to setOf(+            "el", "la", "los", "las", "de", "y", "es", "yo", "un", "una",+            "en", "para", "con", "por", "que", "estoy", "cómo", "estás",+        ),+        "de" to setOf(+            "der", "die", "das", "und", "ist", "ich", "sie", "wir", "ein", "eine",+            "in", "für", "mit", "von", "zu", "den", "nicht", "es", "wie", "geht",+        ),+        "it" to setOf(+            "il", "lo", "la", "i", "le", "di", "e", "io", "un", "una",+            "in", "per", "con", "che", "non", "sono", "questo", "è",+        ),+        "pt" to setOf(+            "o", "a", "os", "as", "de", "e", "eu", "um", "uma", "em",+            "para", "com", "por", "que", "não", "se", "estou", "isto", "é", "você",+        ),+    )++    /** Words that name their language almost on their own (greetings, thanks). */+    private val latinStrongWords: Map<String, Set<String>> = mapOf(+        "en" to setOf("hello", "thanks"),+        "fr" to setOf("bonjour", "merci"),+        "es" to setOf("hola", "gracias"),+        "de" to setOf("danke"),+        "it" to setOf("ciao", "grazie", "buongiorno"),+        "pt" to setOf("olá", "obrigado"),+    )++    private fun scriptOf(text: String): String? {+        var latin = 0+        val counts = linkedMapOf<String, Int>()+        fun bump(key: String) {+            counts[key] = (counts[key] ?: 0) + 1+        }+        for (ch in text) {+            when (ch) {+                in '\u3040'..'\u30FF' -> bump("ja")+                in '\u1100'..'\u11FF', in '\uAC00'..'\uD7A3' -> bump("ko")+                in '\u4E00'..'\u9FFF' -> bump("han")+                in '\u0590'..'\u05FF' -> bump("he")+                in '\u0370'..'\u03FF', in '\u1F00'..'\u1FFF' -> bump("el")+                in '\u0E00'..'\u0E7F' -> bump("th")+                in '\u0600'..'\u06FF', in '\u0750'..'\u077F',+                in '\uFB50'..'\uFDFF', in '\uFE70'..'\uFEFF' -> bump("arabic")+                in '\u0400'..'\u04FF' -> bump("cyrillic")+                in '\u0900'..'\u097F' -> bump("hi")+                in '\u0980'..'\u09FF' -> bump("bn")+                in '\u0B80'..'\u0BFF' -> bump("ta")+                in '\u0C00'..'\u0C7F' -> bump("te")+                in '\u0C80'..'\u0CFF' -> bump("kn")+                in '\u0D00'..'\u0D7F' -> bump("ml")+                in '\u0A80'..'\u0AFF' -> bump("gu")+                in '\u0A00'..'\u0A7F' -> bump("pa")+                in '\u0B00'..'\u0B7F' -> bump("or")+                in '\u0D80'..'\u0DFF' -> bump("si")+                in '\u0530'..'\u058F' -> bump("hy")+                in '\u10A0'..'\u10FF' -> bump("ka")+                in '\u1200'..'\u137F' -> bump("am")+                in '\u1780'..'\u17FF' -> bump("km")+                in '\u0E80'..'\u0EFF' -> bump("lo")+                in '\u1000'..'\u109F' -> bump("my")+                in '\u0F00'..'\u0FFF' -> bump("bo")+                else -> if (ch.isLetter()) latin+++            }+        }+        val strongest = counts.maxByOrNull { it.value } ?: return null+        // A script quoted inside a mostly Latin text does not make the text+        // that language; the script must at least match the Latin letters.+        if (strongest.value < latin) return null+        return when (strongest.key) {+            "han" -> chineseOf(text)+            "arabic" -> arabicScriptOf(text)+            "cyrillic" -> cyrillicOf(text)+            else -> strongest.key+        }+    }++    private fun chineseOf(text: String): String {+        val simplified = text.count { it in simplifiedHan }+        val traditional = text.count { it in traditionalHan }+        return if (traditional > simplified) "zh-Hant" else "zh-Hans"+    }++    private fun arabicScriptOf(text: String): String = when {+        text.any { it in "ٹڈڑے" } -> "ur"+        text.any { it in "پچگژ" || it == '\u06CC' || it == '\u06A9' } -> "fa"+        else -> "ar"+    }++    private fun cyrillicOf(text: String): String {+        val lower = text.lowercase()+        return when {+            'ў' in lower -> "be"+            'ѓ' in lower || 'ѕ' in lower -> "mk"+            'ђ' in lower || 'ћ' in lower -> "sr"+            'ї' in lower || 'є' in lower || 'ґ' in lower || 'і' in lower -> "uk"+            else -> "ru"+        }+    }++    private fun latinOf(text: String): String? {+        val lower = text.lowercase()+        // Letters that settle their language before any word voting.+        if ('đ' in lower || 'ơ' in lower || 'ư' in lower) return "vi"+        if ('ı' in lower || 'ş' in lower || 'ğ' in lower) return "tr"+        val scores = HashMap<String, Int>()+        fun vote(code: String, points: Int) {+            scores[code] = (scores[code] ?: 0) + points+        }+        if ('ñ' in lower || '¿' in lower || '¡' in lower) vote("es", STRONG_SCORE)+        if ('ã' in lower || 'õ' in lower) vote("pt", STRONG_SCORE)+        if ('ß' in lower) vote("de", STRONG_SCORE)+        val words = lower.split(Regex("[^\\p{L}]+")).filter { it.isNotEmpty() }+        for (word in words) {+            for ((code, stopwords) in latinStopwords) {+                if (word in stopwords) vote(code, 1)+            }+            for ((code, strong) in latinStrongWords) {+                if (word in strong) vote(code, STRONG_SCORE)+            }+        }+        val ranked = scores.entries.sortedByDescending { it.value }+        val winner = ranked.firstOrNull() ?: return null+        val runnerUp = ranked.getOrNull(1)?.value ?: 0+        if (winner.value < MIN_LATIN_SCORE || winner.value <= runnerUp) return null+        return winner.key+    }++    /** Entry point used by the top-level [detectLanguageCode]. */+    fun detect(text: String): String? {+        if (text.isBlank()) return null+        return scriptOf(text) ?: latinOf(text)+    }+}++/**+ * Best-effort language code (a [Languages] code, e.g. `fr`, `zh-Hans`) for+ * [text], or null when the text carries no evidence this detector trusts.+ * See [LanguageDetection] for what counts as evidence.+ */+fun detectLanguageCode(text: String): String? = LanguageDetection.detect(text)
translate/src/main/java/com/vayunmathur/translate/domain/Languages.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/domain/Languages.kt b/translate/src/main/java/com/vayunmathur/translate/domain/Languages.ktindex eae70dd80f..513d4e6bec 100644--- a/translate/src/main/java/com/vayunmathur/translate/domain/Languages.kt+++ b/translate/src/main/java/com/vayunmathur/translate/domain/Languages.kt@@ -22,7 +22,8 @@ object Languages {     /**      * Sentinel source option: let the engine detect the language. NLLB always needs      * an explicit source token, so [com.vayunmathur.translate.platform.NllbTranslator]-     * falls back to English (`eng_Latn`, mirrored here) when the source is [AUTO].+     * detects the source with [detectLanguageCode] and only falls back to English+     * (`eng_Latn`, mirrored here) when detection finds no evidence it trusts.      */     val AUTO = Language("auto", "Auto (detect)", "Auto", "eng_Latn") 
translate/src/main/java/com/vayunmathur/translate/platform/NllbTranslator.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/platform/NllbTranslator.kt b/translate/src/main/java/com/vayunmathur/translate/platform/NllbTranslator.ktindex b143a708f8..88b98cce33 100644--- a/translate/src/main/java/com/vayunmathur/translate/platform/NllbTranslator.kt+++ b/translate/src/main/java/com/vayunmathur/translate/platform/NllbTranslator.kt@@ -5,6 +5,7 @@ import com.vayunmathur.library.log.Log import com.vayunmathur.library.ml.NllbHandle import com.vayunmathur.translate.domain.Languages import com.vayunmathur.translate.domain.TranslationEngine+import com.vayunmathur.translate.domain.detectLanguageCode import com.vayunmathur.translate.domain.translateInChunks import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.sync.Mutex@@ -17,14 +18,15 @@ import kotlinx.coroutines.withContext  *  * The model is loaded lazily from [NllbModel.modelDir] the first time it is needed, and only  * if the two files have been downloaded; until then [isAvailable] is false and the UI shows- * a download prompt. Language detection is unnecessary - the UI's source picker names the- * source - so [detectLanguage] returns null.+ * a download prompt.  *  * NLLB needs BOTH the source and the target language: the source token leads the encoder- * input and the target token forced-BOSes the decoder. A null [from] (the UI's Auto- * sentinel) falls back to the [AUTO_FALLBACK] source rather than running in the wrong- * language: native cannot detect, and guessing any other language would mistranslate- * instead of failing.+ * input and the target token forced-BOSes the decoder. Native cannot detect the source+ * language, so a null [from] (the UI's Auto sentinel) is detected here by+ * [detectLanguageCode] — a French text under Auto gets the French source token, not the+ * English one. Only when the detector finds no evidence it trusts does the+ * [AUTO_FALLBACK] source apply: English, because it is the highest-resource+ * training pair and the least surprising fallback.  *  * Long input is translated in sentence-sized chunks  * ([com.vayunmathur.translate.domain.translateInChunks]) under the same lock:@@ -49,7 +51,7 @@ class NllbTranslator(private val context: Context) : TranslationEngine {         lock.withLock { ensure() != null }     } -    override suspend fun detectLanguage(text: String): String? = null+    override suspend fun detectLanguage(text: String): String? = detectLanguageCode(text)      // Broad catch is deliberate: the native translator throws undocumented     // RuntimeExceptions on bad input, which read as "untranslatable".@@ -57,7 +59,10 @@ class NllbTranslator(private val context: Context) : TranslationEngine {     override suspend fun translate(text: String, from: String?, to: String): String? =         withContext(Dispatchers.Default) {             if (text.isBlank()) return@withContext ""-            val source = NllbModel.tokenId(Languages.byCode(from ?: AUTO_FALLBACK).flores)+            // Auto means detect first; the English token is only the fallback.+            val requested = from?.takeIf { it.isNotBlank() && it != Languages.AUTO.code }+            val sourceCode = requested ?: detectLanguageCode(text) ?: AUTO_FALLBACK+            val source = NllbModel.tokenId(Languages.byCode(sourceCode).flores)                 ?: return@withContext null             val target = NllbModel.tokenId(Languages.byCode(to).flores)                 ?: return@withContext null@@ -142,8 +147,9 @@ class NllbTranslator(private val context: Context) : TranslationEngine {         private const val TAG = "NllbTranslator"          /**-         * The source used when the UI's source is Auto. English, because it is the-         * highest-resource training pair and the least surprising mistranslation - and+         * The source used when the UI's source is Auto and [detectLanguageCode]+         * found no evidence it trusts. English, because it is the+         * highest-resource training pair and the least surprising fallback - and          * because [com.vayunmathur.translate.domain.Languages.AUTO] mirrors it, so the          * two cannot drift apart without the compiler noticing only one changed.          */
translate/src/test/java/com/vayunmathur/translate/domain/LanguageDetectionTest.kt
diff --git a/translate/src/test/java/com/vayunmathur/translate/domain/LanguageDetectionTest.kt b/translate/src/test/java/com/vayunmathur/translate/domain/LanguageDetectionTest.ktnew file mode 100644index 0000000000..1fd03e6df7--- /dev/null+++ b/translate/src/test/java/com/vayunmathur/translate/domain/LanguageDetectionTest.kt@@ -0,0 +1,81 @@+package com.vayunmathur.translate.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++class LanguageDetectionTest {++    @Test+    fun `french sample is detected as french not english`() {+        assertEquals(+            "fr",+            detectLanguageCode("Bonjour le monde, je suis heureux et je voudrais un café avec vous."),+        )+    }++    @Test+    fun `spanish sample is detected as spanish`() {+        assertEquals(+            "es",+            detectLanguageCode("Hola mundo, ¿cómo estás? Yo estoy bien y gracias por todo."),+        )+    }++    @Test+    fun `german sample is detected as german`() {+        assertEquals(+            "de",+            detectLanguageCode("Guten Morgen, wie geht es dir? Ich bin hier und das ist gut."),+        )+    }++    @Test+    fun `italian and portuguese samples are detected`() {+        assertEquals("it", detectLanguageCode("Buongiorno, io sono qui e questo è il mondo."))+        assertEquals("pt", detectLanguageCode("Olá, eu estou aqui e isto é o mundo para você."))+    }++    @Test+    fun `english sample is detected as english`() {+        assertEquals(+            "en",+            detectLanguageCode("Hello, I am here and this is the world for you."),+        )+    }++    @Test+    fun `unambiguous scripts are detected`() {+        assertEquals("ja", detectLanguageCode("こんにちは、世界。今日は良い天気です。"))+        assertEquals("ko", detectLanguageCode("안녕하세요, 오늘은 좋은 날씨입니다."))+        assertEquals("el", detectLanguageCode("Γειά σου κόσμε, πώς είσαι σήμερα;"))+        assertEquals("he", detectLanguageCode("שלום עולם, מה שלומך היום?"))+        assertEquals("th", detectLanguageCode("สวัสดีโลก วันนี้อากาศดีมาก"))+        assertEquals("hi", detectLanguageCode("नमस्ते दुनिया, आज मौसम अच्छा है।"))+    }++    @Test+    fun `chinese script variants are distinguished`() {+        assertEquals("zh-Hans", detectLanguageCode("我们在这里学习中文。"))+        assertEquals("zh-Hant", detectLanguageCode("我們在這裡學習中文。"))+    }++    @Test+    fun `cyrillic variants are distinguished where the letters allow it`() {+        assertEquals("ru", detectLanguageCode("Привет мир, как дела сегодня?"))+        assertEquals("uk", detectLanguageCode("Привіт світе, як справи сьогодні?"))+    }++    @Test+    fun `arabic script defaults to arabic with persian letters as persian`() {+        assertEquals("ar", detectLanguageCode("مرحبا بالعالم، كيف حالك اليوم؟"))+        assertEquals("fa", detectLanguageCode("سلام جهان، امروز چطور هستی؟"))+    }++    @Test+    fun `ambiguous or blank text is not guessed`() {+        assertNull(detectLanguageCode(""))+        assertNull(detectLanguageCode("   "))+        assertNull(detectLanguageCode("xyzzy plugh"))+    }+}
translate/src/test/java/com/vayunmathur/translate/platform/PlatformEnginesTest.kt
diff --git a/translate/src/test/java/com/vayunmathur/translate/platform/PlatformEnginesTest.kt b/translate/src/test/java/com/vayunmathur/translate/platform/PlatformEnginesTest.ktindex 2008f4b53e..9a696e4ef0 100644--- a/translate/src/test/java/com/vayunmathur/translate/platform/PlatformEnginesTest.kt+++ b/translate/src/test/java/com/vayunmathur/translate/platform/PlatformEnginesTest.kt@@ -28,7 +28,13 @@ class PlatformEnginesTest {     fun `nllb translator without downloads is unavailable and fails closed`() = runBlocking {         val translator = NllbTranslator(context)         assertFalse(translator.isAvailable())-        assertNull(translator.detectLanguage("hello"))+        // Auto detection (regression): this French sample used to come back+        // undetected and was then translated with the English source token.+        assertEquals(+            "fr",+            translator.detectLanguage("Bonjour le monde, je suis heureux et je voudrais un café avec vous."),+        )+        assertEquals("en", translator.detectLanguage("hello"))         assertEquals("", translator.translate("", null, "es"))         assertEquals("", translator.translate("   ", "en", "es"))         assertNull(translator.translate("hello", null, "es"))