Modern Apps git

← Modern-Apps.git

photos: store face boxes, best-resolution crops, and named people

Commit
5cdaf7629d06fff4b33f705919880353cb1d686d
Author
vayun-mathur <[email protected]>
When
2026-08-23 02:35 UTC (3 months ago)
Parents
7a7ce30

Diff

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 46b56febb8..56d95b7ed2 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/FaceData.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/FaceData.kt@@ -10,32 +10,38 @@ import androidx.room.Update import kotlinx.coroutines.flow.Flow  /**- * One unnamed person discovered by on-device face clustering. Faces whose- * embeddings are close enough (cosine similarity, see- * [com.vayunmathur.photos.util.FaceRecognizer]) share a [Person]. Nobody is- * named — a cluster is just "the same face seen across photos".+ * 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.  *  * [centroid] is the running mean of every face embedding in the cluster, packed- * as bytes; it is updated incrementally as new faces are added. The `rep*`- * fields point at one representative face (a photo id plus its normalised- * bounding box, 0..1) so the UI can show a cropped thumbnail without a name.+ * as bytes; it is updated incrementally as new faces are added.+ *+ * [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+ * until a name is chosen. There is no representative face here: the cluster's+ * best face is a pure function of the [PhotoFace] rows, picked at read time.  */ @Entity data class Person(     @PrimaryKey(autoGenerate = true) val id: Long = 0,     val centroid: ByteArray,     val faceCount: Int,-    val repPhotoId: Long,-    val repLeft: Float,-    val repTop: Float,-    val repRight: Float,-    val repBottom: Float,+    val name: String?, )  /**  * 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.+ *+ * [left]/[top]/[right]/[bottom] are the detector's box normalised 0..1, and+ * [srcWidth]/[srcHeight] are the dimensions of the bitmap it was measured+ * against. ImageDecoder applies EXIF rotation, so those are *display*+ * orientation — unlike [Photo.width]/[Photo.height], which come from MediaStore+ * un-corrected and are transposed for rotated JPEGs. They are duplicated across+ * a photo's face rows, which is the price of not needing a second table.  */ @Entity(indices = [Index(value = ["photoId"]), Index(value = ["clusterId"])]) data class PhotoFace(@@ -43,6 +49,12 @@ data class PhotoFace(     val photoId: Long,     val clusterId: Long,     val embedding: ByteArray,+    val left: Float,+    val top: Float,+    val right: Float,+    val bottom: Float,+    val srcWidth: Int,+    val srcHeight: Int, )  @Dao@@ -66,6 +78,10 @@ interface FaceDao {     @Query("DELETE FROM Person WHERE id = :id")     suspend fun deletePerson(id: Long) +    /** Name a cluster (or clear its name with null). */+    @Query("UPDATE Person SET name = :name WHERE id = :id")+    suspend fun setPersonName(id: Long, name: String?)+     @Insert     suspend fun insertPhotoFaces(faces: List<PhotoFace>) 
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 7cc49e10fb..9cbeb344af 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt@@ -117,13 +117,13 @@ data class PhotoEmbedding(     val clipEmbedding: ByteArray, ) -@Database(entities = [Photo::class, Person::class, PhotoFace::class], version = 15, exportSchema = false)+@Database(entities = [Photo::class, Person::class, PhotoFace::class], version = 16, exportSchema = false) abstract class PhotoDatabase : RoomDatabase() {     abstract fun photoDao(): PhotoDao     abstract fun faceDao(): FaceDao      companion object : com.vayunmathur.library.util.DatabaseMigrations {-        override val migrations: List<Migration> = listOf(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)+        override val migrations: List<Migration> = listOf(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)     } } @@ -246,3 +246,25 @@ val MIGRATION_14_15 = Migration(14, 15) {     // as it is rescanned.     it.execSQL("UPDATE Photo SET ocrScanned = 0, ocrBoxes = NULL") }++val MIGRATION_15_16 = Migration(15, 16) {+    // Faces now store their own geometry, so a cluster's best face can be picked+    // at read time (largest in source pixels) and the viewer can outline faces;+    // Person drops its single representative face and gains a user-chosen name.+    // Existing face rows have no geometry to backfill, so both tables are+    // dropped, recreated and re-derived by the background indexer — the same+    // drop-recreate-reset MIGRATION_7_8 did, for the same reason. Photo, OCR and+    // CLIP data are untouched. Nothing is lost: no names exist before this.+    //+    // Names live on the cluster row, so a future FaceRecognizer.EMBEDDER_VERSION+    // bump (which clears clusters) will clear them too. 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 NOT NULL, `embedding` BLOB 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")+}
photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt b/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.ktindex 78884ad5cc..3ab40958c9 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt@@ -59,6 +59,7 @@ class PhotosRepository private constructor(context: Context) :     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 insertPhotoFaces(faces: List<PhotoFace>) = faceDao.insertPhotoFaces(faces)     suspend fun deletePhotoFacesByPhotoIds(photoIds: List<Long>) = faceDao.deletePhotoFacesByPhotoIds(photoIds)     suspend fun clearPhotoFaces() = faceDao.clearPhotoFaces()
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.ktnew file mode 100644index 0000000000..6f4b184bc7--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/ui/FaceBoxLayer.kt@@ -0,0 +1,171 @@+package com.vayunmathur.photos.ui++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.TransformOrigin+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.invisibleClickable+import com.vayunmathur.photos.util.PhotoFaceBoxes+import kotlin.math.roundToInt++/**+ * Outlines the faces detected in a photo, with the person's name where there is+ * one, and opens that person's photo set when a face is tapped.+ *+ * [boxes] are normalised against the detection bitmap, so they are mapped through+ * the same `ContentScale.Fit` letterbox the image is drawn in — see+ * [imageFitTransform], which the OCR overlay also uses — against the source+ * dimensions stored with the faces rather than MediaStore's un-EXIF-corrected+ * ones.+ *+ * The caller passes the image's zoom/pan `graphicsLayer` in [modifier], so the+ * GPU transform carries the boxes and there is no pan/zoom maths here. Only the+ * things that must hold their on-screen size are counter-scaled by [zoom]: the+ * stroke widths, and the name labels.+ *+ * Colours are fixed rather than themed for the reason spelled out on+ * [OcrTextLayer]: a dynamic-colour pastel vanishes over a bright photo, so every+ * line is a light stroke sitting inside a dark halo.+ */+@Composable+fun FaceBoxLayer(+    boxes: PhotoFaceBoxes,+    containerSize: IntSize,+    zoom: Float,+    onFaceClick: (Long) -> Unit,+    modifier: Modifier = Modifier,+) {+    val placements = remember(boxes, containerSize) {+        val fit = imageFitTransform(boxes.srcWidth, boxes.srcHeight, containerSize)+            ?: return@remember emptyList<FacePlacement>()+        boxes.faces.mapNotNull { face ->+            val left = fit.originX + face.left * boxes.srcWidth * fit.scale+            val top = fit.originY + face.top * boxes.srcHeight * fit.scale+            val right = fit.originX + face.right * boxes.srcWidth * fit.scale+            val bottom = fit.originY + face.bottom * boxes.srcHeight * fit.scale+            if (right <= left || bottom <= top) return@mapNotNull null+            FacePlacement(+                clusterId = face.clusterId,+                name = face.name,+                topLeft = Offset(left, top),+                size = Size(right - left, bottom - top),+            )+        }+    }+    if (placements.isEmpty()) return++    val density = LocalDensity.current++    Box(modifier = modifier) {+        Canvas(modifier = Modifier.fillMaxSize()) {+            // Pre-divided by the zoom this whole layer sits inside, so the lines+            // stay a constant thickness on screen instead of ballooning with the+            // photo.+            val halo = OUTLINE_HALO.toPx() / zoom+            val line = OUTLINE_STROKE.toPx() / zoom+            val corner = CornerRadius(BOX_CORNER.toPx() / zoom)+            placements.forEach { p ->+                // Wide dark stroke first, narrow light stroke centred inside it:+                // one of the two always contrasts, whatever is underneath.+                drawRoundRect(+                    color = Color.Black.copy(alpha = 0.55f),+                    topLeft = p.topLeft,+                    size = p.size,+                    cornerRadius = corner,+                    style = Stroke(width = halo),+                )+                drawRoundRect(+                    color = Color.White.copy(alpha = 0.9f),+                    topLeft = p.topLeft,+                    size = p.size,+                    cornerRadius = corner,+                    style = Stroke(width = line),+                )+            }+        }++        placements.forEach { p ->+            // 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) }+            )++            // Unnamed clusters are left as bare outlines rather than labelled+            // with a placeholder.+            if (p.name != null) {+                Box(+                    Modifier+                        .offset {+                            IntOffset(+                                p.topLeft.x.roundToInt(),+                                (p.topLeft.y + p.size.height).roundToInt(),+                            )+                        }+                        // Counter-scaled from its own anchor for the same reason+                        // the strokes are divided above: without this the text+                        // grows with pinch-zoom.+                        .graphicsLayer {+                            transformOrigin = TransformOrigin(0f, 0f)+                            scaleX = 1f / zoom+                            scaleY = 1f / zoom+                        }+                ) {+                    Text(+                        text = p.name,+                        color = Color.White,+                        style = MaterialTheme.typography.labelMedium,+                        maxLines = 1,+                        overflow = TextOverflow.Ellipsis,+                        modifier = Modifier+                            .background(+                                color = Color.Black.copy(alpha = 0.55f),+                                shape = RoundedCornerShape(4.dp),+                            )+                            .padding(horizontal = 6.dp, vertical = 2.dp),+                    )+                }+            }+        }+    }+}++/** One face resolved to on-screen pixels of the un-zoomed container. */+private data class FacePlacement(+    val clusterId: Long,+    val name: String?,+    val topLeft: Offset,+    val size: Size,+)++private val OUTLINE_STROKE = 1.dp+private val OUTLINE_HALO = 3.dp+private val BOX_CORNER = 6.dp
photos/src/main/java/com/vayunmathur/photos/ui/ImageFit.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/ImageFit.kt b/photos/src/main/java/com/vayunmathur/photos/ui/ImageFit.ktnew file mode 100644index 0000000000..c6ec80beb8--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/ui/ImageFit.kt@@ -0,0 +1,41 @@+package com.vayunmathur.photos.ui++import androidx.compose.ui.unit.IntSize++/**+ * Where a `ContentScale.Fit` + `Alignment.Center` image lands inside its+ * container: a uniform [scale] plus the letterbox [originX]/[originY] offset.+ *+ * Both the OCR text layer and the face-box layer overlay geometry that was+ * measured in the pixels of some source bitmap, so both need this same mapping;+ * sharing it is what keeps the two overlays from drifting apart.+ */+data class ImageFitTransform(+    val scale: Float,+    val originX: Float,+    val originY: Float,+)++/**+ * Resolve the letterbox for a [srcWidth] x [srcHeight] image drawn to fit+ * [containerSize], or null if either is degenerate.+ *+ * The source dimensions must be the *display-orientation* dimensions of the+ * bitmap the coordinates came from, not+ * [com.vayunmathur.photos.data.Photo.width]/[com.vayunmathur.photos.data.Photo.height]:+ * MediaStore's values are not EXIF-corrected and are transposed for rotated+ * JPEGs, which would turn every box 90°.+ */+fun imageFitTransform(srcWidth: Int, srcHeight: Int, containerSize: IntSize): ImageFitTransform? {+    if (srcWidth <= 0 || srcHeight <= 0) return null+    if (containerSize.width <= 0 || containerSize.height <= 0) return null+    val scale = minOf(+        containerSize.width.toFloat() / srcWidth,+        containerSize.height.toFloat() / srcHeight,+    )+    return ImageFitTransform(+        scale = scale,+        originX = (containerSize.width - srcWidth * scale) / 2f,+        originY = (containerSize.height - srcHeight * scale) / 2f,+    )+}
photos/src/main/java/com/vayunmathur/photos/ui/OcrTextLayer.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/OcrTextLayer.kt b/photos/src/main/java/com/vayunmathur/photos/ui/OcrTextLayer.ktindex a573172e54..bbe6bded96 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/OcrTextLayer.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/OcrTextLayer.kt@@ -231,12 +231,10 @@ private fun placeBoxes(     measure: (String) -> IntSize, ): List<OcrPlacement> {     // ContentScale.Fit + Alignment.Center: uniform scale, letterboxed and centred.-    val fit = minOf(-        containerSize.width.toFloat() / layout.w,-        containerSize.height.toFloat() / layout.h,-    )-    val originX = (containerSize.width - layout.w * fit) / 2f-    val originY = (containerSize.height - layout.h * fit) / 2f+    val transform = imageFitTransform(layout.w, layout.h, containerSize) ?: return emptyList()+    val fit = transform.scale+    val originX = transform.originX+    val originY = transform.originY      return layout.boxes.mapNotNull { box ->         // The letterbox is a uniform scale, so mapping the corners through it
photos/src/main/java/com/vayunmathur/photos/ui/PeoplePage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PeoplePage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PeoplePage.ktindex 56930825c7..39a529fe86 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PeoplePage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PeoplePage.kt@@ -1,5 +1,11 @@ package com.vayunmathur.photos.ui +import android.content.Context+import android.net.Uri+import android.provider.ContactsContract+import android.util.Log+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.ui.res.pluralStringResource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box@@ -21,7 +27,10 @@ import com.vayunmathur.library.ui.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip@@ -29,6 +38,7 @@ import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.core.net.toUri import com.vayunmathur.library.image.compose.AsyncImage@@ -43,6 +53,9 @@ import com.vayunmathur.photos.util.FaceRecognizer import com.vayunmathur.photos.util.GalleryViewModel import com.vayunmathur.photos.util.PeopleUiState import com.vayunmathur.photos.util.PersonCluster+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext  /** Binds [GalleryViewModel] to the stateless [PeopleScreen]. */ @Composable@@ -51,12 +64,30 @@ fun PeoplePage(     galleryViewModel: GalleryViewModel, ) {     val context = LocalContext.current+    val scope = rememberCoroutineScope()     val people by galleryViewModel.people.collectAsState()     val indexing by galleryViewModel.faceIndexing.collectAsState()     val scanned by galleryViewModel.faceScannedCount.collectAsState()     val target by galleryViewModel.faceTargetCount.collectAsState()     val modelsAvailable = remember { FaceRecognizer.modelsAvailable(context) } +    // The contact picker's result carries only the picked contact, with nothing to+    // say which cluster was being named, so the cluster id is parked here across+    // the launch — the same pending-state shape PhotoPage's delete flow uses.+    // An activity-result launcher can't live on a ViewModel, so it lives here in+    // the binder and PeopleScreen just gets a lambda (see GalleryActions' KDoc).+    var pendingClusterId by remember { mutableStateOf<Long?>(null) }+    val pickContact = rememberLauncherForActivityResult(ActivityResultContracts.PickContact()) { uri ->+        val clusterId = pendingClusterId+        pendingClusterId = null+        // A cancelled picker returns null; nothing to do.+        if (uri == null || clusterId == null) return@rememberLauncherForActivityResult+        scope.launch {+            val name = withContext(Dispatchers.IO) { contactDisplayName(context, uri) }+            if (name != null) galleryViewModel.setPersonName(clusterId, name)+        }+    }+     PeopleScreen(         backStack = backStack,         state = PeopleUiState(@@ -66,13 +97,33 @@ fun PeoplePage(             faceScannedCount = scanned,             faceTargetCount = target,         ),+        onNameClick = { person ->+            pendingClusterId = person.id+            pickContact.launch(null)+        },     ) } +/**+ * The display name behind a URI from [ActivityResultContracts.PickContact], which+ * grants read access to that one contact — so this works without READ_CONTACTS.+ */+private fun contactDisplayName(context: Context, uri: Uri): String? = try {+    context.contentResolver.query(+        uri,+        arrayOf(ContactsContract.Contacts.DISPLAY_NAME),+        null, null, null,+    )?.use { cursor ->+        if (cursor.moveToFirst()) cursor.getString(0)?.takeIf { it.isNotBlank() } else null+    }+} catch (e: Exception) {+    Log.w("PeoplePage", "Could not read the picked contact's name", e)+    null+}+ /**  * The people grid, with no dependency on the ViewModel so it can be rendered from a  * `@Preview` — see `src/screenshotTest`, which is where the store listing images come from.- * Navigation is the screen's only callback, so there is no actions interface.  */ @OptIn(ExperimentalMaterial3Api::class) @Composable@@ -84,6 +135,12 @@ fun PeopleScreen(      * one crops a MediaStore image, which Layoutlib cannot decode.      */     faceThumbnail: @Composable (PersonCluster, Modifier) -> Unit = { person, modifier -> FaceThumbnail(person, modifier) },+    /**+     * Name (or rename) a cluster. Opens the contact picker, which needs an+     * activity-result launcher, so the binder owns it — a preview renders the+     * labels fine with the no-op default.+     */+    onNameClick: (PersonCluster) -> Unit = {}, ) {     // Show progress while there are still photos left to scan (or the worker is     // actively running); it disappears on its own once everything is scanned.@@ -114,6 +171,7 @@ fun PeopleScreen(                             people = state.people,                             modifier = Modifier.weight(1f),                             faceThumbnail = faceThumbnail,+                            onNameClick = onNameClick,                         ) { person ->                             backStack.add(Route.PhotoPage(person.coverPhoto.id, person.photos))                         }@@ -155,6 +213,7 @@ private fun PeopleGrid(     people: List<PersonCluster>,     modifier: Modifier = Modifier,     faceThumbnail: @Composable (PersonCluster, Modifier) -> Unit,+    onNameClick: (PersonCluster) -> Unit,     onClick: (PersonCluster) -> Unit, ) {     LazyVerticalGrid(@@ -175,41 +234,62 @@ private fun PeopleGrid(                         .clip(CircleShape)                         .invisibleClickable { onClick(person) },                 )+                // The name is its own tap target: the avatar keeps opening the+                // person's photos, and tapping an existing name is how renaming+                // works (it just reopens the picker).+                Text(+                    text = person.name ?: stringResource(R.string.people_unnamed),+                    style = MaterialTheme.typography.bodyMedium,+                    color = MaterialTheme.colorScheme.onSurface,+                    maxLines = 1,+                    overflow = TextOverflow.Ellipsis,+                    modifier = Modifier+                        .padding(top = 4.dp)+                        .invisibleClickable { onNameClick(person) },+                )                 Text(                     text = pluralStringResource(R.plurals.people_photo_count, person.photos.size, person.photos.size),                     style = MaterialTheme.typography.bodySmall,                     color = MaterialTheme.colorScheme.onSurfaceVariant,-                    modifier = Modifier.padding(top = 4.dp),                 )             }         }     } } -/** The representative face of a cluster, cropped from its cover photo. Unnamed. */+/** The representative face of a cluster, cropped from its cover photo. */ @Composable private fun FaceThumbnail(person: PersonCluster, modifier: Modifier) {     val context = LocalContext.current-    // Remember the Coil request keyed only on the STABLE face identity (cluster-    // id + source file + face box). This keeps the model identity and cache keys-    // constant across re-emissions, so the same face is never re-decoded/re-fetched-    // (no flashing) even when the surrounding list re-emits during indexing.-    val cacheKey = "face_${person.id}_${person.coverPhoto.dateModified}"-    val request = remember(-        person.id,-        person.coverPhoto.uri,-        person.coverPhoto.dateModified,-        person.faceLeft, person.faceTop, person.faceRight, person.faceBottom,-    ) {+    // `size` downsamples at *decode* time and transformations run after it, so+    // asking for 256 would decode the whole photo to 256px and only then cut the+    // face out — a face spanning 15% of the frame would arrive as ~38px stretched+    // across a full-width circle. Scaling the request up by the box fraction puts+    // the cropped result near TARGET_FACE_PX instead; the clamp stops a tiny face+    // asking for an enormous decode.+    val boxFraction = minOf(person.faceRight - person.faceLeft, person.faceBottom - person.faceTop)+    val requestSize = remember(boxFraction) {+        if (boxFraction <= 0f) TARGET_FACE_PX+        else (TARGET_FACE_PX / boxFraction).toInt().coerceIn(TARGET_FACE_PX, MAX_FACE_DECODE_PX)+    }+    // The representative face changes as indexing finds a better one, so the+    // memory key has to carry the box and the decode size or a stale crop would be+    // served forever. The disk cache holds the *pre-transform* fetched bytes (the+    // original file, see ImageLoader), so its key is photo identity alone —+    // including the box or the size there would just store the same file twice.+    val diskKey = "face_src_${person.coverPhoto.id}_${person.coverPhoto.dateModified}"+    val memoryKey = "face_${person.id}_${diskKey}_${person.faceLeft}_${person.faceTop}_" ++        "${person.faceRight}_${person.faceBottom}_$requestSize"+    val request = remember(person.coverPhoto.uri, memoryKey, diskKey, requestSize) {         ImageRequest.Builder(context)             .data(person.coverPhoto.uri.toUri())             .transformations(                 FaceCropTransformation(person.faceLeft, person.faceTop, person.faceRight, person.faceBottom)             )-            .diskCacheKey(cacheKey)-            .memoryCacheKey(cacheKey)+            .diskCacheKey(diskKey)+            .memoryCacheKey(memoryKey)             .crossfade(false)-            .size(256)+            .size(requestSize)             .build()     }     AsyncImage(@@ -219,3 +299,9 @@ private fun FaceThumbnail(person: PersonCluster, modifier: Modifier) {         modifier = modifier,     ) }++/** Roughly the on-screen size of a face circle in the 3-column grid. */+private const val TARGET_FACE_PX = 256++/** Ceiling on the decode a small face may ask for, to bound memory and time. */+private const val MAX_FACE_DECODE_PX = 1536
photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.ktindex f9f9dfb012..bf3da90a8d 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt@@ -98,6 +98,7 @@ import com.vayunmathur.photos.domain.OcrBoxStore import com.vayunmathur.photos.util.GalleryViewModel import com.vayunmathur.photos.util.LiveWallpaperLauncher import com.vayunmathur.photos.util.PhotoMapViewModel+import com.vayunmathur.photos.util.PhotoFaceBoxes import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.compose.LocalLifecycleOwner@@ -130,6 +131,8 @@ fun PhotoPage(galleryViewModel: GalleryViewModel, photoMapViewModel: PhotoMapVie             .toList()     }     val matchedCounts by galleryViewModel.faceCountByPhoto.collectAsState()+    val faceBoxes by galleryViewModel.faceBoxesByPhoto.collectAsState()+    val people by galleryViewModel.people.collectAsState()      // In-viewer delete: move the current photo to the system trash via the same     // MediaStore IntentSender flow the grid uses. MANAGE_MEDIA (enforced at app@@ -235,6 +238,13 @@ fun PhotoPage(galleryViewModel: GalleryViewModel, photoMapViewModel: PhotoMapVie                         isMetadataVisible = isMetadataVisible,                         currentZoom = zoomState,                         peopleCount = matchedCounts[photo.id] ?: 0,+                        faceBoxes = faceBoxes[photo.id],+                        onOpenPerson = { clusterId ->+                            // The same navigation the People grid performs.+                            people.firstOrNull { it.id == clusterId }?.let { cluster ->+                                backStack?.add(Route.PhotoPage(cluster.coverPhoto.id, cluster.photos))+                            }+                        },                         onZoomUpdate = { newState -> zoomStates[photo.id] = newState },                         onToggleMetadata = { isMetadataVisible = !isMetadataVisible },                         refreshKey = refreshKey,@@ -295,6 +305,8 @@ fun PhotoDetailView(         isMetadataVisible: Boolean,         currentZoom: ZoomState,         peopleCount: Int = 0,+        faceBoxes: PhotoFaceBoxes? = null,+        onOpenPerson: (Long) -> Unit = {},         onZoomUpdate: (ZoomState) -> Unit,         onToggleMetadata: () -> Unit,         refreshKey: Int = 0,@@ -503,6 +515,29 @@ fun PhotoDetailView(             }         } +        // Above the OCR layer so a face tap wins over the selection container's+        // invisible text. The tradeoff is that text selection is blocked inside a+        // face rect; faces and text rarely overlap, and the other way round — the+        // selection layer eating face taps — is worse. Gated so the layer is not+        // composed while the chrome is hidden, or its tap targets would swallow+        // the single tap that brings the chrome back.+        faceBoxes?.takeIf { isSettled && size != IntSize.Zero }?.let { boxes ->+            AnimatedVisibility(+                    visible = isMetadataVisible,+                    enter = fadeIn(),+                    exit = fadeOut(),+                    modifier = Modifier.fillMaxSize().then(zoomModifier)+            ) {+                FaceBoxLayer(+                        boxes = boxes,+                        containerSize = size,+                        zoom = currentZoom.scale,+                        onFaceClick = onOpenPerson,+                        modifier = Modifier.fillMaxSize()+                )+            }+        }+         AnimatedVisibility(                 visible = isMetadataVisible,                 enter = fadeIn(),
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 bc602d7033..a6115db57f 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/GalleryViewModel.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/GalleryViewModel.kt@@ -101,32 +101,51 @@ class GalleryViewModel(     val faceTargetCount: StateFlow<Int> = photoDao.getFaceTargetCountFlow()         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), 0) -    /** Photos grouped by unnamed person-cluster, for the People view. */+    /**+     * Photos grouped by person-cluster, for the People view.+     *+     * A cluster's representative is derived here rather than stored: whichever of+     * its faces covers the most *source* pixels, which is the one that survives+     * being cropped into a thumbnail. Area is+     * `(right-left) * (bottom-top) * photo.width * photo.height`, and those two+     * fractions multiply against both dimensions, so the ranking is unaffected by+     * MediaStore's width/height being transposed for EXIF-rotated JPEGs.+     *+     * Deriving it also means the cover photo and the box always come from the+     * same face, so a trashed photo can no longer leave a box cropping an+     * unrelated image.+     */     val people: StateFlow<List<PersonCluster>> =         combine(photoDao.getAllFlow(), faceDao.personsFlow(), faceDao.allFacesFlow()) { allPhotos, persons, faces ->             val byId = allPhotos.filter { !it.isTrashed }.associateBy { it.id }             val facesByCluster = faces.groupBy { it.clusterId }             persons.mapNotNull { person ->-                val personPhotos = facesByCluster[person.id].orEmpty()-                    .mapNotNull { byId[it.photoId] }-                    .distinctBy { it.id }-                    .sortedByDescending { it.date }-                if (personPhotos.isEmpty()) return@mapNotNull null-                val cover = byId[person.repPhotoId] ?: personPhotos.first()+                val clusterFaces = facesByCluster[person.id].orEmpty()+                    .mapNotNull { face -> byId[face.photoId]?.let { face to it } }+                if (clusterFaces.isEmpty()) return@mapNotNull null+                val (bestFace, bestPhoto) = clusterFaces.maxBy { (face, photo) ->+                    (face.right - face.left).toDouble() * (face.bottom - face.top) *+                        photo.width * photo.height+                }                 PersonCluster(                     id = person.id,-                    coverPhoto = cover,-                    faceLeft = person.repLeft,-                    faceTop = person.repTop,-                    faceRight = person.repRight,-                    faceBottom = person.repBottom,-                    photos = personPhotos,+                    name = person.name,+                    coverPhoto = bestPhoto,+                    faceLeft = bestFace.left,+                    faceTop = bestFace.top,+                    faceRight = bestFace.right,+                    faceBottom = bestFace.bottom,+                    photos = clusterFaces.map { it.second }+                        .distinctBy { it.id }+                        .sortedByDescending { it.date },                 )             }.sortedByDescending { it.photos.size }         }             // Per-photo writes during indexing re-emit the source flows constantly;             // drop emissions where the projected cluster list is unchanged (value             // equality of the PersonCluster data class) so the grid doesn't churn.+            // The representative can legitimately change mid-scan, so real changes+            // still get through.             .distinctUntilChanged()             .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) @@ -136,6 +155,33 @@ class GalleryViewModel(             faces.groupBy { it.photoId }.mapValues { (_, list) -> list.size }         }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyMap()) +    /**+     * Face geometry per photo, for the viewer's face overlay. Combined with the+     * clusters because the label text lives on [com.vayunmathur.photos.data.Person],+     * not on the face row — which is also why [faceCountByPhoto] can't be reused.+     */+    val faceBoxesByPhoto: StateFlow<Map<Long, PhotoFaceBoxes>> =+        combine(faceDao.allFacesFlow(), faceDao.personsFlow()) { faces, persons ->+            val nameByCluster = persons.associate { it.id to it.name }+            faces.groupBy { it.photoId }.mapValues { (_, rows) ->+                PhotoFaceBoxes(+                    // Duplicated across a photo's rows, so any one of them serves.+                    srcWidth = rows.first().srcWidth,+                    srcHeight = rows.first().srcHeight,+                    faces = rows.map { row ->+                        FaceBox(+                            clusterId = row.clusterId,+                            name = nameByCluster[row.clusterId],+                            left = row.left,+                            top = row.top,+                            right = row.right,+                            bottom = row.bottom,+                        )+                    },+                )+            }+        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyMap())+     init {         // Debounced search: re-query whenever the query string changes.         viewModelScope.launch {@@ -271,6 +317,13 @@ class GalleryViewModel(         SyncWorker.enqueue(getApplication())     } +    /** Name a person-cluster, or clear its name with null. */+    fun setPersonName(id: Long, name: String?) {+        viewModelScope.launch(Dispatchers.IO) {+            repository.setPersonName(id, name)+        }+    }+     companion object {         private const val TAG = "GalleryViewModel" @@ -308,9 +361,11 @@ fun GalleryViewModelFactory(     return GalleryViewModelFactory(application, repo) } -/** An unnamed person-cluster and the library photos they appear in. */+/** A person-cluster and the library photos they appear in. */ data class PersonCluster(     val id: Long,+    /** The name the user picked from their contacts, or null while unnamed. */+    val name: String?,     val coverPhoto: Photo,     val faceLeft: Float,     val faceTop: Float,@@ -319,6 +374,27 @@ data class PersonCluster(     val photos: List<Photo>, ) +/**+ * The faces detected in one photo, plus the dimensions their boxes are+ * normalised against — the display-orientation dimensions of the detection+ * bitmap, which is what the overlay needs to rebuild the letterbox rect.+ */+data class PhotoFaceBoxes(+    val srcWidth: Int,+    val srcHeight: Int,+    val faces: List<FaceBox>,+)++/** One face box (normalised 0..1) and the cluster it was grouped into. */+data class FaceBox(+    val clusterId: Long,+    val name: String?,+    val left: Float,+    val top: Float,+    val right: Float,+    val bottom: Float,+)+ /** Availability of on-device semantic search, for the search UI. */ enum class SearchAiState {     /** The bundled TinyCLIP model loaded and is serving embeddings. */
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 f9e7980796..c0bf04c428 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.kt@@ -570,7 +570,7 @@ 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, unsupervised, and unnamed.+ * on-device and unsupervised.  *  * Clustering is greedy and incremental: each face joins the nearest existing  * cluster if similarity >= [FaceRecognizer.CLUSTER_THRESHOLD], otherwise it@@ -619,6 +619,10 @@ suspend fun runFaceIndexing(repository: PhotosRepository, context: Context) {             if (bitmap != null) {                 decoded++                 didInference = true+                // Read before recycle: the box columns are normalised against+                // this bitmap, so its dimensions have to be stored with them.+                val srcWidth = bitmap.width+                val srcHeight = bitmap.height                 val faces = FaceRecognizer.detectAndEmbed(context, bitmap)                 bitmap.recycle()                 if (faces.isNotEmpty()) {@@ -626,11 +630,17 @@ suspend fun runFaceIndexing(repository: PhotosRepository, context: Context) {                     Log.i("FaceWorker", "photo ${photo.id}: ${faces.size} face(s) (running total: $facesTotal)")                 }                 val rows = faces.map { face ->-                    val clusterId = assignToCluster(face, photo, clusters, repository)+                    val clusterId = assignToCluster(face, clusters, repository)                     PhotoFace(                         photoId = photo.id,                         clusterId = clusterId,                         embedding = FaceRecognizer.floatsToBytes(face.embedding),+                        left = face.left,+                        top = face.top,+                        right = face.right,+                        bottom = face.bottom,+                        srcWidth = srcWidth,+                        srcHeight = srcHeight,                     )                 }                 if (rows.isNotEmpty()) repository.insertPhotoFaces(rows)@@ -669,7 +679,6 @@ private const val FACE_INTER_ITEM_DELAY_MS = 250L  */ private suspend fun assignToCluster(     face: FaceRecognizer.DetectedFace,-    photo: Photo,     clusters: MutableList<Cluster>,     repository: PhotosRepository, ): Long {@@ -701,11 +710,7 @@ private suspend fun assignToCluster(     val person = Person(         centroid = FaceRecognizer.floatsToBytes(face.embedding),         faceCount = 1,-        repPhotoId = photo.id,-        repLeft = face.left,-        repTop = face.top,-        repRight = face.right,-        repBottom = face.bottom,+        name = null,     )     val id = repository.insertPerson(person)     clusters += Cluster(person.copy(id = id), face.embedding.copyOf())@@ -739,6 +744,10 @@ private suspend fun mergeSimilarClusters(repository: PhotosRepository) {                 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,                 )                 repository.reassignCluster(b.id, a.id)                 repository.updatePerson(merged)
photos/src/main/res/values/strings.xml
diff --git a/photos/src/main/res/values/strings.xml b/photos/src/main/res/values/strings.xmlindex a8e016b58d..7bf6f5bc49 100644--- a/photos/src/main/res/values/strings.xml+++ b/photos/src/main/res/values/strings.xml@@ -62,6 +62,8 @@         <item quantity="one"><xliff:g id="count" example="12">%1$d</xliff:g> photo</item>         <item quantity="other"><xliff:g id="count" example="12">%1$d</xliff:g> photos</item>     </plurals>+    <!-- Label under a person grid cell with no name yet; tapping it opens the contact picker. Adjective -->+    <string name="people_unnamed">Unnamed</string>     <!-- Photo detail badge: number of people in this photo. Plural handling. %1$d = count -->     <plurals name="people_in_photo">         <!-- Singular: one person in photo -->
photos/src/screenshotTest/kotlin/com/vayunmathur/photos/ui/MetadataPreviews.kt
diff --git a/photos/src/screenshotTest/kotlin/com/vayunmathur/photos/ui/MetadataPreviews.kt b/photos/src/screenshotTest/kotlin/com/vayunmathur/photos/ui/MetadataPreviews.ktindex c6fb1e57ce..dbbcd3d0dd 100644--- a/photos/src/screenshotTest/kotlin/com/vayunmathur/photos/ui/MetadataPreviews.kt+++ b/photos/src/screenshotTest/kotlin/com/vayunmathur/photos/ui/MetadataPreviews.kt@@ -186,12 +186,18 @@ private fun samplePhoto(id: Long, name: String, date: Long): Photo = Photo(     panoData = null, ) -/** Face clusters, ordered largest first the way the ViewModel emits them. */+/**+ * Face clusters, ordered largest first the way the ViewModel emits them. The first+ * few are named and the rest are not, so the grid's name label renders in both+ * states.+ */ private fun samplePeople(): List<PersonCluster> {     val photos = samplePhotos()+    val names = listOf("Ana Ruiz", "Priya Nair", "Tom Baker", null, null, null)     return listOf(9, 7, 6, 5, 3, 2).mapIndexed { i, count ->         PersonCluster(             id = i + 1L,+            name = names[i],             coverPhoto = photos[i * 3],             faceLeft = 0.31f,             faceTop = 0.18f,