Modern Apps git

← Modern-Apps.git

new app: translate

Commit
5fb300d49d62bd6242fa71ac1ac560538e377d67
Author
Vayun Mathur <[email protected]>
When
2026-07-30 20:55 UTC (4 months ago)
Parents
7d9347c

Diff

scripts/translate/quant_check.py
diff --git a/scripts/translate/quant_check.py b/scripts/translate/quant_check.pynew file mode 100644index 0000000000..7902b061c0--- /dev/null+++ b/scripts/translate/quant_check.py@@ -0,0 +1,131 @@+#!/usr/bin/env python3+"""+Parity / quality check for quantized Small100 ncnn models.++Compares int4/int8 quantized ncnn .bin sizes and inspects param quantize terms.+For deeper quality: optional HF reference translation if transformers installed.++Usage:+  python scripts/translate/quant_check.py --bundle /path/to/bundle/upload \+         --quantized scripts/translate/quantized/int4++Requires: none for size checks; transformers + sentencepiece for BLEU (optional).+"""+import argparse+import hashlib+import json+import os+import re+import sys+from pathlib import Path++def sha256_file(p: Path) -> str:+    h = hashlib.sha256()+    with open(p, "rb") as f:+        for chunk in iter(lambda: f.read(1 << 20), b""):+            h.update(chunk)+    return h.hexdigest()++def parse_quant_terms(param_path: Path):+    terms = {}+    with open(param_path) as f:+        lines = f.readlines()+    if not lines:+        return terms+    # first line: magic + layer count+    for line in lines[1:]:+        parts = line.split()+        if not parts:+            continue+        name = parts[1] if len(parts) > 1 else "?"+        # extract 18= term (quantize term) and 6= scale nibble+        m = re.search(r"18=(\d+)", line)+        if m:+            terms[name] = int(m.group(1))+    return terms++def main():+    ap = argparse.ArgumentParser()+    ap.add_argument("--bundle", type=Path, default=Path.home() / ".claude/jobs/1dfd8c6b/tmp/small100/bundle/upload",+                    help="fp16 original bundle")+    ap.add_argument("--quantized", type=Path, default=Path("scripts/translate/quantized/int4"),+                    help="quantized bundle dir")+    ap.add_argument("--all-variants", action="store_true", help="check all quantized variants")+    args = ap.parse_args()++    bundle = args.bundle+    qdir = args.quantized+    if not bundle.exists():+        print(f"bundle not found: {bundle}", file=sys.stderr)+        sys.exit(1)++    def report_one(label: str, bdir: Path):+        print(f"\n=== {label}: {bdir} ===")+        if not bdir.exists():+            print(f"  MISSING DIR {bdir}")+            return+        for fname in ["encoder.ncnn.param", "encoder.ncnn.bin", "decoder.ncnn.param", "decoder.ncnn.bin",+                       "sentencepiece.bpe.model", "vocab.txt", "pos_weights.f32.bin"]:+            p = bdir / fname+            if not p.exists():+                print(f"  MISSING {fname}")+                continue+            sz = p.stat().st_size+            print(f"  {fname:30s} {sz/1e6:7.1f} MB")+        # quant terms+        for comp in ["encoder.ncnn.param", "decoder.ncnn.param"]:+            pp = bdir / comp+            if not pp.exists():+                continue+            terms = parse_quant_terms(pp)+            if terms:+                # 18=401 => bits=4 block=64 (bits*100 + blockcode 1), 18=801 => bits=8 block=64+                uniq = sorted(set(terms.values()))+                print(f"  {comp} quantize_terms: {uniq} ({len(terms)} quantized layers)")+                # decode+                for v in uniq:+                    bits = v // 100+                    block_code = v % 100+                    block = [32, 64, 128][block_code] if block_code < 3 else f"code={block_code}"+                    print(f"    term {v} => bits={bits} block={block}")+            else:+                print(f"  {comp}: no quantized terms (fp16 or unquantized)")++    # fp16 baseline+    report_one("FP16 baseline", bundle)+    if args.all_variants:+        base = qdir.parent if qdir.name.startswith("int") else qdir+        if base.exists():+            for sub in sorted(base.iterdir()):+                if sub.is_dir():+                    report_one(f"Variant {sub.name}", sub)+    else:+        report_one(f"Quantized {qdir.name}", qdir)++    # Try optional HF translation parity on a few sentences+    try:+        from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer+        import torch+        print("\n=== HF reference translation sample (EN->ES) ===")+        model_id = "alirezamsh/small100"+        tok = M2M100Tokenizer.from_pretrained(model_id)+        model = M2M100ForConditionalGeneration.from_pretrained(model_id)+        model.eval()+        sentences = [+            "Hello, how are you?",+            "The weather is nice today.",+            "I love machine translation.",+        ]+        for s in sentences:+            tok.src_lang = "en"+            encoded = tok(s, return_tensors="pt")+            generated = model.generate(**encoded, forced_bos_token_id=tok.get_lang_id("es"))+            out = tok.batch_decode(generated, skip_special_tokens=True)[0]+            print(f"  EN: {s}")+            print(f"  ES: {out}")+    except Exception as e:+        print(f"\n=== HF check skipped: {e} ===")+        print("Install transformers+torch+sentencepiece for BLEU parity check.")++if __name__ == "__main__":+    main()
scripts/translate/quantize_small100.sh
diff --git a/scripts/translate/quantize_small100.sh b/scripts/translate/quantize_small100.shnew file mode 100755index 0000000000..8c13ac9598--- /dev/null+++ b/scripts/translate/quantize_small100.sh@@ -0,0 +1,89 @@+#!/usr/bin/env bash+# Quantizes SMaLL-100 ncnn bundle via ncnn weight-only block quantization.+#+# Inputs:  fp16 bundle dir from `/tmp/small100/bundle/upload/` or R2 download+#          containing encoder.ncnn.{param,bin} + decoder.ncnn.{param,bin}+# Outputs: quantized bundle under scripts/translate/quantized/int4/ and int8/+#+# Requires host tools built via:+#   cmake -DNCNN_BUILD_TOOLS=ON -DNCNN_WEIGHT_QUANT=ON -DNCNN_INT8=ON ... \+#   && make ncnnllm2table ncnnllm2int -j+#+# Usage:+#   ./scripts/translate/quantize_small100.sh [bundle_dir] [out_root]+#   bundle_dir defaults to $HOME/.claude/jobs/.../bundle/upload if present,+#   else scripts/translate/bundle (user-provided).+#   out_root defaults to scripts/translate/quantized+set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"++# Resolve input bundle: arg > canonical job output > fallback+DEFAULT_BUNDLE="/Users/vayun/.claude/jobs/1dfd8c6b/tmp/small100/bundle/upload"+BUNDLE="${1:-}"+if [[ -z "$BUNDLE" ]]; then+  if [[ -d "$DEFAULT_BUNDLE" ]]; then+    BUNDLE="$DEFAULT_BUNDLE"+  else+    BUNDLE="$SCRIPT_DIR/bundle"+  fi+fi++OUT_ROOT="${2:-$SCRIPT_DIR/quantized}"+TOOLS="/Users/vayun/Documents/ncnn-android/build-host/tools/quantize"++if [[ ! -f "$BUNDLE/encoder.ncnn.param" ]]; then+  echo "bundle not found: $BUNDLE does not contain encoder.ncnn.param" >&2+  exit 1+fi+for bin in ncnnllm2int ncnnllm2table; do+  if [[ ! -x "$TOOLS/$bin" ]]; then+    echo "missing tool $TOOLS/$bin — build host tools first:" >&2+    echo "  mkdir -p /tmp/ncnn-host && cd /tmp/ncnn-host && cmake -DNCNN_BUILD_TOOLS=ON -DNCNN_WEIGHT_QUANT=ON -DNCNN_INT8=ON -DNCNN_BUILD_EXAMPLES=OFF ... <ncnn-android-root> && make ncnnllm2int ncnnllm2table -j" >&2+    exit 1+  fi+done++mkdir -p "$OUT_ROOT/int4" "$OUT_ROOT/int8" "$OUT_ROOT/int4-128"++echo "=== Original sizes ==="+ls -lh "$BUNDLE"/encoder.ncnn.bin "$BUNDLE"/decoder.ncnn.bin+du -sh "$BUNDLE"++quant_one() {+  local bits="$1" block="$2" method="$3" in_param="$4" in_bin="$5" out_param="$6" out_bin="$7"+  echo ""+  echo "--- Quantizing $(basename "$in_param") bits=$bits block=$block method=$method ---"+  "$TOOLS/ncnnllm2int" "$in_param" "$in_bin" "$out_param" "$out_bin" method="$method" bits="$bits" block="$block"+  echo " -> $(du -h "$out_bin" | cut -f1) $out_bin"+}++# int4 mseclip block=64 — best size/quality without calibration data (auto-dequant in ncnn with NCNN_WEIGHT_QUANT=ON)+quant_one 4 64 mseclip "$BUNDLE/encoder.ncnn.param" "$BUNDLE/encoder.ncnn.bin" "$OUT_ROOT/int4/encoder.ncnn.param" "$OUT_ROOT/int4/encoder.ncnn.bin"+quant_one 4 64 mseclip "$BUNDLE/decoder.ncnn.param" "$BUNDLE/decoder.ncnn.bin" "$OUT_ROOT/int4/decoder.ncnn.param" "$OUT_ROOT/int4/decoder.ncnn.bin"+# copy supporting files (fp32/fp16, not quantized)+cp -v "$BUNDLE/sentencepiece.bpe.model" "$BUNDLE/vocab.txt" "$BUNDLE/pos_weights.f32.bin" "$OUT_ROOT/int4/"++# int4 mseclip block=128 — smaller scales overhead+quant_one 4 128 mseclip "$BUNDLE/encoder.ncnn.param" "$BUNDLE/encoder.ncnn.bin" "$OUT_ROOT/int4-128/encoder.ncnn.param" "$OUT_ROOT/int4-128/encoder.ncnn.bin"+quant_one 4 128 mseclip "$BUNDLE/decoder.ncnn.param" "$BUNDLE/decoder.ncnn.bin" "$OUT_ROOT/int4-128/decoder.ncnn.param" "$OUT_ROOT/int4-128/decoder.ncnn.bin"+cp -v "$BUNDLE/sentencepiece.bpe.model" "$BUNDLE/vocab.txt" "$BUNDLE/pos_weights.f32.bin" "$OUT_ROOT/int4-128/"++# int8 mseclip block=64 — quality fallback+quant_one 8 64 mseclip "$BUNDLE/encoder.ncnn.param" "$BUNDLE/encoder.ncnn.bin" "$OUT_ROOT/int8/encoder.ncnn.param" "$OUT_ROOT/int8/encoder.ncnn.bin"+quant_one 8 64 mseclip "$BUNDLE/decoder.ncnn.param" "$BUNDLE/decoder.ncnn.bin" "$OUT_ROOT/int8/decoder.ncnn.param" "$OUT_ROOT/int8/decoder.ncnn.bin"+cp -v "$BUNDLE/sentencepiece.bpe.model" "$BUNDLE/vocab.txt" "$BUNDLE/pos_weights.f32.bin" "$OUT_ROOT/int8/"++echo ""+echo "=== Final size report ==="+echo "fp16 original: $(du -sh "$BUNDLE" | cut -f1) ($(ls -lh "$BUNDLE"/encoder.ncnn.bin "$BUNDLE"/decoder.ncnn.bin | awk '{print $5}' | paste -sd+ -))"+echo "int4 b64:      $(du -sh "$OUT_ROOT/int4" | cut -f1)  encoder=$(du -h "$OUT_ROOT/int4/encoder.ncnn.bin" | cut -f1) decoder=$(du -h "$OUT_ROOT/int4/decoder.ncnn.bin" | cut -f1)"+echo "int4 b128:     $(du -sh "$OUT_ROOT/int4-128" | cut -f1)  encoder=$(du -h "$OUT_ROOT/int4-128/encoder.ncnn.bin" | cut -f1) decoder=$(du -h "$OUT_ROOT/int4-128/decoder.ncnn.bin" | cut -f1)"+echo "int8 b64:      $(du -sh "$OUT_ROOT/int8" | cut -f1)  encoder=$(du -h "$OUT_ROOT/int8/encoder.ncnn.bin" | cut -f1) decoder=$(du -h "$OUT_ROOT/int8/decoder.ncnn.bin" | cut -f1)"+echo ""+echo "Quantized params embed Embed still fp16 (131M * fp16 = 262M per net); only Gemm+MHA quantized."+echo "Compat: ncnn loader auto-dequantizes if built with -DNCNN_WEIGHT_QUANT=ON (AAR: src/main/cpp/CMakeLists.txt)."+echo ""+echo "Next: parity / BLEU validation via scripts/translate/quant_check.py and upload via upload_small100_r2.sh:"+echo "  ./scripts/translate/upload_small100_r2.sh $OUT_ROOT/int4 --prefix small100-int4/"
scripts/translate/upload_small100_r2.sh
diff --git a/scripts/translate/upload_small100_r2.sh b/scripts/translate/upload_small100_r2.shnew file mode 100755index 0000000000..3df14555e4--- /dev/null+++ b/scripts/translate/upload_small100_r2.sh@@ -0,0 +1,76 @@+#!/usr/bin/env bash+# Uploads the Small100 ncnn bundle (fp16 or int4 quantized) to R2 bucket `maps`,+# served at https://data.vayunmathur.com/models/small100/ (or subpath).+#+# Credentials are read from the environment (never hardcoded). Run from trusted shell:+#+#   export AWS_ACCESS_KEY_ID=...        # R2 access key id+#   export AWS_SECRET_ACCESS_KEY=...    # R2 secret+#   export R2_ENDPOINT=https://<account>.r2.cloudflarestorage.com+#   ./scripts/translate/upload_small100_r2.sh <bundle_dir> [--prefix small100/]+#   # int4 quantized:+#   ./scripts/translate/upload_small100_r2.sh scripts/translate/quantized/int4+#+# <bundle_dir> must contain: encoder.ncnn.{param,bin}, decoder.ncnn.{param,bin},+# sentencepiece.bpe.model, vocab.txt, pos_weights.f32.bin+#+# Quantization notes:+# - int4 weight-only block quant (ncnnllm): 680 MB vs 1.14 GB fp16, term 401=bits4 b64 mseclip+# - Embed stays fp16 (131M*fp16=262MB per net); Gemm+MHA quantized (36+13 layers)+# - AAR must be built with -DNCNN_WEIGHT_QUANT=ON (src/main/cpp/CMakeLists.txt + build.gradle.kts)+# - After upload, update Small100Model.kt SHA256 via: shasum -a 256 bundle/* | cut -d' ' -f1+set -euo pipefail++BUNDLE=""+PREFIX="small100/"+while [[ $# -gt 0 ]]; do+  case "$1" in+    --prefix) PREFIX="$2"; shift 2;;+    --prefix=*) PREFIX="${1#--prefix=}"; shift;;+    -h|--help)+      echo "usage: upload_small100_r2.sh <bundle_dir> [--prefix small100/]"+      echo "  default prefix small100/ (int4 replaces current); use small100-int4/ for side-by-side"+      exit 0;;+    *) BUNDLE="$1"; shift;;+  esac+done++if [[ -z "$BUNDLE" ]]; then+  echo "usage: upload_small100_r2.sh <bundle_dir> [--prefix small100/]" >&2+  exit 1+fi++: "${AWS_ACCESS_KEY_ID:?set AWS_ACCESS_KEY_ID}"+: "${AWS_SECRET_ACCESS_KEY:?set AWS_SECRET_ACCESS_KEY}"+: "${R2_ENDPOINT:?set R2_ENDPOINT}"+export AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-auto}"++# Validate+for f in encoder.ncnn.param encoder.ncnn.bin decoder.ncnn.param decoder.ncnn.bin sentencepiece.bpe.model vocab.txt pos_weights.f32.bin; do+  if [[ ! -f "$BUNDLE/$f" ]]; then+    echo "missing $BUNDLE/$f" >&2+    exit 1+  fi+done++echo "=== Local bundle $BUNDLE (upload to s3://maps/models/$PREFIX) ==="+ls -lh "$BUNDLE"+echo "SHA256:"+for f in encoder.ncnn.param encoder.ncnn.bin decoder.ncnn.param decoder.ncnn.bin; do+  echo "  $f $(shasum -a 256 "$BUNDLE/$f" | cut -d' ' -f1)"+done++# Normalize prefix to end with /+[[ "$PREFIX" != */ ]] && PREFIX="$PREFIX/"++aws s3 sync "$BUNDLE" "s3://maps/models/$PREFIX" \+  --endpoint-url "$R2_ENDPOINT" --checksum-algorithm CRC32++echo "--- uploaded objects s3://maps/models/$PREFIX ---"+aws s3 ls "s3://maps/models/$PREFIX" --endpoint-url "$R2_ENDPOINT"++echo ""+echo "If you replaced small100/ with int4, also update Small100Model.kt FILES SHA256:"+for f in encoder.ncnn.param encoder.ncnn.bin decoder.ncnn.param decoder.ncnn.bin sentencepiece.bpe.model vocab.txt pos_weights.f32.bin; do+  printf '  %s: %s\n' "$f" "$(shasum -a 256 "$BUNDLE/$f" | cut -d' ' -f1)"+done
translate/build.gradle.kts
diff --git a/translate/build.gradle.kts b/translate/build.gradle.ktsnew file mode 100644index 0000000000..7a5966108f--- /dev/null+++ b/translate/build.gradle.kts@@ -0,0 +1,30 @@+plugins {+    id("common-conventions-app")+    id("common-conventions-metadata")+    alias(libs.plugins.ksp)+}++launcherIcon {+    symbol = "translate"+}++android {+    defaultConfig {+        applicationId = "com.vayunmathur.translate"+    }+}++dependencies {+    // On-device translation runs entirely in the ncnn AAR (SMaLL-100 via the+    // Small100 class); the model files are downloaded at runtime from the mirror.+    implementation(libs.ncnn.android)+    implementation(project(":library:downloadservice"))+    implementation(project(":library:ocr"))+    implementation(project(":library:network"))+    implementation(libs.androidx.datastore.preferences)+    implementation(libs.androidx.camera.core)+    implementation(libs.androidx.camera.camera2)+    implementation(libs.androidx.camera.lifecycle)+    implementation(libs.androidx.camera.view)+    implementation(libs.androidx.camera.compose)+}
translate/src/main/AndroidManifest.xml
diff --git a/translate/src/main/AndroidManifest.xml b/translate/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..584a58488b--- /dev/null+++ b/translate/src/main/AndroidManifest.xml@@ -0,0 +1,43 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++    <uses-permission android:name="android.permission.CAMERA" />+    <uses-permission android:name="android.permission.RECORD_AUDIO" />++    <uses-feature android:name="android.hardware.camera.any" android:required="false" />++    <!-- Android 11+ package visibility: without this, SpeechRecognizer can't see an+         installed recognition service and isRecognitionAvailable() returns false. -->+    <queries>+        <intent>+            <action android:name="android.speech.RecognitionService" />+        </intent>+    </queries>++    <application+        android:allowBackup="true"+        android:dataExtractionRules="@xml/data_extraction_rules"+        android:icon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:roundIcon="@mipmap/ic_launcher"+        android:supportsRtl="true"+        android:theme="@style/Theme.General">+        <activity+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:name=".MainActivity"+            android:exported="true"+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>+            <!-- "Translate" appears in the text-selection context menu of other apps. -->+            <intent-filter>+                <action android:name="android.intent.action.PROCESS_TEXT" />+                <category android:name="android.intent.category.DEFAULT" />+                <data android:mimeType="text/plain" />+            </intent-filter>+        </activity>+    </application>++</manifest>
translate/src/main/java/com/vayunmathur/translate/MainActivity.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/MainActivity.kt b/translate/src/main/java/com/vayunmathur/translate/MainActivity.ktnew file mode 100644index 0000000000..f451748640--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/MainActivity.kt@@ -0,0 +1,77 @@+package com.vayunmathur.translate++import android.content.Intent+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels+import androidx.compose.runtime.Composable+import com.vayunmathur.library.downloadservice.InitialModelDownloadChecker+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.NavKey+import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.translate.ui.CameraTranslateScreen+import com.vayunmathur.translate.ui.TextTranslateScreen+import com.vayunmathur.translate.util.Small100Model+import com.vayunmathur.translate.util.TranslateViewModel+import kotlinx.serialization.Serializable++class MainActivity : ComponentActivity() {+    private val viewModel: TranslateViewModel by viewModels()++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        enableEdgeToEdge()+        // "Translate" from another app's text-selection menu prefills the input.+        val initialText = processTextFromIntent(intent)+        val ds = DataStoreUtils.getInstance(this)+        setContent {+            DynamicTheme {+                // Auto-install SMaLL-100 (~1.2 GB) on first open, like OpenAssistant's+                // InitialModelDownloadChecker for Gemma + SigLIP2. The checker gates on+                // actual disk presence and starts the DownloadManager loop immediately+                // in a LaunchedEffect, showing per-file progress + speed.+                InitialModelDownloadChecker(ds, Small100Model.FILES) {+                    Navigation(viewModel, initialText)+                }+            }+        }+    }++    private fun processTextFromIntent(intent: Intent?): String {+        if (intent?.action != Intent.ACTION_PROCESS_TEXT) return ""+        return intent.getCharSequenceExtra(Intent.EXTRA_PROCESS_TEXT)?.toString().orEmpty()+    }+}++@Serializable+sealed interface Route : NavKey {+    @Serializable+    data object Text : Route++    @Serializable+    data object Camera : Route+}++@Composable+fun Navigation(viewModel: TranslateViewModel, initialText: String) {+    val backStack = rememberNavBackStack<Route>(Route.Text)+    MainNavigation(backStack) {+        entry<Route.Text> {+            TextTranslateScreen(+                viewModel = viewModel,+                initialText = initialText,+                onOpenCamera = { backStack.add(Route.Camera) },+            )+        }+        entry<Route.Camera> {+            CameraTranslateScreen(+                viewModel = viewModel,+                onBack = { backStack.pop() },+            )+        }+    }+}
translate/src/main/java/com/vayunmathur/translate/ui/CameraTranslateScreen.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/ui/CameraTranslateScreen.kt b/translate/src/main/java/com/vayunmathur/translate/ui/CameraTranslateScreen.ktnew file mode 100644index 0000000000..7f653d2b49--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/ui/CameraTranslateScreen.kt@@ -0,0 +1,317 @@+package com.vayunmathur.translate.ui++import android.Manifest+import android.graphics.Bitmap+import android.graphics.Matrix+import android.util.Log+import androidx.camera.core.Camera+import androidx.camera.core.CameraSelector+import androidx.camera.core.ImageAnalysis+import androidx.camera.core.Preview+import androidx.camera.lifecycle.ProcessCameraProvider+import androidx.camera.lifecycle.awaitInstance+import androidx.camera.view.PreviewView+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.BoxWithConstraints+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.rememberUpdatedState+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.compose.ui.viewinterop.AndroidView+import androidx.lifecycle.compose.LocalLifecycleOwner+import com.vayunmathur.library.ui.IconBack+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconFlashOff+import com.vayunmathur.library.ui.IconFlashOn+import com.vayunmathur.library.ui.IconPause+import com.vayunmathur.library.ui.IconPlay+import com.vayunmathur.library.ui.PermissionsChecker+import com.vayunmathur.library.ui.Text+import com.vayunmathur.translate.util.Languages+import com.vayunmathur.translate.util.TranslateViewModel+import kotlinx.coroutines.launch+import java.util.concurrent.Executors+import java.util.concurrent.atomic.AtomicBoolean+import java.util.concurrent.atomic.AtomicLong+import kotlin.math.max+import kotlin.math.roundToInt++/** Minimum gap between analyzed frames (ms) — throttles OCR to keep it light. */+private const val ANALYSIS_INTERVAL_MS = 700L++/** One translated line positioned in the (upright) analysed-bitmap's pixel space. */+private data class OverlayBox(+    val left: Int,+    val top: Int,+    val right: Int,+    val bottom: Int,+    val text: String,+    val translated: Boolean,+)++@Composable+fun CameraTranslateScreen(viewModel: TranslateViewModel, onBack: () -> Unit) {+    PermissionsChecker(+        permissions = arrayOf(Manifest.permission.CAMERA),+        text = "Grant camera access to translate what you see",+    ) {+        CameraContent(viewModel, onBack)+    }+}++@Composable+private fun CameraContent(viewModel: TranslateViewModel, onBack: () -> Unit) {+    val context = LocalContext.current+    val lifecycleOwner = LocalLifecycleOwner.current+    val scope = rememberCoroutineScope()+    val density = LocalDensity.current++    val sourceLang by viewModel.sourceLang.collectAsState()+    val targetLang by viewModel.targetLang.collectAsState()+    val translationAvailable by viewModel.translationAvailable.collectAsState()++    val previewView = remember { PreviewView(context) }+    var camera by remember { mutableStateOf<Camera?>(null) }+    var torchOn by remember { mutableStateOf(false) }+    var paused by remember { mutableStateOf(false) }++    // OCR/translation results, in analysed-bitmap pixel coords.+    var overlays by remember { mutableStateOf<List<OverlayBox>>(emptyList()) }+    var frameW by remember { mutableStateOf(0) }+    var frameH by remember { mutableStateOf(0) }+    var frozenFrame by remember { mutableStateOf<Bitmap?>(null) }++    // Read by the analysis-thread callback; kept fresh via rememberUpdatedState.+    val pausedState = rememberUpdatedState(paused)+    val availableState = rememberUpdatedState(translationAvailable)++    val analysisExecutor = remember { Executors.newSingleThreadExecutor() }+    val inFlight = remember { AtomicBoolean(false) }+    val lastMs = remember { AtomicLong(0L) }++    DisposableEffect(Unit) {+        onDispose { analysisExecutor.shutdown() }+    }++    LaunchedEffect(torchOn) {+        camera?.cameraControl?.enableTorch(torchOn)+    }++    LaunchedEffect(Unit) {+        val provider = ProcessCameraProvider.awaitInstance(context)+        val preview = Preview.Builder().build().also {+            it.surfaceProvider = previewView.surfaceProvider+        }+        val analysis = ImageAnalysis.Builder()+            .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)+            .build()++        analysis.setAnalyzer(analysisExecutor) { proxy ->+            val now = System.currentTimeMillis()+            if (pausedState.value || inFlight.get() || now - lastMs.get() < ANALYSIS_INTERVAL_MS) {+                proxy.close()+                return@setAnalyzer+            }+            lastMs.set(now)+            inFlight.set(true)+            val bmp = try {+                proxy.toBitmap()+            } catch (t: Throwable) {+                Log.e(TAG, "toBitmap failed", t)+                null+            }+            val rotation = proxy.imageInfo.rotationDegrees+            proxy.close()+            if (bmp == null) {+                inFlight.set(false)+                return@setAnalyzer+            }+            // Heavy work off the analysis thread; OCR/translate suspend internally+            // onto Dispatchers.Default. State writes happen back on the main thread.+            scope.launch {+                try {+                    val upright = rotateBitmap(bmp, rotation)+                    val result = viewModel.ocr.recognizeDetailed(upright)+                    val boxes = result.boxes.map { box ->+                        val translation =+                            if (availableState.value) viewModel.translate(box.text) else null+                        OverlayBox(+                            left = box.left,+                            top = box.top,+                            right = box.right,+                            bottom = box.bottom,+                            text = translation ?: box.text,+                            translated = translation != null,+                        )+                    }+                    frameW = upright.width+                    frameH = upright.height+                    overlays = boxes+                    frozenFrame = upright+                } finally {+                    inFlight.set(false)+                }+            }+        }++        try {+            provider.unbindAll()+            camera = provider.bindToLifecycle(+                lifecycleOwner,+                CameraSelector.DEFAULT_BACK_CAMERA,+                preview,+                analysis,+            )+        } catch (t: Throwable) {+            Log.e(TAG, "Camera bind failed", t)+        }+    }++    Box(modifier = Modifier.fillMaxSize().background(Color.Black)) {+        BoxWithConstraints(modifier = Modifier.fillMaxSize()) {+            val viewW = constraints.maxWidth.toFloat()+            val viewH = constraints.maxHeight.toFloat()++            // Live preview, or the frozen last frame while paused.+            val frozen = frozenFrame+            if (paused && frozen != null) {+                Image(+                    bitmap = frozen.asImageBitmap(),+                    contentDescription = null,+                    modifier = Modifier.fillMaxSize(),+                    contentScale = ContentScale.Crop,+                )+            } else {+                AndroidView(factory = { previewView }, modifier = Modifier.fillMaxSize())+            }++            // Map analysed-bitmap coords -> view coords assuming PreviewView's default+            // FILL_CENTER (center-crop): scale by the larger ratio, then centre.+            if (frameW > 0 && frameH > 0) {+                val scale = max(viewW / frameW, viewH / frameH)+                val dx = (viewW - frameW * scale) / 2f+                val dy = (viewH - frameH * scale) / 2f+                overlays.forEach { ob ->+                    val l = ob.left * scale + dx+                    val t = ob.top * scale + dy+                    val w = (ob.right - ob.left) * scale+                    val h = (ob.bottom - ob.top) * scale+                    if (w <= 0f || h <= 0f) return@forEach+                    val fontSp = (with(density) { h.toDp().value } * 0.5f).coerceIn(9f, 22f)+                    Box(+                        modifier = Modifier+                            .offset { IntOffset(l.roundToInt(), t.roundToInt()) }+                            .size(+                                width = with(density) { w.toDp() },+                                height = with(density) { h.toDp() },+                            )+                            .clip(RoundedCornerShape(4.dp))+                            .background(Color(0xF2000000))+                            .padding(horizontal = 3.dp),+                        contentAlignment = Alignment.Center,+                    ) {+                        Text(+                            text = ob.text,+                            color = Color.White,+                            fontSize = fontSp.sp,+                            maxLines = 1,+                            overflow = TextOverflow.Ellipsis,+                        )+                    }+                }+            }+        }++        // Back button (top-left).+        IconButton(+            onClick = onBack,+            modifier = Modifier+                .align(Alignment.TopStart)+                .padding(8.dp)+                .background(Color(0x99000000), RoundedCornerShape(24.dp)),+        ) {+            IconBack(tint = Color.White)+        }++        if (!translationAvailable) {+            Text(+                text = "Translation model not installed — showing detected text only",+                color = Color.White,+                modifier = Modifier+                    .align(Alignment.TopCenter)+                    .padding(top = 12.dp)+                    .background(Color(0xB3000000), RoundedCornerShape(12.dp))+                    .padding(horizontal = 12.dp, vertical = 6.dp),+            )+        }++        // Bottom controls: language pickers + pause/resume + torch.+        Row(+            modifier = Modifier+                .align(Alignment.BottomCenter)+                .fillMaxWidth()+                .padding(12.dp)+                .background(Color(0xB3000000), RoundedCornerShape(24.dp))+                .padding(horizontal = 8.dp, vertical = 4.dp),+            verticalAlignment = Alignment.CenterVertically,+            horizontalArrangement = Arrangement.SpaceBetween,+        ) {+            LanguagePicker(+                selectedCode = sourceLang,+                options = Languages.SOURCES,+                onSelected = viewModel::setSource,+                modifier = Modifier.width(120.dp),+            )+            IconButton(onClick = { paused = !paused }) {+                if (paused) IconPlay(tint = Color.White) else IconPause(tint = Color.White)+            }+            IconButton(onClick = { torchOn = !torchOn }) {+                if (torchOn) IconFlashOn(tint = Color.White) else IconFlashOff(tint = Color.White)+            }+            LanguagePicker(+                selectedCode = targetLang,+                options = Languages.TARGETS,+                onSelected = viewModel::setTarget,+                modifier = Modifier.width(120.dp),+            )+        }+    }+}++/** Rotate [src] by [degrees] so OCR sees an upright image. Returns [src] if 0°. */+private fun rotateBitmap(src: Bitmap, degrees: Int): Bitmap {+    if (degrees % 360 == 0) return src+    val matrix = Matrix().apply { postRotate(degrees.toFloat()) }+    return Bitmap.createBitmap(src, 0, 0, src.width, src.height, matrix, true)+}++private const val TAG = "CameraTranslate"
translate/src/main/java/com/vayunmathur/translate/ui/LanguagePicker.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/ui/LanguagePicker.kt b/translate/src/main/java/com/vayunmathur/translate/ui/LanguagePicker.ktnew file mode 100644index 0000000000..69a6bffbba--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/ui/LanguagePicker.kt@@ -0,0 +1,61 @@+package com.vayunmathur.translate.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.DropdownMenu+import com.vayunmathur.library.ui.DropdownMenuItem+import com.vayunmathur.library.ui.IconArrowDropDown+import com.vayunmathur.library.ui.IconCheck+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.translate.util.Language+import com.vayunmathur.translate.util.Languages++/**+ * A compact language selector: a text button showing the current language's+ * native name plus a dropdown of [options]. The checked item is marked.+ */+@Composable+fun LanguagePicker(+    selectedCode: String,+    options: List<Language>,+    onSelected: (String) -> Unit,+    modifier: Modifier = Modifier,+    enabled: Boolean = true,+) {+    var expanded by remember { mutableStateOf(false) }+    Box(modifier) {+        TextButton(onClick = { expanded = true }, enabled = enabled) {+            Text(+                text = Languages.byCode(selectedCode).nativeName,+                maxLines = 1,+                overflow = TextOverflow.Ellipsis,+            )+            IconArrowDropDown(Modifier.size(20.dp))+        }+        DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {+            options.forEach { lang ->+                DropdownMenuItem(+                    text = { Text("${lang.nativeName}  ·  ${lang.englishName}") },+                    onClick = {+                        onSelected(lang.code)+                        expanded = false+                    },+                    trailingIcon = if (lang.code == selectedCode) {+                        { IconCheck(Modifier.size(18.dp)) }+                    } else {+                        null+                    },+                )+            }+        }+    }+}
translate/src/main/java/com/vayunmathur/translate/ui/TextTranslateScreen.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslateScreen.kt b/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslateScreen.ktnew file mode 100644index 0000000000..6927b9d05b--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/ui/TextTranslateScreen.kt@@ -0,0 +1,313 @@+package com.vayunmathur.translate.ui++import android.Manifest+import android.content.ClipData+import android.content.ClipboardManager+import android.content.Context+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.FloatingActionButton+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconCamera+import com.vayunmathur.library.ui.IconCopy+import com.vayunmathur.library.ui.IconMic+import com.vayunmathur.library.ui.IconSpeak+import com.vayunmathur.library.ui.IconStop+import com.vayunmathur.library.ui.IconSwapLanguages+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.translate.util.AndroidSpeechRecognizer+import com.vayunmathur.translate.util.Languages+import com.vayunmathur.translate.util.NativeSpeech+import com.vayunmathur.translate.util.SpeechRecognizerEngine+import com.vayunmathur.translate.util.TranslateViewModel+import kotlinx.coroutines.delay++/** Debounce window for live translation as the user types (ms). */+private const val TRANSLATE_DEBOUNCE_MS = 400L++/**+ * Home screen. The SMaLL-100 model (~1.2 GB) is now auto-installed on open via+ * [com.vayunmathur.library.downloadservice.InitialModelDownloadChecker] in+ * MainActivity (like OpenAssistant), so this screen never needs to show a+ * manual Download button. By the time we get here the files are on disk and+ * [TranslateViewModel] has loaded the ncnn engine.+ */+@Composable+fun TextTranslateScreen(+    viewModel: TranslateViewModel,+    initialText: String,+    onOpenCamera: () -> Unit,+) {+    val context = LocalContext.current++    val sourceLang by viewModel.sourceLang.collectAsState()+    val targetLang by viewModel.targetLang.collectAsState()+    val translationAvailable by viewModel.translationAvailable.collectAsState()++    var inputText by remember { mutableStateOf(initialText) }+    var outputText by remember { mutableStateOf("") }+    var isTranslating by remember { mutableStateOf(false) }++    // --- Live speech-to-text engine (native offline preferred, else platform) ---+    val speech: SpeechRecognizerEngine = remember(context) {+        NativeSpeech().takeIf { it.isAvailable() } ?: AndroidSpeechRecognizer(context)+    }+    var listening by remember { mutableStateOf(false) }+    var speechError by remember { mutableStateOf<String?>(null) }+    DisposableEffect(speech) { onDispose { speech.destroy() } }++    fun startListening() {+        speechError = null+        listening = true+        speech.start(+            languageCode = sourceLang,+            onPartial = { inputText = it },+            onFinal = {+                inputText = it+                listening = false+            },+            onError = {+                speechError = it+                listening = false+            },+        )+    }++    val micPermission = rememberLauncherForActivityResult(+        ActivityResultContracts.RequestPermission()+    ) { granted ->+        if (granted) startListening() else speechError = "Microphone permission is required"+    }++    // Live, debounced translation as input / language selection changes.+    LaunchedEffect(inputText, sourceLang, targetLang, translationAvailable) {+        if (inputText.isBlank()) {+            outputText = ""+            isTranslating = false+            return@LaunchedEffect+        }+        if (!translationAvailable) return@LaunchedEffect+        delay(TRANSLATE_DEBOUNCE_MS)+        isTranslating = true+        outputText = viewModel.translate(inputText).orEmpty()+        isTranslating = false+    }++    Scaffold(+        topBar = {+            TopAppBar(+                title = { Text("Translate") },+                actions = {+                    IconButton(onClick = onOpenCamera) {+                        IconCamera()+                    }+                },+            )+        },+        floatingActionButton = {+            // While listening the button is a Stop: tap ends capture (stopListening)+            // and the recognizer still delivers its last result via onFinal — it does+            // not cancel. Idle, it's a Mic that starts a new session.+            FloatingActionButton(+                onClick = {+                    if (listening) {+                        speech.stop()+                    } else {+                        micPermission.launch(Manifest.permission.RECORD_AUDIO)+                    }+                },+                containerColor = if (listening) {+                    MaterialTheme.colorScheme.errorContainer+                } else {+                    MaterialTheme.colorScheme.primaryContainer+                },+            ) {+                if (listening) IconStop() else IconMic()+            }+        },+    ) { padding ->+        Column(+            modifier = Modifier+                .fillMaxSize()+                .padding(padding)+                .verticalScroll(rememberScrollState())+                .padding(16.dp),+            verticalArrangement = Arrangement.spacedBy(12.dp),+        ) {+            LanguageBar(+                sourceCode = sourceLang,+                targetCode = targetLang,+                onSource = viewModel::setSource,+                onTarget = viewModel::setTarget,+                onSwap = viewModel::swap,+            )++            OutlinedTextField(+                value = inputText,+                onValueChange = { inputText = it },+                modifier = Modifier+                    .fillMaxWidth()+                    .heightIn(min = 120.dp),+                label = { Text("Enter text") },+                minLines = 4,+            )++            if (listening) {+                Text(+                    text = "Listening…",+                    color = MaterialTheme.colorScheme.primary,+                    fontWeight = FontWeight.Medium,+                )+            }+            speechError?.let {+                Text(text = it, color = MaterialTheme.colorScheme.error)+            }++            OutputCard(+                translationAvailable = translationAvailable,+                isTranslating = isTranslating,+                outputText = outputText,+                onCopy = { copyToClipboard(context, outputText) },+                onSpeak = { viewModel.speak(outputText, targetLang) },+            )+        }+    }+}++@Composable+private fun LanguageBar(+    sourceCode: String,+    targetCode: String,+    onSource: (String) -> Unit,+    onTarget: (String) -> Unit,+    onSwap: () -> Unit,+) {+    Row(+        modifier = Modifier.fillMaxWidth(),+        verticalAlignment = Alignment.CenterVertically,+        horizontalArrangement = Arrangement.SpaceBetween,+    ) {+        LanguagePicker(+            selectedCode = sourceCode,+            options = Languages.SOURCES,+            onSelected = onSource,+            modifier = Modifier.width(140.dp),+        )+        IconButton(+            onClick = onSwap,+            // Nothing to swap into while the source is auto-detect.+            enabled = sourceCode != Languages.AUTO.code,+        ) {+            IconSwapLanguages()+        }+        LanguagePicker(+            selectedCode = targetCode,+            options = Languages.TARGETS,+            onSelected = onTarget,+            modifier = Modifier.width(140.dp),+        )+    }+}++@Composable+private fun OutputCard(+    translationAvailable: Boolean,+    isTranslating: Boolean,+    outputText: String,+    onCopy: () -> Unit,+    onSpeak: () -> Unit,+) {+    Card(modifier = Modifier.fillMaxWidth()) {+        Column(+            modifier = Modifier+                .fillMaxWidth()+                .padding(16.dp),+            verticalArrangement = Arrangement.spacedBy(12.dp),+        ) {+            if (!translationAvailable) {+                // Should never happen — the outer InitialModelDownloadChecker+                // downloads the model before any Navigation is composed, and+                // TranslateViewModel loads the engine on init. Show a loading+                // spinner if the engine is still initializing.+                Row(verticalAlignment = Alignment.CenterVertically) {+                    CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)+                    Spacer(Modifier.width(8.dp))+                    Text("Loading translator…", color = MaterialTheme.colorScheme.onSurfaceVariant)+                }+                return@Column+            }++            Row(verticalAlignment = Alignment.CenterVertically) {+                Text(+                    text = "Translation",+                    fontWeight = FontWeight.Medium,+                    color = MaterialTheme.colorScheme.primary,+                )+                if (isTranslating) {+                    Spacer(Modifier.width(8.dp))+                    CircularProgressIndicator(modifier = Modifier.size(16.dp), strokeWidth = 2.dp)+                }+            }++            Text(+                text = outputText.ifBlank { "Translation will appear here" },+                color = if (outputText.isBlank()) {+                    MaterialTheme.colorScheme.onSurfaceVariant+                } else {+                    MaterialTheme.colorScheme.onSurface+                },+            )++            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+                TextButton(onClick = onCopy, enabled = outputText.isNotBlank()) {+                    IconCopy(Modifier.size(18.dp))+                    Spacer(Modifier.width(6.dp))+                    Text("Copy")+                }+                TextButton(onClick = onSpeak, enabled = outputText.isNotBlank()) {+                    IconSpeak(Modifier.size(18.dp))+                    Spacer(Modifier.width(6.dp))+                    Text("Speak")+                }+            }+        }+    }+}++private fun copyToClipboard(context: Context, text: String) {+    if (text.isBlank()) return+    val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager+    clipboard?.setPrimaryClip(ClipData.newPlainText("translation", text))+}
translate/src/main/java/com/vayunmathur/translate/util/Languages.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/util/Languages.kt b/translate/src/main/java/com/vayunmathur/translate/util/Languages.ktnew file mode 100644index 0000000000..1fd7d97400--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/util/Languages.kt@@ -0,0 +1,52 @@+package com.vayunmathur.translate.util++/**+ * One selectable language. [code] is the BCP-47 / ISO-639-1 code used both as the+ * translation-engine language id and (via [java.util.Locale]) for text-to-speech.+ * [AUTO] is a sentinel meaning "detect the source language automatically" and is+ * only offered as a *source*, never a target.+ */+data class Language(+    val code: String,+    val englishName: String,+    val nativeName: String,+)++object Languages {+    /** Sentinel source option: let the engine detect the language. */+    val AUTO = Language("auto", "Auto (detect)", "Auto")++    /** ~20 common languages, curated. Codes are ISO-639-1 for TTS Locale support. */+    val ALL: List<Language> = listOf(+        Language("en", "English", "English"),+        Language("es", "Spanish", "Español"),+        Language("fr", "French", "Français"),+        Language("de", "German", "Deutsch"),+        Language("it", "Italian", "Italiano"),+        Language("pt", "Portuguese", "Português"),+        Language("nl", "Dutch", "Nederlands"),+        Language("ru", "Russian", "Русский"),+        Language("pl", "Polish", "Polski"),+        Language("tr", "Turkish", "Türkçe"),+        Language("ar", "Arabic", "العربية"),+        Language("hi", "Hindi", "हिन्दी"),+        Language("zh", "Chinese", "中文"),+        Language("ja", "Japanese", "日本語"),+        Language("ko", "Korean", "한국어"),+        Language("vi", "Vietnamese", "Tiếng Việt"),+        Language("th", "Thai", "ไทย"),+        Language("id", "Indonesian", "Bahasa Indonesia"),+        Language("uk", "Ukrainian", "Українська"),+        Language("sv", "Swedish", "Svenska"),+    )++    /** Sources include the [AUTO] sentinel; targets are the concrete languages. */+    val SOURCES: List<Language> = listOf(AUTO) + ALL+    val TARGETS: List<Language> = ALL++    /** Look up a language by [code], falling back to [AUTO] then [en]. */+    fun byCode(code: String): Language =+        if (code == AUTO.code) AUTO else ALL.firstOrNull { it.code == code } ?: ALL.first()++    fun displayName(code: String): String = byCode(code).nativeName+}
translate/src/main/java/com/vayunmathur/translate/util/Small100Model.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/util/Small100Model.kt b/translate/src/main/java/com/vayunmathur/translate/util/Small100Model.ktnew file mode 100644index 0000000000..d11e17c85f--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/util/Small100Model.kt@@ -0,0 +1,72 @@+package com.vayunmathur.translate.util++import android.content.Context+import com.vayunmathur.library.downloadservice.ModelDownloadItem+import com.vayunmathur.library.downloadservice.downloadModels+import com.vayunmathur.library.util.DataStoreUtils+import java.io.File++/**+ * Runtime-download config for the on-device **SMaLL-100** translation model+ * (converted to ncnn). Quantization attempt:+ * - int4 weight-only block quant via ncnnllm (mseclip b64) produced 680 MB vs+ *   1.14 GB fp16 (36 enc + 13 dec Gemm+MHA layers, term 401), Embed stays fp16+ *   (262 MB ×2 floor).+ * - **CRASH**: int4 MHA `forward_weight_block_quantize` triggered MTE+ *   SEGV_MTESERR in `libncnn_android.so` at `multiheadattention.cpp:793`+ *   (Pixel 9 Pro XL, Android 17, OpenMP worker). Tombstone 28:+ *   `pc 0x490224 -> forward_weight_block_quantize (.omp_outlined_debug__.33)`.+ *   Root cause: ncnn int4 block-quant MHA not MTE-clean (packed int4 unpack may+ *   read out-of-tag). Roll back to fp16 stable; alternative path: Gemm-only+ *   int4 or classic Embed int8 via ncnn2int8.+ *+ * Files are fetched mirror-only from `data.vayunmathur.com/models/small100/`+ * with SHA-256 pinning via [downloadModels]. Auto-install via+ * `InitialModelDownloadChecker` in MainActivity (like OpenAssistant).+ */+object Small100Model {+    private const val BASE = "https://data.vayunmathur.com/models/small100/"+    const val DIR = "small100"++    /** The 7 runtime files — fp16 stable (int4 MHA crashes on Pixel 9 MTE, see above). */+    val FILES: List<ModelDownloadItem> = listOf(+        item("encoder.ncnn.param", "4c86bc19318933169474ddab957c7031cbce48d95c06d3159d487e6a941959c8"),+        item("encoder.ncnn.bin", "06d34fe528960b8f5246592d99b4bfaf27b164fc4a49bd5a13d95eadb87d13a2"),+        item("decoder.ncnn.param", "e3fd9b9be770d93a022d98c8b29f5ed603e08b04be424da8480cacfce00467bf"),+        item("decoder.ncnn.bin", "2bedd93dc073cb1840c563acfa5e70816893c6fbf678a538fdad68f90325ec70"),+        item("sentencepiece.bpe.model", "d8f7c76ed2a5e0822be39f0a4f95a55eb19c78f4593ce609e2edbc2aea4d380a"),+        item("vocab.txt", "84733eadc2b3f2a21c55687336ca538e55650233bcc729650cd53c2d2fc77319"),+        item("pos_weights.f32.bin", "254e2cf622a8e498df8600c5052ec492129b5ca8932ada1e514a091c26f9dd80"),+    )++    private fun item(name: String, sha256: String) =+        ModelDownloadItem("$BASE$name", "$DIR/$name", "SMaLL-100 $name", sha256)++    /** Directory the ncnn `Small100` loads from. */+    fun modelDir(context: Context): File = File(context.getExternalFilesDir(null), DIR)++    /** True once every model file is present on disk. */+    fun isDownloaded(context: Context): Boolean {+        val root = context.getExternalFilesDir(null) ?: return false+        return FILES.all { File(root, it.fileName).exists() }+    }++    /** Download any missing files (skips present ones); suspends until complete. */+    suspend fun download(context: Context, ds: DataStoreUtils) = downloadModels(context, ds, FILES)++    /** Averaged 0..1 download progress across the files, read from DataStore. */+    fun progress(ds: DataStoreUtils): Float =+        (FILES.map { ds.getDouble("progress_${it.fileName}") ?: 0.0 }.average()).toFloat()++    /**+     * SMaLL-100 target-language token ids (`128004 + fairseq index`) for the app's+     * offered languages. SMaLL-100 needs only the target language (it's prepended to+     * the source), so no source id is required.+     */+    val LANG_ID: Map<String, Int> = mapOf(+        "en" to 128022, "es" to 128023, "fr" to 128028, "de" to 128020, "it" to 128045,+        "pt" to 128075, "nl" to 128067, "ru" to 128077, "pl" to 128073, "tr" to 128093,+        "ar" to 128006, "hi" to 128036, "zh" to 128102, "ja" to 128046, "ko" to 128052,+        "vi" to 128097, "th" to 128090, "id" to 128041, "uk" to 128094, "sv" to 128087,+    )+}
translate/src/main/java/com/vayunmathur/translate/util/Small100Translator.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/util/Small100Translator.kt b/translate/src/main/java/com/vayunmathur/translate/util/Small100Translator.ktnew file mode 100644index 0000000000..e1a2f66795--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/util/Small100Translator.kt@@ -0,0 +1,78 @@+package com.vayunmathur.translate.util++import android.content.Context+import android.util.Log+import com.vayunmathur.ncnn.Small100+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.coroutines.withContext++/**+ * [TranslationEngine] backed by the ncnn AAR's [Small100] (on-device SMaLL-100).+ * The model is loaded lazily from [Small100Model.modelDir] the first time it's+ * needed and only if the files have been downloaded; until then [isAvailable] is+ * false and the UI shows a download prompt. Language detection is unnecessary —+ * SMaLL-100 only needs the target language — so [detectLanguage] returns null.+ */+class Small100Translator(private val context: Context) : TranslationEngine {++    private val lock = Mutex()+    private var model: Small100? = null+    private var loadFailed = false++    override suspend fun isAvailable(): Boolean = withContext(Dispatchers.Default) {+        lock.withLock { ensure() }+    }++    override suspend fun detectLanguage(text: String): String? = null++    override suspend fun translate(text: String, from: String?, to: String): String? =+        withContext(Dispatchers.Default) {+            if (text.isBlank()) return@withContext ""+            val tgtId = Small100Model.LANG_ID[to] ?: return@withContext null+            lock.withLock {+                if (!ensure()) return@withContext null+                try {+                    model?.translate(text, tgtId)?.ifBlank { null }+                } catch (t: Throwable) {+                    Log.e(TAG, "translate failed", t)+                    null+                }+            }+        }++    /** Call after a successful model download so the next use loads it. */+    suspend fun reset() = lock.withLock { loadFailed = false }++    fun close() {+        model?.close()+        model = null+    }++    /** Load the ncnn model once, if the files are present. Returns whether it's ready. */+    private fun ensure(): Boolean {+        model?.let { return true }+        if (loadFailed) return false+        if (!Small100Model.isDownloaded(context)) return false+        return try {+            val m = Small100(Small100Model.modelDir(context).absolutePath)+            if (m.isAvailable) {+                model = m+                true+            } else {+                m.close()+                loadFailed = true+                false+            }+        } catch (t: Throwable) {+            Log.e(TAG, "Small100 load failed", t)+            loadFailed = true+            false+        }+    }++    companion object {+        private const val TAG = "Small100Translator"+    }+}
translate/src/main/java/com/vayunmathur/translate/util/SpeechRecognizerEngine.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/util/SpeechRecognizerEngine.kt b/translate/src/main/java/com/vayunmathur/translate/util/SpeechRecognizerEngine.ktnew file mode 100644index 0000000000..f7ab8e59f5--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/util/SpeechRecognizerEngine.kt@@ -0,0 +1,184 @@+package com.vayunmathur.translate.util++import android.content.Context+import android.content.Intent+import android.os.Bundle+import android.speech.RecognitionListener+import android.speech.RecognizerIntent+import android.speech.SpeechRecognizer+import android.util.Log+import java.util.Locale++/**+ * Live speech-to-text, behind a clean interface. Implementations stream partial+ * transcripts via [onPartial] as words arrive and a final transcript via+ * [onFinal]. All callbacks are delivered on the main thread.+ */+interface SpeechRecognizerEngine {+    /** True if this engine can actually transcribe on this device. */+    fun isAvailable(): Boolean++    /**+     * Begin listening for speech in [languageCode] (ISO-639-1, "auto" allowed —+     * falls back to the device default). [onPartial] fires repeatedly with the+     * best in-progress hypothesis; [onFinal] fires once with the settled text;+     * [onError] reports a human-readable failure.+     */+    fun start(+        languageCode: String,+        onPartial: (String) -> Unit,+        onFinal: (String) -> Unit,+        onError: (String) -> Unit,+    )++    /** Stop listening (keeps the engine usable for a later [start]). */+    fun stop()++    /** Release all resources. */+    fun destroy()+}++/**+ * Offline speech recognition backed by [TranslateNative]. Stubbed: no whisper+ * weights are bundled so [isAvailable] is false and [start] immediately errors,+ * causing callers to fall back to [AndroidSpeechRecognizer]. Kept as a clean+ * seam for a real on-device model. Never crashes if the native lib is absent.+ */+class NativeSpeech : SpeechRecognizerEngine {++    override fun isAvailable(): Boolean {+        if (!TranslateNative.isAvailable) return false+        return try {+            TranslateNative.nativeSpeechAvailable()+        } catch (t: Throwable) {+            Log.e(TAG, "nativeSpeechAvailable failed", t)+            false+        }+    }++    override fun start(+        languageCode: String,+        onPartial: (String) -> Unit,+        onFinal: (String) -> Unit,+        onError: (String) -> Unit,+    ) {+        // No offline model shipped; report unavailable so the caller falls back.+        onError("Offline speech model not installed")+    }++    override fun stop() {}+    override fun destroy() {}++    companion object {+        private const val TAG = "NativeSpeech"+    }+}++/**+ * Speech recognition using the platform [SpeechRecognizer] with partial results+ * (`EXTRA_PARTIAL_RESULTS`). Works on devices that ship a recognizer (most, via+ * Google/Samsung). Must be created and used on the main thread.+ */+class AndroidSpeechRecognizer(private val context: Context) : SpeechRecognizerEngine {++    private var recognizer: SpeechRecognizer? = null++    override fun isAvailable(): Boolean = SpeechRecognizer.isRecognitionAvailable(context)++    override fun start(+        languageCode: String,+        onPartial: (String) -> Unit,+        onFinal: (String) -> Unit,+        onError: (String) -> Unit,+    ) {+        if (!isAvailable()) {+            onError("Speech recognition unavailable on this device")+            return+        }+        // Recreate per session so a previous error state never leaks in.+        recognizer?.destroy()+        val sr = SpeechRecognizer.createSpeechRecognizer(context).also { recognizer = it }++        val locale = if (languageCode == Languages.AUTO.code) {+            Locale.getDefault()+        } else {+            Locale.forLanguageTag(languageCode)+        }++        val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {+            putExtra(+                RecognizerIntent.EXTRA_LANGUAGE_MODEL,+                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM,+            )+            putExtra(RecognizerIntent.EXTRA_LANGUAGE, locale.toLanguageTag())+            putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)+            putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1)+        }++        sr.setRecognitionListener(object : RecognitionListener {+            override fun onReadyForSpeech(params: Bundle?) {}+            override fun onBeginningOfSpeech() {}+            override fun onRmsChanged(rmsdB: Float) {}+            override fun onBufferReceived(buffer: ByteArray?) {}+            override fun onEndOfSpeech() {}++            override fun onError(error: Int) {+                onError(describeError(error))+            }++            override fun onPartialResults(partialResults: Bundle?) {+                firstResult(partialResults)?.let(onPartial)+            }++            override fun onResults(results: Bundle?) {+                firstResult(results)?.let(onFinal)+            }++            override fun onEvent(eventType: Int, params: Bundle?) {}+        })++        try {+            sr.startListening(intent)+        } catch (t: Throwable) {+            Log.e(TAG, "startListening failed", t)+            onError("Could not start speech recognition")+        }+    }++    override fun stop() {+        try {+            recognizer?.stopListening()+        } catch (_: Throwable) {+        }+    }++    override fun destroy() {+        try {+            recognizer?.destroy()+        } catch (_: Throwable) {+        }+        recognizer = null+    }++    private fun firstResult(bundle: Bundle?): String? =+        bundle?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)+            ?.firstOrNull()+            ?.takeIf { it.isNotBlank() }++    private fun describeError(error: Int): String = when (error) {+        SpeechRecognizer.ERROR_AUDIO -> "Audio recording error"+        SpeechRecognizer.ERROR_CLIENT -> "Client error"+        SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS -> "Microphone permission denied"+        SpeechRecognizer.ERROR_NETWORK -> "Network error"+        SpeechRecognizer.ERROR_NETWORK_TIMEOUT -> "Network timeout"+        SpeechRecognizer.ERROR_NO_MATCH -> "No speech recognized"+        SpeechRecognizer.ERROR_RECOGNIZER_BUSY -> "Recognizer busy"+        SpeechRecognizer.ERROR_SERVER -> "Server error"+        SpeechRecognizer.ERROR_SPEECH_TIMEOUT -> "No speech input"+        else -> "Speech recognition error"+    }++    companion object {+        private const val TAG = "AndroidSpeech"+    }+}
translate/src/main/java/com/vayunmathur/translate/util/TranslateNative.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/util/TranslateNative.kt b/translate/src/main/java/com/vayunmathur/translate/util/TranslateNative.ktnew file mode 100644index 0000000000..189434903d--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/util/TranslateNative.kt@@ -0,0 +1,64 @@+package com.vayunmathur.translate.util++import android.util.Log++/**+ * JNI bridge to the native Rust translation / speech engine+ * (`libtranslate_engine.so`, built from `translate/src/main/rust/`).+ *+ * Mirrors the inert-safe loader pattern of `com.vayunmathur.pdf.util.PdfNative`+ * and `library:ocr`'s `OcrEngine`: the library is loaded once inside a+ * try/catch so a missing `.so` (e.g. an ABI with no build, or a debug run+ * without the cargo task) leaves [isAvailable] false and the app degrades+ * gracefully instead of crashing at class-load time.+ *+ * IMPORTANT (honesty): the native side is a **stub**. No model weights are+ * bundled and on-device neural translation (ncnn) / speech (whisper) must be+ * built and shipped separately, so [nativeLoadModel] returns 0 ("no model")+ * and [nativeTranslate] / [nativeDetectLanguage] return null. Consequently the+ * Kotlin engines below report "not installed" rather than inventing text. When a+ * real backend is dropped into the Rust crate these signatures do not change.+ *+ * All entry points are blocking and must be called off the main thread. Handles+ * returned by [nativeLoadModel] are opaque; 0 means "no model loaded".+ */+object TranslateNative {++    /** True if `libtranslate_engine.so` was found and loaded for this ABI. */+    val isAvailable: Boolean =+        try {+            System.loadLibrary("translate_engine")+            Log.i(TAG, "libtranslate_engine loaded")+            true+        } catch (t: Throwable) {+            Log.e(TAG, "System.loadLibrary(translate_engine) failed", t)+            false+        }++    /**+     * Load a translation model bundle from [modelDir] and return an opaque+     * handle, or 0 if no usable model is present (the current stubbed default).+     */+    external fun nativeLoadModel(modelDir: String): Long++    /** Release the model behind [handle]. Safe to call with 0. */+    external fun nativeFreeModel(handle: Long)++    /** Detect the language of [text]; returns an ISO-639-1 code or null. */+    external fun nativeDetectLanguage(handle: Long, text: String): String?++    /**+     * Translate [text] from [from] (null = auto-detect) to [to]. Returns the+     * translation, or null when no model is loaded / translation is unavailable.+     */+    external fun nativeTranslate(handle: Long, text: String, from: String?, to: String): String?++    /**+     * Whether the native offline speech-to-text model is present. Stubbed to+     * false (no bundled whisper weights) so the Kotlin side falls back to the+     * platform `SpeechRecognizer`.+     */+    external fun nativeSpeechAvailable(): Boolean++    private const val TAG = "TranslateNative"+}
translate/src/main/java/com/vayunmathur/translate/util/TranslateSettings.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/util/TranslateSettings.kt b/translate/src/main/java/com/vayunmathur/translate/util/TranslateSettings.ktnew file mode 100644index 0000000000..ad45cb05e8--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/util/TranslateSettings.kt@@ -0,0 +1,33 @@+package com.vayunmathur.translate.util++import android.content.Context+import androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.core.stringPreferencesKey+import androidx.datastore.preferences.preferencesDataStore+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.map++private val Context.dataStore by preferencesDataStore(name = "translate_settings")++/** Persists the last-used source/target languages so they survive app restarts. */+class TranslateSettings(private val context: Context) {++    private val sourceKey = stringPreferencesKey("source_lang")+    private val targetKey = stringPreferencesKey("target_lang")++    suspend fun source(): String =+        context.dataStore.data.map { it[sourceKey] }.first() ?: Languages.AUTO.code++    suspend fun target(): String =+        context.dataStore.data.map { it[targetKey] }.first() ?: DEFAULT_TARGET++    suspend fun setSource(code: String) =+        context.dataStore.edit { it[sourceKey] = code }.let { }++    suspend fun setTarget(code: String) =+        context.dataStore.edit { it[targetKey] = code }.let { }++    companion object {+        private const val DEFAULT_TARGET = "es"+    }+}
translate/src/main/java/com/vayunmathur/translate/util/TranslateViewModel.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/util/TranslateViewModel.kt b/translate/src/main/java/com/vayunmathur/translate/util/TranslateViewModel.ktnew file mode 100644index 0000000000..b59fb16e19--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/util/TranslateViewModel.kt@@ -0,0 +1,82 @@+package com.vayunmathur.translate.util++import android.app.Application+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.library.ocr.OcrEngine+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.launch++/**+ * Holds the shared engines (translation, OCR, TTS) and the persisted language+ * selection. The SMaLL-100 model (~1.2 GB) is now gated via+ * [com.vayunmathur.library.downloadservice.InitialModelDownloadChecker] in+ * MainActivity — just like OpenAssistant — so it starts installing automatically+ * as soon as the page is opened. By the time this screen is shown,+ * [Small100Model] files are already present, and we just load the ncnn engine.+ */+class TranslateViewModel(app: Application) : AndroidViewModel(app) {++    val translator: TranslationEngine = Small100Translator(app)+    val ocr = OcrEngine(app)+    private val tts = TtsSpeaker(app)+    private val settings = TranslateSettings(app)++    private val _sourceLang = MutableStateFlow(Languages.AUTO.code)+    val sourceLang: StateFlow<String> = _sourceLang.asStateFlow()++    private val _targetLang = MutableStateFlow("es")+    val targetLang: StateFlow<String> = _targetLang.asStateFlow()++    /** True once the ncnn engine is loaded (model already downloaded by the checker). */+    private val _translationAvailable = MutableStateFlow(false)+    val translationAvailable: StateFlow<Boolean> = _translationAvailable.asStateFlow()++    init {+        viewModelScope.launch {+            _sourceLang.value = settings.source()+            _targetLang.value = settings.target()+            _translationAvailable.value = translator.isAvailable()+        }+    }++    fun setSource(code: String) {+        _sourceLang.value = code+        viewModelScope.launch { settings.setSource(code) }+    }++    fun setTarget(code: String) {+        _targetLang.value = code+        viewModelScope.launch { settings.setTarget(code) }+    }++    /** Swap source and target. No-op while source is Auto (nothing to swap into). */+    fun swap() {+        val src = _sourceLang.value+        if (src == Languages.AUTO.code) return+        val tgt = _targetLang.value+        setSource(tgt)+        setTarget(src)+    }++    /** Translate using the current selection; [from] null means auto-detect. */+    suspend fun translate(text: String): String? {+        val from = _sourceLang.value.takeIf { it != Languages.AUTO.code }+        return translator.translate(text, from, _targetLang.value)+    }++    /** Speak [text] in [languageCode] (defaults to the current target). */+    fun speak(text: String, languageCode: String = _targetLang.value) =+        tts.speak(text, languageCode)++    fun stopSpeaking() = tts.stop()++    override fun onCleared() {+        super.onCleared()+        ocr.close()+        (translator as? Small100Translator)?.close()+        tts.shutdown()+    }+}
translate/src/main/java/com/vayunmathur/translate/util/TranslationEngine.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/util/TranslationEngine.kt b/translate/src/main/java/com/vayunmathur/translate/util/TranslationEngine.ktnew file mode 100644index 0000000000..edab76a12e--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/util/TranslationEngine.kt@@ -0,0 +1,109 @@+package com.vayunmathur.translate.util++import android.content.Context+import android.util.Log+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.coroutines.withContext+import java.io.File++/**+ * On-device translation, behind a clean interface so a real neural backend can+ * be dropped in without touching the UI. All calls are safe to invoke from a+ * coroutine and run off the main thread.+ */+interface TranslationEngine {+    /** True if a translation model is loaded and translation will actually work. */+    suspend fun isAvailable(): Boolean++    /** Best-effort ISO-639-1 language code for [text], or null if unknown. */+    suspend fun detectLanguage(text: String): String?++    /**+     * Translate [text] to [to]. [from] is the source language code, or null to+     * auto-detect. Returns null if the engine is unavailable (caller shows a+     * "model not installed" state) — never a fabricated translation.+     */+    suspend fun translate(text: String, from: String?, to: String): String?+}++/**+ * [TranslationEngine] backed by [TranslateNative]. Loads a model bundle from the+ * app's files dir once; because no weights are bundled the native load returns a+ * 0 handle, so [isAvailable] is false and the UI reports "not installed". This is+ * intentional and honest — see [TranslateNative].+ */+class NativeTranslator(private val context: Context) : TranslationEngine {++    private val lock = Mutex()+    private var handle: Long = 0L+    private var initTried = false++    override suspend fun isAvailable(): Boolean = withContext(Dispatchers.Default) {+        lock.withLock { ensureModel() }+    }++    override suspend fun detectLanguage(text: String): String? = withContext(Dispatchers.Default) {+        if (text.isBlank()) return@withContext null+        lock.withLock {+            if (!ensureModel()) return@withContext null+            try {+                TranslateNative.nativeDetectLanguage(handle, text)+            } catch (t: Throwable) {+                Log.e(TAG, "detectLanguage failed", t)+                null+            }+        }+    }++    override suspend fun translate(text: String, from: String?, to: String): String? =+        withContext(Dispatchers.Default) {+            if (text.isBlank()) return@withContext ""+            lock.withLock {+                if (!ensureModel()) return@withContext null+                try {+                    TranslateNative.nativeTranslate(handle, text, from, to)+                } catch (t: Throwable) {+                    Log.e(TAG, "translate failed", t)+                    null+                }+            }+        }++    /** Free the native model. Safe to call more than once. */+    fun close() {+        if (handle != 0L) {+            try {+                TranslateNative.nativeFreeModel(handle)+            } catch (_: Throwable) {+            }+            handle = 0L+        }+        initTried = false+    }++    /** Try to load the model exactly once; returns whether a model is loaded. */+    private fun ensureModel(): Boolean {+        if (handle != 0L) return true+        if (initTried) return false+        initTried = true+        if (!TranslateNative.isAvailable) return false+        return try {+            // Models would live under filesDir/translate_models once a real+            // backend + downloader exist. Absent weights -> native returns 0.+            val dir = File(context.filesDir, MODEL_DIR).absolutePath+            handle = TranslateNative.nativeLoadModel(dir)+            handle != 0L+        } catch (t: Throwable) {+            Log.e(TAG, "nativeLoadModel failed", t)+            handle = 0L+            false+        }+    }++    companion object {+        private const val TAG = "NativeTranslator"+        private const val MODEL_DIR = "translate_models"+    }+}
translate/src/main/java/com/vayunmathur/translate/util/TtsSpeaker.kt
diff --git a/translate/src/main/java/com/vayunmathur/translate/util/TtsSpeaker.kt b/translate/src/main/java/com/vayunmathur/translate/util/TtsSpeaker.ktnew file mode 100644index 0000000000..f6c2753bb3--- /dev/null+++ b/translate/src/main/java/com/vayunmathur/translate/util/TtsSpeaker.kt@@ -0,0 +1,71 @@+package com.vayunmathur.translate.util++import android.content.Context+import android.speech.tts.TextToSpeech+import android.util.Log+import java.util.Locale++/**+ * Small wrapper over [TextToSpeech] that speaks translated text in the target+ * language's locale. Owns the engine lifecycle: create once, [shutdown] when the+ * owner is cleared. Safe to call [speak] before the engine finishes initialising+ * (the request is simply dropped).+ */+class TtsSpeaker(context: Context) {++    private var tts: TextToSpeech? = null+    @Volatile private var ready = false++    init {+        tts = TextToSpeech(context.applicationContext) { status ->+            ready = status == TextToSpeech.SUCCESS+            if (!ready) Log.w(TAG, "TextToSpeech init failed: $status")+        }+    }++    /** Whether the target [languageCode] can be spoken (locale data available). */+    fun isLanguageSupported(languageCode: String): Boolean {+        val engine = tts ?: return false+        if (!ready) return false+        return when (engine.isLanguageAvailable(Locale.forLanguageTag(languageCode))) {+            TextToSpeech.LANG_AVAILABLE,+            TextToSpeech.LANG_COUNTRY_AVAILABLE,+            TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE -> true+            else -> false+        }+    }++    /** Speak [text] in [languageCode], flushing any in-progress utterance. */+    fun speak(text: String, languageCode: String) {+        val engine = tts ?: return+        if (!ready || text.isBlank()) return+        try {+            engine.language = Locale.forLanguageTag(languageCode)+            engine.speak(text, TextToSpeech.QUEUE_FLUSH, null, UTTERANCE_ID)+        } catch (t: Throwable) {+            Log.e(TAG, "speak failed", t)+        }+    }++    fun stop() {+        try {+            tts?.stop()+        } catch (_: Throwable) {+        }+    }++    fun shutdown() {+        try {+            tts?.stop()+            tts?.shutdown()+        } catch (_: Throwable) {+        }+        tts = null+        ready = false+    }++    companion object {+        private const val TAG = "TtsSpeaker"+        private const val UTTERANCE_ID = "translate_output"+    }+}
translate/src/main/res/values/strings.xml
diff --git a/translate/src/main/res/values/strings.xml b/translate/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..6b8df84bbf--- /dev/null+++ b/translate/src/main/res/values/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+    <string name="app_name">Translate</string>+</resources>
translate/src/main/rust/Cargo.lock
diff --git a/translate/src/main/rust/Cargo.lock b/translate/src/main/rust/Cargo.locknew file mode 100644index 0000000000..b5100478b2--- /dev/null+++ b/translate/src/main/rust/Cargo.lock@@ -0,0 +1,126 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "cesu8"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"++[[package]]+name = "jni"+version = "0.21.1"+dependencies = [+ "cesu8",+ "jni-sys 0.3.1",+ "log",+ "thiserror",+]++[[package]]+name = "jni-sys"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"+dependencies = [+ "jni-sys 0.4.1",+]++[[package]]+name = "jni-sys"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"+dependencies = [+ "jni-sys-macros",+]++[[package]]+name = "jni-sys-macros"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"+dependencies = [+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "log"+version = "0.4.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"++[[package]]+name = "proc-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "syn"+version = "3.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "thiserror"+version = "2.0.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09a43598840e33d5b0331f38c5e30d13bb11c11210a4b58f0d9b18a5a5eefcd9"+dependencies = [+ "thiserror-impl",+]++[[package]]+name = "thiserror-impl"+version = "2.0.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "43cbfe0cf76104d42a574802844187e84a305e531ed54455f11fbde0f10541cd"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.3",+]++[[package]]+name = "translate_engine"+version = "0.1.0"+dependencies = [+ "jni",+]++[[package]]+name = "unicode-ident"+version = "1.0.24"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
translate/src/main/rust/Cargo.toml
diff --git a/translate/src/main/rust/Cargo.toml b/translate/src/main/rust/Cargo.tomlnew file mode 100644index 0000000000..5416c9c4ae--- /dev/null+++ b/translate/src/main/rust/Cargo.toml@@ -0,0 +1,30 @@+# Standalone-workspace crate (like games/voxels) so it is detached from the root+# Cargo workspace and the rustNativeLib gradle task can `cargo build` in place.+[workspace]++[workspace.dependencies]+# Mirror the root catalog's JNI fork by relative path. Depth is 4 `../` because+# translate/src/main/rust -> (rust,main,src,translate) -> repo root, then+# third_party/jni-android. (games/voxels needs 5 `../` due to the extra games/ dir.)+jni = { path = "../../../../third_party/jni-android", version = "0.21" }++[package]+name = "translate_engine"+version = "0.1.0"+edition = "2021"+description = "On-device translation / speech engine JNI boundary for the Translate app (model inference honestly stubbed — no bundled weights)"+license = "GPL-2.0-only"++[lib]+name = "translate_engine"+crate-type = ["cdylib"]++[dependencies]+jni.workspace = true++[profile.release]+opt-level = 3+lto = true+codegen-units = 1+panic = "abort"+strip = true
translate/src/main/rust/src/jni_bindings.rs
diff --git a/translate/src/main/rust/src/jni_bindings.rs b/translate/src/main/rust/src/jni_bindings.rsnew file mode 100644index 0000000000..1997685eb7--- /dev/null+++ b/translate/src/main/rust/src/jni_bindings.rs@@ -0,0 +1,152 @@+//! JNI entry points for `com.vayunmathur.translate.util.TranslateNative`.+//!+//! Every extern fn is wrapped in `catch_unwind` so a Rust panic becomes a thrown+//! Java exception (or a safe default) instead of unwinding across the FFI+//! boundary (UB). String handling never `unwrap`s: malformed Modified-UTF-8 or a+//! null jstring is turned into a clean error / empty value. This mirrors the+//! safe-helper pattern in `pdf/src/main/rust/src/jni_bindings.rs`.++use crate::*;+use jni::objects::{JClass, JString};+use jni::sys::{jboolean, jlong, jstring, JNI_FALSE};+use jni::JNIEnv;+use std::panic::{catch_unwind, AssertUnwindSafe};++/// Convert a (possibly null) JString to Rust String, clearing any pending+/// exception on decode failure and returning an empty string.+fn jstr<'local>(env: &mut JNIEnv<'local>, s: &JString<'local>) -> String {+    if s.is_null() {+        return String::new();+    }+    match env.get_string(s) {+        Ok(js) => js.into(),+        Err(_) => {+            let _ = env.exception_clear();+            String::new()+        }+    }+}++/// Convert a nullable JString into `Option<String>` (None if the ref is null).+fn jstr_opt<'local>(env: &mut JNIEnv<'local>, s: &JString<'local>) -> Option<String> {+    if s.is_null() {+        None+    } else {+        Some(jstr(env, s))+    }+}++/// Convert `Option<String>` into a jstring, returning null on `None` or on any+/// allocation/encoding error (so the Kotlin side sees `null`).+fn string_or_null<'local>(env: &mut JNIEnv<'local>, value: Option<String>) -> jstring {+    match value {+        Some(s) => match env.new_string(s) {+            Ok(js) => js.into_raw(),+            Err(_) => {+                let _ = env.exception_clear();+                std::ptr::null_mut()+            }+        },+        None => std::ptr::null_mut(),+    }+}++/// `TranslateNative.nativeLoadModel(String) -> long`. Returns a non-zero handle,+/// or 0 when no model is available (always, in this stubbed build).+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_translate_util_TranslateNative_nativeLoadModel<'local>(+    mut env: JNIEnv<'local>,+    _class: JClass<'local>,+    model_dir: JString<'local>,+) -> jlong {+    match catch_unwind(AssertUnwindSafe(|| {+        let dir = jstr(&mut env, &model_dir);+        load_model(&dir) as jlong+    })) {+        Ok(v) => v,+        Err(_) => {+            let _ = env.exception_clear();+            let _ = env.throw_new("java/lang/RuntimeException", "Native panic in nativeLoadModel");+            0+        }+    }+}++/// `TranslateNative.nativeFreeModel(long)`. Safe with a 0 handle.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_translate_util_TranslateNative_nativeFreeModel<'local>(+    env: JNIEnv<'local>,+    _class: JClass<'local>,+    handle: jlong,+) {+    let res = catch_unwind(AssertUnwindSafe(|| {+        free_model(handle as ModelHandle);+    }));+    if res.is_err() {+        let _ = env.exception_clear();+    }+}++/// `TranslateNative.nativeDetectLanguage(long, String) -> String`. Null when the+/// language cannot be determined (always, in this stubbed build).+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_translate_util_TranslateNative_nativeDetectLanguage<'local>(+    mut env: JNIEnv<'local>,+    _class: JClass<'local>,+    handle: jlong,+    text: JString<'local>,+) -> jstring {+    match catch_unwind(AssertUnwindSafe(|| {+        let t = jstr(&mut env, &text);+        let detected = detect_language(handle as ModelHandle, &t);+        string_or_null(&mut env, detected)+    })) {+        Ok(v) => v,+        Err(_) => {+            let _ = env.exception_clear();+            std::ptr::null_mut()+        }+    }+}++/// `TranslateNative.nativeTranslate(long, String, String?, String) -> String`.+/// `from` may be null (auto-detect). Returns null when no model is loaded (so the+/// Kotlin side reports "not installed") — never a fabricated translation.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_translate_util_TranslateNative_nativeTranslate<'local>(+    mut env: JNIEnv<'local>,+    _class: JClass<'local>,+    handle: jlong,+    text: JString<'local>,+    from: JString<'local>,+    to: JString<'local>,+) -> jstring {+    match catch_unwind(AssertUnwindSafe(|| {+        let t = jstr(&mut env, &text);+        let from_opt = jstr_opt(&mut env, &from);+        let to_s = jstr(&mut env, &to);+        let out = translate(handle as ModelHandle, &t, from_opt.as_deref(), &to_s);+        string_or_null(&mut env, out)+    })) {+        Ok(v) => v,+        Err(_) => {+            let _ = env.exception_clear();+            std::ptr::null_mut()+        }+    }+}++/// `TranslateNative.nativeSpeechAvailable() -> boolean`. False in this build.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_translate_util_TranslateNative_nativeSpeechAvailable<'local>(+    env: JNIEnv<'local>,+    _class: JClass<'local>,+) -> jboolean {+    match catch_unwind(AssertUnwindSafe(|| speech_available() as jboolean)) {+        Ok(v) => v,+        Err(_) => {+            let _ = env.exception_clear();+            JNI_FALSE+        }+    }+}
translate/src/main/rust/src/lib.rs
diff --git a/translate/src/main/rust/src/lib.rs b/translate/src/main/rust/src/lib.rsnew file mode 100644index 0000000000..bd74159c6b--- /dev/null+++ b/translate/src/main/rust/src/lib.rs@@ -0,0 +1,74 @@+//! Native engine for the Translate app: the JNI boundary for on-device+//! translation, language detection and (offline) speech availability.+//!+//! # Why this is a stub+//!+//! The user's goal is *fully on-device* translation (ideally ncnn) and *offline*+//! speech-to-text (whisper/Vosk). Both require:+//!   1. Model weights (hundreds of MB) which are **not bundled** in this repo, and+//!   2. A native inference runtime that must be **built on-device / per-ABI**,+//!      which cannot be compiled or verified in this environment.+//!+//! Rather than fabricate translations, this crate exposes the real JNI surface+//! the Kotlin side expects and returns honest "not available" values:+//!   * [`load_model`] returns `0` (no model) because no weights are present.+//!   * [`translate`] / [`detect_language`] return `None` (→ null jstring), so the+//!     Kotlin `NativeTranslator` reports `isAvailable() == false` and the UI shows+//!     "Translation model not installed".+//!   * [`speech_available`] returns `false`, so Kotlin falls back to the platform+//!     `android.speech.SpeechRecognizer`.+//!+//! # Where a real backend plugs in+//!+//! `load_model` would `ncnn::Net::load_param/load_model` (or memory-map a+//! flatbuffer NMT model) from `model_dir`, box it, and return the pointer as an+//! opaque `jlong` handle. `translate` would tokenize `text`, run the encoder /+//! decoder (with a language tag derived from `from`/`to`), detokenize, and return+//! the string. `free_model` would drop the boxed net. `detect_language` would run+//! a small fastText-style classifier. None of that changes the JNI signatures+//! below, so the drop-in is isolated to this file.++mod jni_bindings;++/// Opaque model handle. `0` means "no model loaded". A real backend would return+/// `Box::into_raw(Box::new(net)) as i64`.+pub type ModelHandle = i64;++/// Load a translation model bundle from `model_dir`. Stubbed to always report+/// "no model" (`0`) because no weights are shipped. The path is where a real+/// downloader would place `*.param` / `*.bin` files.+pub fn load_model(_model_dir: &str) -> ModelHandle {+    0+}++/// Free the model behind `handle`. No-op for the stub (nothing was allocated).+/// A real backend would reconstruct the `Box` from the raw pointer and drop it.+pub fn free_model(handle: ModelHandle) {+    if handle == 0 {+        return;+    }+    // Real backend:+    //   unsafe { drop(Box::from_raw(handle as usize as *mut Net)); }+}++/// Best-effort language detection. Stubbed: no classifier bundled → `None`.+pub fn detect_language(_handle: ModelHandle, _text: &str) -> Option<String> {+    None+}++/// Translate `text` from `from` (None = auto-detect) to `to`. Stubbed: returns+/// `None` whenever no model is loaded, which is always in this build. This is+/// deliberate — we never invent a translation.+pub fn translate(handle: ModelHandle, _text: &str, _from: Option<&str>, _to: &str) -> Option<String> {+    if handle == 0 {+        return None;+    }+    // Real backend runs inference here and returns Some(translated).+    None+}++/// Whether an offline speech-to-text model is present. Stubbed to `false` (no+/// bundled whisper/Vosk weights) so Kotlin uses the platform recognizer.+pub fn speech_available() -> bool {+    false+}