Modern Apps git

← Modern-Apps.git

photos: remove onnx runtime

Commit
293547eeea6369862f7177c6cc32c03026034e21
Author
Vayun Mathur <[email protected]>
When
2026-07-25 04:16 UTC (4 months ago)
Parents
0faa94f

Diff

photos/build.gradle.kts
diff --git a/photos/build.gradle.kts b/photos/build.gradle.ktsindex d550bce503..9f5871fa51 100644--- a/photos/build.gradle.kts+++ b/photos/build.gradle.kts@@ -13,13 +13,9 @@ android {         applicationId = "com.vayunmathur.photos"     }     androidResources {-        noCompress += "tflite"-        // The on-device EdgeFace face embedder (edgeface.onnx) is already-        // compressed; store it uncompressed so ONNX Runtime can read it directly-        // from assets. (SigLIP2 semantic search now lives in OpenAssistant.)-        noCompress += "onnx"-        // ncnn-android is generalist; photos only uses PpOcr (OCR), so strip the-        // portrait (erdnet) model it never loads.+        // Face (SCRFD), embedding (MobileFaceNet), segmentation (U²-Net) and OCR+        // all come from the generalist ncnn-android AAR; photos does not use the+        // portrait (erdnet) model, so strip it from this APK.         ignoreAssetsPattern = "!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~:erdnet.*"     }     packaging {@@ -46,11 +42,10 @@ dependencies {     implementation(libs.coil.compose)     implementation(libs.coil.video)     implementation(libs.androidx.exifinterface)-    // Face detection (BlazeFace), face embedding (EdgeFace), and subject-    // segmentation (U²-Net) all run on ONNX Runtime (MIT, FOSS, no Play-    // Services / no MediaPipe). Photos owns this dependency directly (it is no-    // longer pulled in transitively via :library:ocr, which now uses ncnn).-    implementation(libs.onnxruntime.android)+    // On-device face detection (SCRFD), face embedding (MobileFaceNet) and+    // subject segmentation (U²-Net) run on ncnn via the generalist AAR (BSD-3,+    // no ONNX Runtime / Play Services / MediaPipe). OCR uses it via :library:ocr.+    implementation("com.github.vayun-mathur:ncnn-android:1.1.0")      implementRoom(libs)     implementation(project(":library:room"))
photos/src/main/assets/blazeface.onnx
diff --git a/photos/src/main/assets/blazeface.onnx b/photos/src/main/assets/blazeface.onnxdeleted file mode 100644index 4236e33cf0..0000000000Binary files a/photos/src/main/assets/blazeface.onnx 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.onnxdeleted file mode 100644index bd2519ed50..0000000000Binary files a/photos/src/main/assets/edgeface.onnx 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.onnxdeleted file mode 100644index 4f21f9afd3..0000000000Binary files a/photos/src/main/assets/u2netp.onnx and /dev/null 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 7c3aeadc42..af2b271846 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/FaceRecognizer.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/FaceRecognizer.kt@@ -7,126 +7,66 @@ import android.graphics.Matrix import android.graphics.Paint import android.graphics.Rect import android.util.Log-import ai.onnxruntime.OnnxTensor-import ai.onnxruntime.OrtEnvironment-import ai.onnxruntime.OrtSession+import com.vayunmathur.ncnn.FaceDetector+import com.vayunmathur.ncnn.FaceEmbedder import java.nio.ByteBuffer import java.nio.ByteOrder-import java.nio.FloatBuffer-import java.nio.LongBuffer import kotlin.math.sqrt  /**- * On-device face detection + recognition. Everything runs locally with no Google- * Play Services and no cloud (F-Droid clean).+ * On-device face detection + recognition. Everything runs locally on **ncnn**+ * (CPU-only, BSD-3 — no ONNX Runtime, no Google Play Services, F-Droid clean).  *  * Pipeline:- *  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.- *  3. Embedding — a dedicated FACE-recognition model ([EMBEDDER_ASSET],- *     **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 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]).+ *  1. Detection — **SCRFD** ([FaceDetector], nihui's `scrfd_500m_kps`) finds+ *     faces and returns a bounding box + 5 landmarks (the two eyes are used for+ *     alignment). Anchor decode + NMS run natively.+ *  2. Alignment — the two eye landmarks drive a similarity transform (rotate ++ *     uniform scale + translate) onto a canonical [INPUT_SIZE]² crop.+ *  3. Embedding — **MobileFaceNet** ([FaceEmbedder], insightface `w600k_mbf`,+ *     ArcFace-trained) produces a 512-d embedding from the aligned crop. Pixels+ *     are normalised (px - 127.5)/127.5 (handled natively). The result is+ *     L2-normalised here.+ *  4. Matching — cosine similarity clusters faces of the same person+ *     (see [CLUSTER_THRESHOLD]).  *- * ## Required model assets (in `photos/src/main/assets/`)- *- *  - [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,- *    normalised (px - 127.5) / 127.5; output: a 512-d float embedding (the- *    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 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].- *    When you change the model, bump [EMBEDDER_VERSION] so existing clusters are- *    rebuilt with the new embeddings.- *- * If either model is missing the feature stays inert (no crash): see- * [modelsAvailable], which the UI checks before enabling.+ * The models live inside the `ncnn-android` AAR, so they are always available.  */ object FaceRecognizer {-    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. */+    /** Square input side (px) the embedder expects. ArcFace/MobileFaceNet is 112. */     const val INPUT_SIZE = 112      /**      * Bump this whenever the embedder model (or preprocessing) changes. The face      * 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; 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.)+     * (v5 = BlazeFace + EdgeFace on ONNX Runtime; v6 = SCRFD detector ++     * MobileFaceNet embedder on ncnn — different embeddings, so a re-scan runs.)      */-    const val EMBEDDER_VERSION = 5+    const val EMBEDDER_VERSION = 6      /**-     * Minimum cosine similarity for a face to join an existing cluster instead of-     * starting a new one. Single tunable knob. EdgeFace is ArcFace-trained, so-     * its cosine distribution is more spread out than MobileFaceNet's ~0.4–0.6:-     * same-person pairs sit higher and impostors lower, so a stricter floor is-     * appropriate. 0.55 is the starting point — validate on sample faces and-     * adjust: higher = stricter/more clusters, lower = looser/fewer clusters.+     * Minimum cosine similarity for a face to join an existing cluster. ArcFace+     * (MobileFaceNet) has a spread-out cosine distribution; 0.5 is a reasonable+     * starting floor — validate on sample faces and adjust (higher = stricter/+     * more clusters, lower = looser/fewer).      */-    const val CLUSTER_THRESHOLD = 0.55f+    const val CLUSTER_THRESHOLD = 0.5f -    /**-     * Cosine similarity above which two whole clusters are merged in the-     * second-pass cleanup (reduces duplicate person-groups). Kept a bit stricter-     * than [CLUSTER_THRESHOLD] because it compares averaged centroids.-     */-    const val MERGE_THRESHOLD = 0.65f+    /** Cosine above which two whole clusters merge in the second-pass cleanup. */+    const val MERGE_THRESHOLD = 0.6f      private const val TAG = "FaceRecognizer" -    // Canonical eye positions inside the aligned crop, as fractions of the side.-    // Derived from the standard ArcFace 5-point template at 112px-    // (left eye 38.29, right eye 73.53, both at y≈51.7).+    // Canonical eye positions inside the aligned crop (ArcFace 5-point template).     private const val LEFT_EYE_X = 38.2946f / 112f     private const val RIGHT_EYE_X = 73.5318f / 112f     private const val EYE_Y = 51.6963f / 112f      /**      * One detected face: its L2-normalised embedding plus the detector's bounding-     * box, normalised to 0..1 of the source image so it survives resizing (used-     * for the representative thumbnail crop in the UI).+     * box, normalised to 0..1 of the source image so it survives resizing.      */     data class DetectedFace(         val embedding: FloatArray,@@ -136,23 +76,13 @@ object FaceRecognizer {         val bottom: Float,     ) -    private val env: OrtEnvironment by lazy { OrtEnvironment.getEnvironment() }     private val lock = Any()--    @Volatile private var detector: OrtSession? = null-    @Volatile private var embedder: OrtSession? = null+    @Volatile private var detector: FaceDetector? = null+    @Volatile private var embedder: FaceEmbedder? = null     @Volatile private var initFailed = false -    /** True only if both model assets are present in the APK. */-    fun modelsAvailable(context: Context): Boolean =-        assetExists(context, DETECTOR_ASSET) && assetExists(context, EMBEDDER_ASSET)--    private fun assetExists(context: Context, name: String): Boolean = try {-        context.assets.open(name).close()-        true-    } catch (_: Exception) {-        false-    }+    /** True if the native models could be loaded (they ship inside the AAR). */+    fun modelsAvailable(context: Context): Boolean = ensureInit(context)      @Synchronized     private fun ensureInit(context: Context): Boolean {@@ -160,35 +90,20 @@ object FaceRecognizer {         if (initFailed) return false         return try {             val app = context.applicationContext-            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)+            detector = FaceDetector(app)+            embedder = FaceEmbedder(app)             true         } catch (e: Throwable) {-            Log.e(TAG, "Face models unavailable — drop a BlazeFace $DETECTOR_ASSET and an EdgeFace $EMBEDDER_ASSET into photos assets (see FaceRecognizer docs).", e)+            Log.e(TAG, "Face models unavailable", e)             try { detector?.close() } catch (_: Exception) {}-            detector = null             try { embedder?.close() } catch (_: Exception) {}+            detector = null             embedder = null             initFailed = true             false         }     } -    private fun readAsset(context: Context, name: String): ByteArray? = try {-        context.assets.open(name).use { it.readBytes() }-    } catch (_: Exception) {-        null-    }-     /** Detect every face in [bitmap] and return one [DetectedFace] per face. */     fun detectAndEmbed(context: Context, bitmap: Bitmap): List<DetectedFace> {         if (!ensureInit(context)) return emptyList()@@ -198,25 +113,26 @@ object FaceRecognizer {         val argb = if (bitmap.config == Bitmap.Config.ARGB_8888) bitmap         else bitmap.copy(Bitmap.Config.ARGB_8888, false) -        val detections = try {-            runDetector(det, argb)+        val faces = try {+            det.detect(argb)         } catch (e: Exception) {             Log.e(TAG, "Face detection failed", e)+            if (argb != bitmap) argb.recycle()             return emptyList()         } -        val out = ArrayList<DetectedFace>(detections.size)-        for (d in detections) {-            val rect = faceRect(d, argb.width, argb.height) ?: continue-            val aligned = alignFace(argb, d, rect) ?: continue+        val out = ArrayList<DetectedFace>(faces.size)+        for (f in faces) {+            val rect = faceRect(f, argb.width, argb.height) ?: continue+            val aligned = alignFace(argb, f, rect) ?: continue             try {-                val embedding = l2Normalize(embed(emb, aligned))+                val embedding = l2Normalize(emb.embed(aligned))                 out += DetectedFace(                     embedding = embedding,-                    left = rect.left.toFloat() / argb.width,-                    top = rect.top.toFloat() / argb.height,-                    right = rect.right.toFloat() / argb.width,-                    bottom = rect.bottom.toFloat() / argb.height,+                    left = f.left,+                    top = f.top,+                    right = f.right,+                    bottom = f.bottom,                 )             } catch (e: Exception) {                 Log.e(TAG, "Face embedding failed", e)@@ -224,100 +140,22 @@ object FaceRecognizer {                 aligned.recycle()             }         }+        if (argb != bitmap) argb.recycle()         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,-    )--    /**-     * 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 landmarks are unavailable.+     * Warp the source so the two eye landmarks land on fixed canonical positions+     * in an [INPUT_SIZE] crop (similarity transform). Falls back to a plain box+     * crop when landmarks are unusable.      */-    private fun alignFace(src: Bitmap, d: RawDetection, box: Rect): Bitmap? {-        val hasEyes = d.leftEyeX != 0f || d.leftEyeY != 0f || d.rightEyeX != 0f || d.rightEyeY != 0f+    private fun alignFace(src: Bitmap, f: FaceDetector.Face, box: Rect): Bitmap? {+        val hasEyes = f.leftEyeX != 0f || f.leftEyeY != 0f || f.rightEyeX != 0f || f.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.+            // Sort eyes by x so the left-most maps to the left canonical eye.             val eyes = listOf(-                floatArrayOf(d.leftEyeX * src.width, d.leftEyeY * src.height),-                floatArrayOf(d.rightEyeX * src.width, d.rightEyeY * src.height),+                floatArrayOf(f.leftEyeX * src.width, f.leftEyeY * src.height),+                floatArrayOf(f.rightEyeX * src.width, f.rightEyeY * src.height),             ).sortedBy { it[0] }             val srcPts = floatArrayOf(eyes[0][0], eyes[0][1], eyes[1][0], eyes[1][1])             val dstPts = floatArrayOf(@@ -330,65 +168,27 @@ object FaceRecognizer {                     val outBmp = Bitmap.createBitmap(INPUT_SIZE, INPUT_SIZE, Bitmap.Config.ARGB_8888)                     Canvas(outBmp).drawBitmap(src, matrix, Paint(Paint.FILTER_BITMAP_FLAG))                     outBmp-                } catch (_: Exception) {-                    null-                }+                } catch (_: Exception) { null }             }         }-        // 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)             if (scaled != crop) crop.recycle()             scaled-        } catch (_: Exception) {-            null-        }-    }--    /**-     * Run the embedder on an [INPUT_SIZE] aligned crop, returning the raw vector.-     * EdgeFace/ArcFace expects an NCHW planar `[1,3,H,W]` float tensor with pixels-     * normalised (px - 127.5) / 127.5.-     */-    private fun embed(session: OrtSession, face: Bitmap): FloatArray {-        val area = INPUT_SIZE * INPUT_SIZE-        val pixels = IntArray(area)-        face.getPixels(pixels, 0, INPUT_SIZE, 0, 0, INPUT_SIZE, INPUT_SIZE)-        val input = FloatArray(3 * area)-        for (i in 0 until area) {-            val p = pixels[i]-            input[i] = (((p shr 16) and 0xFF) - 127.5f) / 127.5f          // R plane-            input[area + i] = (((p shr 8) and 0xFF) - 127.5f) / 127.5f     // G plane-            input[2 * area + i] = ((p and 0xFF) - 127.5f) / 127.5f         // B plane-        }-        synchronized(lock) {-            val inputName = session.inputNames.iterator().next()-            OnnxTensor.createTensor(-                env,-                FloatBuffer.wrap(input),-                longArrayOf(1, 3, INPUT_SIZE.toLong(), INPUT_SIZE.toLong()),-            ).use { tensor ->-                session.run(mapOf(inputName to tensor)).use { result ->-                    val out = result.get(0) as OnnxTensor-                    val vec = FloatArray(out.info.shape.last().toInt())-                    out.floatBuffer.get(vec)-                    return vec-                }-            }-        }+        } catch (_: Exception) { null }     }      /** 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+    private fun faceRect(f: FaceDetector.Face, w: Int, h: Int): Rect? {+        val bw = (f.right - f.left) * w+        val bh = (f.bottom - f.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)+        val left = (f.left * w - marginX).toInt().coerceIn(0, w - 1)+        val top = (f.top * h - marginY).toInt().coerceIn(0, h - 1)+        val right = (f.right * w + marginX).toInt().coerceIn(left + 1, w)+        val bottom = (f.bottom * h + marginY).toInt().coerceIn(top + 1, h)         if (right - left < 8 || bottom - top < 8) return null         return Rect(left, top, right, bottom)     }@@ -396,14 +196,8 @@ object FaceRecognizer {     /** Cosine similarity of two embeddings (range roughly -1..1). */     fun similarity(a: FloatArray, b: FloatArray): Float {         if (a.size != b.size || a.isEmpty()) return -1f-        var dot = 0f-        var na = 0f-        var nb = 0f-        for (i in a.indices) {-            dot += a[i] * b[i]-            na += a[i] * a[i]-            nb += b[i] * b[i]-        }+        var dot = 0f; var na = 0f; var nb = 0f+        for (i in a.indices) { dot += a[i] * b[i]; na += a[i] * a[i]; nb += b[i] * b[i] }         if (na == 0f || nb == 0f) return -1f         return dot / (sqrt(na) * sqrt(nb))     }
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 d353289864..86eb96eae9 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/MlSegmentation.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/MlSegmentation.kt@@ -1,32 +1,26 @@ 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.vayunmathur.ncnn.Segmenter import com.vayunmathur.photos.data.Selection-import java.nio.FloatBuffer  /**  * 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).+ * **U²-Net portable** salient-object detection on **ncnn** (CPU-only, BSD-3, no+ * ONNX Runtime, 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).+ * 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).  *- * 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.+ * The model + preprocessing live inside the `ncnn-android` AAR ([Segmenter]);+ * input 320×320 RGB, ImageNet-normalised; output a 320×320 saliency map through+ * a sigmoid.  */ fun segmentSubject(context: Context, bitmap: Bitmap, onResult: (Selection?) -> Unit) {     Thread {@@ -36,83 +30,47 @@ 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 segmenter: Segmenter? = null @Volatile private var segInitTried = false -private fun ensureSession(context: Context): OrtSession? {-    segSession?.let { return it }+private fun ensureSegmenter(context: Context): Segmenter? {+    segmenter?.let { return it }     synchronized(segLock) {-        segSession?.let { return it }+        segmenter?.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 }+            Segmenter(context.applicationContext).also { segmenter = it }         } catch (e: Throwable) {-            Log.e("MlSegmentation", "U\u00b2-Net segmenter unavailable — add $ASSET to photos assets (see prepare_models.py).", e)+            Log.e("MlSegmentation", "U\u00b2-Net segmenter unavailable", e)             null         }     } }  private fun runSegmenter(context: Context, bitmap: Bitmap): Selection? {-    val session = ensureSession(context) ?: return null+    val seg = ensureSegmenter(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.+    // Cap the returned mask resolution for speed/memory; the model runs at its+    // fixed input size 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) -    // 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 result = synchronized(segLock) { seg.segment(safe) }+    if (safe != bitmap) safe.recycle() -    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-            }-        }-    }+    val sw = result.width+    val sh = result.height+    val saliency = result.mask      // Normalise to 0..1 (U²-Net output isn't guaranteed to span the full range).     var lo = Float.MAX_VALUE@@ -120,18 +78,16 @@ private fun runSegmenter(context: Context, bitmap: Bitmap): Selection? {     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.+    // Upsample the model mask to the (w,h) selection grid and threshold.     val mask = FloatArray(w * h)     for (y in 0 until h) {-        val sy = (y * SIZE / h).coerceIn(0, SIZE - 1)+        val sy = (y * sh / h).coerceIn(0, sh - 1)         for (x in 0 until w) {-            val sx = (x * SIZE / w).coerceIn(0, SIZE - 1)-            val norm = (saliency[sy * SIZE + sx] - lo) / range+            val sx = (x * sw / w).coerceIn(0, sw - 1)+            val norm = (saliency[sy * sw + sx] - lo) / range             mask[y * w + x] = if (norm >= FG_THRESHOLD) 1f else 0f         }     } -    // Feather the hard edge slightly so cutouts aren't jagged.     return Selection(mask, w, h).applyFeather(1.5f) }