Modern Apps git

← Modern-Apps.git

photos: remove all tflite models

Commit
dc0dc85f4c0d52d6882b4337d29b3f8de586e118
Author
Vayun Mathur <[email protected]>
When
2026-07-08 21:44 UTC (5 months ago)
Parents
075c337

Diff

photos/build.gradle.kts
diff --git a/photos/build.gradle.kts b/photos/build.gradle.ktsindex 757148ce0b..2b46293492 100644--- a/photos/build.gradle.kts+++ b/photos/build.gradle.kts@@ -39,10 +39,10 @@ dependencies {     implementation(libs.coil.compose)     implementation(libs.coil.video)     implementation(libs.androidx.exifinterface)-    implementation(libs.mediapipe.tasks.vision)-    // Face + semantic image search both run on ONNX Runtime (MIT, FOSS, no Play-    // Services / no ML Kit). The native .so already ships via :library:ocr, but-    // this module needs its own compile dependency to call the ORT API directly.+    // Face detection (BlazeFace), face embedding (EdgeFace), and subject+    // segmentation (U²-Net) all run on ONNX Runtime (MIT, FOSS, no Play+    // Services / no MediaPipe). The native .so ships via :library:ocr, but this+    // module needs its own compile dependency to call the ORT API directly.     implementation(libs.onnxruntime.android)      implementRoom(libs)
photos/src/main/assets/blazeface.onnx
diff --git a/photos/src/main/assets/blazeface.onnx b/photos/src/main/assets/blazeface.onnxnew file mode 100644index 0000000000..4236e33cf0Binary files /dev/null and b/photos/src/main/assets/blazeface.onnx differ
photos/src/main/assets/deeplab_v3.tflite
diff --git a/photos/src/main/assets/deeplab_v3.tflite b/photos/src/main/assets/deeplab_v3.tflitedeleted file mode 100644index 420a934fdb..0000000000Binary files a/photos/src/main/assets/deeplab_v3.tflite and /dev/null differ
photos/src/main/assets/edgeface.onnx
diff --git a/photos/src/main/assets/edgeface.onnx b/photos/src/main/assets/edgeface.onnxindex 6ebba27eb9..bd2519ed50 100644Binary files a/photos/src/main/assets/edgeface.onnx and b/photos/src/main/assets/edgeface.onnx differ
photos/src/main/assets/face_detector.tflite
diff --git a/photos/src/main/assets/face_detector.tflite b/photos/src/main/assets/face_detector.tflitedeleted file mode 100644index 1b2b5220b8..0000000000Binary files a/photos/src/main/assets/face_detector.tflite and /dev/null differ
photos/src/main/assets/u2netp.onnx
diff --git a/photos/src/main/assets/u2netp.onnx b/photos/src/main/assets/u2netp.onnxnew file mode 100644index 0000000000..4f21f9afd3Binary files /dev/null and b/photos/src/main/assets/u2netp.onnx differ
photos/src/main/java/com/vayunmathur/photos/util/FaceRecognizer.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/FaceRecognizer.kt b/photos/src/main/java/com/vayunmathur/photos/util/FaceRecognizer.ktindex 65b7ec5f07..7c3aeadc42 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/FaceRecognizer.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/FaceRecognizer.kt@@ -6,19 +6,14 @@ import android.graphics.Canvas import android.graphics.Matrix import android.graphics.Paint import android.graphics.Rect-import android.graphics.RectF import android.util.Log import ai.onnxruntime.OnnxTensor import ai.onnxruntime.OrtEnvironment import ai.onnxruntime.OrtSession-import com.google.mediapipe.framework.image.BitmapImageBuilder-import com.google.mediapipe.tasks.components.containers.Detection-import com.google.mediapipe.tasks.core.BaseOptions-import com.google.mediapipe.tasks.vision.core.RunningMode-import com.google.mediapipe.tasks.vision.facedetector.FaceDetector import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.FloatBuffer+import java.nio.LongBuffer import kotlin.math.sqrt  /**@@ -26,9 +21,12 @@ import kotlin.math.sqrt  * Play Services and no cloud (F-Droid clean).  *  * Pipeline:- *  1. Detection — MediaPipe BlazeFace ([DETECTOR_ASSET]) finds faces and returns- *     6 keypoints per face (eyes, nose, mouth, ears).- *  2. Alignment — we take the two eye keypoints and compute a similarity+ *  1. Detection — a **BlazeFace** ONNX model ([DETECTOR_ASSET]) run on ONNX+ *     Runtime finds faces and returns a bounding box + 6 landmarks per face+ *     (eyes, nose, mouth, cheeks). Anchor decoding and NMS are baked into the+ *     graph, so we just feed a 128x128 image (plus conf/iou/max-detection+ *     scalars) and read back the selected boxes. No MediaPipe / Play Services.+ *  2. Alignment — we take the two eye landmarks and compute a similarity  *     transform (rotate + uniform scale + translate) that maps them onto a fixed  *     canonical position inside a [INPUT_SIZE]x[INPUT_SIZE] crop. Aligning faces  *     to a canonical pose is what makes same-person matching reliable.@@ -36,16 +34,22 @@ import kotlin.math.sqrt  *     **EdgeFace**) runs on the aligned crop via an ONNX Runtime [OrtSession]  *     (`com.microsoft.onnxruntime`, MIT — no LiteRT/TensorFlow-Lite dependency  *     is needed here). EdgeFace is an- *     ArcFace-trained transformer-CNN hybrid; the shipped export is INT8- *     weight-quantized (a few MB). Pixels are packed **NCHW** planar and+ *     ArcFace-trained transformer-CNN hybrid; the shipped export is fp32+ *     (a few MB). Pixels are packed **NCHW** planar and  *     normalised as (px - 127.5) / 127.5, the ArcFace convention.  *  4. Matching — embeddings are L2-normalised and compared with cosine  *     similarity to cluster faces of the same person (see [CLUSTER_THRESHOLD]).  *  * ## Required model assets (in `photos/src/main/assets/`)  *- *  - [DETECTOR_ASSET] — MediaPipe BlazeFace short-range (Apache-2.0):- *    https://storage.googleapis.com/mediapipe-models/face_detector/blaze_face_short_range/float16/1/blaze_face_short_range.tflite+ *  - [DETECTOR_ASSET] — a **BlazeFace** face detector in ONNX format (short+ *    range, 128x128 input, decode+NMS in-graph). Sourced from+ *    `garavv/blazeface-onnx` (`blaze.onnx`); `prepare_models.py` downloads it to+ *    `photos/src/main/assets/blazeface.onnx`. Input NCHW `[1,3,128,128]` RGB in+ *    [0,1] (plain /255); output `[1,N,16]` per-face rows of normalised+ *    `[top_y, top_x, bot_y, bot_x, leftEyeX, leftEyeY, rightEyeX, rightEyeY,+ *    noseX, noseY, mouthX, mouthY, leftCheekX, leftCheekY, rightCheekX,+ *    rightCheekY]`.  *  *  - [EMBEDDER_ASSET] — an **EdgeFace** face-recognition embedder in ONNX  *    format. Expected input: NCHW `[1,3,`[INPUT_SIZE]`,`[INPUT_SIZE]`]` RGB,@@ -53,9 +57,11 @@ import kotlin.math.sqrt  *    dimension is read from the model at run time). The code L2-normalises the  *    output itself.  *- *    Generate it with `scripts/photos/prepare_models.py`, which fetches the- *    EdgeFace weights, exports to ONNX and applies INT8 dynamic quantization,- *    writing `photos/src/main/assets/edgeface.onnx`. NOTE: EdgeFace ships under a+    Generate it with `scripts/photos/prepare_models.py`, which fetches the+ *    EdgeFace weights and exports to **fp32** ONNX, writing+ *    `photos/src/main/assets/edgeface.onnx`. (It is intentionally not INT8+ *    quantized: dynamic quant emits `ConvInteger`, which the ONNX Runtime+ *    Android package cannot run.) NOTE: EdgeFace ships under a  *    **non-commercial** research licence — this project uses it deliberately;  *    swap the asset if you need a permissive licence. If the input size differs  *    from 112, update [INPUT_SIZE]; if the normalisation differs, update [embed].@@ -66,9 +72,17 @@ import kotlin.math.sqrt  * [modelsAvailable], which the UI checks before enabling.  */ object FaceRecognizer {-    const val DETECTOR_ASSET = "face_detector.tflite"+    const val DETECTOR_ASSET = "blazeface.onnx"     const val EMBEDDER_ASSET = "edgeface.onnx" +    /** Square input side (px) the BlazeFace detector expects. */+    private const val DETECT_SIZE = 128++    /** Detector thresholds (fed as graph inputs; decode + NMS run in-graph). */+    private const val DETECT_CONF = 0.5f+    private const val DETECT_IOU = 0.3f+    private const val DETECT_MAX = 25L+     /** Square input side (px) the embedder expects. EdgeFace/ArcFace is 112. */     const val INPUT_SIZE = 112 @@ -77,9 +91,11 @@ object FaceRecognizer {      * worker compares it against a stored value and, on mismatch, clears existing      * clusters and re-scans so photos are re-grouped with the new embeddings.      * (v1 = old MobileNetV3 general embedder; v2 = MobileFaceNet + alignment;-     * v3 = EdgeFace INT8 on ONNX Runtime.)+     * v3 = EdgeFace INT8 on ONNX Runtime; v4 = EdgeFace fp32 — INT8 dynamic+     * quant emits ConvInteger, which ORT-Android can't run; v5 = BlazeFace ONNX+     * detector replacing MediaPipe, which shifts alignment/embeddings slightly.)      */-    const val EMBEDDER_VERSION = 3+    const val EMBEDDER_VERSION = 5      /**      * Minimum cosine similarity for a face to join an existing cluster instead of@@ -123,7 +139,7 @@ object FaceRecognizer {     private val env: OrtEnvironment by lazy { OrtEnvironment.getEnvironment() }     private val lock = Any() -    @Volatile private var detector: FaceDetector? = null+    @Volatile private var detector: OrtSession? = null     @Volatile private var embedder: OrtSession? = null     @Volatile private var initFailed = false @@ -144,25 +160,21 @@ object FaceRecognizer {         if (initFailed) return false         return try {             val app = context.applicationContext-            detector = FaceDetector.createFromOptions(-                app,-                FaceDetector.FaceDetectorOptions.builder()-                    .setBaseOptions(BaseOptions.builder().setModelAssetPath(DETECTOR_ASSET).build())-                    .setRunningMode(RunningMode.IMAGE)-                    .setMinDetectionConfidence(0.5f)-                    .build(),-            )-            val modelBytes = readAsset(app, EMBEDDER_ASSET)-                ?: throw IllegalStateException("Missing $EMBEDDER_ASSET")             val opts = OrtSession.SessionOptions().apply {                 // Single-threaded keeps sustained CPU/battery use low.                 setIntraOpNumThreads(1)                 setInterOpNumThreads(1)             }+            val detBytes = readAsset(app, DETECTOR_ASSET)+                ?: throw IllegalStateException("Missing $DETECTOR_ASSET")+            detector = env.createSession(detBytes, opts)+            val modelBytes = readAsset(app, EMBEDDER_ASSET)+                ?: throw IllegalStateException("Missing $EMBEDDER_ASSET")             embedder = env.createSession(modelBytes, opts)             true         } catch (e: Throwable) {-            Log.e(TAG, "Face models unavailable — drop $DETECTOR_ASSET and an EdgeFace $EMBEDDER_ASSET into photos assets (see FaceRecognizer docs).", e)+            Log.e(TAG, "Face models unavailable — drop a BlazeFace $DETECTOR_ASSET and an EdgeFace $EMBEDDER_ASSET into photos assets (see FaceRecognizer docs).", e)+            try { detector?.close() } catch (_: Exception) {}             detector = null             try { embedder?.close() } catch (_: Exception) {}             embedder = null@@ -187,16 +199,16 @@ object FaceRecognizer {         else bitmap.copy(Bitmap.Config.ARGB_8888, false)          val detections = try {-            det.detect(BitmapImageBuilder(argb).build()).detections()+            runDetector(det, argb)         } catch (e: Exception) {             Log.e(TAG, "Face detection failed", e)             return emptyList()         }          val out = ArrayList<DetectedFace>(detections.size)-        for (detection in detections) {-            val rect = faceRect(detection.boundingBox(), argb.width, argb.height) ?: continue-            val aligned = alignFace(argb, detection, rect) ?: continue+        for (d in detections) {+            val rect = faceRect(d, argb.width, argb.height) ?: continue+            val aligned = alignFace(argb, d, rect) ?: continue             try {                 val embedding = l2Normalize(embed(emb, aligned))                 out += DetectedFace(@@ -215,22 +227,99 @@ object FaceRecognizer {         return out     } +    /** One raw BlazeFace detection: bbox + eye landmarks, all normalised 0..1. */+    private class RawDetection(+        val top: Float,+        val left: Float,+        val bottom: Float,+        val right: Float,+        val leftEyeX: Float,+        val leftEyeY: Float,+        val rightEyeX: Float,+        val rightEyeY: Float,+    )+     /**-     * Warp the source image so the two eye keypoints land on fixed canonical+     * Run BlazeFace on [bmp] (plain-resized to [DETECT_SIZE]²) and return the+     * selected detections. Anchor decode + NMS run in-graph; the output is+     * `[1,N,16]` of normalised `[top_y, top_x, bot_y, bot_x, leftEyeX, leftEyeY,+     * rightEyeX, rightEyeY, ...]` — only the first 8 columns are used here.+     * Coords are normalised to the (stretched) input, which maps directly back to+     * the source image since the resize is a full stretch.+     */+    private fun runDetector(session: OrtSession, bmp: Bitmap): List<RawDetection> {+        val scaled = Bitmap.createScaledBitmap(bmp, DETECT_SIZE, DETECT_SIZE, true)+        val px = IntArray(DETECT_SIZE * DETECT_SIZE)+        scaled.getPixels(px, 0, DETECT_SIZE, 0, 0, DETECT_SIZE, DETECT_SIZE)+        if (scaled != bmp) scaled.recycle()++        val area = DETECT_SIZE * DETECT_SIZE+        val input = FloatArray(3 * area)+        for (i in 0 until area) {+            val p = px[i]+            input[i] = ((p shr 16) and 0xFF) / 255f            // R plane+            input[area + i] = ((p shr 8) and 0xFF) / 255f       // G plane+            input[2 * area + i] = (p and 0xFF) / 255f           // B plane+        }++        synchronized(lock) {+            val tensors = HashMap<String, OnnxTensor>()+            try {+                tensors["image"] = OnnxTensor.createTensor(+                    env, FloatBuffer.wrap(input),+                    longArrayOf(1, 3, DETECT_SIZE.toLong(), DETECT_SIZE.toLong()),+                )+                tensors["conf_threshold"] = OnnxTensor.createTensor(+                    env, FloatBuffer.wrap(floatArrayOf(DETECT_CONF)), longArrayOf(1),+                )+                tensors["max_detections"] = OnnxTensor.createTensor(+                    env, LongBuffer.wrap(longArrayOf(DETECT_MAX)), longArrayOf(1),+                )+                tensors["iou_threshold"] = OnnxTensor.createTensor(+                    env, FloatBuffer.wrap(floatArrayOf(DETECT_IOU)), longArrayOf(1),+                )+                session.run(tensors).use { result ->+                    val outTensor = result.get(0) as OnnxTensor+                    val shape = outTensor.info.shape // [1, N, 16]+                    val n = if (shape.size >= 2) shape[1].toInt() else 0+                    if (n <= 0) return emptyList()+                    val buf = FloatArray(n * 16)+                    outTensor.floatBuffer.get(buf)+                    val list = ArrayList<RawDetection>(n)+                    for (k in 0 until n) {+                        val o = k * 16+                        // Skip zero-padded / degenerate rows.+                        if (buf[o + 2] - buf[o] <= 0f || buf[o + 3] - buf[o + 1] <= 0f) continue+                        list += RawDetection(+                            top = buf[o], left = buf[o + 1], bottom = buf[o + 2], right = buf[o + 3],+                            leftEyeX = buf[o + 4], leftEyeY = buf[o + 5],+                            rightEyeX = buf[o + 6], rightEyeY = buf[o + 7],+                        )+                    }+                    return list+                }+            } finally {+                tensors.values.forEach { it.close() }+            }+        }+    }++    /**+     * Warp the source image so the two eye landmarks land on fixed canonical      * positions in an [INPUT_SIZE] crop (a similarity transform: rotation +      * uniform scale + translation). Falls back to a plain resized box crop when-     * eye keypoints are unavailable.+     * eye landmarks are unavailable.      */-    private fun alignFace(src: Bitmap, detection: Detection, box: Rect): Bitmap? {-        val keypoints = detection.keypoints().orElse(null)-        if (keypoints != null && keypoints.size >= 2) {+    private fun alignFace(src: Bitmap, d: RawDetection, box: Rect): Bitmap? {+        val hasEyes = d.leftEyeX != 0f || d.leftEyeY != 0f || d.rightEyeX != 0f || d.rightEyeY != 0f+        if (hasEyes) {             // Sort the two eyes by x so the left-most maps to the left canonical             // eye — keeps the face upright and never mirrored.-            val eyes = listOf(keypoints[0], keypoints[1]).sortedBy { it.x() }-            val srcPts = floatArrayOf(-                eyes[0].x() * src.width, eyes[0].y() * src.height,-                eyes[1].x() * src.width, eyes[1].y() * src.height,-            )+            val eyes = listOf(+                floatArrayOf(d.leftEyeX * src.width, d.leftEyeY * src.height),+                floatArrayOf(d.rightEyeX * src.width, d.rightEyeY * src.height),+            ).sortedBy { it[0] }+            val srcPts = floatArrayOf(eyes[0][0], eyes[0][1], eyes[1][0], eyes[1][1])             val dstPts = floatArrayOf(                 LEFT_EYE_X * INPUT_SIZE, EYE_Y * INPUT_SIZE,                 RIGHT_EYE_X * INPUT_SIZE, EYE_Y * INPUT_SIZE,@@ -246,7 +335,7 @@ object FaceRecognizer {                 }             }         }-        // Fallback: no usable keypoints — scale the axis-aligned box to the input.+        // Fallback: no usable landmarks — scale the axis-aligned box to the input.         return try {             val crop = Bitmap.createBitmap(src, box.left, box.top, box.width(), box.height())             val scaled = Bitmap.createScaledBitmap(crop, INPUT_SIZE, INPUT_SIZE, true)@@ -290,14 +379,16 @@ object FaceRecognizer {         }     } -    /** Expand the detector box by a small margin and clamp it to the image. */-    private fun faceRect(box: RectF, w: Int, h: Int): Rect? {-        val marginX = box.width() * 0.15f-        val marginY = box.height() * 0.15f-        val left = (box.left - marginX).toInt().coerceIn(0, w - 1)-        val top = (box.top - marginY).toInt().coerceIn(0, h - 1)-        val right = (box.right + marginX).toInt().coerceIn(left + 1, w)-        val bottom = (box.bottom + marginY).toInt().coerceIn(top + 1, h)+    /** Expand the normalised detector box by a small margin and clamp to pixels. */+    private fun faceRect(d: RawDetection, w: Int, h: Int): Rect? {+        val bw = (d.right - d.left) * w+        val bh = (d.bottom - d.top) * h+        val marginX = bw * 0.15f+        val marginY = bh * 0.15f+        val left = (d.left * w - marginX).toInt().coerceIn(0, w - 1)+        val top = (d.top * h - marginY).toInt().coerceIn(0, h - 1)+        val right = (d.right * w + marginX).toInt().coerceIn(left + 1, w)+        val bottom = (d.bottom * h + marginY).toInt().coerceIn(top + 1, h)         if (right - left < 8 || bottom - top < 8) return null         return Rect(left, top, right, bottom)     }
photos/src/main/java/com/vayunmathur/photos/util/MlSegmentation.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/MlSegmentation.kt b/photos/src/main/java/com/vayunmathur/photos/util/MlSegmentation.ktindex 790418329a..d353289864 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/MlSegmentation.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/MlSegmentation.kt@@ -1,22 +1,32 @@ package com.vayunmathur.photos.util +import ai.onnxruntime.OnnxTensor+import ai.onnxruntime.OrtEnvironment+import ai.onnxruntime.OrtSession import android.content.Context import android.graphics.Bitmap import android.os.Handler import android.os.Looper import android.util.Log-import com.google.mediapipe.framework.image.BitmapImageBuilder-import com.google.mediapipe.framework.image.ByteBufferExtractor-import com.google.mediapipe.tasks.core.BaseOptions-import com.google.mediapipe.tasks.vision.core.RunningMode-import com.google.mediapipe.tasks.vision.imagesegmenter.ImageSegmenter import com.vayunmathur.photos.data.Selection+import java.nio.FloatBuffer  /**- * Auto-select the foreground subject with an on-device neural model (DeepLabV3- * via MediaPipe Tasks — standalone, NO Google Play Services). Pixels whose- * predicted class is not background (index 0) form the selection. Runs off the- * main thread; [onResult] is posted to the main thread (null on failure).+ * Auto-select the foreground subject with an on-device neural model —+ * **U²-Net portable** salient-object detection on ONNX Runtime (standalone, no+ * MediaPipe, no Google Play Services, F-Droid clean).+ *+ * Unlike the old DeepLabV3 (Pascal-VOC, 21 fixed classes — it could only find the+ * ~20 VOC categories and called everything else background), U²-Net predicts a+ * general per-pixel saliency map, so it selects arbitrary subjects. Pixels above+ * [FG_THRESHOLD] form the selection; the hard edge is feathered slightly so+ * cutouts aren't jagged. Runs off the main thread; [onResult] is posted to the+ * main thread (null on failure or if the model asset is missing).+ *+ * Model asset: [ASSET] `u2netp.onnx` (~4.6 MB, Apache-2.0; generate with+ * `scripts/photos/prepare_models.py`). Input NCHW `[1,3,`[SIZE]`,`[SIZE]`]` RGB,+ * ImageNet-normalised; primary output `[1,1,`[SIZE]`,`[SIZE]`]` saliency already+ * through a sigmoid.  */ fun segmentSubject(context: Context, bitmap: Bitmap, onResult: (Selection?) -> Unit) {     Thread {@@ -26,36 +36,102 @@ fun segmentSubject(context: Context, bitmap: Bitmap, onResult: (Selection?) -> U     }.start() } +private const val ASSET = "u2netp.onnx"+private const val SIZE = 320+private const val FG_THRESHOLD = 0.5f+// ImageNet normalisation (the rembg U²-Net preprocessing convention).+private val MEAN = floatArrayOf(0.485f, 0.456f, 0.406f)+private val STD = floatArrayOf(0.229f, 0.224f, 0.225f)++private val ortEnv: OrtEnvironment by lazy { OrtEnvironment.getEnvironment() }+private val segLock = Any()+@Volatile private var segSession: OrtSession? = null+@Volatile private var segInitTried = false++private fun ensureSession(context: Context): OrtSession? {+    segSession?.let { return it }+    synchronized(segLock) {+        segSession?.let { return it }+        if (segInitTried) return null+        segInitTried = true+        return try {+            val bytes = context.applicationContext.assets.open(ASSET).use { it.readBytes() }+            val opts = OrtSession.SessionOptions().apply {+                setIntraOpNumThreads(1)+                setInterOpNumThreads(1)+            }+            ortEnv.createSession(bytes, opts).also { segSession = it }+        } catch (e: Throwable) {+            Log.e("MlSegmentation", "U\u00b2-Net segmenter unavailable — add $ASSET to photos assets (see prepare_models.py).", e)+            null+        }+    }+}+ private fun runSegmenter(context: Context, bitmap: Bitmap): Selection? {-    // Cap input size for speed; the mask is returned at the input resolution.+    val session = ensureSession(context) ?: return null++    // Cap the returned mask resolution for speed/memory; the model itself always+    // runs at its fixed [SIZE] input and we upsample the saliency map to this.     val maxDim = 512     val scale = minOf(1f, maxDim.toFloat() / maxOf(bitmap.width, bitmap.height))     val w = (bitmap.width * scale).toInt().coerceAtLeast(1)     val h = (bitmap.height * scale).toInt().coerceAtLeast(1)-    val scaled = if (w == bitmap.width && h == bitmap.height) bitmap-    else Bitmap.createScaledBitmap(bitmap, w, h, true)-    val argb = if (scaled.config == Bitmap.Config.ARGB_8888) scaled-    else scaled.copy(Bitmap.Config.ARGB_8888, false)--    val options = ImageSegmenter.ImageSegmenterOptions.builder()-        .setBaseOptions(BaseOptions.builder().setModelAssetPath("deeplab_v3.tflite").build())-        .setRunningMode(RunningMode.IMAGE)-        .setOutputCategoryMask(true)-        .setOutputConfidenceMasks(false)-        .build()--    ImageSegmenter.createFromOptions(context, options).use { segmenter ->-        val result = segmenter.segment(BitmapImageBuilder(argb).build())-        val maskImage = result.categoryMask().orElse(null) ?: return null-        val mw = maskImage.width-        val mh = maskImage.height-        val buffer = ByteBufferExtractor.extract(maskImage)-        val arr = FloatArray(mw * mh)-        for (i in 0 until mw * mh) {-            val cls = buffer.get(i).toInt() and 0xFF-            arr[i] = if (cls != 0) 1f else 0f++    // Preprocess: resize to SIZE×SIZE, RGB, /255 then ImageNet normalise, NCHW.+    val safe = if (bitmap.config == Bitmap.Config.HARDWARE || bitmap.config == null) {+        bitmap.copy(Bitmap.Config.ARGB_8888, false)+    } else bitmap+    val input = Bitmap.createScaledBitmap(safe, SIZE, SIZE, true)+    val px = IntArray(SIZE * SIZE)+    input.getPixels(px, 0, SIZE, 0, 0, SIZE, SIZE)+    if (input != safe) input.recycle()+    if (safe != bitmap) safe.recycle()++    val area = SIZE * SIZE+    val chw = FloatArray(3 * area)+    for (i in 0 until area) {+        val p = px[i]+        chw[i] = ((((p shr 16) and 0xFF) / 255f) - MEAN[0]) / STD[0]           // R+        chw[area + i] = ((((p shr 8) and 0xFF) / 255f) - MEAN[1]) / STD[1]     // G+        chw[2 * area + i] = (((p and 0xFF) / 255f) - MEAN[2]) / STD[2]         // B+    }++    val saliency: FloatArray = synchronized(segLock) {+        val inputName = session.inputNames.iterator().next()+        OnnxTensor.createTensor(+            ortEnv,+            FloatBuffer.wrap(chw),+            longArrayOf(1, 3, SIZE.toLong(), SIZE.toLong()),+        ).use { tensor ->+            session.run(mapOf(inputName to tensor)).use { result ->+                // First output is the main saliency map [1,1,SIZE,SIZE] (sigmoid).+                val out = result.get(0) as OnnxTensor+                val vec = FloatArray(area)+                out.floatBuffer.get(vec)+                vec+            }+        }+    }++    // Normalise to 0..1 (U²-Net output isn't guaranteed to span the full range).+    var lo = Float.MAX_VALUE+    var hi = -Float.MAX_VALUE+    for (v in saliency) { if (v < lo) lo = v; if (v > hi) hi = v }+    val range = (hi - lo).takeIf { it > 1e-6f } ?: 1f++    // Upsample the SIZE×SIZE mask to the (w,h) selection grid (nearest is fine;+    // the edge gets feathered below) and threshold into a foreground mask.+    val mask = FloatArray(w * h)+    for (y in 0 until h) {+        val sy = (y * SIZE / h).coerceIn(0, SIZE - 1)+        for (x in 0 until w) {+            val sx = (x * SIZE / w).coerceIn(0, SIZE - 1)+            val norm = (saliency[sy * SIZE + sx] - lo) / range+            mask[y * w + x] = if (norm >= FG_THRESHOLD) 1f else 0f         }-        // Feather the hard class edge slightly so cutouts aren't jagged.-        return Selection(arr, mw, mh).applyFeather(1.5f)     }++    // Feather the hard edge slightly so cutouts aren't jagged.+    return Selection(mask, w, h).applyFeather(1.5f) }
photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.kt b/photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.ktindex cf807cce28..60da9125c9 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.kt@@ -43,6 +43,7 @@ import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.delay import kotlinx.coroutines.ensureActive import kotlinx.coroutines.sync.Mutex@@ -334,6 +335,25 @@ suspend fun setExifData(photos: List<Photo>, database: PhotoDatabase, context: C     } } +/**+ * Sustained on-device AI indexing (OCR, CLIP, face models) heats the phone.+ * On top of the short per-item pauses, each indexing loop takes a longer+ * "cooling break" every [BATCH_COOLDOWN_EVERY] items it actually ran inference+ * on, idling for [BATCH_COOLDOWN_MS] so the device can shed heat before the next+ * batch. [processed] is the running count of AI-processed items in this run.+ */+private suspend fun coolDownBetweenBatches(processed: Int, tag: String) {+    if (processed > 0 && processed % BATCH_COOLDOWN_EVERY == 0) {+        Log.i(tag, "Cooling break after $processed items: pausing ${BATCH_COOLDOWN_MS}ms to let the device cool")+        delay(BATCH_COOLDOWN_MS)+    }+}++// Number of AI-processed items between cooling breaks, and how long each break+// lasts. Kept modest so indexing still makes steady progress in the background.+private const val BATCH_COOLDOWN_EVERY = 20+private const val BATCH_COOLDOWN_MS = 5_000L+ suspend fun runOCR(database: PhotoDatabase, context: Context) = coroutineScope {     val photoDao = database.photoDao()     val photos = photoDao.getUnscannedForOCR().sortedByDescending { it.date }@@ -346,6 +366,7 @@ suspend fun runOCR(database: PhotoDatabase, context: Context) = coroutineScope {         return@coroutineScope     } +    var processed = 0     try {         for (photo in photos) {             ensureActive()@@ -379,6 +400,9 @@ suspend fun runOCR(database: PhotoDatabase, context: Context) = coroutineScope {              // Short pause between images keeps sustained CPU/battery use low.             delay(OCR_INTER_ITEM_DELAY_MS)+            // Longer cooling break every batch so the device can shed heat.+            processed+++            coolDownBetweenBatches(processed, "OCRWorker")         }     } finally {         ocrEngine.close()@@ -500,6 +524,7 @@ suspend fun runClipIndexing(database: PhotoDatabase, context: Context) = corouti     val photos = photoDao.getUnscannedForClip().sortedByDescending { it.date }     if (photos.isEmpty()) return@coroutineScope +    var processed = 0     for (photo in photos) {         ensureActive() @@ -535,6 +560,9 @@ suspend fun runClipIndexing(database: PhotoDatabase, context: Context) = corouti          // Short pause between images keeps sustained CPU/battery use low.         delay(CLIP_INTER_ITEM_DELAY_MS)+        // Longer cooling break every batch so the device can shed heat.+        processed+++        coolDownBetweenBatches(processed, "ClipWorker")     } } @@ -615,12 +643,25 @@ suspend fun runFaceIndexing(database: PhotoDatabase, context: Context) {         .toMutableList()      val photos = photoDao.getUnscannedForFaces().sortedByDescending { it.date }+    Log.i("FaceWorker", "Face indexing start: ${photos.size} photos to scan, ${clusters.size} existing clusters")+    var facesTotal = 0+    var photosWithFaces = 0+    var decoded = 0     for (photo in photos) {+        currentCoroutineContext().ensureActive()++        var didInference = false         try {             val bitmap = loadBitmapForFaces(context, photo.uri.toUri())             if (bitmap != null) {+                decoded+++                didInference = true                 val faces = FaceRecognizer.detectAndEmbed(context, bitmap)                 bitmap.recycle()+                if (faces.isNotEmpty()) {+                    photosWithFaces++; facesTotal += faces.size+                    Log.i("FaceWorker", "photo ${photo.id}: ${faces.size} face(s) (running total: $facesTotal)")+                }                 val rows = faces.map { face ->                     val clusterId = assignToCluster(face, photo, clusters, faceDao)                     PhotoFace(@@ -637,7 +678,16 @@ suspend fun runFaceIndexing(database: PhotoDatabase, context: Context) {          // Mark scanned regardless of outcome so we don't retry forever.         photoDao.upsertAll(listOf(photo.copy(faceScanned = true)))++        // Face indexing runs two ONNX models per photo (detector + embedder), so+        // pace it like OCR/CLIP: a short pause after each photo we actually ran+        // inference on, plus a longer cooling break every batch.+        if (didInference) {+            delay(FACE_INTER_ITEM_DELAY_MS)+            coolDownBetweenBatches(decoded, "FaceWorker")+        }     }+    Log.i("FaceWorker", "Face indexing done: decoded=$decoded/${photos.size}, $facesTotal faces in $photosWithFaces photos, ${faceDao.getPersons().size} clusters")      // Second pass: fold together clusters whose centroids ended up very close,     // which trims duplicate person-groups created early in the scan.@@ -647,6 +697,8 @@ suspend fun runFaceIndexing(database: PhotoDatabase, context: Context) { /** A cluster held in memory during a scan: its [Person] row plus cached centroid. */ private class Cluster(var person: Person, var centroid: FloatArray) +private const val FACE_INTER_ITEM_DELAY_MS = 250L+ /**  * Put [face] in the nearest cluster above [FaceRecognizer.CLUSTER_THRESHOLD],  * updating that cluster's running-mean centroid, or start a new cluster. Returns
scripts/chess/extract_learn.py
diff --git a/scripts/chess/extract_learn.py b/scripts/chess/extract_learn.pyindex 5c2f525a70..70c585202b 100644--- a/scripts/chess/extract_learn.py+++ b/scripts/chess/extract_learn.py@@ -284,10 +284,13 @@ def main():      categories = []     total_levels = 0+    stage_id = 1     for cat_key, stage_keys in CATEGORIES:         stages = []         for sk in stage_keys:             stage = parse_stage(os.path.join(stage_dir, f"{sk}.ts"), sk, learn, site)+            stage = {"id": stage_id, **stage}+            stage_id += 1             stages.append(stage)             total_levels += len(stage["levels"])         categories.append({"key": cat_key, "name": learn.get(cat_key, cat_key), "stages": stages})
scripts/photos/README.md
diff --git a/scripts/photos/README.md b/scripts/photos/README.mdindex 60d8624ba7..cfb8000b74 100644--- a/scripts/photos/README.md+++ b/scripts/photos/README.md@@ -1,18 +1,26 @@ # Photos model assets -`prepare_models.py` regenerates the on-device ML binary the Photos app ships in-`photos/src/main/assets/`. Run it whenever you want to refresh or re-quantize the-model; the app loads whatever is on disk and is otherwise inert (no crash) if the-asset is missing.+`prepare_models.py` regenerates the on-device ML binaries the Photos app ships in+`photos/src/main/assets/`. Run it whenever you want to refresh the models; the app+loads whatever is on disk and is otherwise inert (no crash) if an asset is missing.  ## What it produces  | Asset | Source | Format | ~Size | | --- | --- | --- | --- |-| `edgeface.onnx` | EdgeFace `edgeface-s-gamma-05` (anjith2006/edgeface, transformers mirror) | INT8 dynamic | 4 MB |--MediaPipe's `face_detector.tflite` and the editor's `deeplab_v3.tflite` are-unrelated and stay as-is.+| `blazeface.onnx` | BlazeFace ONNX (garavv/blazeface-onnx, `blaze.onnx`) | fp32, decode+NMS in-graph | ~0.5 MB |+| `u2netp.onnx` | U²-Net portable (BritishWerewolf/U-2-Netp) | fp32 salient-object | ~4.6 MB |+| `edgeface.onnx` | EdgeFace `edgeface-s-gamma-05` (anjith2006/edgeface, transformers mirror) | fp32 | ~16 MB |++> **Not INT8-quantized on purpose.** EdgeFace is a CNN; `quantize_dynamic` turns+> its Conv layers into `ConvInteger`, which the ONNX Runtime **Android** package+> can't run (`ORT_NOT_IMPLEMENTED: ConvInteger`) — it loads on desktop but fails+> on-device, silently disabling face grouping. Use *static* quantization+> (calibration images → supported `QLinearConv`) if you need the size back.++Everything runs on ONNX Runtime now: face **detection** (BlazeFace), face+**embedding** (EdgeFace), and subject **segmentation** (U²-Net). The app no longer+depends on MediaPipe at all.  ### Semantic (CLIP) search moved to OpenAssistant 
scripts/photos/prepare_models.py
diff --git a/scripts/photos/prepare_models.py b/scripts/photos/prepare_models.pyindex 8e41fae314..d83aec6a4d 100644--- a/scripts/photos/prepare_models.py+++ b/scripts/photos/prepare_models.py@@ -1,15 +1,34 @@ #!/usr/bin/env python3 """Prepare the on-device ML model assets for the Photos app. -Produces one binary the app loads from `photos/src/main/assets/`:--  EdgeFace face embedder (INT8) -> `edgeface.onnx`+Produces three binaries the app loads from `photos/src/main/assets/`:++  1. BlazeFace face detector -> `blazeface.onnx`+     Downloaded as-is from the HuggingFace ONNX export `garavv/blazeface-onnx`+     (`blaze.onnx`, ~0.5 MB). Anchor decoding + NMS are baked into the graph+     (inputs: image[1,3,128,128] RGB in [0,1], conf_threshold, max_detections,+     iou_threshold; output [1,N,16] = normalised box + 6 landmarks). Plain fp32+     ONNX ops, so it runs on the ONNX Runtime Android package. Replaces the old+     MediaPipe face detector.++  2. U²-Net portable subject segmenter -> `u2netp.onnx`+     Downloaded as-is from `BritishWerewolf/U-2-Netp` (~4.6 MB, Apache-2.0).+     Salient-object detection for the editor's "select subject" tool. Input NCHW+     [1,3,320,320] RGB ImageNet-normalised; primary output [1,1,320,320] saliency+     (sigmoid). Replaces DeepLabV3 (which only knew the 20 Pascal-VOC classes),+     which — together with the BlazeFace swap — lets the app drop MediaPipe.++  3. EdgeFace face embedder (fp32) -> `edgeface.onnx`      EdgeFace `edgeface-s-gamma-05` loaded from the transformers-format Hub      mirror `anjith2006/edgeface` (bundles the model code + safetensors, so no-     GitHub checkout), exported to ONNX and INT8 weight-quantized-     (`onnxruntime.quantization.quantize_dynamic`). Input NCHW [1,3,112,112]+     GitHub checkout), exported to fp32 ONNX. Input NCHW [1,3,112,112]      normalised (px-127.5)/127.5; output a 512-d embedding. +     NOT INT8-quantized on purpose: EdgeFace is a CNN, and dynamic quantization+     turns its Conv layers into `ConvInteger`, which the ONNX Runtime Android+     package cannot run (`ORT_NOT_IMPLEMENTED: ConvInteger`) — it would load fine+     on desktop but fail on-device, silently disabling face grouping.+      NOTE: EdgeFace ships under a NON-COMMERCIAL research licence. This project      uses it deliberately (see the plan / FaceRecognizer docs). Swap it out if      you need a permissive licence.@@ -35,7 +54,6 @@ from __future__ import annotations import argparse import os import sys-import tempfile  # Repo layout: scripts/photos/prepare_models.py -> repo root is two levels up. REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))@@ -53,11 +71,72 @@ EDGEFACE_OUT = os.path.join(ASSETS_DIR, "edgeface.onnx") FACE_INPUT_SIZE = 112 EMBED_DIM = 512 +# BlazeFace face DETECTOR, downloaded as-is from the HuggingFace ONNX export+# `garavv/blazeface-onnx`. It bakes anchor decoding + NMS into the graph (inputs:+# image[1,3,128,128], conf_threshold, max_detections, iou_threshold; output+# [1,N,16] of normalised box + 6 landmarks). Plain fp32 ONNX ops only, so it runs+# on the ONNX Runtime Android package. Replaces the old MediaPipe detector.+BLAZEFACE_HF_REPO = "garavv/blazeface-onnx"+BLAZEFACE_SRC_FILE = "blaze.onnx"+BLAZEFACE_OUT = os.path.join(ASSETS_DIR, "blazeface.onnx")++# U²-Net portable: salient-object segmentation used by the editor's "select+# subject" tool. Downloaded as-is from the ONNX export `BritishWerewolf/U-2-Netp`+# (Apache-2.0, ~4.6 MB). Replaces DeepLabV3 (which only knew the 20 Pascal-VOC+# classes) so arbitrary subjects can be selected. Standard fp32 ONNX ops.+U2NETP_HF_REPO = "BritishWerewolf/U-2-Netp"+U2NETP_SRC_FILE = "onnx/model.onnx"+U2NETP_OUT = os.path.join(ASSETS_DIR, "u2netp.onnx")+  def _mb(path: str) -> str:     return f"{os.path.getsize(path) / (1024 * 1024):.1f} MB"  +def prepare_u2netp() -> None:+    """Download the U²-Net portable segmenter and validate it in place."""+    import numpy as np+    import onnxruntime as ort+    import shutil+    from huggingface_hub import hf_hub_download++    print(f"[U2Netp] downloading {U2NETP_SRC_FILE} from {U2NETP_HF_REPO} ...")+    cached = hf_hub_download(repo_id=U2NETP_HF_REPO, filename=U2NETP_SRC_FILE)+    os.makedirs(ASSETS_DIR, exist_ok=True)+    shutil.copyfile(cached, U2NETP_OUT)+    print(f"[U2Netp] wrote {U2NETP_OUT} ({_mb(U2NETP_OUT)})")++    sess = ort.InferenceSession(U2NETP_OUT, providers=["CPUExecutionProvider"])+    in_name = sess.get_inputs()[0].name+    out = sess.run(None, {in_name: np.zeros((1, 3, 320, 320), dtype=np.float32)})[0]+    assert out.shape[-1] == 320 and out.shape[-2] == 320, f"[U2Netp] unexpected output {out.shape}"+    print(f"[U2Netp] smoke inference OK, output shape {out.shape}")+++def prepare_blazeface() -> None:+    """Download the BlazeFace ONNX detector and validate it in place."""+    import numpy as np+    import onnxruntime as ort+    import shutil+    from huggingface_hub import hf_hub_download++    print(f"[BlazeFace] downloading {BLAZEFACE_SRC_FILE} from {BLAZEFACE_HF_REPO} ...")+    cached = hf_hub_download(repo_id=BLAZEFACE_HF_REPO, filename=BLAZEFACE_SRC_FILE)+    os.makedirs(ASSETS_DIR, exist_ok=True)+    shutil.copyfile(cached, BLAZEFACE_OUT)+    print(f"[BlazeFace] wrote {BLAZEFACE_OUT} ({_mb(BLAZEFACE_OUT)})")++    sess = ort.InferenceSession(BLAZEFACE_OUT, providers=["CPUExecutionProvider"])+    out = sess.run(None, {+        "image": np.zeros((1, 3, 128, 128), dtype=np.float32),+        "conf_threshold": np.array([0.5], dtype=np.float32),+        "max_detections": np.array([25], dtype=np.int64),+        "iou_threshold": np.array([0.3], dtype=np.float32),+    })[0]+    assert out.shape[-1] == 16, f"[BlazeFace] expected 16 cols per box, got {out.shape}"+    print(f"[BlazeFace] smoke inference OK, output shape {out.shape}")++ def _load_edgeface_torch():     """Load the pretrained EdgeFace model (eval mode) from the HuggingFace mirror. @@ -111,39 +190,38 @@ def _load_edgeface_torch():   def prepare_edgeface() -> None:-    """Export EdgeFace to ONNX, INT8-quantize it, and validate."""+    """Export EdgeFace to fp32 ONNX and validate.++    We deliberately do **not** INT8-quantize. EdgeFace is a CNN, and+    `quantize_dynamic` turns its Conv layers into `ConvInteger` ops, which the+    ONNX Runtime **Android** package has no kernel for — the model then throws+    `ORT_NOT_IMPLEMENTED: ConvInteger` at session creation on-device and face+    grouping silently produces nothing. fp32 is a few MB larger but loads+    everywhere. (If you need the size back, use *static* quantization with+    calibration images so Conv becomes the supported `QLinearConv`, not+    `ConvInteger` — dynamic quant is only safe for MatMul/Transformer models.)+    """     import numpy as np     import onnxruntime as ort     import torch-    from onnxruntime.quantization import QuantType, quantize_dynamic      model = _load_edgeface_torch()      os.makedirs(ASSETS_DIR, exist_ok=True)-    with tempfile.TemporaryDirectory() as tmp:-        fp32_path = os.path.join(tmp, "edgeface_fp32.onnx")-        dummy = torch.zeros(1, 3, FACE_INPUT_SIZE, FACE_INPUT_SIZE, dtype=torch.float32)-        print(f"[EdgeFace] exporting fp32 ONNX ({fp32_path}) ...")-        # Static [1,3,112,112] via the legacy (TorchScript) exporter: the app only-        # ever embeds one crop at a time, and a static graph avoids the sequence /-        # shape-inference ops the dynamo exporter emits that break quantize_dynamic.-        torch.onnx.export(-            model,-            dummy,-            fp32_path,-            input_names=["input"],-            output_names=["embedding"],-            opset_version=17,-            do_constant_folding=True,-            dynamo=False,-        )--        print(f"[EdgeFace] INT8 dynamic quantization -> {EDGEFACE_OUT} ...")-        quantize_dynamic(-            fp32_path,-            EDGEFACE_OUT,-            weight_type=QuantType.QInt8,-        )+    dummy = torch.zeros(1, 3, FACE_INPUT_SIZE, FACE_INPUT_SIZE, dtype=torch.float32)+    print(f"[EdgeFace] exporting fp32 ONNX -> {EDGEFACE_OUT} ...")+    # Static [1,3,112,112] via the legacy (TorchScript) exporter: the app only+    # ever embeds one crop at a time, and a static graph keeps the op set small.+    torch.onnx.export(+        model,+        dummy,+        EDGEFACE_OUT,+        input_names=["input"],+        output_names=["embedding"],+        opset_version=17,+        do_constant_folding=True,+        dynamo=False,+    )     print(f"[EdgeFace] wrote {EDGEFACE_OUT} ({_mb(EDGEFACE_OUT)})")      sess = ort.InferenceSession(EDGEFACE_OUT, providers=["CPUExecutionProvider"])@@ -160,18 +238,22 @@ def main() -> int:     ).parse_args()      try:+        prepare_blazeface()+        prepare_u2netp()         prepare_edgeface()     except Exception as e:  # noqa: BLE001-        print(f"[EdgeFace] FAILED: {e}", file=sys.stderr)+        print(f"[prepare] FAILED: {e}", file=sys.stderr)         print("\n=== Summary ===")-        state = _mb(EDGEFACE_OUT) if os.path.exists(EDGEFACE_OUT) else "missing"-        print(f"  {'edgeface.onnx':26s} {state}")+        for path, label in ((BLAZEFACE_OUT, "blazeface.onnx"), (U2NETP_OUT, "u2netp.onnx"), (EDGEFACE_OUT, "edgeface.onnx")):+            state = _mb(path) if os.path.exists(path) else "missing"+            print(f"  {label:26s} {state}")         return 1      print("\n=== Summary ===")-    state = _mb(EDGEFACE_OUT) if os.path.exists(EDGEFACE_OUT) else "missing"-    print(f"  {'edgeface.onnx':26s} {state}")-    print("\nEdgeFace model prepared.")+    for path, label in ((BLAZEFACE_OUT, "blazeface.onnx"), (U2NETP_OUT, "u2netp.onnx"), (EDGEFACE_OUT, "edgeface.onnx")):+        state = _mb(path) if os.path.exists(path) else "missing"+        print(f"  {label:26s} {state}")+    print("\nModels prepared.")     return 0