Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions app/src/main/java/helium314/keyboard/latin/ai/TextPieces.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
// SPDX-License-Identifier: GPL-3.0-only
package helium314.keyboard.latin.ai

/** Splits a long text for an on-device model, which has little room for input and answer */
object TextPieces {
/** [text] of all pieces in order is the original; only pieces with [forModel] are sent to the model */
data class Piece(val text: String, val forModel: Boolean)

// indentation and list markers are layout, a model could drop them
private val LINE = Regex("(\\s*(?:(?:[-*•]|\\d{1,3}[.)])[ \\t]+)?)(.*?)([ \\t\\r]*)")
private val SENTENCE_END = Regex("(?<=[.!?][\"')\\]]?)\\s+|(?<=[。!?])")

/** roughly the tokens a model needs, in characters of English text */
fun cost(text: String): Int = text.sumOf { c: Char ->
when {
c.code < 0x250 -> 1
c.code < 0x2E80 -> 2
else -> 4
}
}

/**
* With [perLine] every line is a piece of its own, otherwise lines are kept together up to [maxCost].
* Longer lines are split after sentences, or at spaces.
*/
fun split(text: String, maxCost: Int, perLine: Boolean): List<Piece> {
if (!perLine && cost(text) <= maxCost) return listOf(Piece(text, true))
val pieces = mutableListOf<Piece>()
fun layout(s: String) { if (s.isNotEmpty()) pieces.add(Piece(s, false)) }
text.split('\n').forEachIndexed { index, line ->
if (index > 0) layout("\n")
val (start, body, end) = LINE.matchEntire(line)?.destructured ?: run {
layout(line)
return@forEachIndexed
}
layout(start)
for ((part, space) in splitLong(body, maxCost)) {
if (part.isNotEmpty()) pieces.add(Piece(part, part.any { it.isLetter() }))
layout(space)
}
layout(end)
}
return if (perLine) pieces else join(pieces, maxCost)
}

/** parts of at most [maxCost], each with the whitespace that followed it */
private fun splitLong(line: String, maxCost: Int): List<Pair<String, String>> {
val parts = mutableListOf<Pair<String, String>>()
var rest = line
while (cost(rest) > maxCost) {
var fits = 0
var used = 0
while (fits < rest.length && used + cost(rest[fits].toString()) <= maxCost) used += cost(rest[fits++].toString())
fits = fits.coerceAtLeast(1)
val sentence = SENTENCE_END.findAll(rest).takeWhile { it.range.first <= fits }.lastOrNull { it.range.first > 0 }
val space = rest.lastIndexOf(' ', fits).takeIf { it > 0 }
val cut = sentence?.range?.first ?: space ?: fits
val part = rest.substring(0, cut).trimEnd()
val next = rest.substring(cut).trimStart()
parts.add(part to rest.substring(part.length, rest.length - next.length))
rest = next
}
parts.add(rest to "")
return parts
}

/** joins neighbours into pieces of at most [maxCost] */
private fun join(pieces: List<Piece>, maxCost: Int): List<Piece> {
val result = mutableListOf<Piece>()
val current = StringBuilder() // starts with a piece for the model
val between = StringBuilder() // layout after it, part of the piece only if more text follows
fun finish() {
if (current.isNotEmpty()) result.add(Piece(current.toString(), true))
if (between.isNotEmpty()) result.add(Piece(between.toString(), false))
current.clear()
between.clear()
}
for (piece in pieces) {
if (!piece.forModel) {
if (current.isEmpty()) result.add(piece) else between.append(piece.text)
continue
}
if (current.isNotEmpty() && cost(current.toString()) + cost(between.toString()) + cost(piece.text) > maxCost) finish()
current.append(between).append(piece.text)
between.clear()
}
finish()
return result
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@
*/
package helium314.keyboard.latin.utils

import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.currentCoroutineContext
import helium314.keyboard.latin.ai.TextPieces
import helium314.keyboard.latin.ai.AiResultChecks
import helium314.keyboard.latin.R
import helium314.keyboard.keyboard.KeyboardSwitcher
import android.os.Looper
import android.os.Handler
import android.app.ActivityManager
import androidx.core.content.edit
import android.content.Context
import android.content.SharedPreferences
Expand Down Expand Up @@ -352,22 +361,74 @@ class ProofreadService(private val context: Context) {
// busy from before loading until the answer is back: a memory warning must not unload the model in between
OfflineAiLoader.busy.incrementAndGet()
try {
return generate(text, overridePrompt, showThinking, targetLanguage)
// a custom key's prompt may need the whole text, e.g. to summarize it
return if (overridePrompt == null || targetLanguage != null)
inPieces(text, targetLanguage != null) { generate(it, overridePrompt, showThinking, targetLanguage) }
else if (text.length > MAX_SINGLE_TEXT) tooLong(text)
else generate(text, overridePrompt, showThinking, targetLanguage)
} finally {
OfflineAiLoader.busy.decrementAndGet()
}
}

private fun tooLong(text: String): Result<String> =
Result.failure(ProofreadException("Text is too long for offline model (${text.length} characters). Please select a shorter passage."))

/**
* Runs [process] on one part of the text after the other and puts the results together. Proofreading works line by
* line and keeps a part it can't correct; a translation only succeeds as a whole.
*/
private suspend fun inPieces(
text: String,
translation: Boolean,
process: suspend (String) -> Result<String>
): Result<String> {
if (text.length > MAX_TEXT) return tooLong(text)
val memory = ActivityManager.MemoryInfo()
(context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).getMemoryInfo(memory)
val maxCost = if (memory.totalMem > BIG_MEMORY) 4000 else 2000
val pieces = TextPieces.split(text, maxCost, perLine = !translation)
val total = pieces.count { it.forModel }
var done = 0
var kept = 0
val result = StringBuilder()
for (piece in pieces) {
if (!piece.forModel) {
result.append(piece.text)
continue
}
currentCoroutineContext().ensureActive() // cancelled between two parts
done++
if (total > 1) showProgress("$done / $total")
val answer = process(piece.text)
if (total == 1) {
result.append(answer.getOrElse { return answer })
continue
}
val corrected = answer.getOrNull()
// far longer than the part means the model made something up
val usable = corrected != null && corrected.length <= piece.text.length * 2 + 20
&& (translation || !AiResultChecks.isCutOff(corrected, piece.text, AiResultChecks.MIN_PROOFREAD_SHARE))
if (translation && !usable) return answer.exceptionOrNull()?.let { Result.failure(it) }
?: Result.failure(ProofreadException(context.getString(R.string.translation_output_truncated)))
if (!usable) kept++
result.append(if (usable) corrected else piece.text)
}
if (total > 1 && kept == total) return Result.failure(ProofreadException("Model produced no output"))
if (kept > 0) showProgress(context.getString(R.string.proofread_output_truncated) + " ($kept / $total)")
return Result.success(result.toString())
}

private fun showProgress(message: String) {
Handler(Looper.getMainLooper()).post { KeyboardSwitcher.getInstance().showToast(message, true) }
}

private suspend fun generate(
text: String,
overridePrompt: String?,
showThinking: Boolean?,
targetLanguage: String?
): Result<String> = withContext(Dispatchers.IO) {
if (text.length > 12000) {
return@withContext Result.failure(ProofreadException("Text is too long for offline model (${text.length} characters). Please select a shorter passage."))
}

val modelPath = getModelPath()
if (modelPath.isNullOrBlank()) {
return@withContext Result.failure(ProofreadException("Model not loaded. Please select a GGUF model file."))
Expand Down Expand Up @@ -752,6 +813,10 @@ class ProofreadService(private val context: Context) {
companion object {
private const val TAG = "LlamaProofreadService"
private const val KEY_MODEL_PATH = "offline_model_path"
private const val MAX_SINGLE_TEXT = 12000
// below the 60000 characters read around the cursor, so a longer text is never replaced by a part of it
private const val MAX_TEXT = 30000
private const val BIG_MEMORY = 7L * 1024 * 1024 * 1024
internal const val KEY_LOAD_UNFINISHED = "offline_model_load_unfinished"
private const val KEY_DECODER_PATH = "offline_decoder_path"
private const val KEY_TOKENIZER_PATH = "offline_tokenizer_path"
Expand Down
34 changes: 34 additions & 0 deletions app/src/test/java/helium314/keyboard/latin/TextPiecesTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// SPDX-License-Identifier: GPL-3.0-only
package helium314.keyboard.latin

import helium314.keyboard.latin.ai.TextPieces
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue

class TextPiecesTest {
private fun forModel(text: String, max: Int, perLine: Boolean): List<String> {
val pieces = TextPieces.split(text, max, perLine)
assertEquals(text, pieces.joinToString("") { it.text }) // nothing lost or added
return pieces.filter { it.forModel }.map { it.text }
}

@Test fun `each line is a piece without its list marker`() {
val text = "rdtube\n- the first point\n 2) the second one \n\n---\n123\n"
assertEquals(listOf("rdtube", "the first point", "the second one"), forModel(text, 100, true))
}

@Test fun `long lines are split after sentences, else at spaces, else anywhere`() {
assertEquals(listOf("One two three.", "Four five six."), forModel("One two three. Four five six.", 20, true))
assertEquals(listOf("one two", "three four"), forModel("one two three four", 11, true))
assertEquals(listOf("abcde", "fghij", "k"), forModel("abcdefghijk", 5, true))
assertTrue(forModel("這是一個很長的句子。這是另一個句子。", 40, true).all { TextPieces.cost(it) <= 40 })
}

@Test fun `without per line, lines stay together as far as they fit`() {
assertEquals(listOf("a short text\nof two lines"), forModel("a short text\nof two lines", 100, false))
assertEquals(listOf("first line\nsecond line", "third line"), forModel("first line\nsecond line\n\nthird line", 25, false))
val long = (1..200).joinToString(" ") { "Sentence number $it." }
assertTrue(forModel(long, 300, false).all { TextPieces.cost(it) <= 300 })
}
}
Loading