translate: long text is chunked instead of silently truncated
- Commit
8bf8443d4d31e9d7ed7ced985809828fddae97d0- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-30 19:27 UTC (5 days ago)
- Parents
0bd6d53
NLLB decoding stops at 128 tokens by design (and hard-fails past 1024 source tokens), and the handle's contract says callers must split into sentences first. The app passed the entire user text in one call, so any paragraph whose translation exceeded ~127 tokens came back missing its tail — displayed as the complete translation and written to history that way. New pure domain/TranslationChunks splits on sentence boundaries (word boundaries next, hard cut only for a single over-long spaceless run; decimals and CJK terminators handled) under a 100-char budget that stays under the token cap, and translateInChunks fails closed: any chunk failing fails the whole translation instead of leaving a hole. Short text stays a single chunk, unchanged. 13 new splitter tests cover reconstruction with no loss, boundary rules and fail-closed behaviour. Verified: :translate:testDevUnitTest 80/80 passes; lint errors are pre-existing on untouched Route.kt.
Diff
translate/AGENTS.md
diff --git a/translate/AGENTS.md b/translate/AGENTS.mdindex f69425e5de..91ec1bc45a 100644--- a/translate/AGENTS.md+++ b/translate/AGENTS.md@@ -21,6 +21,7 @@ _Install: ./install translate (dev by default)._ **Gotchas:** - First run without downloaded models must degrade gracefully — never assume the NLLB weights exist - Camera overlay coordinates must track preview rotation; test on rotation, not just portrait+- Long input is translated in sentence-sized chunks (`domain/TranslationChunks` via `NllbTranslator`): the native decoder caps one call's output and returns hitting the cap as a successful partial translation, so a whole paragraph in one call silently loses its tail ## Key files ### Root — entry + navigation@@ -30,6 +31,7 @@ _Install: ./install translate (dev by default)._ ### data/ + domain/ — settings, languages, engine contract - com/vayunmathur/translate/data/TranslateSettings.kt - com/vayunmathur/translate/domain/TranslationEngine.kt+- com/vayunmathur/translate/domain/TranslationChunks.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/TranslationChunks.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/domain/TranslationChunks.kt b/translate/src/main/java/com/vayunmathur/translate/domain/TranslationChunks.ktnew file mode 100644index 0000000000..74e9af9e5d--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/domain/TranslationChunks.kt@@ -0,0 +1,142 @@+package com.vayunmathur.translate.domain++/**+ * Splitting long input for the on-device NLLB engine, and translating the+ * pieces without ever losing one silently.+ *+ * The native decoder is capped at 128 steps per call (the first step is the+ * forced target-language token, so at most 127 tokens of translation come+ * back), and hitting that cap returns the partial translation as a success:+ * nothing in the result says the tail was dropped. The engine's handle+ * therefore requires long text to be split into sentences first. Until this+ * existed the app passed whole paragraphs in one call, so any translation+ * longer than the cap came back silently truncated — and was then displayed+ * and saved to history as if it were complete.+ *+ * [MAX_TRANSLATION_CHUNK_CHARS] is the character budget that keeps one chunk+ * under the token cap: in the densest scripts the tokenizer emits roughly+ * one token per character, so 100 source characters leave headroom under+ * 127 output tokens even when a translation expands somewhat. It is a+ * conservative bound, not an exact token count — the tokenizer lives behind+ * the native handle and cannot be counted from here.+ */++/** Character budget for one engine call. See the file doc for the reasoning. */+const val MAX_TRANSLATION_CHUNK_CHARS = 100++private val SENTENCE_END = setOf('.', '!', '?', '…')+private val CJK_SENTENCE_END = setOf('。', '!', '?')++/**+ * Splits [text] into chunks of at most [maxChars] characters, in order, with+ * no text lost, duplicated, or reordered: joining the result with single+ * spaces reproduces [text] up to whitespace normalisation.+ *+ * Breaks prefer sentence boundaries, then word boundaries. A single word+ * (or a run of a spaceless script) longer than [maxChars] is cut at+ * [maxChars] — the only case that can break inside a word, and unavoidable+ * without a tokenizer. Blank input yields no chunks.+ */+fun splitTranslationChunks(text: String, maxChars: Int = MAX_TRANSLATION_CHUNK_CHARS): List<String> {+ require(maxChars > 0) { "maxChars must be positive" }+ val units = splitSentences(text).flatMap { sentence -> splitLongSentence(sentence, maxChars) }+ val chunks = mutableListOf<String>()+ val current = StringBuilder()+ for (unit in units) {+ val separator = if (current.isEmpty()) 0 else 1+ if (current.length + separator + unit.length > maxChars) {+ chunks += current.toString()+ current.clear()+ }+ if (current.isNotEmpty()) current.append(' ')+ current.append(unit)+ }+ if (current.isNotEmpty()) chunks += current.toString()+ return chunks+}++/**+ * Translates [text] chunk by chunk via [translateOne] and joins the results+ * with single spaces, preserving the input order.+ *+ * Fail-closed, like the engine contract: if any chunk fails (null), the+ * whole translation fails rather than returning a text with a hole in the+ * middle. A chunk that translates to blank (it held nothing the tokenizer+ * maps to text) contributes nothing. Returns "" only for blank input; a+ * non-blank input whose every chunk came back blank returns null.+ */+fun translateInChunks(+ text: String,+ maxChars: Int = MAX_TRANSLATION_CHUNK_CHARS,+ translateOne: (String) -> String?,+): String? {+ val chunks = splitTranslationChunks(text, maxChars)+ if (chunks.isEmpty()) return ""+ val parts = mutableListOf<String>()+ for (chunk in chunks) {+ val part = translateOne(chunk) ?: return null+ if (part.isNotBlank()) parts += part.trim()+ }+ return parts.joinToString(" ").ifBlank { null }+}++/** Whole sentences from [text], terminators kept, surrounding whitespace dropped. */+private fun splitSentences(text: String): List<String> {+ val sentences = mutableListOf<String>()+ var start = 0+ var i = 0+ while (i < text.length) {+ val c = text[i]+ if (c == '\n' || c == '\r') {+ addSentence(sentences, text, start, i)+ i+++ while (i < text.length && text[i].isWhitespace()) i+++ start = i+ continue+ }+ val cjkEnd = c in CJK_SENTENCE_END+ if (cjkEnd || c in SENTENCE_END) {+ // A '.' between digits is a decimal point, not a sentence end.+ val decimal = c == '.' && i > start && text[i - 1].isDigit() &&+ i + 1 < text.length && text[i + 1].isDigit()+ val next = text.getOrNull(i + 1)+ if (!decimal && (cjkEnd || next == null || next.isWhitespace())) {+ var end = i + 1+ while (end < text.length && text[end] in SENTENCE_END) end+++ addSentence(sentences, text, start, end)+ i = end+ while (i < text.length && text[i].isWhitespace()) i+++ start = i+ continue+ }+ }+ i+++ }+ addSentence(sentences, text, start, text.length)+ return sentences+}++private fun addSentence(out: MutableList<String>, text: String, from: Int, to: Int) {+ val sentence = text.substring(from, to).trim()+ if (sentence.isNotEmpty()) out += sentence+}++/**+ * Cuts one over-long [sentence] into pieces of at most [maxChars], preferring+ * the last word boundary inside the budget. Only a piece with no whitespace+ * in the budget at all is cut mid-word at the budget.+ */+private fun splitLongSentence(sentence: String, maxChars: Int): List<String> {+ if (sentence.length <= maxChars) return listOf(sentence)+ val pieces = mutableListOf<String>()+ var rest = sentence+ while (rest.length > maxChars) {+ val window = rest.substring(0, maxChars)+ val cut = window.lastIndexOf(' ').takeIf { it > 0 } ?: maxChars+ val piece = rest.substring(0, cut).trim()+ if (piece.isNotEmpty()) pieces += piece+ rest = rest.substring(cut).trimStart()+ }+ if (rest.isNotEmpty()) pieces += rest+ return pieces+}
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 8af65187ee..b143a708f8 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.translateInChunks import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock@@ -25,6 +26,12 @@ import kotlinx.coroutines.withContext * language: native cannot detect, and guessing any other language would mistranslate * instead of failing. *+ * Long input is translated in sentence-sized chunks+ * ([com.vayunmathur.translate.domain.translateInChunks]) under the same lock:+ * the native decoder caps one call's output and returns hitting the cap as a+ * successful partial translation, so a whole paragraph in one call silently+ * loses its tail.+ * * # The lock is not only for the handle * * A translation keeps its KV caches on the device and re-records the network on the way in,@@ -57,7 +64,13 @@ class NllbTranslator(private val context: Context) : TranslationEngine { lock.withLock { val handle = ensure() ?: return@withContext null try {- handle.translate(text, source, target)?.ifBlank { null }+ // Chunked, per the handle's contract: one call per+ // sentence-sized piece (see domain/TranslationChunks).+ // A single whole-text call is silently capped by the+ // native decoder and loses everything past the cap.+ translateInChunks(text) { chunk ->+ handle.translate(chunk, source, target)+ } } catch (e: Exception) { Log.error(TAG, "translate failed", e) null
translate/src/test/java/com/vayunmathur/translate/domain/TranslationChunksTest.kt
diff --git a/translate/src/test/java/com/vayunmathur/translate/domain/TranslationChunksTest.kt b/translate/src/test/java/com/vayunmathur/translate/domain/TranslationChunksTest.ktnew file mode 100644index 0000000000..965be47c7c--- /dev/null+++ b/translate/src/test/java/com/vayunmathur/translate/domain/TranslationChunksTest.kt@@ -0,0 +1,123 @@+package com.vayunmathur.translate.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++class TranslationChunksTest {++ // --- splitTranslationChunks ---------------------------------------------++ @Test+ fun `blank input yields no chunks`() {+ assertEquals(emptyList(), splitTranslationChunks(""))+ assertEquals(emptyList(), splitTranslationChunks(" \n "))+ }++ @Test+ fun `short text is one unchanged chunk`() {+ assertEquals(listOf("Hello world."), splitTranslationChunks("Hello world."))+ assertEquals(listOf("One. Two."), splitTranslationChunks("One. Two.", maxChars = 100))+ }++ @Test+ fun `sentences pack up to the budget and no further`() {+ val text = "Alpha bravo. Charlie delta. Echo foxtrot."+ val chunks = splitTranslationChunks(text, maxChars = 15)+ assertEquals(listOf("Alpha bravo.", "Charlie delta.", "Echo foxtrot."), chunks)+ assertEquals(text, chunks.joinToString(" "))+ }++ @Test+ fun `long sentence splits at word boundaries not mid-word`() {+ val text = "alpha beta gamma delta epsilon"+ val chunks = splitTranslationChunks(text, maxChars = 11)+ assertEquals(listOf("alpha beta", "gamma delta", "epsilon"), chunks)+ assertTrue(chunks.all { it.length <= 11 })+ assertEquals(text, chunks.joinToString(" "))+ }++ @Test+ fun `single over-long word is the only mid-word cut`() {+ val chunks = splitTranslationChunks("abcdefghij", maxChars = 4)+ assertEquals(listOf("abcd", "efgh", "ij"), chunks)+ assertEquals("abcdefghij", chunks.joinToString(""))+ }++ @Test+ fun `decimal point is not a sentence boundary`() {+ val chunks = splitTranslationChunks("Pi is 3.14 today. It rained.", maxChars = 18)+ assertEquals(listOf("Pi is 3.14 today.", "It rained."), chunks)+ }++ @Test+ fun `cjk terminators split without following whitespace`() {+ assertEquals(listOf("行く。 次です。"), splitTranslationChunks("行く。次です。", maxChars = 10))+ assertTrue(splitTranslationChunks("行く。次です。", maxChars = 3).all { it.length <= 3 })+ }++ @Test+ fun `paragraph is fully preserved across chunks at the default budget`() {+ // Regression for the silent-truncation bug: a whole paragraph sent in+ // one engine call came back capped, losing every later sentence.+ val text = (1..12).joinToString(" ") { "Sentence $it is here." }+ val chunks = splitTranslationChunks(text)+ assertTrue(chunks.size > 1, "paragraph must be split: $chunks")+ assertTrue(chunks.all { it.length <= MAX_TRANSLATION_CHUNK_CHARS })+ assertEquals(text, chunks.joinToString(" "))+ }++ // --- translateInChunks ----------------------------------------------------++ @Test+ fun `every chunk is translated in order and joined`() {+ val calls = mutableListOf<String>()+ val result = translateInChunks("One. Two.", maxChars = 5) { chunk ->+ calls += chunk+ chunk.uppercase()+ }+ assertEquals(listOf("One.", "Two."), calls)+ assertEquals("ONE. TWO.", result)+ }++ @Test+ fun `no chunk handed to the engine exceeds the budget`() {+ // With an echo engine the result must equal the input exactly: any+ // dropped, duplicated, or reordered chunk breaks the equality.+ val text = (1..20).joinToString(" ") { "Sentence number $it is here to stay." }+ val calls = mutableListOf<String>()+ val result = translateInChunks(text) { chunk ->+ calls += chunk+ chunk+ }+ assertTrue(calls.size > 1)+ assertTrue(calls.all { it.length <= MAX_TRANSLATION_CHUNK_CHARS })+ assertEquals(text, result)+ }++ @Test+ fun `one failed chunk fails the whole translation`() {+ val result = translateInChunks("One. Two.", maxChars = 5) { chunk ->+ if (chunk == "Two.") null else chunk+ }+ assertNull(result)+ }++ @Test+ fun `blank chunk results are skipped but all-blank fails closed`() {+ val result = translateInChunks("Hello. …", maxChars = 6) { chunk ->+ if (chunk == "…") "" else chunk+ }+ assertEquals("Hello.", result)+ assertNull(translateInChunks("Hello.") { "" })+ }++ @Test+ fun `blank input translates to blank without calling the engine`() {+ var called = false+ val result = translateInChunks(" ") { called = true; it }+ assertEquals("", result)+ assertTrue(!called)+ }+}