photos: reorganization to openassistant for searching
- Commit
64bc5ede41aca223e810400881c4ed4eb21a17db- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-08 18:34 UTC (5 months ago)
- Parents
9fe56ca
Diff
photos/src/main/assets/edgeface.onnx
diff --git a/photos/src/main/assets/edgeface.onnx b/photos/src/main/assets/edgeface.onnxnew file mode 100644index 0000000000..6ebba27eb9Binary files /dev/null and b/photos/src/main/assets/edgeface.onnx differ
photos/src/main/assets/mobilefacenet.tflite
diff --git a/photos/src/main/assets/mobilefacenet.tflite b/photos/src/main/assets/mobilefacenet.tflitedeleted file mode 100644index dcba8d1efa..0000000000Binary files a/photos/src/main/assets/mobilefacenet.tflite and /dev/null differ
photos/src/main/java/com/vayunmathur/photos/data/Photo.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/Photo.kt b/photos/src/main/java/com/vayunmathur/photos/data/Photo.ktindex 8f728c3470..9acf65798b 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/Photo.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/Photo.kt@@ -35,11 +35,12 @@ data class Photo( // True once this photo has been through OCR (mirrors [faceScanned]); keeps // the OCR worker from re-processing the same photo on every sync. val ocrScanned: Boolean = false,- // L2-normalised MobileCLIP image embedding (float[] packed little-endian as- // bytes), null until scanned. Semantic search cosine-compares the query's- // text embedding against these. Videos and un-scanned photos stay null.+ // L2-normalised semantic image embedding (float[] packed little-endian as+ // bytes), produced by OpenAssistant (SigLIP2); null until scanned. Semantic+ // search cosine-compares the query's text embedding against these. Videos and+ // un-scanned photos stay null. val clipEmbedding: ByteArray? = null,- // True once this photo has been through the MobileCLIP image encoder- // (mirrors [ocrScanned]); keeps the CLIP worker from re-embedding on sync.+ // True once this photo has been sent to the embedder (mirrors [ocrScanned]);+ // keeps the worker from re-embedding the same photo on every sync. val clipScanned: Boolean = false, ) : DatabaseItem
photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.ktindex 360e9d5129..46991422bb 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt@@ -54,8 +54,8 @@ interface PhotoDao { @Query("SELECT * FROM Photo WHERE clipScanned = 0 AND isTrashed = 0 AND duration IS NULL") suspend fun getUnscannedForClip(): List<Photo> - /** Photos already embedded by MobileCLIP (numerator of the progress bar). */- @Query("SELECT count(*) FROM Photo WHERE clipScanned = 1 AND isTrashed = 0 AND duration IS NULL")+ /** Photos with a stored embedding, i.e. actually indexed (progress numerator). */+ @Query("SELECT count(*) FROM Photo WHERE clipEmbedding IS NOT NULL AND isTrashed = 0 AND duration IS NULL") fun getClipCountFlow(): Flow<Int> /** Photos that count toward CLIP embedding (denominator of the progress bar). */@@ -158,9 +158,9 @@ val MIGRATION_8_9 = Migration(8, 9) { } val MIGRATION_9_10 = Migration(9, 10) {- // Add on-device MobileCLIP semantic search: store each photo's L2-normalised- // image embedding (BLOB) plus a clipScanned flag that mirrors ocrScanned so- // the CLIP worker only embeds new photos. OCR text and faces are untouched.+ // Add semantic-search columns: store each photo's L2-normalised image+ // embedding (BLOB) plus a clipScanned flag that mirrors ocrScanned so the+ // worker only embeds new photos. OCR text and faces are untouched. // SQL mirrors Room's generated schema exactly so schema validation passes. it.execSQL("ALTER TABLE Photo ADD COLUMN clipEmbedding BLOB") it.execSQL("ALTER TABLE Photo ADD COLUMN clipScanned INTEGER NOT NULL DEFAULT 0")
photos/src/main/java/com/vayunmathur/photos/util/ClipEmbedder.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/ClipEmbedder.kt b/photos/src/main/java/com/vayunmathur/photos/util/ClipEmbedder.ktindex cc20096653..ebf878078b 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/ClipEmbedder.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/ClipEmbedder.kt@@ -32,8 +32,8 @@ object ClipEmbedder { /** * Bump whenever the embedding space changes so [ClipWorker] clears every- * stored vector and re-indexes. Bumped from 1 (512-d on-device MobileCLIP)- * to 2 for the move to OpenAssistant's 768-d SigLIP2 space.+ * stored vector and re-indexes. Bumped to 2 for the move to OpenAssistant's+ * 768-d SigLIP2 embedding space. */ const val EMBEDDER_VERSION = 2
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 dbdc91a344..65b7ec5f07 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/FaceRecognizer.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/FaceRecognizer.kt@@ -8,17 +8,17 @@ 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 org.tensorflow.lite.Interpreter-import java.io.FileInputStream import java.nio.ByteBuffer import java.nio.ByteOrder-import java.nio.MappedByteBuffer-import java.nio.channels.FileChannel+import java.nio.FloatBuffer import kotlin.math.sqrt /**@@ -33,10 +33,12 @@ import kotlin.math.sqrt * 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],- * MobileFaceNet) runs on the aligned crop via a LiteRT (formerly TensorFlow- * Lite) [Interpreter], so we control preprocessing. LiteRT 1.x keeps the- * drop-in `org.tensorflow.lite.Interpreter` API. Pixels are normalised as- * (px - 127.5) / 128.+ * **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+ * 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]). *@@ -45,17 +47,17 @@ import kotlin.math.sqrt * - [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 *- * - [EMBEDDER_ASSET] — a **MobileFaceNet** face-recognition embedder in plain- * TFLite format. Expected input: [INPUT_SIZE]x[INPUT_SIZE] RGB, normalised- * (px - 127.5) / 128; output: a 128/192/512-d float embedding (the output- * dimension is read from the model, so any of these works). The code- * L2-normalises the output itself.+ * - [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. *- * Ship a PERMISSIVELY-LICENSED (Apache-2.0 / MIT) MobileFaceNet `.tflite`- * only. This build does NOT bundle one (we removed the old general-purpose- * MobileNetV3 embedder because it is not discriminative for face identity and- * we must not silently fall back to it). Drop a verified MobileFaceNet file at- * `photos/src/main/assets/mobilefacenet.tflite`. If the input size differs+ * 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+ * **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.@@ -65,34 +67,36 @@ import kotlin.math.sqrt */ object FaceRecognizer { const val DETECTOR_ASSET = "face_detector.tflite"- const val EMBEDDER_ASSET = "mobilefacenet.tflite"+ const val EMBEDDER_ASSET = "edgeface.onnx" - /** Square input side (px) the embedder expects. MobileFaceNet is 112. */+ /** Square input side (px) the embedder expects. EdgeFace/ArcFace 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.)+ * (v1 = old MobileNetV3 general embedder; v2 = MobileFaceNet + alignment;+ * v3 = EdgeFace INT8 on ONNX Runtime.) */- const val EMBEDDER_VERSION = 2+ const val EMBEDDER_VERSION = 3 /** * Minimum cosine similarity for a face to join an existing cluster instead of- * starting a new one. Single tunable knob. For MobileFaceNet, same-person- * cosine is typically ~0.4–0.6 (very different from a general image- * embedder), so 0.5 is a sensible default: higher = stricter/more clusters,- * lower = looser/fewer clusters.+ * 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. */- const val CLUSTER_THRESHOLD = 0.5f+ const val CLUSTER_THRESHOLD = 0.55f /** * 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.6f+ const val MERGE_THRESHOLD = 0.65f private const val TAG = "FaceRecognizer" @@ -116,9 +120,11 @@ object FaceRecognizer { val bottom: Float, ) + private val env: OrtEnvironment by lazy { OrtEnvironment.getEnvironment() }+ private val lock = Any()+ @Volatile private var detector: FaceDetector? = null- @Volatile private var embedder: Interpreter? = null- @Volatile private var embeddingDim: Int = 0+ @Volatile private var embedder: OrtSession? = null @Volatile private var initFailed = false /** True only if both model assets are present in the APK. */@@ -146,29 +152,29 @@ object FaceRecognizer { .setMinDetectionConfidence(0.5f) .build(), )- val interpreter = Interpreter(- loadModelFile(app, EMBEDDER_ASSET),- Interpreter.Options().apply { setNumThreads(2) },- )- // Output shape is [1, D]; read D so any 128/192/512-d model works.- embeddingDim = interpreter.getOutputTensor(0).shape().last()- embedder = interpreter+ 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)+ }+ embedder = env.createSession(modelBytes, opts) true } catch (e: Throwable) {- Log.e(TAG, "Face models unavailable — drop $DETECTOR_ASSET and a MobileFaceNet $EMBEDDER_ASSET into photos assets (see FaceRecognizer docs).", e)+ Log.e(TAG, "Face models unavailable — drop $DETECTOR_ASSET and an EdgeFace $EMBEDDER_ASSET into photos assets (see FaceRecognizer docs).", e) detector = null+ try { embedder?.close() } catch (_: Exception) {} embedder = null initFailed = true false } } - private fun loadModelFile(context: Context, asset: String): MappedByteBuffer {- context.assets.openFd(asset).use { fd ->- FileInputStream(fd.fileDescriptor).use { input ->- return input.channel.map(FileChannel.MapMode.READ_ONLY, fd.startOffset, fd.declaredLength)- }- }+ 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. */@@ -251,23 +257,37 @@ object FaceRecognizer { } } - /** Run the embedder on an [INPUT_SIZE] aligned crop, returning the raw vector. */- private fun embed(interpreter: Interpreter, face: Bitmap): FloatArray {- val input = ByteBuffer.allocateDirect(INPUT_SIZE * INPUT_SIZE * 3 * 4).order(ByteOrder.nativeOrder())- val pixels = IntArray(INPUT_SIZE * INPUT_SIZE)+ /**+ * 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)- for (pixel in pixels) {- val r = (pixel shr 16) and 0xFF- val g = (pixel shr 8) and 0xFF- val b = pixel and 0xFF- input.putFloat((r - 127.5f) / 128f)- input.putFloat((g - 127.5f) / 128f)- input.putFloat((b - 127.5f) / 128f)+ 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+ }+ } }- input.rewind()- val output = Array(1) { FloatArray(embeddingDim) }- interpreter.run(input, output)- return output[0] } /** Expand the detector box by a small margin and clamp it to the image. */
photos/src/main/java/com/vayunmathur/photos/util/GalleryViewModel.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/GalleryViewModel.kt b/photos/src/main/java/com/vayunmathur/photos/util/GalleryViewModel.ktindex 19f7f993c7..0db1cae581 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/GalleryViewModel.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/GalleryViewModel.kt@@ -278,8 +278,8 @@ class GalleryViewModel( /** * Minimum cosine similarity for a photo to count as a semantic match. * Single most-important tunable knob. SigLIP2 is sigmoid-trained and- * 768-d, so its cosine distribution differs from the old MobileCLIP-S0- * (512-d) space — **retune this against real photos** after the move to+ * 768-d, so its cosine distribution differs from the previous 512-d+ * embedding space — **retune this against real photos** after the move to * OpenAssistant. Higher = stricter/fewer, lower = looser/more; results * are ranked and capped so the best matches still surface first. */
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 84bd94c815..cf807cce28 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.kt@@ -26,9 +26,8 @@ import androidx.work.ListenableWorker.Result as WorkResult import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.util.buildDatabase import com.vayunmathur.library.ocr.OcrEngine-import com.vayunmathur.sdk.openassistant.AssistantNotInstalledException+import com.vayunmathur.sdk.openassistant.EmbeddingImageFailedException import com.vayunmathur.sdk.openassistant.EmbeddingModelDownloadingException-import com.vayunmathur.sdk.openassistant.EmbeddingUnsupportedException import com.vayunmathur.sdk.openassistant.OpenAssistant import com.vayunmathur.photos.data.Person import com.vayunmathur.photos.data.Photo@@ -38,7 +37,9 @@ import com.vayunmathur.photos.data.PhotoDatabase import com.vayunmathur.photos.data.VideoData import android.graphics.Bitmap import android.graphics.ImageDecoder+import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope@@ -476,7 +477,8 @@ suspend fun runClipIndexing(database: PhotoDatabase, context: Context) = corouti } // If the embedder version OR the OA-provided model id changed, old embeddings- // are incompatible (e.g. 512-d MobileCLIP → 768-d SigLIP2): clear them and+ // are incompatible (e.g. the previous 512-d space → 768-d SigLIP2): clear+ // them and // re-embed every photo. Photo rows themselves (OCR text, faces) are untouched. val modelId = try { ClipEmbedder.embeddingInfo(context).modelId@@ -501,26 +503,35 @@ suspend fun runClipIndexing(database: PhotoDatabase, context: Context) = corouti for (photo in photos) { ensureActive() + val t0 = System.currentTimeMillis() val embedding = try { // OpenAssistant decodes the URI, so photos no longer decodes a bitmap. ClipEmbedder.imageEmbedding(context, photo.uri.toUri())- } catch (e: EmbeddingModelDownloadingException) {- // Models went unavailable mid-run: stop and retry later WITHOUT- // marking these photos scanned.- Log.i("ClipWorker", "Embedding models downloading; pausing indexing")- return@coroutineScope- } catch (e: AssistantNotInstalledException) {- return@coroutineScope- } catch (e: EmbeddingUnsupportedException) {+ } catch (e: EmbeddingImageFailedException) {+ // Provider is healthy but this one image couldn't be embedded (e.g.+ // decode failed): mark it scanned with no vector so we skip it rather+ // than blocking the queue on it forever.+ Log.w("ClipWorker", "Skipping un-embeddable photo ${photo.id}: ${e.message}")+ photoDao.upsertAll(listOf(photo.copy(clipEmbedding = null, clipScanned = true)))+ delay(CLIP_INTER_ITEM_DELAY_MS)+ continue+ } catch (e: TimeoutCancellationException) {+ // OpenAssistant didn't respond in time — treat as a transient outage:+ // pause WITHOUT marking scanned so these photos retry later.+ Log.w("ClipWorker", "Embedding request timed out; pausing indexing") return@coroutineScope+ } catch (e: CancellationException) {+ throw e } catch (e: Exception) {- Log.e("ClipWorker", "Error embedding photo ${photo.id}", e)- null+ // Any other failure (not installed / too old / models downloading /+ // service unreachable / load failure) is systemic: stop the run+ // WITHOUT marking scanned so these photos retry once OA is healthy.+ Log.w("ClipWorker", "Embedding unavailable; pausing indexing", e)+ return@coroutineScope } - val bytes = embedding?.let { ClipEmbedder.floatsToBytes(it) }- // Store result and mark scanned regardless of per-image outcome (mirrors OCR).- photoDao.upsertAll(listOf(photo.copy(clipEmbedding = bytes, clipScanned = true)))+ Log.d("ClipWorker", "Embedded photo ${photo.id} (${embedding.size}d) in ${System.currentTimeMillis() - t0}ms")+ photoDao.upsertAll(listOf(photo.copy(clipEmbedding = ClipEmbedder.floatsToBytes(embedding), clipScanned = true))) // Short pause between images keeps sustained CPU/battery use low. delay(CLIP_INTER_ITEM_DELAY_MS)
scripts/chess/__pycache__/generate_puzzles.cpython-312.pyc
diff --git a/scripts/chess/__pycache__/generate_puzzles.cpython-312.pyc b/scripts/chess/__pycache__/generate_puzzles.cpython-312.pycnew file mode 100644index 0000000000..0ea25be3a6Binary files /dev/null and b/scripts/chess/__pycache__/generate_puzzles.cpython-312.pyc differ
scripts/photos/README.md
diff --git a/scripts/photos/README.md b/scripts/photos/README.mdnew file mode 100644index 0000000000..60d8624ba7--- /dev/null+++ b/scripts/photos/README.md@@ -0,0 +1,51 @@+# 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.++## 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.++### Semantic (CLIP) search moved to OpenAssistant++Photos no longer bundles any CLIP/SigLIP assets. Semantic image/text search is+served by the **OpenAssistant** app, which downloads SigLIP2+(`onnx-community/siglip2-base-patch16-224-ONNX`) directly from HuggingFace at+runtime, on demand. There is nothing to prepare here for search — see+`SiglipEmbedder.kt` in the openassistant module.++## Usage++```bash+cd scripts/photos+python -m venv .venv && source .venv/bin/activate+pip install -r requirements.txt++python prepare_models.py # EdgeFace+```++The script exports the model, runs a smoke inference (asserting the 512-d+output), writes it into `photos/src/main/assets/`, and prints the final on-disk+size.++## Notes++- **Network + torch:** EdgeFace needs network access (HuggingFace) plus `torch` ++ `transformers` (the `anjith2006/edgeface` mirror bundles the model code on the+ Hub and is loaded with `trust_remote_code=True`, so no GitHub checkout is+ required). If the step can't run in your environment, run it elsewhere and copy+ the resulting binary in.+- **EdgeFace licence:** EdgeFace is released for **non-commercial research**.+ This project uses it deliberately (see `FaceRecognizer` docs). If you need a+ permissive licence, substitute a different 112x112 ArcFace-style embedder and+ update `FaceRecognizer.kt` (`EMBEDDER_ASSET`, normalisation, `EMBEDDER_VERSION`).+- **Version bumps:** changing the face model/preprocessing requires bumping+ `FaceRecognizer.EMBEDDER_VERSION` so the app rebuilds face clusters.
scripts/photos/prepare_models.py
diff --git a/scripts/photos/prepare_models.py b/scripts/photos/prepare_models.pynew file mode 100644index 0000000000..8e41fae314--- /dev/null+++ b/scripts/photos/prepare_models.py@@ -0,0 +1,179 @@+#!/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`+ 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]+ normalised (px-127.5)/127.5; output a 512-d embedding.++ 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.++Semantic photo search (image/text CLIP embedding) is **no longer prepared here**:+it moved out of Photos into the OpenAssistant app, which downloads SigLIP2+(`onnx-community/siglip2-base-patch16-224-ONNX`) directly from HuggingFace at+runtime, on demand. Photos ships no CLIP assets.++The step runs a smoke inference and asserts the expected output before the file+is accepted, then prints the final on-disk size.++Usage:+ pip install -r requirements.txt+ python prepare_models.py++Needs `huggingface_hub`, `onnx`, `onnxruntime`, `numpy`, and `torch`. If your+environment lacks network access or torch, run this in an environment that has+them; the produced binary is all the app needs.+"""+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__), "..", ".."))+ASSETS_DIR = os.path.join(REPO_ROOT, "photos", "src", "main", "assets")++# EdgeFace variant: "s" (small, gamma 0.5) is the size/accuracy sweet spot and+# outputs a 512-d embedding. We load the transformers-format mirror+# (anjith2006/edgeface), which bundles the model code + safetensors weights on+# the HuggingFace Hub, so no GitHub checkout is needed. Its preprocessor uses+# rescale 1/255 + normalize mean/std 0.5 == (px-127.5)/127.5, matching+# FaceRecognizer.embed(). See https://github.com/otroshi/edgeface for the source.+EDGEFACE_HF_REPO = "anjith2006/edgeface"+EDGEFACE_SUBFOLDER = "edgeface-s-gamma-05"+EDGEFACE_OUT = os.path.join(ASSETS_DIR, "edgeface.onnx")+FACE_INPUT_SIZE = 112+EMBED_DIM = 512+++def _mb(path: str) -> str:+ return f"{os.path.getsize(path) / (1024 * 1024):.1f} MB"+++def _load_edgeface_torch():+ """Load the pretrained EdgeFace model (eval mode) from the HuggingFace mirror.++ `anjith2006/edgeface` ships the model definition (`modeling_edgeface.py`) and+ safetensors weights on the Hub, so `trust_remote_code=True` builds the model+ without a GitHub checkout. Returns an nn.Module whose forward takes an NCHW+ `[N,3,112,112]` float tensor and yields a 512-d embedding.+ """+ import torch+ from torch import nn+ from transformers import AutoModel++ print(f"[EdgeFace] loading '{EDGEFACE_SUBFOLDER}' from {EDGEFACE_HF_REPO} ...")+ base = AutoModel.from_pretrained(+ EDGEFACE_HF_REPO,+ subfolder=EDGEFACE_SUBFOLDER,+ trust_remote_code=True,+ )+ base.eval()++ class EmbeddingWrapper(nn.Module):+ """Normalise the model output to a single 512-d embedding tensor."""++ def __init__(self, model):+ super().__init__()+ self.model = model++ def forward(self, pixel_values):+ out = self.model(pixel_values)+ if isinstance(out, torch.Tensor):+ return out+ for attr in ("image_embeds", "embeddings", "pooler_output", "last_hidden_state"):+ val = getattr(out, attr, None)+ if val is not None:+ return val+ if isinstance(out, (tuple, list)):+ return out[0]+ raise TypeError(f"Unrecognised EdgeFace output type: {type(out)}")++ wrapper = EmbeddingWrapper(base)+ wrapper.eval()++ # Probe the output shape so we fail fast on a wrong variant/wrapper.+ with torch.no_grad():+ probe = wrapper(torch.zeros(1, 3, FACE_INPUT_SIZE, FACE_INPUT_SIZE))+ assert probe.shape[-1] == EMBED_DIM, (+ f"[EdgeFace] expected {EMBED_DIM}-d embedding, got {tuple(probe.shape)}"+ )+ print(f"[EdgeFace] loaded, embedding shape {tuple(probe.shape)}")+ return wrapper+++def prepare_edgeface() -> None:+ """Export EdgeFace to ONNX, INT8-quantize it, and validate."""+ 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,+ )+ print(f"[EdgeFace] wrote {EDGEFACE_OUT} ({_mb(EDGEFACE_OUT)})")++ sess = ort.InferenceSession(EDGEFACE_OUT, providers=["CPUExecutionProvider"])+ in_name = sess.get_inputs()[0].name+ dummy = np.zeros((1, 3, FACE_INPUT_SIZE, FACE_INPUT_SIZE), dtype=np.float32)+ out = sess.run(None, {in_name: dummy})[0]+ assert out.shape[-1] == EMBED_DIM, f"[EdgeFace] expected {EMBED_DIM}-d output, got {out.shape}"+ print(f"[EdgeFace] smoke inference OK, output shape {out.shape}")+++def main() -> int:+ argparse.ArgumentParser(+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter+ ).parse_args()++ try:+ prepare_edgeface()+ except Exception as e: # noqa: BLE001+ print(f"[EdgeFace] 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}")+ 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.")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())
scripts/photos/requirements.txt
diff --git a/scripts/photos/requirements.txt b/scripts/photos/requirements.txtnew file mode 100644index 0000000000..96ad120d8e--- /dev/null+++ b/scripts/photos/requirements.txt@@ -0,0 +1,12 @@+# CLIP vision encoder download + validation (Xenova/mobileclip_s0).+huggingface_hub>=0.23+onnx>=1.16+onnxruntime>=1.19+numpy>=1.24++# EdgeFace export only (HuggingFace transformers mirror -> ONNX before INT8).+# Heavy; skip if you only run `prepare_models.py --clip`.+torch>=2.2+transformers>=4.44+timm>=1.0+safetensors>=0.4
sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/Exceptions.kt
diff --git a/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/Exceptions.kt b/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/Exceptions.ktindex bdf36564ad..4ff490ce41 100644--- a/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/Exceptions.kt+++ b/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/Exceptions.kt@@ -14,6 +14,14 @@ class AssistantException(message: String) : Exception(message) class EmbeddingUnsupportedException : Exception("The installed OpenAssistant is too old to provide embeddings; please update it") +/**+ * OpenAssistant is up and the models are ready, but this specific request could+ * not be embedded (e.g. the image failed to decode on OpenAssistant's side).+ * Unlike the other embedding exceptions this is **per-item**: the caller should+ * skip this item rather than treat the whole provider as unavailable.+ */+class EmbeddingImageFailedException(message: String) : Exception(message)+ /** * OpenAssistant accepted the embed request but the SigLIP2 models are still * downloading on demand, so no vector is available yet. [progress] is a 0..1
sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/OpenAssistant.kt
diff --git a/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/OpenAssistant.kt b/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/OpenAssistant.ktindex eaa52fcfdc..e441c5f273 100644--- a/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/OpenAssistant.kt+++ b/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/OpenAssistant.kt@@ -1,5 +1,6 @@ package com.vayunmathur.sdk.openassistant +import android.content.ClipData import android.content.ComponentName import android.content.Context import android.content.Intent@@ -198,7 +199,13 @@ class OpenAssistant(private val context: Context, private val timeoutMs: Long = } else -> { val error = data?.getString("error") ?: "Embedding failed"- cont.resumeWithException(AssistantException(error))+ // per_item = the provider is up but this specific request+ // couldn't be embedded → caller skips just this item.+ if (data?.getBoolean("per_item") == true) {+ cont.resumeWithException(EmbeddingImageFailedException(error))+ } else {+ cont.resumeWithException(AssistantException(error))+ } } } }@@ -208,9 +215,12 @@ class OpenAssistant(private val context: Context, private val timeoutMs: Long = putExtra("embed_mode", mode) if (text != null) putExtra("user_text", text) if (uri != null) {- // Single content:// URI in an ArrayList<Uri>, granted read so- // the exported service can openInputStream it (copyUriToFile).+ // Single content:// URI in an ArrayList<Uri> for the service to+ // read, AND in ClipData so FLAG_GRANT_READ_URI_PERMISSION+ // actually grants access — the grant flag applies to the+ // intent's data/ClipData, NOT to URIs buried in extras. putParcelableArrayListExtra("image_uris", arrayListOf(uri))+ clipData = ClipData.newRawUri("image_uris", uri) addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) } putExtra("RECEIVER", receiver as ResultReceiver)