photos: redesign face grouping (5-point alignment, quality gate, batch average linkage)
- Commit
3cfae06e00db17f7c724d4e9b76f6dec77e5fa8a- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-06 22:20 UTC (29 days ago)
- Parents
aaf9c05
The old grouping assigned each face greedily to the nearest running-mean centroid and never revisited it, then chain-merged centroids. One wrong join dragged a centroid toward another person, so people were both split and merged, and results depended on scan order. - library/ml: SCRFD now returns all five landmarks across JNI (15 floats per face; packing moved to post::nms_extra::flatten with a host test). - Alignment: least-squares similarity transform of all five landmarks onto the ArcFace template; no unaligned fallback. EMBEDDER_VERSION 7 -> 8. - Quality: only faces >= 48 px, score >= 0.7, near-frontal and sharp may form people; others are stored and can only attach. Face decode 720 -> 1280 px. - Grouping: scanning stores faces unassigned; a batch pass regroups all stored embeddings: mutual-kNN micro-clusters, then exact average linkage (NN-chain on per-cluster sums), min 3 faces unless named, strict attach for low-quality faces. Differently named groups never merge. Person ids and names carry across regroups by face overlap. - DB 18 -> 19: PhotoFace.clusterId nullable, new clusterable column; tables recreated and rescanned (names reset once). - UI: People hides unnamed groups under 3 faces; unassigned face boxes are not tappable. Thresholds are untuned defaults in FaceClusterConfig / FaceQuality. Tested with synthetic-embedding unit tests (incl. bridge faces between two people); not yet run on a device.
Diff
library/ml/src/main/java/com/vayunmathur/library/ml/Faces.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/Faces.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/Faces.ktindex 7f3f0e2363..5dd695d47c 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/Faces.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/Faces.kt@@ -43,6 +43,18 @@ data class DetectedFaceBox( val rightEyeY: Float, /** Detector confidence, post-sigmoid. */ val score: Float,+ /** Nose tip. */+ val noseX: Float,+ /** Nose tip. */+ val noseY: Float,+ /** Left mouth corner, in the detector's keypoint order. */+ val mouthLeftX: Float,+ /** Left mouth corner. */+ val mouthLeftY: Float,+ /** Right mouth corner. */+ val mouthRightX: Float,+ /** Right mouth corner. */+ val mouthRightY: Float, ) /**@@ -106,7 +118,7 @@ class FaceDetector(context: Context, assetName: String = DEFAULT_ASSET) : AutoCl } } - /** Nine floats per face; see `MlNative.detectFaces` for the order. */+ /** Fifteen floats per face; see `MlNative.detectFaces` for the order. */ private fun unpack(flat: FloatArray): List<DetectedFaceBox> { if (flat.size % FLOATS_PER_FACE != 0) { Log.error(TAG, "${flat.size} floats is not a whole number of faces")@@ -125,6 +137,12 @@ class FaceDetector(context: Context, assetName: String = DEFAULT_ASSET) : AutoCl rightEyeX = flat[at + 6], rightEyeY = flat[at + 7], score = flat[at + 8],+ noseX = flat[at + 9],+ noseY = flat[at + 10],+ mouthLeftX = flat[at + 11],+ mouthLeftY = flat[at + 12],+ mouthRightX = flat[at + 13],+ mouthRightY = flat[at + 14], ) at += FLOATS_PER_FACE }@@ -142,7 +160,7 @@ class FaceDetector(context: Context, assetName: String = DEFAULT_ASSET) : AutoCl /** What `:photos` ships. */ const val DEFAULT_ASSET: String = "scrfd_500m.maml" private const val TAG = "FaceDetector"- private const val FLOATS_PER_FACE = 9+ private const val FLOATS_PER_FACE = 15 } }
library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt
diff --git a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.ktindex 7d5da82592..6f0de637d5 100644--- a/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt+++ b/library/ml/src/main/java/com/vayunmathur/library/ml/MlNative.kt@@ -545,10 +545,11 @@ internal object MlNative { external fun destroyWhisper(handle: Long) /**- * Detect faces in [pixels] and return them flattened, nine floats per face.+ * Detect faces in [pixels] and return them flattened, fifteen floats per face. * * The layout per face is `left, top, right, bottom, leftEyeX, leftEyeY, rightEyeX,- * rightEyeY, score`, every coordinate a fraction of the bitmap. Letterboxing, the+ * rightEyeY, score, noseX, noseY, mouthLeftX, mouthLeftY, mouthRightX, mouthRightY`,+ * every coordinate a fraction of the bitmap. Letterboxing, the * forward pass, the anchor decode and non-maximum suppression all happen natively, so * this crosses the boundary once per bitmap rather than once per proposal. *
library/ml/src/main/rust/src/bridge.rs
diff --git a/library/ml/src/main/rust/src/bridge.rs b/library/ml/src/main/rust/src/bridge.rsindex d5a258a11e..d259209c93 100644--- a/library/ml/src/main/rust/src/bridge.rs+++ b/library/ml/src/main/rust/src/bridge.rs@@ -264,11 +264,11 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_segment<' .resolve::<jni::errors::LogErrorAndDefault>() } -/// Detect faces in `pixels` and return them flattened, nine floats each.+/// Detect faces in `pixels` and return them flattened, fifteen floats each. /// /// The layout per face is `left, top, right, bottom, leftEyeX, leftEyeY, rightEyeX,-/// rightEyeY, score` — deliberately the argument order of the old ncnn JNI's `Face`-/// constructor, so the Kotlin mapping is a straight read and a reviewer can diff the two.+/// rightEyeY, score, noseX, noseY, mouthLeftX, mouthLeftY, mouthRightX, mouthRightY`.+/// Every coordinate /// Every coordinate is a fraction of the source bitmap, so it survives the caller /// resizing. ///@@ -322,9 +322,6 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_detectFac .resolve::<jni::errors::LogErrorAndDefault>() } -/// Nine floats per detected face. See the entry point above for the order.-const FACE_FLOATS: usize = 9;- /// Letterbox, run, decode, suppress, and flatten. fn detect(state: &mut Handle, width: u32, height: u32) -> Result<Vec<f32>, String> { let fit = Letterbox::square(width, height, scrfd::LONG_SIDE)?;@@ -353,25 +350,11 @@ fn detect(state: &mut Handle, width: u32, height: u32) -> Result<Vec<f32>, Strin nms::suppress(&mut faces, nms::IOU_THRESHOLD); nms::to_source(&mut faces, &fit, width, height); - let mut flat = Vec::with_capacity(faces.len() * FACE_FLOATS);- for face in &faces {- flat.extend_from_slice(&face.bounds);- // Landmarks 0 and 1 are the eyes, which is all the alignment in- // `FaceRecognizer.alignFace` uses. The nose and mouth corners are decoded and- // dropped here rather than carried across a boundary nothing reads them through.- let (left_eye, right_eye) = match (face.keypoints.first(), face.keypoints.get(1)) {- (Some(a), Some(b)) => (*a, *b),- _ => ((0.0, 0.0), (0.0, 0.0)),- };- flat.push(left_eye.0);- flat.push(left_eye.1);- flat.push(right_eye.0);- flat.push(right_eye.1);- flat.push(face.score);- }- Ok(flat)+ Ok(nms::flatten(&faces)) } +/// Both PP-OCRv5 networks+ /// Both PP-OCRv5 networks and the dictionary between them. A separate handle type from /// [`Handle`] because it owns two `Net`s, and separately destroyed for the same reason: /// one `destroy` that guessed which kind of pointer it had been given would be a
library/ml/src/main/rust/src/post/nms.rs
diff --git a/library/ml/src/main/rust/src/post/nms.rs b/library/ml/src/main/rust/src/post/nms.rsindex 537eb91760..4fc1887e6a 100644--- a/library/ml/src/main/rust/src/post/nms.rs+++ b/library/ml/src/main/rust/src/post/nms.rs@@ -167,7 +167,7 @@ pub fn decode( Ok(()) } -pub use super::nms_extra::suppress;+pub use super::nms_extra::{flatten, suppress, FACE_FLOATS}; /// Map coordinates out of the letterboxed space and back onto the source image. ///
library/ml/src/main/rust/src/post/nms_extra.rs
diff --git a/library/ml/src/main/rust/src/post/nms_extra.rs b/library/ml/src/main/rust/src/post/nms_extra.rsindex 1f527e382a..ef23ad9e24 100644--- a/library/ml/src/main/rust/src/post/nms_extra.rs+++ b/library/ml/src/main/rust/src/post/nms_extra.rs@@ -26,3 +26,41 @@ pub fn suppress(faces: &mut Vec<Face>, threshold: f32) { } *faces = kept; }++/// Floats per face in [`flatten`]'s output, which is the JNI wire format.+pub const FACE_FLOATS: usize = 15;++/// Pack faces for JNI: bounds, both eyes, score, then nose and the two mouth corners.+///+/// Keypoints keep SCRFD's order (left eye, right eye, nose, mouth left, mouth right); the+/// Kotlin side aligns on all five, so none are dropped.+pub fn flatten(faces: &[Face]) -> Vec<f32> {+ let mut flat = Vec::with_capacity(faces.len() * FACE_FLOATS);+ for face in faces {+ let [left_eye, right_eye, nose, mouth_left, mouth_right] = face.keypoints;+ flat.extend_from_slice(&face.bounds);+ flat.extend_from_slice(&[left_eye.0, left_eye.1, right_eye.0, right_eye.1, face.score]);+ flat.extend_from_slice(&[nose.0, nose.1, mouth_left.0, mouth_left.1, mouth_right.0, mouth_right.1]);+ }+ flat+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn flatten_packs_bounds_eyes_score_then_nose_and_mouth() {+ let face = Face {+ score: 0.9,+ bounds: [0.1, 0.2, 0.3, 0.4],+ keypoints: [(1.0, 2.0), (3.0, 4.0), (5.0, 6.0), (7.0, 8.0), (9.0, 10.0)],+ };+ let flat = flatten(&[face, face]);+ assert_eq!(flat.len(), 2 * FACE_FLOATS);+ assert_eq!(+ &flat[..FACE_FLOATS],+ &[0.1, 0.2, 0.3, 0.4, 1.0, 2.0, 3.0, 4.0, 0.9, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]+ );+ }+}
photos/AGENTS.md
diff --git a/photos/AGENTS.md b/photos/AGENTS.mdindex 9651f1e93c..3c3c21ea76 100644--- a/photos/AGENTS.md+++ b/photos/AGENTS.md@@ -67,9 +67,13 @@ _Install: ./install photos (dev by default)._ - com/vayunmathur/photos/data/RedEyeData.kt - com/vayunmathur/photos/data/VideoEditState.kt - com/vayunmathur/photos/data/BitmapExtensions.kt-### domain/ — OCR + motion-photo helpers (pure logic)+### domain/ — OCR, motion-photo and face-grouping logic (pure) - com/vayunmathur/photos/domain/PhotoOcr.kt - com/vayunmathur/photos/domain/MotionPhotoXmp.kt+- com/vayunmathur/photos/domain/FaceAlignment.kt — five-point ArcFace alignment+- com/vayunmathur/photos/domain/FaceQuality.kt — which faces may form people+- com/vayunmathur/photos/domain/FaceClustering.kt — batch average-linkage grouping+- com/vayunmathur/photos/domain/FaceClusterIdentity.kt — keeps person ids/names across regroups ### glance/ — home widget - com/vayunmathur/photos/glance/PhotoGlanceWidget.kt - com/vayunmathur/photos/glance/PhotoGlanceWidgetReceiver.kt
photos/src/main/java/com/vayunmathur/photos/data/FaceData.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/FaceData.kt b/photos/src/main/java/com/vayunmathur/photos/data/FaceData.ktindex d10f65a807..bb6d101e7f 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/FaceData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/FaceData.kt@@ -9,13 +9,12 @@ import androidx.room3.Query import kotlinx.coroutines.flow.Flow /**- * One person discovered by on-device face clustering. Faces whose embeddings are- * close enough (cosine similarity, see- * [com.vayunmathur.photos.util.FaceRecognizer]) share a [Person] — a cluster is- * "the same face seen across photos", found without any supervision.+ * One person found by face clustering (see [com.vayunmathur.photos.domain.clusterFaces]). *- * [centroid] is the running mean of every face embedding in the cluster, packed- * as bytes; it is updated incrementally as new faces are added.+ * [centroid] is the normalised mean of the person's clusterable face embeddings, packed+ * as bytes, and [faceCount] counts every face assigned to it; both are rewritten by each+ * clustering pass. The row id survives re-clustering when the new cluster mostly holds+ * this person's faces ([com.vayunmathur.photos.domain.resolveIdentities]). * * [name] is the one piece of face data the user supplies, from the contact * picker, and the only one that cannot be regenerated by re-scanning. It is null@@ -31,9 +30,11 @@ data class Person( ) /**- * A face detected in a library photo. [clusterId] is the [Person] it was- * grouped into. [embedding] is kept so faces can be re-clustered later without- * re-scanning the original photo.+ * A face detected in a library photo. [clusterId] is the [Person] it was grouped into,+ * or null if it belongs to no person. [embedding] is kept so every clustering pass can+ * re-group all faces without re-scanning photos. [clusterable] records whether the face+ * passed [com.vayunmathur.photos.domain.FaceQuality]; only clusterable faces form+ * persons, the rest can only attach to one. * * [left]/[top]/[right]/[bottom] are the detector's box normalised 0..1, and * [srcWidth]/[srcHeight] are the dimensions of the bitmap it was measured@@ -46,8 +47,9 @@ data class Person( data class PhotoFace( @PrimaryKey(autoGenerate = true) val id: Long = 0, val photoId: Long,- val clusterId: Long,+ val clusterId: Long?, val embedding: ByteArray,+ val clusterable: Boolean, val left: Float, val top: Float, val right: Float,@@ -66,7 +68,7 @@ data class PhotoFace( */ data class FaceGeometry( val photoId: Long,- val clusterId: Long,+ val clusterId: Long?, val left: Float, val top: Float, val right: Float,@@ -75,6 +77,14 @@ data class FaceGeometry( val srcHeight: Int, ) +/** What one clustering pass reads per face. */+data class FaceClusterRow(+ val id: Long,+ val clusterId: Long?,+ val embedding: ByteArray,+ val clusterable: Boolean,+)+ @Dao interface FaceDao { @Insert@@ -100,28 +110,13 @@ interface FaceDao { /** * Update only the columns the clustering pass owns. *- * Deliberately not an `@Update` of the whole [Person]: the indexer works- * from a snapshot loaded at scan start, so writing the entire row would- * clobber a [Person.name] the user entered *while* the scan was running- * with the stale null from that snapshot.+ * Deliberately not an `@Update` of the whole [Person]: clustering works from a+ * snapshot, so writing the entire row would clobber a [Person.name] the user+ * entered *while* it was running. */ @Query("UPDATE Person SET centroid = :centroid, faceCount = :faceCount WHERE id = :id") suspend fun updateClusterCentroid(id: Long, centroid: ByteArray, faceCount: Int) - /**- * Fold a merged cluster into the survivor [id].- *- * A name is the one thing here the user typed, so the survivor keeps its own- * if it has one and otherwise inherits [fallbackName] from the discarded- * row. `COALESCE` reads the *current* name rather than a snapshot, for the- * same reason [updateClusterCentroid] exists.- */- @Query(- "UPDATE Person SET centroid = :centroid, faceCount = :faceCount, " +- "name = COALESCE(name, :fallbackName) WHERE id = :id"- )- suspend fun mergeClusterInto(id: Long, centroid: ByteArray, faceCount: Int, fallbackName: String?)- @Insert suspend fun insertPhotoFaces(faces: List<PhotoFace>) @@ -131,9 +126,16 @@ interface FaceDao { @Query("DELETE FROM PhotoFace") suspend fun clearPhotoFaces() - /** Move every face from one cluster to another (used by the merge pass). */- @Query("UPDATE PhotoFace SET clusterId = :newId WHERE clusterId = :oldId")- suspend fun reassignCluster(oldId: Long, newId: Long)+ /** Every face's embedding and current person, for a clustering pass. */+ @Query("SELECT id, clusterId, embedding, clusterable FROM PhotoFace")+ suspend fun getClusterRows(): List<FaceClusterRow>++ @Query("UPDATE PhotoFace SET clusterId = NULL")+ suspend fun clearClusterAssignments()++ /** Keep [ids] under SQLite's bound-parameter limit; see [FaceRepository.applyClustering]. */+ @Query("UPDATE PhotoFace SET clusterId = :clusterId WHERE id IN (:ids)")+ suspend fun assignFaces(ids: List<Long>, clusterId: Long) /** * Every detected face's geometry, for grouping photos by cluster in the UI.
photos/src/main/java/com/vayunmathur/photos/data/FaceRepository.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/FaceRepository.kt b/photos/src/main/java/com/vayunmathur/photos/data/FaceRepository.ktindex b157692fdb..b69f0e2d22 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/FaceRepository.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/FaceRepository.kt@@ -19,19 +19,34 @@ class FaceRepository private constructor(context: Context) : fun personsFlow(): Flow<List<Person>> = faceDao.personsFlow() fun faceGeometryFlow(): Flow<List<FaceGeometry>> = faceDao.faceGeometryFlow()- suspend fun insertPerson(person: Person): Long = faceDao.insertPerson(person)- suspend fun updateClusterCentroid(id: Long, centroid: ByteArray, faceCount: Int) =- faceDao.updateClusterCentroid(id, centroid, faceCount)- suspend fun mergeClusterInto(id: Long, centroid: ByteArray, faceCount: Int, fallbackName: String?) =- faceDao.mergeClusterInto(id, centroid, faceCount, fallbackName) suspend fun getPersons(): List<Person> = faceDao.getPersons() suspend fun clearPersons() = faceDao.clearPersons()- suspend fun deletePerson(id: Long) = faceDao.deletePerson(id) suspend fun setPersonName(id: Long, name: String?) = faceDao.setPersonName(id, name) suspend fun clearPhotoFaces() = faceDao.clearPhotoFaces()- suspend fun reassignCluster(oldId: Long, newId: Long) = faceDao.reassignCluster(oldId, newId)+ suspend fun getClusterRows(): List<FaceClusterRow> = faceDao.getClusterRows() suspend fun photoIdsForCluster(clusterId: Long): List<Long> = faceDao.photoIdsForCluster(clusterId) + /**+ * Replace every face's person assignment with one clustering pass's result, in one+ * transaction so the People view never sees a half-applied regrouping.+ *+ * Kept persons only get their centroid and count rewritten, so a name entered during+ * the pass survives; new persons start unnamed.+ */+ suspend fun applyClustering(persons: List<ResolvedPersonRow>, deletedPersonIds: List<Long>) =+ db.withWriteTransaction {+ faceDao.clearClusterAssignments()+ deletedPersonIds.forEach { faceDao.deletePerson(it) }+ for (person in persons) {+ val id = person.personId?.also {+ faceDao.updateClusterCentroid(it, person.centroid, person.faceIds.size)+ } ?: faceDao.insertPerson(+ Person(centroid = person.centroid, faceCount = person.faceIds.size, name = null),+ )+ person.faceIds.chunked(ASSIGN_CHUNK).forEach { faceDao.assignFaces(it, id) }+ }+ }+ /** * Commit one batch of face scanning atomically: replace the face rows for * [photoIds] and mark those photos scanned in the same transaction.@@ -49,6 +64,9 @@ class FaceRepository private constructor(context: Context) : } companion object {+ /** Below SQLite's 999 bound-parameter limit, leaving room for the cluster id. */+ private const val ASSIGN_CHUNK = 900+ @Volatile private var instance: FaceRepository? = null @@ -58,3 +76,6 @@ class FaceRepository private constructor(context: Context) : } } }++/** One person to write: [personId] null means insert a new row. */+class ResolvedPersonRow(val personId: Long?, val centroid: ByteArray, val faceIds: List<Long>)
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 f6aec54b13..859846e873 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt@@ -284,7 +284,7 @@ data class ExifResult( val pano: PanoData?, ) -@Database(entities = [Photo::class, Person::class, PhotoFace::class], version = 18, exportSchema = false)+@Database(entities = [Photo::class, Person::class, PhotoFace::class], version = 19, exportSchema = false) abstract class PhotoDatabase : RoomDatabase() { abstract fun photoDao(): PhotoDao abstract fun photoScanDao(): PhotoScanDao@@ -295,7 +295,7 @@ abstract class PhotoDatabase : RoomDatabase() { MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4, MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16,- MIGRATION_16_17, MIGRATION_17_18,+ MIGRATION_16_17, MIGRATION_17_18, MIGRATION_18_19, ) } }@@ -378,6 +378,31 @@ val MIGRATION_17_18 = Migration(17, 18) { it.execSQL("ALTER TABLE Photo ADD COLUMN album TEXT") } +val MIGRATION_18_19 = Migration(18, 19) {+ // Face grouping was rebuilt: faces are aligned on five landmarks (new embeddings),+ // carry a quality flag, and are clustered in one batch pass where a face may belong+ // to no person (clusterId NULL). SQLite cannot relax NOT NULL in place, and every+ // embedding is stale anyway, so both tables are dropped, recreated and re-derived+ // by the background indexer, as in MIGRATION_15_16. Person names are cleared;+ // accepted. SQL mirrors Room's generated schema exactly so schema validation passes.+ it.execSQL("DROP TABLE IF EXISTS Person")+ it.execSQL("DROP TABLE IF EXISTS PhotoFace")+ it.execSQL(+ "CREATE TABLE IF NOT EXISTS `Person` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " ++ "`centroid` BLOB NOT NULL, `faceCount` INTEGER NOT NULL, `name` TEXT)"+ )+ it.execSQL(+ "CREATE TABLE IF NOT EXISTS `PhotoFace` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " ++ "`photoId` INTEGER NOT NULL, `clusterId` INTEGER, `embedding` BLOB NOT NULL, " ++ "`clusterable` INTEGER NOT NULL, " ++ "`left` REAL NOT NULL, `top` REAL NOT NULL, `right` REAL NOT NULL, `bottom` REAL NOT NULL, " ++ "`srcWidth` INTEGER NOT NULL, `srcHeight` INTEGER NOT NULL)"+ )+ it.execSQL("CREATE INDEX IF NOT EXISTS `index_PhotoFace_photoId` ON `PhotoFace` (`photoId`)")+ it.execSQL("CREATE INDEX IF NOT EXISTS `index_PhotoFace_clusterId` ON `PhotoFace` (`clusterId`)")+ it.execSQL("UPDATE Photo SET faceScanned = 0")+}+ val MIGRATION_8_9 = Migration(8, 9) { // Move OCR text off the FTS side-table and onto the Photo row so search is a // plain case-insensitive LIKE (no external inference service). ocrScanned
photos/src/main/java/com/vayunmathur/photos/domain/FaceAlignment.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/domain/FaceAlignment.kt b/photos/src/main/java/com/vayunmathur/photos/domain/FaceAlignment.ktnew file mode 100644index 0000000000..f5b2fef9c8--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/domain/FaceAlignment.kt@@ -0,0 +1,53 @@+package com.vayunmathur.photos.domain++/** Side of the square crop the face embedder takes. */+const val ALIGNED_FACE_SIZE = 112++/**+ * ArcFace's five-point template in a [ALIGNED_FACE_SIZE] crop, interleaved `x, y`:+ * left eye, right eye, nose, left mouth corner, right mouth corner. The embedder was+ * trained on crops warped onto exactly these points (insightface `norm_crop`).+ */+val ARCFACE_TEMPLATE: FloatArray = floatArrayOf(+ 38.2946f, 51.6963f,+ 73.5318f, 51.5014f,+ 56.0252f, 71.7366f,+ 41.5493f, 92.3655f,+ 70.7299f, 92.2041f,+)++/**+ * Least-squares similarity transform (rotation, uniform scale, translation; no+ * reflection) taking the interleaved points [src] onto [dst].+ *+ * Returns `[a, b, tx, c, d, ty]` with `x' = a·x + b·y + tx`, `y' = c·x + d·y + ty`, the+ * order `android.graphics.Matrix.setValues` reads, or null when [src] has no spread.+ */+fun similarityTransform(src: FloatArray, dst: FloatArray): FloatArray? {+ require(src.size == dst.size && src.size >= 4 && src.size % 2 == 0)+ val n = src.size / 2+ var sx = 0f; var sy = 0f; var dx = 0f; var dy = 0f+ for (i in 0 until n) {+ sx += src[2 * i]; sy += src[2 * i + 1]+ dx += dst[2 * i]; dy += dst[2 * i + 1]+ }+ sx /= n; sy /= n; dx /= n; dy /= n++ var dot = 0f; var cross = 0f; var spread = 0f+ for (i in 0 until n) {+ val px = src[2 * i] - sx+ val py = src[2 * i + 1] - sy+ val qx = dst[2 * i] - dx+ val qy = dst[2 * i + 1] - dy+ dot += px * qx + py * qy+ cross += px * qy - py * qx+ spread += px * px + py * py+ }+ if (spread < 1e-6f) return null+ val a = dot / spread+ val c = cross / spread+ return floatArrayOf(+ a, -c, dx - (a * sx - c * sy),+ c, a, dy - (c * sx + a * sy),+ )+}
photos/src/main/java/com/vayunmathur/photos/domain/FaceClusterIdentity.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/domain/FaceClusterIdentity.kt b/photos/src/main/java/com/vayunmathur/photos/domain/FaceClusterIdentity.ktnew file mode 100644index 0000000000..b1f1f8afcd--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/domain/FaceClusterIdentity.kt@@ -0,0 +1,46 @@+package com.vayunmathur.photos.domain++/** A cluster bound to a person row: [personId] is null when it needs a new row. */+class ResolvedPerson(val personId: Long?, val cluster: FaceCluster)++/** Persons to keep or insert, in cluster order, and person ids to delete. */+class IdentityResolution(val persons: List<ResolvedPerson>, val deletedPersonIds: List<Long>)++/**+ * Carry person ids (and so their names) across a re-cluster.+ *+ * Each new cluster takes the previous person that holds most of its faces, greedily by+ * overlap and one-to-one, so a person who splits keeps its id on the larger part and two+ * persons that merge keep the larger one's. Previous persons left unmatched are deleted.+ *+ * @param previousPersonOfFace face id → the person id it was assigned to last run.+ */+fun resolveIdentities(+ clusters: List<FaceCluster>,+ previousPersonOfFace: Map<Long, Long>,+ previousPersonIds: Collection<Long>,+): IdentityResolution {+ class Candidate(val overlap: Int, val cluster: Int, val personId: Long)++ val candidates = ArrayList<Candidate>()+ clusters.forEachIndexed { c, cluster ->+ cluster.faceIds.asList().mapNotNull { previousPersonOfFace[it] }+ .groupingBy { it }.eachCount()+ .forEach { (personId, overlap) -> candidates += Candidate(overlap, c, personId) }+ }+ candidates.sortWith(+ compareByDescending<Candidate> { it.overlap }.thenBy { it.cluster }.thenBy { it.personId },+ )++ val assigned = arrayOfNulls<Long>(clusters.size)+ val usedPersons = HashSet<Long>()+ for (candidate in candidates) {+ if (assigned[candidate.cluster] != null || candidate.personId in usedPersons) continue+ assigned[candidate.cluster] = candidate.personId+ usedPersons += candidate.personId+ }+ return IdentityResolution(+ persons = clusters.mapIndexed { c, cluster -> ResolvedPerson(assigned[c], cluster) },+ deletedPersonIds = previousPersonIds.filter { it !in usedPersons }.sorted(),+ )+}
photos/src/main/java/com/vayunmathur/photos/domain/FaceClustering.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/domain/FaceClustering.kt b/photos/src/main/java/com/vayunmathur/photos/domain/FaceClustering.ktnew file mode 100644index 0000000000..512004e740--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/domain/FaceClustering.kt@@ -0,0 +1,282 @@+package com.vayunmathur.photos.domain++import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.ensureActive+import kotlin.math.min+import kotlin.math.sqrt++/** Untuned defaults for ArcFace-style unit embeddings (MobileFaceNet w600k). */+object FaceClusterConfig {+ /** Neighbours per face considered for stage-A links. */+ const val NEIGHBORS = 5++ /** Cosine a mutual-neighbour pair needs to join a micro-cluster. Strict on purpose. */+ const val MICRO_LINK = 0.65f++ /** Average pairwise cosine two clusters need to merge. */+ const val AVERAGE_LINK = 0.35f++ /** Faces a cluster needs to become a person, unless it carries a name. */+ const val MIN_CLUSTER_FACES = 3++ /** Cosine to a person's mean an unclustered face needs to join it. */+ const val ATTACH_SIMILARITY = 0.60f++ /** How far the best person must beat the runner-up for that attach. */+ const val ATTACH_MARGIN = 0.10f+}++/**+ * One stored face. [embedding] must be L2-normalised. [label] is the name of the person+ * it belonged to in the previous run, if that person was named.+ */+class ClusterInput(+ val faceId: Long,+ val embedding: FloatArray,+ val clusterable: Boolean,+ val label: String?,+)++/** One person: its faces, the normalised mean of its clusterable faces, and its name label. */+class FaceCluster(val faceIds: LongArray, val centroid: FloatArray, val label: String?)++/** People found, plus faces that belong to none of them. */+class ClusteringResult(val clusters: List<FaceCluster>, val unassigned: LongArray)++/**+ * Group faces into people. Deterministic for a given set of faces, whatever their order.+ *+ * 1. Clusterable faces that are mutual top-[FaceClusterConfig.NEIGHBORS] neighbours with+ * cosine ≥ [FaceClusterConfig.MICRO_LINK] form micro-clusters (union-find, best links+ * first).+ * 2. Micro-clusters merge by exact average linkage (nearest-neighbour chain) while the+ * average pairwise cosine is ≥ [FaceClusterConfig.AVERAGE_LINK]. For unit vectors that+ * average is `ΣA·ΣB / (|A|·|B|)`, so only per-cluster sums are kept. Unlike a running+ * centroid with a per-face threshold, one look-alike pair cannot pull two people+ * together: every pair across the clusters counts. Faces or clusters with different+ * labels never join, in either stage.+ * 3. Clusters under [FaceClusterConfig.MIN_CLUSTER_FACES] without a label are dissolved.+ * 4. Remaining faces (low quality or dissolved) attach to a person only if clearly+ * closest to its mean; they never move a mean, so they cannot bridge two people.+ */+suspend fun clusterFaces(faces: List<ClusterInput>): ClusteringResult {+ val sorted = faces.sortedBy { it.faceId }+ val core = sorted.filter { it.clusterable }+ val merged = averageLinkage(microClusters(core), FaceClusterConfig.AVERAGE_LINK)+ .sortedBy { it.members.min() }+ val (kept, dissolved) = merged.partition {+ it.members.size >= FaceClusterConfig.MIN_CLUSTER_FACES || it.label != null+ }+ val pool = sorted.filter { !it.clusterable } + dissolved.flatMap { g -> g.members.map { core[it] } }+ return attach(kept.map { g -> g to g.members.map { core[it].faceId } }, pool.sortedBy { it.faceId })+}++private class Group(val sum: FloatArray, val members: MutableList<Int>, var label: String?)++private suspend fun microClusters(core: List<ClusterInput>): MutableList<Group> {+ val n = core.size+ if (n == 0) return mutableListOf()+ val dim = core[0].embedding.size+ val flat = FloatArray(n * dim)+ core.forEachIndexed { i, f -> f.embedding.copyInto(flat, i * dim) }+ val k = min(FaceClusterConfig.NEIGHBORS, n - 1)+ val (neighbors, sims) = topNeighbors(flat, n, dim, k)+ val (root, label) = unionWithLabels(mutualEdges(neighbors, sims, n, k), Array(n) { core[it].label })++ val byRoot = LinkedHashMap<Int, MutableList<Int>>()+ for (i in 0 until n) byRoot.getOrPut(root[i]) { mutableListOf() } += i+ return byRoot.mapTo(mutableListOf()) { (r, members) ->+ val sum = FloatArray(dim)+ for (i in members) for (d in 0 until dim) sum[d] += flat[i * dim + d]+ Group(sum, members, label[r])+ }+}++private class Edge(val a: Int, val b: Int, val sim: Float)++/** Pairs that are in each other's top-k with cosine ≥ [FaceClusterConfig.MICRO_LINK], best first. */+private fun mutualEdges(neighbors: IntArray, sims: FloatArray, n: Int, k: Int): List<Edge> {+ val edges = ArrayList<Edge>()+ for (i in 0 until n) {+ for (slot in 0 until k) {+ val j = neighbors[i * k + slot]+ val s = sims[i * k + slot]+ if (j > i && s >= FaceClusterConfig.MICRO_LINK && (0 until k).any { neighbors[j * k + it] == i }) {+ edges += Edge(i, j, s)+ }+ }+ }+ // Best links first, because the label constraint makes union order matter.+ return edges.sortedWith(compareByDescending<Edge> { it.sim }.thenBy { it.a }.thenBy { it.b })+}++/** Union-find over [edges] that never joins differently labelled sets; returns roots and root labels. */+private fun unionWithLabels(edges: List<Edge>, label: Array<String?>): Pair<IntArray, Array<String?>> {+ val parent = IntArray(label.size) { it }+ fun find(x: Int): Int {+ var r = x+ while (parent[r] != r) { parent[r] = parent[parent[r]]; r = parent[r] }+ return r+ }+ for (edge in edges) {+ val ri = find(edge.a)+ val rj = find(edge.b)+ if (ri == rj || !compatible(label[ri], label[rj])) continue+ parent[rj] = ri+ label[ri] = label[ri] ?: label[rj]+ }+ return IntArray(label.size) { find(it) } to label+}++private fun compatible(a: String?, b: String?) = a == null || b == null || a == b++/** Each row's [k] most similar other rows, best first; ties keep the lower index. */+private suspend fun topNeighbors(flat: FloatArray, n: Int, dim: Int, k: Int): Pair<IntArray, FloatArray> {+ val neighbors = IntArray(n * k) { -1 }+ val sims = FloatArray(n * k) { Float.NEGATIVE_INFINITY }+ if (k <= 0) return neighbors to sims+ val workers = Runtime.getRuntime().availableProcessors().coerceIn(1, n)+ val chunk = (n + workers - 1) / workers+ coroutineScope {+ (0 until workers).map { w ->+ async(Dispatchers.Default) {+ for (i in w * chunk until min(n, (w + 1) * chunk)) {+ ensureActive()+ val base = i * k+ for (j in 0 until n) {+ if (j == i) continue+ val s = dot(flat, i * dim, flat, j * dim, dim)+ if (s <= sims[base + k - 1]) continue+ var at = k - 1+ while (at > 0 && s > sims[base + at - 1]) {+ sims[base + at] = sims[base + at - 1]+ neighbors[base + at] = neighbors[base + at - 1]+ at--+ }+ sims[base + at] = s+ neighbors[base + at] = j+ }+ }+ }+ }.awaitAll()+ }+ return neighbors to sims+}++/**+ * Nearest-neighbour-chain average linkage, cut at [threshold].+ *+ * A group whose best link is under [threshold] can never merge above it (average linkage+ * is reducible, and the label constraint keeps it so), so it is finished immediately+ * instead of building the whole dendrogram.+ */+private fun averageLinkage(groups: MutableList<Group>, threshold: Float): List<Group> {+ val active = BooleanArray(groups.size) { true }+ var remaining = groups.size+ var lowest = 0+ val chain = ArrayList<Int>()+ val done = ArrayList<Group>()+ while (remaining > 0) {+ if (chain.isEmpty()) {+ while (!active[lowest]) lowest+++ chain += lowest+ }+ val a = chain.last()+ val prev = if (chain.size >= 2) chain[chain.size - 2] else -1+ val (best, bestSim) = nearest(groups, active, a, prev)+ when {+ best < 0 || bestSim < threshold -> {+ done += groups[a]+ active[a] = false+ remaining--+ chain.removeAt(chain.size - 1)+ }+ best == prev -> {+ chain.removeAt(chain.size - 1)+ chain.removeAt(chain.size - 1)+ active[merge(groups, a, prev)] = false+ remaining--+ }+ else -> chain += best+ }+ }+ return done+}++/** [a]'s most-linked active group; ties go to [prev] so the chain cannot cycle. */+private fun nearest(groups: List<Group>, active: BooleanArray, a: Int, prev: Int): Pair<Int, Float> {+ var best = prev+ var bestSim = if (prev >= 0) linkage(groups[a], groups[prev]) else Float.NEGATIVE_INFINITY+ for (b in groups.indices) {+ if (!active[b] || b == a || b == prev) continue+ val s = linkage(groups[a], groups[b])+ if (s > bestSim) { bestSim = s; best = b }+ }+ return best to bestSim+}++/** Fold the higher-indexed of [a] and [b] into the other; returns the index folded away. */+private fun merge(groups: List<Group>, a: Int, b: Int): Int {+ val (keep, drop) = if (a < b) a to b else b to a+ val g = groups[keep]+ val other = groups[drop]+ for (d in g.sum.indices) g.sum[d] += other.sum[d]+ g.members += other.members+ g.label = g.label ?: other.label+ return drop+}++private fun linkage(a: Group, b: Group): Float {+ if (!compatible(a.label, b.label)) return Float.NEGATIVE_INFINITY+ return dot(a.sum, 0, b.sum, 0, a.sum.size) / (a.members.size.toFloat() * b.members.size)+}++private fun attach(kept: List<Pair<Group, List<Long>>>, pool: List<ClusterInput>): ClusteringResult {+ val centroids = kept.map { normalized(it.first.sum) }+ val attached = List(kept.size) { mutableListOf<Long>() }+ val unassigned = ArrayList<Long>()+ for (face in pool) {+ var best = -1+ var bestSim = -1f+ var second = -1f+ for ((c, centroid) in centroids.withIndex()) {+ val label = kept[c].first.label+ if (!compatible(face.label, label)) continue+ val s = dot(face.embedding, 0, centroid, 0, centroid.size)+ if (s > bestSim) { second = bestSim; bestSim = s; best = c } else if (s > second) second = s+ }+ if (best >= 0 && bestSim >= FaceClusterConfig.ATTACH_SIMILARITY &&+ bestSim - second >= FaceClusterConfig.ATTACH_MARGIN+ ) {+ attached[best] += face.faceId+ } else {+ unassigned += face.faceId+ }+ }+ val clusters = kept.mapIndexed { c, (group, ids) ->+ FaceCluster((ids + attached[c]).sorted().toLongArray(), centroids[c], group.label)+ }+ return ClusteringResult(clusters, unassigned.toLongArray())+}++private fun normalized(v: FloatArray): FloatArray {+ val norm = sqrt(dot(v, 0, v, 0, v.size))+ return if (norm == 0f) v.copyOf() else FloatArray(v.size) { v[it] / norm }+}++private fun dot(a: FloatArray, aOff: Int, b: FloatArray, bOff: Int, len: Int): Float {+ var s0 = 0f; var s1 = 0f; var s2 = 0f; var s3 = 0f+ var d = 0+ while (d + 3 < len) {+ s0 += a[aOff + d] * b[bOff + d]+ s1 += a[aOff + d + 1] * b[bOff + d + 1]+ s2 += a[aOff + d + 2] * b[bOff + d + 2]+ s3 += a[aOff + d + 3] * b[bOff + d + 3]+ d += 4+ }+ while (d < len) { s0 += a[aOff + d] * b[bOff + d]; d++ }+ return (s0 + s1) + (s2 + s3)+}
photos/src/main/java/com/vayunmathur/photos/domain/FaceQuality.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/domain/FaceQuality.kt b/photos/src/main/java/com/vayunmathur/photos/domain/FaceQuality.ktnew file mode 100644index 0000000000..37d652b523--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/domain/FaceQuality.kt@@ -0,0 +1,76 @@+package com.vayunmathur.photos.domain++import kotlin.math.abs+import kotlin.math.min+import kotlin.math.sqrt++/**+ * Whether a detected face is reliable enough to *form* person clusters.+ *+ * Small, blurry, low-confidence and side-on faces give embeddings that sit between+ * identities and bridge them, so they are kept out of cluster formation. They can still+ * join an existing person later through the stricter attach step in [clusterFaces].+ * Thresholds are untuned defaults.+ */+object FaceQuality {+ /** Shortest box side, in pixels of the decoded bitmap. */+ const val MIN_FACE_SIDE_PX = 48f++ /** Detector confidence; NMS already drops anything under 0.5. */+ const val MIN_SCORE = 0.7f++ /** Nose offset from the eye midpoint, along the eye axis, as a fraction of eye distance. */+ const val MAX_YAW_RATIO = 0.35f++ /** Laplacian variance of the aligned crop's luma (0..255). Heuristic. */+ const val MIN_SHARPNESS = 20f++ /**+ * @param landmarks the five SCRFD points in pixels, interleaved, in [ARCFACE_TEMPLATE] order.+ */+ fun isClusterable(+ boxWidthPx: Float,+ boxHeightPx: Float,+ score: Float,+ landmarks: FloatArray,+ sharpness: Float,+ ): Boolean =+ min(boxWidthPx, boxHeightPx) >= MIN_FACE_SIDE_PX &&+ score >= MIN_SCORE &&+ yawRatio(landmarks) <= MAX_YAW_RATIO &&+ sharpness >= MIN_SHARPNESS++ /** 0 for a frontal face, growing as the head turns; rotation-invariant. */+ fun yawRatio(landmarks: FloatArray): Float {+ val ex = landmarks[2] - landmarks[0]+ val ey = landmarks[3] - landmarks[1]+ val eyeDistance = sqrt(ex * ex + ey * ey)+ if (eyeDistance < 1e-3f) return Float.POSITIVE_INFINITY+ val midX = (landmarks[0] + landmarks[2]) / 2f+ val midY = (landmarks[1] + landmarks[3]) / 2f+ val along = (landmarks[4] - midX) * ex + (landmarks[5] - midY) * ey+ return abs(along) / (eyeDistance * eyeDistance)+ }++ /** Variance of the 4-neighbour Laplacian over the luma of an ARGB_8888 buffer. */+ fun laplacianVariance(argb: IntArray, width: Int, height: Int): Float {+ if (width < 3 || height < 3) return 0f+ val luma = FloatArray(width * height) { i ->+ val p = argb[i]+ 0.299f * ((p shr 16) and 0xff) + 0.587f * ((p shr 8) and 0xff) + 0.114f * (p and 0xff)+ }+ var sum = 0.0+ var sumSq = 0.0+ for (y in 1 until height - 1) {+ for (x in 1 until width - 1) {+ val i = y * width + x+ val lap = luma[i - 1] + luma[i + 1] + luma[i - width] + luma[i + width] - 4f * luma[i]+ sum += lap+ sumSq += lap * lap+ }+ }+ val count = (width - 2) * (height - 2)+ val mean = sum / count+ return (sumSq / count - mean * mean).toFloat()+ }+}
photos/src/main/java/com/vayunmathur/photos/ui/FaceBoxLayer.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/FaceBoxLayer.kt b/photos/src/main/java/com/vayunmathur/photos/ui/FaceBoxLayer.ktindex 811c9b467c..410b876676 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/FaceBoxLayer.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/FaceBoxLayer.kt@@ -114,15 +114,18 @@ fun FaceBoxLayer( // One transparent tap target per face. Compose hit-tests through the // zoom graphicsLayer, so positioning these in un-zoomed container // space is correct while the photo is magnified.- Box(- Modifier- .offset { IntOffset(p.topLeft.x.roundToInt(), p.topLeft.y.roundToInt()) }- .requiredSize(- width = with(density) { p.size.width.toDp() },- height = with(density) { p.size.height.toDp() },- )- .invisibleClickable { onFaceClick(p.clusterId) }- )+ // Faces that belong to no person are outlined but not tappable.+ p.clusterId?.let { clusterId ->+ Box(+ Modifier+ .offset { IntOffset(p.topLeft.x.roundToInt(), p.topLeft.y.roundToInt()) }+ .requiredSize(+ width = with(density) { p.size.width.toDp() },+ height = with(density) { p.size.height.toDp() },+ )+ .invisibleClickable { onFaceClick(clusterId) }+ )+ } // Unnamed clusters are left as bare outlines rather than labelled // with a placeholder.@@ -166,7 +169,7 @@ fun FaceBoxLayer( /** One face resolved to on-screen pixels of the un-zoomed container. */ private data class FacePlacement(- val clusterId: Long,+ val clusterId: Long?, val name: String?, val topLeft: Offset, val size: Size,
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 f9a03fb275..481b4521e1 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/FaceRecognizer.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/FaceRecognizer.kt@@ -5,13 +5,16 @@ import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Matrix import android.graphics.Paint-import android.graphics.Rect import com.vayunmathur.library.log.Log import androidx.core.graphics.createBitmap-import androidx.core.graphics.scale import com.vayunmathur.library.ml.DetectedFaceBox import com.vayunmathur.library.ml.FaceDetector import com.vayunmathur.library.ml.FaceEmbedder+import com.vayunmathur.photos.domain.ALIGNED_FACE_SIZE+import com.vayunmathur.photos.domain.ARCFACE_TEMPLATE+import com.vayunmathur.photos.domain.FaceQuality+import com.vayunmathur.photos.domain.clusterFaces+import com.vayunmathur.photos.domain.similarityTransform import java.io.IOException import java.nio.ByteBuffer import java.nio.ByteOrder@@ -23,15 +26,16 @@ import kotlin.math.sqrt * * Pipeline: * 1. Detection — **SCRFD 500M** ([FaceDetector]) finds faces and returns a bounding box- * + 5 landmarks (the two eyes are used for alignment). Letterboxing, anchor decode- * and NMS all run natively.- * 2. Alignment — the two eye landmarks drive a similarity transform (rotate +- * uniform scale + translate) onto a canonical [INPUT_SIZE]² crop.+ * + 5 landmarks (eyes, nose, mouth corners). Letterboxing, anchor decode and NMS all+ * run natively.+ * 2. Alignment — a least-squares similarity transform maps all five landmarks onto+ * ArcFace's template ([similarityTransform]) in an [INPUT_SIZE]² crop. Faces whose+ * landmarks give no transform are skipped rather than embedded unaligned. * 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 natively. The result is L2-normalised here.- * 4. Matching — cosine similarity clusters faces of the same person- * (see [CLUSTER_THRESHOLD]).+ * 4. Quality — [FaceQuality] decides whether the face may form person clusters.+ * Grouping itself happens later, over all stored faces, in [clusterFaces]. * * The models ship as `.maml` assets in this app. They are **GPU-only**: on a device * without Vulkan fp16 compute [modelsAvailable] is false and people clustering turns off,@@ -40,7 +44,7 @@ import kotlin.math.sqrt object FaceRecognizer { /** Square input side (px) the embedder expects. ArcFace/MobileFaceNet is 112. */- const val INPUT_SIZE = 112+ const val INPUT_SIZE = ALIGNED_FACE_SIZE /** * Bump this whenever the embedder model (or preprocessing) changes. The face@@ -50,34 +54,19 @@ object FaceRecognizer { * MobileFaceNet embedder on ncnn; v7 = the same two models on `:library:ml`'s * Vulkan runtime — fp16 weights, fp32 accumulation and our own letterbox, so the * embeddings are close to v6's but not identical, and mixing the two spaces in one- * index would cluster badly.)+ * index would cluster badly; v8 = five-point alignment instead of two eyes.) */- const val EMBEDDER_VERSION = 7-- /**- * 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.5f-- /** Cosine above which two whole clusters merge in the second-pass cleanup. */- const val MERGE_THRESHOLD = 0.6f+ const val EMBEDDER_VERSION = 8 private const val TAG = "FaceRecognizer" - private const val FACE_MARGIN_FRACTION = 0.15f+ /** Below this a face is not even embedded; [FaceQuality] applies the real size floor. */ private const val MIN_FACE_SIZE_PX = 8 - // 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.+ * One detected face: its L2-normalised embedding, the detector's bounding box+ * normalised to 0..1 of the source image so it survives resizing, and whether it+ * passed [FaceQuality]. */ data class DetectedFace( val embedding: FloatArray,@@ -85,6 +74,7 @@ object FaceRecognizer { val top: Float, val right: Float, val bottom: Float,+ val clusterable: Boolean, ) @Volatile private var detector: FaceDetector? = null@@ -167,8 +157,11 @@ object FaceRecognizer { /** Embed a single detected face, or null when it should be skipped. */ private fun embedOneFace(emb: FaceEmbedder, argb: Bitmap, f: DetectedFaceBox): DetectedFace? {- val rect = faceRect(f, argb.width, argb.height) ?: return null- val aligned = alignFace(argb, f, rect) ?: return null+ val boxWidth = (f.right - f.left) * argb.width+ val boxHeight = (f.bottom - f.top) * argb.height+ if (boxWidth < MIN_FACE_SIZE_PX || boxHeight < MIN_FACE_SIZE_PX) return null+ val landmarks = landmarksPx(f, argb.width, argb.height)+ val aligned = alignFace(argb, landmarks) ?: return null try { // Null means the inference failed on this crop; the others may still be // fine, so skip this face rather than abandoning the photo.@@ -176,67 +169,42 @@ object FaceRecognizer { Log.error(TAG, "Face embedding failed") return null }+ val pixels = IntArray(INPUT_SIZE * INPUT_SIZE)+ aligned.getPixels(pixels, 0, INPUT_SIZE, 0, 0, INPUT_SIZE, INPUT_SIZE)+ val sharpness = FaceQuality.laplacianVariance(pixels, INPUT_SIZE, INPUT_SIZE) return DetectedFace( embedding = l2Normalize(raw), left = f.left, top = f.top, right = f.right, bottom = f.bottom,+ clusterable = FaceQuality.isClusterable(boxWidth, boxHeight, f.score, landmarks, sharpness), ) } finally { aligned.recycle() } } - /**- * 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, f: DetectedFaceBox, box: Rect): Bitmap? {- val hasEyes = f.leftEyeX != 0f || f.leftEyeY != 0f || f.rightEyeX != 0f || f.rightEyeY != 0f- if (hasEyes) {- // Sort eyes by x so the left-most maps to the left canonical eye.- val eyes = listOf(- 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(- LEFT_EYE_X * INPUT_SIZE, EYE_Y * INPUT_SIZE,- RIGHT_EYE_X * INPUT_SIZE, EYE_Y * INPUT_SIZE,- )- val matrix = Matrix()- if (matrix.setPolyToPoly(srcPts, 0, dstPts, 0, 2)) {- return try {- val outBmp = createBitmap(INPUT_SIZE, INPUT_SIZE)- Canvas(outBmp).drawBitmap(src, matrix, Paint(Paint.FILTER_BITMAP_FLAG))- outBmp- } catch (_: Exception) { null }- }- }+ /** The five landmarks in pixels, interleaved, in [ARCFACE_TEMPLATE] order. */+ private fun landmarksPx(f: DetectedFaceBox, w: Int, h: Int) = floatArrayOf(+ f.leftEyeX * w, f.leftEyeY * h,+ f.rightEyeX * w, f.rightEyeY * h,+ f.noseX * w, f.noseY * h,+ f.mouthLeftX * w, f.mouthLeftY * h,+ f.mouthRightX * w, f.mouthRightY * h,+ )++ /** Warp [src] so [landmarks] land on [ARCFACE_TEMPLATE]; null if they give no transform. */+ private fun alignFace(src: Bitmap, landmarks: FloatArray): Bitmap? {+ val t = similarityTransform(landmarks, ARCFACE_TEMPLATE) ?: return null+ val matrix = Matrix().apply { setValues(floatArrayOf(t[0], t[1], t[2], t[3], t[4], t[5], 0f, 0f, 1f)) } return try {- val crop = Bitmap.createBitmap(src, box.left, box.top, box.width(), box.height())- val scaled = crop.scale(INPUT_SIZE, INPUT_SIZE)- if (scaled != crop) crop.recycle()- scaled+ val out = createBitmap(INPUT_SIZE, INPUT_SIZE)+ Canvas(out).drawBitmap(src, matrix, Paint(Paint.FILTER_BITMAP_FLAG))+ out } catch (_: Exception) { null } } - /** Expand the normalised detector box by a small margin and clamp to pixels. */- private fun faceRect(f: DetectedFaceBox, w: Int, h: Int): Rect? {- val bw = (f.right - f.left) * w- val bh = (f.bottom - f.top) * h- val marginX = bw * FACE_MARGIN_FRACTION- val marginY = bh * FACE_MARGIN_FRACTION- 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 < MIN_FACE_SIZE_PX || bottom - top < MIN_FACE_SIZE_PX) return null- return Rect(left, top, right, bottom)- }- /** 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
photos/src/main/java/com/vayunmathur/photos/util/FaceWorker.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/util/FaceWorker.kt b/photos/src/main/java/com/vayunmathur/photos/util/FaceWorker.ktindex c9ba8c1a6e..62f69590a8 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/FaceWorker.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/FaceWorker.kt@@ -30,16 +30,19 @@ import com.vayunmathur.photos.data.ClipResult import com.vayunmathur.photos.data.ExifResult import com.vayunmathur.photos.data.FaceRepository import com.vayunmathur.photos.data.OcrResult-import com.vayunmathur.photos.data.Person import com.vayunmathur.photos.data.Photo import com.vayunmathur.photos.data.PhotoFace import com.vayunmathur.photos.data.PhotoScanRepository import com.vayunmathur.photos.data.PhotoScanTarget import com.vayunmathur.photos.data.PhotosRepository+import com.vayunmathur.photos.data.ResolvedPersonRow import com.vayunmathur.photos.data.VideoData import com.vayunmathur.photos.data.toJson+import com.vayunmathur.photos.domain.ClusterInput import com.vayunmathur.photos.domain.MIN_OCR_DIM+import com.vayunmathur.photos.domain.clusterFaces import com.vayunmathur.photos.domain.decodeForOcr+import com.vayunmathur.photos.domain.resolveIdentities import com.vayunmathur.photos.domain.toLayout import android.graphics.Bitmap import android.graphics.ImageDecoder@@ -95,14 +98,12 @@ class FaceWorker(context: Context, params: WorkerParameters) : CoroutineWorker(c } /**- * Scan any not-yet-scanned library photos for faces, then group each detected- * face into a [Person] cluster by cosine similarity of its embedding — all- * on-device and unsupervised.+ * Scan not-yet-scanned library photos for faces, then regroup every stored face into+ * persons — all on-device and unsupervised. *- * Clustering is greedy and incremental: each face joins the nearest existing- * cluster if similarity >= [FaceRecognizer.CLUSTER_THRESHOLD], otherwise it- * starts a new cluster. Each cluster keeps a running-mean [Person.centroid] that- * is updated as faces are added, so we never have to re-scan old photos.+ * Scanning only stores faces, unassigned. Grouping is a separate batch pass over all+ * stored embeddings ([com.vayunmathur.photos.domain.clusterFaces]) run whenever new+ * faces landed, so the result never depends on the order photos were scanned in. */ suspend fun runFaceIndexing( faceRepository: FaceRepository,@@ -130,14 +131,8 @@ suspend fun runFaceIndexing( dataStore.setLong("face_embedder_version", FaceRecognizer.EMBEDDER_VERSION.toLong()) } - // Load existing clusters into memory once; centroids are cached as floats and- // updated in place so we avoid re-reading them for every face.- val clusters = faceRepository.getPersons()- .map { Cluster(it, FaceRecognizer.bytesToFloats(it.centroid)) }- .toMutableList()- val photos = scanRepository.getUnscannedForFaces()- Log.status("FaceWorker", "Face indexing start: ${photos.size} photos to scan, ${clusters.size} existing clusters")+ Log.status("FaceWorker", "Face indexing start: ${photos.size} photos to scan") var facesTotal = 0 var photosWithFaces = 0 var decoded = 0@@ -145,10 +140,13 @@ suspend fun runFaceIndexing( // See INDEX_FLUSH_EVERY. Face rows are accumulated alongside the scanned ids and // committed with them in one transaction, so a batch is all-or-nothing: a worker // killed mid-batch cannot leave rows behind that a re-scan would duplicate.+ // CLUSTER_DIRTY is raised before rows land, so a worker killed between a commit+ // and the grouping pass still regroups on its next run. val pendingScanned = mutableListOf<Long>() val pendingFaces = mutableListOf<PhotoFace>() suspend fun flush() { if (pendingScanned.isEmpty()) return+ if (pendingFaces.isNotEmpty()) dataStore.setLong(CLUSTER_DIRTY, 1L) faceRepository.commitFaceScan(pendingScanned.toList(), pendingFaces.toList()) pendingScanned.clear() pendingFaces.clear()@@ -160,13 +158,16 @@ suspend fun runFaceIndexing( // Face indexing runs two 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.- val outcome = scanPhotoFaces(context, faceRepository, photo, clusters)+ val outcome = scanPhotoFaces(context, photo) if (outcome.didInference) { decoded++ if (outcome.faces.isNotEmpty()) { photosWithFaces++ facesTotal += outcome.faces.size- Log.status("FaceWorker", "photo ${photo.id}: ${outcome.faces.size} face(s) (running total: $facesTotal)")+ Log.status(+ "FaceWorker",+ "photo ${photo.id}: ${outcome.faces.size} face(s) (running total: $facesTotal)",+ ) } pendingFaces += outcome.faces delay(FACE_INTER_ITEM_DELAY_MS)@@ -180,34 +181,65 @@ suspend fun runFaceIndexing( } finally { withContext(NonCancellable) { runCatching { flush() } } }- val clusterCount = faceRepository.getPersons().size Log.status( "FaceWorker",- "Face indexing done: decoded=$decoded/${photos.size}, " +- "$facesTotal faces in $photosWithFaces photos, $clusterCount clusters",+ "Face scan done: decoded=$decoded/${photos.size}, $facesTotal faces in $photosWithFaces photos", ) - // Second pass: fold together clusters whose centroids ended up very close,- // which trims duplicate person-groups created early in the scan.- mergeSimilarClusters(faceRepository)+ if ((dataStore.getLong(CLUSTER_DIRTY) ?: 0L) != 0L) {+ regroupFaces(faceRepository)+ dataStore.setLong(CLUSTER_DIRTY, 0L)+ } } -/** A cluster held in memory during a scan: its [Person] row plus cached centroid. */-private class Cluster(var person: Person, var centroid: FloatArray)+/** DataStore flag: stored faces changed since the last grouping pass. */+private const val CLUSTER_DIRTY = "face_cluster_dirty"++/**+ * Regroup every stored face from scratch and write the result atomically, keeping+ * person ids (and so names) where the new groups mostly match the old ones.+ */+private suspend fun regroupFaces(faceRepository: FaceRepository) {+ val started = System.nanoTime()+ val rows = faceRepository.getClusterRows()+ val nameOfPerson = faceRepository.getPersons().associate { it.id to it.name }+ val inputs = rows.map { row ->+ ClusterInput(+ faceId = row.id,+ embedding = FaceRecognizer.bytesToFloats(row.embedding),+ clusterable = row.clusterable,+ label = row.clusterId?.let { nameOfPerson[it] },+ )+ }+ val result = withContext(Dispatchers.Default) { clusterFaces(inputs) }+ val previous = rows.mapNotNull { row -> row.clusterId?.let { row.id to it } }.toMap()+ val identities = resolveIdentities(result.clusters, previous, nameOfPerson.keys)+ faceRepository.applyClustering(+ persons = identities.persons.map {+ ResolvedPersonRow(+ personId = it.personId,+ centroid = FaceRecognizer.floatsToBytes(it.cluster.centroid),+ faceIds = it.cluster.faceIds.toList(),+ )+ },+ deletedPersonIds = identities.deletedPersonIds,+ )+ Log.status(+ "FaceWorker",+ "Face grouping: ${rows.size} faces (${rows.count { it.clusterable }} clusterable) -> " ++ "${result.clusters.size} people, ${result.unassigned.size} unassigned, " ++ "${TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started)} ms",+ )+} /** Outcome of scanning one photo for faces: whether inference ran plus any face rows. */ private class FaceScanOutcome(val didInference: Boolean, val faces: List<PhotoFace>) /**- * Decode one photo and run face detection + clustering on it. Inference- * failures yield no faces (the photo is still marked scanned by the caller).+ * Decode one photo and detect + embed its faces. Inference failures yield no faces+ * (the photo is still marked scanned by the caller). Faces are stored unassigned. */-private suspend fun scanPhotoFaces(- context: Context,- faceRepository: FaceRepository,- photo: PhotoScanTarget,- clusters: MutableList<Cluster>,-): FaceScanOutcome {+private fun scanPhotoFaces(context: Context, photo: PhotoScanTarget): FaceScanOutcome { val bitmap = try { loadBitmapForFaces(context, photo.uri.toUri()) } catch (e: IOException) {@@ -233,11 +265,11 @@ private suspend fun scanPhotoFaces( bitmap.recycle() } val rows = faces.map { face ->- val clusterId = assignToCluster(face, clusters, faceRepository) PhotoFace( photoId = photo.id,- clusterId = clusterId,+ clusterId = null, embedding = FaceRecognizer.floatsToBytes(face.embedding),+ clusterable = face.clusterable, left = face.left, top = face.top, right = face.right,@@ -252,107 +284,11 @@ private suspend fun scanPhotoFaces( 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- * the cluster (person) id the face was assigned to.- */-private suspend fun assignToCluster(- face: FaceRecognizer.DetectedFace,- clusters: MutableList<Cluster>,- faceRepository: FaceRepository,-): Long {- var best: Cluster? = null- var bestSim = FaceRecognizer.CLUSTER_THRESHOLD- for (cluster in clusters) {- val sim = FaceRecognizer.similarity(face.embedding, cluster.centroid)- if (sim >= bestSim) {- bestSim = sim- best = cluster- }- }-- if (best != null) {- val n = best.person.faceCount- val mean = FloatArray(best.centroid.size) { i ->- (best.centroid[i] * n + face.embedding[i]) / (n + 1)- }- // Centroid is a running mean kept L2-normalised so cosine stays well-behaved.- best.centroid = FaceRecognizer.l2Normalize(mean)- best.person = best.person.copy(- centroid = FaceRecognizer.floatsToBytes(best.centroid),- faceCount = n + 1,- )- // Column-targeted, so a name the user enters mid-scan is not overwritten- // by the null carried in this snapshot (loaded once at scan start).- faceRepository.updateClusterCentroid(- id = best.person.id,- centroid = best.person.centroid,- faceCount = best.person.faceCount,- )- return best.person.id- }-- val person = Person(- centroid = FaceRecognizer.floatsToBytes(face.embedding),- faceCount = 1,- name = null,- )- val id = faceRepository.insertPerson(person)- clusters += Cluster(person.copy(id = id), face.embedding.copyOf())- return id-}--/**- * Greedily merge clusters whose centroids are within [FaceRecognizer.MERGE_THRESHOLD]- * cosine of each other. Faces from the merged cluster are moved over and the- * centroid becomes the face-count-weighted, L2-normalised mean. O(n^2) over the- * (small) number of person-clusters.+ * Faces are cropped from this decode, so it is larger than the detector's 640 input:+ * faces in group shots then clear [com.vayunmathur.photos.domain.FaceQuality.MIN_FACE_SIDE_PX]+ * and their aligned crops are sharper. */-private suspend fun mergeSimilarClusters(faceRepository: FaceRepository) {- val persons = faceRepository.getPersons().toMutableList()- var i = 0- while (i < persons.size) {- var j = i + 1- while (j < persons.size) {- val a = persons[i]- val b = persons[j]- val sim = FaceRecognizer.similarity(- FaceRecognizer.bytesToFloats(a.centroid),- FaceRecognizer.bytesToFloats(b.centroid),- )- if (sim >= FaceRecognizer.MERGE_THRESHOLD) {- val na = a.faceCount- val nb = b.faceCount- val ca = FaceRecognizer.bytesToFloats(a.centroid)- val cb = FaceRecognizer.bytesToFloats(b.centroid)- val mean = FloatArray(ca.size) { (ca[it] * na + cb[it] * nb) / (na + nb) }- val merged = a.copy(- centroid = FaceRecognizer.floatsToBytes(FaceRecognizer.l2Normalize(mean)),- faceCount = na + nb,- // A name is the one thing here the user typed, so the survivor- // inherits it from whichever side has one rather than losing it- // with the discarded row.- name = a.name ?: b.name,- )- faceRepository.reassignCluster(b.id, a.id)- // The name is resolved in SQL against the row's current value, so a- // name entered since `persons` was read still wins over this snapshot.- faceRepository.mergeClusterInto(- id = a.id,- centroid = merged.centroid,- faceCount = merged.faceCount,- fallbackName = b.name,- )- faceRepository.deletePerson(b.id)- persons[i] = merged- persons.removeAt(j)- } else {- j++- }- }- i++- }-}+private const val FACE_DECODE_LONG_SIDE = 1280 private fun loadBitmapForFaces(context: Context, uri: Uri): Bitmap? { return try {@@ -361,7 +297,7 @@ private fun loadBitmapForFaces(context: Context, uri: Uri): Bitmap? { decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE decoder.isMutableRequired = false val maxDim = maxOf(info.size.width, info.size.height)- val target = 720+ val target = FACE_DECODE_LONG_SIDE if (maxDim > target) { val scale = target.toFloat() / maxDim decoder.setTargetSize(
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 26581e3fbb..deddfd24c8 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/GalleryViewModel.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/GalleryViewModel.kt@@ -1,5 +1,6 @@ package com.vayunmathur.photos.util +import com.vayunmathur.photos.domain.FaceClusterConfig import android.app.Application import android.database.sqlite.SQLiteException import android.net.Uri@@ -159,6 +160,11 @@ class GalleryViewModel( val clusterFaces = facesByCluster[person.id].orEmpty() .mapNotNull { face -> byId[face.photoId]?.let { face to it } } if (clusterFaces.isEmpty()) return@mapNotNull null+ // Tiny groups are mostly strangers in the background; a named one+ // is the user's choice and always shows.+ if (clusterFaces.size < FaceClusterConfig.MIN_CLUSTER_FACES && person.name == null) {+ return@mapNotNull null+ } val (bestFace, bestPhoto) = clusterFaces.maxBy { (face, photo) -> (face.right - face.left).toDouble() * (face.bottom - face.top) * photo.width * photo.height@@ -254,7 +260,7 @@ class GalleryViewModel( faces = rows.map { row -> FaceBox( clusterId = row.clusterId,- name = nameByCluster[row.clusterId],+ name = row.clusterId?.let { nameByCluster[it] }, left = row.left, top = row.top, right = row.right,@@ -566,9 +572,9 @@ data class PhotoFaceBoxes( val faces: List<FaceBox>, ) -/** One face box (normalised 0..1) and the cluster it was grouped into. */+/** One face box (normalised 0..1) and the person it was grouped into, if any. */ data class FaceBox(- val clusterId: Long,+ val clusterId: Long?, val name: String?, val left: Float, val top: Float,
photos/src/test/java/com/vayunmathur/photos/data/PhotosSlice1DbTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/data/PhotosSlice1DbTest.kt b/photos/src/test/java/com/vayunmathur/photos/data/PhotosSlice1DbTest.ktindex f44d7cdf12..5b195193c4 100644--- a/photos/src/test/java/com/vayunmathur/photos/data/PhotosSlice1DbTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/data/PhotosSlice1DbTest.kt@@ -23,7 +23,7 @@ import org.robolectric.annotation.Config * * These pin the worker-facing contracts: the unscanned-photo projections that drive * OCR/CLIP/face indexing, the column-targeted scan writes (which must not clobber- * sibling columns), and the cluster merge/name-preservation semantics.+ * sibling columns), and the face assignment and name-preservation semantics. */ @RunWith(RobolectricTestRunner::class) @Config(sdk = [34])@@ -272,31 +272,31 @@ class PhotosSlice1DbTest { assertContentEquals(centroid(0.9f, 0.1f), row.centroid) } + private fun face(cluster: Long?, pid: Long, clusterable: Boolean = true) = PhotoFace(+ photoId = pid, clusterId = cluster, embedding = ByteArray(8), clusterable = clusterable,+ left = 0f, top = 0f, right = 0.5f, bottom = 0.5f, srcWidth = 100, srcHeight = 100,+ )+ @Test- fun mergeClusterKeepsSurvivorNameAndFallsBack() = runTest {- val survivor = faceDao.insertPerson(Person(centroid = centroid(1f, 0f), faceCount = 2, name = "Ada"))- val merged = Person(centroid = centroid(0.9f, 0.1f), faceCount = 3, name = null)- faceDao.mergeClusterInto(survivor, merged.centroid, merged.faceCount, fallbackName = "Bo")- // Survivor already named: COALESCE keeps "Ada", not the fallback.- assertEquals("Ada", faceDao.getPersons().single().name)+ fun facesStartUnassignedAndCanBeAssignedAndCleared() = runTest {+ val a = faceDao.insertPerson(Person(centroid = centroid(1f, 0f), faceCount = 1, name = null))+ faceDao.insertPhotoFaces(listOf(face(null, 10L), face(null, 11L, clusterable = false)))+ val rows = faceDao.getClusterRows().sortedBy { it.id }+ assertEquals(listOf(null, null), rows.map { it.clusterId })+ assertEquals(listOf(true, false), rows.map { it.clusterable }) - val unnamed = faceDao.insertPerson(Person(centroid = centroid(0f, 1f), faceCount = 1, name = null))- faceDao.mergeClusterInto(unnamed, centroid(0f, 1f), 2, fallbackName = "Bo")- assertEquals("Bo", faceDao.getPersons().first { it.id == unnamed }.name)+ faceDao.assignFaces(rows.map { it.id }, a)+ assertEquals(setOf(10L, 11L), faceDao.photoIdsForCluster(a).toSet())++ faceDao.clearClusterAssignments()+ assertTrue(faceDao.photoIdsForCluster(a).isEmpty())+ assertEquals(2, faceDao.getClusterRows().size) } @Test- fun photoFacesReassignAndClear() = runTest {+ fun photoFacesDeleteByPhotoAndClear() = runTest { val a = faceDao.insertPerson(Person(centroid = centroid(1f, 0f), faceCount = 1, name = null))- val b = faceDao.insertPerson(Person(centroid = centroid(0f, 1f), faceCount = 1, name = null))- fun face(cluster: Long, pid: Long) = PhotoFace(- photoId = pid, clusterId = cluster, embedding = ByteArray(8),- left = 0f, top = 0f, right = 0.5f, bottom = 0.5f, srcWidth = 100, srcHeight = 100,- )- faceDao.insertPhotoFaces(listOf(face(a, 10L), face(b, 11L)))- faceDao.reassignCluster(b, a)- assertEquals(setOf(10L, 11L), faceDao.photoIdsForCluster(a).toSet())- assertTrue(faceDao.photoIdsForCluster(b).isEmpty())+ faceDao.insertPhotoFaces(listOf(face(a, 10L), face(a, 11L))) faceDao.deletePhotoFacesByPhotoIds(listOf(10L)) assertEquals(listOf(11L), faceDao.photoIdsForCluster(a)) faceDao.clearPhotoFaces()
photos/src/test/java/com/vayunmathur/photos/domain/FaceClusteringTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/domain/FaceClusteringTest.kt b/photos/src/test/java/com/vayunmathur/photos/domain/FaceClusteringTest.ktnew file mode 100644index 0000000000..9ce94804e9--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/domain/FaceClusteringTest.kt@@ -0,0 +1,274 @@+package com.vayunmathur.photos.domain++import kotlinx.coroutines.runBlocking+import java.util.Random+import kotlin.math.cos+import kotlin.math.sin+import kotlin.math.sqrt+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Synthetic identities: unit centres in 512-d, faces at a controlled cosine to their centre. */+private class Faces(seed: Long) {+ private val rng = Random(seed)+ private var nextId = 1L++ fun centre(): FloatArray = unit(FloatArray(DIM) { rng.nextGaussian().toFloat() })++ /** A face whose expected cosine to another face of the same centre is [sameSim]. */+ fun face(centre: FloatArray, sameSim: Float = 0.55f, clusterable: Boolean = true, label: String? = null): ClusterInput {+ val noise = unit(FloatArray(DIM) { rng.nextGaussian().toFloat() })+ val a = sqrt(sameSim)+ val b = sqrt(1f - sameSim)+ return ClusterInput(nextId++, unit(FloatArray(DIM) { a * centre[it] + b * noise[it] }), clusterable, label)+ }++ fun many(centre: FloatArray, count: Int, label: String? = null) = List(count) { face(centre, label = label) }++ fun shuffled(list: List<ClusterInput>): List<ClusterInput> = list.shuffled(rng)++ companion object {+ const val DIM = 512+ fun unit(v: FloatArray): FloatArray {+ val n = sqrt(v.fold(0f) { s, x -> s + x * x })+ return FloatArray(v.size) { v[it] / n }+ }+ fun mid(a: FloatArray, b: FloatArray) = unit(FloatArray(DIM) { a[it] + b[it] })+ }+}++private fun partition(result: ClusteringResult): Set<Set<Long>> =+ result.clusters.map { it.faceIds.toSet() }.toSet()++class FaceClusteringTest {++ @Test+ fun eachIdentityBecomesExactlyOneCluster() = runBlocking {+ val gen = Faces(1)+ val people = List(6) { gen.many(gen.centre(), 15) }+ val result = clusterFaces(gen.shuffled(people.flatten()))+ assertEquals(people.map { p -> p.map { it.faceId }.toSet() }.toSet(), partition(result))+ assertEquals(0, result.unassigned.size)+ }++ @Test+ fun bridgeFacesBetweenTwoPeopleDoNotMergeThem() = runBlocking {+ val gen = Faces(2)+ val a = gen.centre()+ val b = gen.centre()+ val aList = gen.many(a, 20)+ val bList = gen.many(b, 20)+ val bridges = List(6) { gen.face(Faces.mid(a, b)) }+ val aFaces = aList.map { it.faceId }.toSet()+ val bFaces = bList.map { it.faceId }.toSet()+ val result = clusterFaces(aList + bList + bridges)+ for (cluster in result.clusters) {+ val ids = cluster.faceIds.toSet()+ assertFalse(ids.any { it in aFaces } && ids.any { it in bFaces }, "a cluster mixes A and B")+ }+ assertTrue(result.clusters.any { it.faceIds.toSet().containsAll(aFaces) }, "A was split")+ assertTrue(result.clusters.any { it.faceIds.toSet().containsAll(bFaces) }, "B was split")+ }++ @Test+ fun inputOrderDoesNotChangeTheResult() = runBlocking {+ val gen = Faces(3)+ val faces = List(5) { gen.many(gen.centre(), 10) }.flatten() + List(4) { gen.face(gen.centre()) }+ val first = partition(clusterFaces(faces))+ repeat(3) { assertEquals(first, partition(clusterFaces(gen.shuffled(faces)))) }+ }++ @Test+ fun clustersBelowTheMinimumAreDissolved() = runBlocking {+ val gen = Faces(4)+ val big = gen.many(gen.centre(), 10)+ val pair = gen.many(gen.centre(), 2)+ val result = clusterFaces(big + pair)+ assertEquals(1, result.clusters.size)+ assertEquals(pair.map { it.faceId }.toSet(), result.unassigned.toSet())+ }++ @Test+ fun aNamedClusterIsKeptAtAnySize() = runBlocking {+ val gen = Faces(5)+ val named = gen.many(gen.centre(), 2, label = "Ann")+ val result = clusterFaces(gen.many(gen.centre(), 10) + named)+ assertTrue(result.clusters.any { it.label == "Ann" && it.faceIds.toSet() == named.map { f -> f.faceId }.toSet() })+ }++ @Test+ fun differentlyNamedClustersNeverMerge() = runBlocking {+ val gen = Faces(6)+ val c = gen.centre()+ val ann = gen.many(c, 8, label = "Ann")+ val bea = gen.many(c, 8, label = "Bea")+ val result = clusterFaces(ann + bea)+ assertEquals(setOf("Ann", "Bea"), result.clusters.mapNotNull { it.label }.toSet())+ for (cluster in result.clusters) {+ val ids = cluster.faceIds.toSet()+ assertFalse(ids.any { id -> ann.any { it.faceId == id } } && ids.any { id -> bea.any { it.faceId == id } })+ }+ }++ @Test+ fun lowQualityFacesAttachOnlyWhenClearlyClosest() = runBlocking {+ val gen = Faces(7)+ val a = gen.centre()+ val b = gen.centre()+ val faces = gen.many(a, 15) + gen.many(b, 15)+ val blurryA = gen.face(a, clusterable = false)+ val between = gen.face(Faces.mid(a, b), clusterable = false)+ val result = clusterFaces(faces + blurryA + between)+ val aCluster = result.clusters.single { blurryA.faceId in it.faceIds }+ assertTrue(faces.take(15).all { it.faceId in aCluster.faceIds })+ assertTrue(between.faceId in result.unassigned)+ }++ @Test+ fun lowQualityFacesNeverFormClustersOnTheirOwn() = runBlocking {+ val gen = Faces(8)+ val c = gen.centre()+ val result = clusterFaces(List(6) { gen.face(c, clusterable = false) })+ assertTrue(result.clusters.isEmpty())+ assertEquals(6, result.unassigned.size)+ }++ @Test+ fun manyIdentitiesStayPure() = runBlocking {+ val gen = Faces(9)+ val people = List(100) { gen.many(gen.centre(), 30) }+ val owner = HashMap<Long, Int>()+ people.forEachIndexed { p, faces -> faces.forEach { owner[it.faceId] = p } }+ val started = System.nanoTime()+ val result = clusterFaces(gen.shuffled(people.flatten()))+ println("clustered ${owner.size} faces in ${(System.nanoTime() - started) / 1_000_000} ms")+ assertEquals(100, result.clusters.size)+ for (cluster in result.clusters) assertEquals(1, cluster.faceIds.map { owner.getValue(it) }.toSet().size)+ }++ @Test+ fun emptyInputGivesNothing() = runBlocking {+ val result = clusterFaces(emptyList())+ assertTrue(result.clusters.isEmpty())+ assertEquals(0, result.unassigned.size)+ }+}++class FaceClusterIdentityTest {++ private fun cluster(vararg ids: Long) = FaceCluster(ids, FloatArray(1), null)++ @Test+ fun clustersKeepThePersonHoldingMostOfTheirFaces() {+ val resolution = resolveIdentities(+ listOf(cluster(1, 2, 3), cluster(4, 5)),+ mapOf(1L to 10L, 2L to 10L, 3L to 11L, 4L to 11L, 5L to 11L),+ listOf(10L, 11L, 12L),+ )+ assertEquals(listOf(10L, 11L), resolution.persons.map { it.personId })+ assertEquals(listOf(12L), resolution.deletedPersonIds)+ }++ @Test+ fun aSplitPersonKeepsItsIdOnTheLargerPart() {+ val resolution = resolveIdentities(+ listOf(cluster(1, 2), cluster(3, 4, 5)),+ mapOf(1L to 7L, 2L to 7L, 3L to 7L, 4L to 7L, 5L to 7L),+ listOf(7L),+ )+ assertNull(resolution.persons[0].personId)+ assertEquals(7L, resolution.persons[1].personId)+ }++ @Test+ fun mergedPersonsKeepTheLargerIdAndDeleteTheOther() {+ val resolution = resolveIdentities(+ listOf(cluster(1, 2, 3, 4, 5, 6, 7)),+ mapOf(1L to 1L, 2L to 1L, 3L to 1L, 4L to 1L, 5L to 2L, 6L to 2L, 7L to 2L),+ listOf(1L, 2L),+ )+ assertEquals(1L, resolution.persons.single().personId)+ assertEquals(listOf(2L), resolution.deletedPersonIds)+ }++ @Test+ fun brandNewFacesGetANewPerson() {+ val resolution = resolveIdentities(listOf(cluster(1, 2, 3)), emptyMap(), emptyList())+ assertNull(resolution.persons.single().personId)+ assertTrue(resolution.deletedPersonIds.isEmpty())+ }+}++class FaceAlignmentTest {++ private fun apply(t: FloatArray, pts: FloatArray) = FloatArray(pts.size) { i ->+ val x = pts[i - i % 2]+ val y = pts[i - i % 2 + 1]+ if (i % 2 == 0) t[0] * x + t[1] * y + t[2] else t[3] * x + t[4] * y + t[5]+ }++ @Test+ fun recoversAKnownSimilarityTransform() {+ val angle = 0.5+ val s = 2.3f+ val forward = floatArrayOf(+ (s * cos(angle)).toFloat(), (-s * sin(angle)).toFloat(), 40f,+ (s * sin(angle)).toFloat(), (s * cos(angle)).toFloat(), -15f,+ )+ val src = apply(forward, ARCFACE_TEMPLATE)+ val back = assertNotNull(similarityTransform(src, ARCFACE_TEMPLATE))+ val mapped = apply(back, src)+ for (i in mapped.indices) assertEquals(ARCFACE_TEMPLATE[i], mapped[i], 1e-2f)+ }++ @Test+ fun theTemplateMapsToItselfAsTheIdentity() {+ val t = assertNotNull(similarityTransform(ARCFACE_TEMPLATE, ARCFACE_TEMPLATE))+ val expected = floatArrayOf(1f, 0f, 0f, 0f, 1f, 0f)+ for (i in expected.indices) assertEquals(expected[i], t[i], 1e-4f)+ }++ @Test+ fun coincidentPointsHaveNoTransform() {+ assertNull(similarityTransform(FloatArray(10) { 5f }, ARCFACE_TEMPLATE))+ }+}++class FaceQualityTest {++ private val frontal = ARCFACE_TEMPLATE.copyOf()++ @Test+ fun aLargeSharpConfidentFrontalFaceIsClusterable() {+ assertTrue(FaceQuality.isClusterable(120f, 140f, 0.9f, frontal, 200f))+ }++ @Test+ fun eachGateRejectsOnItsOwn() {+ assertFalse(FaceQuality.isClusterable(30f, 140f, 0.9f, frontal, 200f))+ assertFalse(FaceQuality.isClusterable(120f, 140f, 0.6f, frontal, 200f))+ assertFalse(FaceQuality.isClusterable(120f, 140f, 0.9f, frontal, 5f))+ val profile = frontal.copyOf().also { it[4] = it[2] }+ assertFalse(FaceQuality.isClusterable(120f, 140f, 0.9f, profile, 200f))+ }++ @Test+ fun yawIsRotationInvariant() {+ val rotated = FloatArray(10) { i -> if (i % 2 == 0) -frontal[i + 1] else frontal[i - 1] }+ assertEquals(FaceQuality.yawRatio(frontal), FaceQuality.yawRatio(rotated), 1e-4f)+ assertTrue(FaceQuality.yawRatio(frontal) < 0.05f)+ }++ @Test+ fun laplacianVarianceSeparatesFlatFromDetailed() {+ val size = 16+ val flat = IntArray(size * size) { 0xff808080.toInt() }+ val checker = IntArray(size * size) { i -> if ((i % size + i / size) % 2 == 0) -1 else 0xff000000.toInt() }+ assertEquals(0f, FaceQuality.laplacianVariance(flat, size, size), 1e-3f)+ assertTrue(FaceQuality.laplacianVariance(checker, size, size) > 1000f)+ }+}
photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1MathTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1MathTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1MathTest.ktindex aaa3b93fbf..8764468720 100644--- a/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1MathTest.kt+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosSlice1MathTest.kt@@ -58,16 +58,6 @@ class PhotosSlice1MathTest { ) } - @Test- fun faceSimilarityUsesThresholdScale() {- // Just above the cluster threshold: same person. Well below: different.- val centroid = floatArrayOf(1f, 0f, 0f)- val close = floatArrayOf(0.9f, 0.1f, 0f)- val far = floatArrayOf(0f, 1f, 0f)- assertTrue(FaceRecognizer.similarity(centroid, close) >= FaceRecognizer.CLUSTER_THRESHOLD)- assertTrue(FaceRecognizer.similarity(centroid, far) < FaceRecognizer.CLUSTER_THRESHOLD)- }- // ---- FaceRecognizer.l2Normalize ---- @Test@@ -145,9 +135,6 @@ class PhotosSlice1MathTest { assertTrue(FaceRecognizer.EMBEDDER_VERSION > 0) assertTrue(ClipEmbedder.EMBEDDER_VERSION > 0) assertTrue(FaceRecognizer.INPUT_SIZE > 0)- assertTrue(FaceRecognizer.CLUSTER_THRESHOLD in 0f..1f)- assertTrue(FaceRecognizer.MERGE_THRESHOLD in 0f..1f)- assertTrue(FaceRecognizer.MERGE_THRESHOLD >= FaceRecognizer.CLUSTER_THRESHOLD) } @Test