photos: make OCR text in the photo viewer selectable
- Commit
0e83d582895ccaa51db75e10f0aa7d1e1a0a3ac5- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-20 18:06 UTC (3 months ago)
- Parents
67a2589
Diff
photos/src/main/java/com/vayunmathur/photos/data/OcrLayout.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/OcrLayout.kt b/photos/src/main/java/com/vayunmathur/photos/data/OcrLayout.ktnew file mode 100644index 0000000000..1b691b0467--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/data/OcrLayout.kt@@ -0,0 +1,50 @@+package com.vayunmathur.photos.data++import android.util.Log+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/** One recognised text line, in the pixel coordinates of the OCR bitmap. */+@Serializable+data class OcrBox(+ val text: String,+ val left: Int,+ val top: Int,+ val right: Int,+ val bottom: Int,+)++/**+ * A photo's OCR result with geometry, stored as JSON in [Photo.ocrBoxes].+ *+ * [w]/[h] are the dimensions of the bitmap OCR actually ran on, not+ * [Photo.width]/[Photo.height]: the OCR decode caps the long side (so the scale+ * differs), and MediaStore's WIDTH/HEIGHT are not EXIF-orientation-corrected,+ * so they are transposed for rotated JPEGs. ImageDecoder applies EXIF rotation,+ * so these are the display-orientation dimensions the viewer needs to rebuild+ * the ContentScale.Fit letterbox rect the boxes sit in.+ */+@Serializable+data class OcrLayout(+ val w: Int,+ val h: Int,+ val boxes: List<OcrBox>,+) {+ /** The lines joined by newlines — what [Photo.ocrText] holds for search. */+ val text: String get() = boxes.joinToString("\n") { it.text }.trim()+}++private val ocrJson = Json { ignoreUnknownKeys = true }++fun OcrLayout.toJson(): String = ocrJson.encodeToString(this)++/** Parse a stored [OcrLayout], or null if absent/unreadable (e.g. an older format). */+fun parseOcrLayout(json: String?): OcrLayout? {+ if (json.isNullOrBlank()) return null+ return try {+ ocrJson.decodeFromString<OcrLayout>(json).takeIf { it.w > 0 && it.h > 0 }+ } catch (e: Exception) {+ Log.w("OcrLayout", "Failed to parse stored OCR layout", e)+ null+ }+}
photos/src/main/java/com/vayunmathur/photos/data/Photo.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/data/Photo.kt b/photos/src/main/java/com/vayunmathur/photos/data/Photo.ktindex 3e0a7732ad..22d0deb680 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/Photo.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/Photo.kt@@ -73,6 +73,11 @@ data class Photo( // MediaStore MIME_TYPE. Null only on rows written before the column existed, // which the next sync backfills. val mimeType: String? = null,+ // The same OCR result as [ocrText] but with per-line geometry, serialised as+ // an [OcrLayout] JSON blob, so the viewer can lay an invisible selectable+ // text layer over the image. Null for videos, for photos with no text, and+ // for rows OCR'd before this column existed (the viewer backfills those).+ val ocrBoxes: String? = null, ) : DatabaseItem { /** True for an animated image, which plays rather than showing a single frame. */ val isGif: Boolean get() = mimeType.equals("image/gif", ignoreCase = true)
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 5645d09e86..104eccce59 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotoDatabase.kt@@ -11,10 +11,12 @@ import kotlinx.coroutines.flow.Flow @Dao interface PhotoDao {- // Excludes the heavy clipEmbedding BLOB and ocrText, which the gallery/photo- // UI never reads, so the first emission on cold start is fast (loading those- // for a large library is what left the grid blank). Semantic search reads- // embeddings via getClipEmbeddings(); OCR text is read via getAll().+ // Excludes the heavy clipEmbedding BLOB, ocrText and ocrBoxes, which the+ // gallery/photo UI never reads, so the first emission on cold start is fast+ // (loading those for a large library is what left the grid blank). Semantic+ // search reads embeddings via getClipEmbeddings(); OCR text is read via+ // getAll(); the viewer's selectable-text overlay reads geometry by id via+ // getOcrBoxes(), because Photos from this flow always have ocrBoxes == null. // // ORDER BY date DESC is served by index_Photo_date, so SQLite returns rows // newest-first on its own background executor. Every consumer (gallery grid,@@ -100,6 +102,13 @@ interface PhotoDao { */ @Query("SELECT count(*) FROM Photo WHERE mimeType IS NULL") suspend fun countMissingMimeType(): Int++ /** A photo's serialised OCR geometry; NULL if never stored (see [Photo.ocrBoxes]). */+ @Query("SELECT ocrBoxes FROM Photo WHERE id = :id")+ suspend fun getOcrBoxes(id: Long): String?++ @Query("UPDATE Photo SET ocrBoxes = :json WHERE id = :id")+ suspend fun setOcrBoxes(id: Long, json: String?) } /** Lightweight projection of a photo's CLIP embedding for in-memory search. */@@ -108,13 +117,13 @@ data class PhotoEmbedding( val clipEmbedding: ByteArray, ) -@Database(entities = [Photo::class, Person::class, PhotoFace::class], version = 13, exportSchema = false)+@Database(entities = [Photo::class, Person::class, PhotoFace::class], version = 14, 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)+ 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) } } @@ -217,3 +226,11 @@ val MIGRATION_12_13 = Migration(12, 13) { // PhotoDao.countMissingMimeType. it.execSQL("ALTER TABLE Photo ADD COLUMN mimeType TEXT") }++val MIGRATION_13_14 = Migration(13, 14) {+ // Add per-line OCR geometry so the viewer can overlay selectable text.+ // Deliberately no `UPDATE Photo SET ocrScanned = 0`: re-running OCR over a+ // whole library is expensive, so already-scanned rows stay NULL and the+ // viewer fills them in one photo at a time as they're opened.+ it.execSQL("ALTER TABLE Photo ADD COLUMN ocrBoxes TEXT")+}
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 d45b782300..78884ad5cc 100644--- a/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt+++ b/photos/src/main/java/com/vayunmathur/photos/data/PhotosRepository.kt@@ -48,6 +48,8 @@ class PhotosRepository private constructor(context: Context) : suspend fun resetClipScanned() = photoDao.resetClipScanned() suspend fun resetFaceScanned() = photoDao.resetFaceScanned() suspend fun countMissingMimeType(): Int = photoDao.countMissingMimeType()+ suspend fun getOcrBoxes(id: Long): String? = photoDao.getOcrBoxes(id)+ suspend fun setOcrBoxes(id: Long, json: String?) = photoDao.setOcrBoxes(id, json) // ------------------------------------------------------------------ // FaceDao suspend wrappers
photos/src/main/java/com/vayunmathur/photos/domain/PhotoOcr.kt
diff --git a/photos/src/main/java/com/vayunmathur/photos/domain/PhotoOcr.kt b/photos/src/main/java/com/vayunmathur/photos/domain/PhotoOcr.ktnew file mode 100644index 0000000000..3e0cc2b14a--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/domain/PhotoOcr.kt@@ -0,0 +1,144 @@+package com.vayunmathur.photos.domain++import android.content.Context+import android.graphics.Bitmap+import android.graphics.ImageDecoder+import android.net.Uri+import android.util.Log+import androidx.core.net.toUri+import com.vayunmathur.library.ocr.OcrEngine+import com.vayunmathur.photos.data.OcrBox+import com.vayunmathur.photos.data.OcrLayout+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.PhotosRepository+import com.vayunmathur.photos.data.parseOcrLayout+import com.vayunmathur.photos.data.toJson+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Deferred+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.async+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock++internal const val OCR_DECODE_MAX = 1280+internal const val MIN_OCR_DIM = 64++/** Decode a downscaled software bitmap for OCR (long side capped at [OCR_DECODE_MAX]). */+internal fun decodeForOcr(context: Context, uri: Uri): Bitmap? {+ return try {+ val source = ImageDecoder.createSource(context.contentResolver, uri)+ ImageDecoder.decodeBitmap(source) { decoder, info, _ ->+ decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE+ decoder.isMutableRequired = false+ val maxDim = maxOf(info.size.width, info.size.height)+ if (maxDim > OCR_DECODE_MAX) {+ val scale = OCR_DECODE_MAX.toFloat() / maxDim+ decoder.setTargetSize(+ (info.size.width * scale).toInt().coerceAtLeast(1),+ (info.size.height * scale).toInt().coerceAtLeast(1),+ )+ }+ }+ } catch (e: Exception) {+ Log.e(TAG, "Failed to decode $uri for OCR", e)+ null+ }+}++/**+ * Supplies the viewer with a photo's OCR geometry, reading [Photo.ocrBoxes] and+ * falling back to running OCR on the spot for rows written before that column+ * existed — writing the result back so the next open is instant.+ *+ * Runs on its own [OcrEngine] rather than sharing the indexing worker's, so an+ * in-progress library scan can't make the viewer wait on that engine's mutex.+ * The engine is created on first use and released once nothing is waiting.+ * In-flight work is memoised per photo id so fast-swiping (or a composition+ * being cancelled and restarted) can't run the same photo twice, and nothing+ * here throws: a missing model or an undecodable image just yields null.+ */+object OcrBoxStore {++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private val lock = Mutex()+ private val inFlight = mutableMapOf<Long, Deferred<OcrLayout?>>()+ private var engine: OcrEngine? = null++ suspend fun layoutFor(context: Context, photo: Photo): OcrLayout? {+ if (photo.videoData != null) return null+ // Only the application context is retained: the engine outlives the+ // composable that asked for it (see the write-back note below).+ val appContext = context.applicationContext+ val repository = PhotosRepository.get(appContext)+ parseOcrLayout(repository.getOcrBoxes(photo.id))?.let { return it }++ // Tiny images (icons/thumbnails) are skipped by the indexer too.+ val largestDim = maxOf(photo.width, photo.height)+ if (largestDim in 1 until MIN_OCR_DIM) return null++ // Runs in [scope], not the caller's, so a swipe that cancels the caller+ // still finishes the write-back — and the next open reads it from the DB.+ val job = lock.withLock {+ inFlight.getOrPut(photo.id) {+ scope.async {+ try {+ recognizeAndStore(appContext, photo, repository)+ } catch (e: CancellationException) {+ throw e+ } catch (e: Exception) {+ Log.e(TAG, "On-demand OCR failed for photo ${photo.id}", e)+ null+ } finally {+ release(photo.id)+ }+ }+ }+ }+ return job.await()+ }++ /** Forget a finished job and, once nothing else is queued, free the models. */+ private suspend fun release(photoId: Long) = lock.withLock {+ inFlight -= photoId+ if (inFlight.isEmpty()) {+ engine?.close()+ engine = null+ }+ }++ private suspend fun recognizeAndStore(+ context: Context,+ photo: Photo,+ repository: PhotosRepository,+ ): OcrLayout? {+ val ocr = lock.withLock { engine ?: OcrEngine(context).also { engine = it } }+ if (!ocr.isAvailable()) return null++ val bitmap = decodeForOcr(context, photo.uri.toUri()) ?: return null+ // The stored geometry is relative to this bitmap, so its dimensions have+ // to be read before it's recycled.+ val width = bitmap.width+ val height = bitmap.height+ val result = try {+ ocr.recognizeDetailed(bitmap)+ } finally {+ bitmap.recycle()+ }+ // An empty result is stored too, so a photo with no text in it isn't+ // re-OCR'd every time it's opened.+ val layout = result.toLayout(width, height)+ repository.setOcrBoxes(photo.id, layout.toJson())+ return layout+ }+}++/** Adapt an [OcrEngine.OcrResult] into the persisted [OcrLayout] shape. */+internal fun OcrEngine.OcrResult.toLayout(width: Int, height: Int) = OcrLayout(+ w = width,+ h = height,+ boxes = boxes.map { OcrBox(it.text, it.left, it.top, it.right, it.bottom) },+)++private const val TAG = "PhotoOcr"
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.ktnew file mode 100644index 0000000000..dc45e1610e--- /dev/null+++ b/photos/src/main/java/com/vayunmathur/photos/ui/OcrTextLayer.kt@@ -0,0 +1,171 @@+package com.vayunmathur.photos.ui++import androidx.compose.animation.AnimatedVisibility+import androidx.compose.animation.fadeIn+import androidx.compose.animation.fadeOut+import androidx.compose.foundation.Canvas+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.offset+import androidx.compose.foundation.layout.requiredSize+import androidx.compose.foundation.text.BasicText+import androidx.compose.foundation.text.selection.LocalTextSelectionColors+import androidx.compose.foundation.text.selection.SelectionContainer+import androidx.compose.foundation.text.selection.TextSelectionColors+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+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.geometry.Offset+import androidx.compose.ui.geometry.Size+import androidx.compose.ui.platform.LocalDensity+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.rememberTextMeasurer+import androidx.compose.ui.unit.IntOffset+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.photos.data.OcrLayout+import kotlin.math.roundToInt++/**+ * An invisible, selectable copy of a photo's recognised text laid over the image,+ * so text in a screenshot or a sign can be long-pressed, dragged over and copied+ * with the platform's own selection UI (Copy / Select all / Share / Translate).+ *+ * [layout]'s coordinates are pixels of the bitmap OCR ran on, so each box is+ * mapped through the `ContentScale.Fit` letterbox this image is drawn in — hence+ * [containerSize] and the layout's own dimensions rather than [com.vayunmathur.photos.data.Photo.width].+ * The caller passes the image's zoom/pan `graphicsLayer` in [modifier] so the+ * text tracks pinch-zoom in lockstep.+ */+@Composable+fun OcrTextLayer(+ layout: OcrLayout,+ containerSize: IntSize,+ showOutlines: Boolean,+ modifier: Modifier = Modifier,+) {+ if (layout.boxes.isEmpty() || containerSize.width <= 0 || containerSize.height <= 0) return++ val measurer = rememberTextMeasurer()+ val style = remember { TextStyle(color = Color.Transparent, fontSize = BASE_FONT_SIZE) }+ val placements = remember(layout, containerSize, style, measurer) {+ placeBoxes(layout, containerSize) { text ->+ measurer.measure(text = text, style = style, maxLines = 1, softWrap = false).size+ }+ }+ if (placements.isEmpty()) return++ val outlineColor = MaterialTheme.colorScheme.primary+ val selectionColors = TextSelectionColors(+ handleColor = outlineColor,+ backgroundColor = outlineColor.copy(alpha = 0.4f),+ )+ val density = LocalDensity.current++ Box(modifier = modifier) {+ // Drawn under the selectable text so it can never intercept a touch. Makes+ // the feature discoverable without adding a control: the regions light up+ // whenever the metadata card is up.+ AnimatedVisibility(visible = showOutlines, enter = fadeIn(), exit = fadeOut()) {+ Canvas(modifier = Modifier.fillMaxSize()) {+ placements.forEach { p ->+ drawRect(+ color = outlineColor.copy(alpha = 0.5f),+ topLeft = Offset(p.left, p.top),+ size = Size(p.width, p.height),+ style = Stroke(width = OUTLINE_STROKE.toPx()),+ )+ }+ }+ }++ CompositionLocalProvider(LocalTextSelectionColors provides selectionColors) {+ SelectionContainer {+ Box(modifier = Modifier.fillMaxSize()) {+ placements.forEach { p ->+ BasicText(+ text = p.text,+ style = style,+ maxLines = 1,+ softWrap = false,+ modifier = Modifier+ .offset { IntOffset(p.left.roundToInt(), p.top.roundToInt()) }+ // Laid out at the glyph run's natural size, then+ // stretched onto the box by the layer transform+ // below. An OCR box's aspect ratio never matches a+ // font's, so a font size alone can only match the+ // box's width or its height, not both.+ .requiredSize(+ width = with(density) { p.measured.width.toDp() },+ height = with(density) { p.measured.height.toDp() },+ )+ .graphicsLayer {+ transformOrigin = TransformOrigin(0f, 0f)+ scaleX = p.scaleX+ scaleY = p.scaleY+ },+ )+ }+ }+ }+ }+ }+}++/** One OCR line resolved to on-screen pixels plus the stretch onto its box. */+private data class OcrPlacement(+ val text: String,+ val left: Float,+ val top: Float,+ val width: Float,+ val height: Float,+ val measured: IntSize,+ val scaleX: Float,+ val scaleY: Float,+)++private fun placeBoxes(+ layout: OcrLayout,+ containerSize: IntSize,+ 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++ return layout.boxes.mapNotNull { box ->+ val width = (box.right - box.left) * fit+ val height = (box.bottom - box.top) * fit+ if (width <= 0f || height <= 0f) return@mapNotNull null+ // Compose concatenates each selectable's text with no separator, so every+ // line has to carry its own newline or a multi-line copy comes out as one+ // run-together string. maxLines = 1 keeps it a single line tall.+ val text = box.text + "\n"+ val measured = measure(text)+ if (measured.width <= 0 || measured.height <= 0) return@mapNotNull null+ OcrPlacement(+ text = text,+ left = originX + box.left * fit,+ top = originY + box.top * fit,+ width = width,+ height = height,+ measured = measured,+ scaleX = width / measured.width,+ scaleY = height / measured.height,+ )+ }+}++private val BASE_FONT_SIZE = 16.sp+private val OUTLINE_STROKE = 1.dp
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 081c3ab9ae..c65b4baaa0 100644--- a/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt+++ b/photos/src/main/java/com/vayunmathur/photos/ui/PhotoPage.kt@@ -48,6 +48,7 @@ import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue+import androidx.compose.runtime.key import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableLongStateOf@@ -91,7 +92,9 @@ import com.vayunmathur.library.ui.IconWallpaper import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.photos.R import com.vayunmathur.photos.Route+import com.vayunmathur.photos.data.OcrLayout import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.domain.OcrBoxStore import com.vayunmathur.photos.util.GalleryViewModel import com.vayunmathur.photos.util.LiveWallpaperLauncher import com.vayunmathur.photos.util.PhotoMapViewModel@@ -332,11 +335,26 @@ fun PhotoDetailView( // Reset zoom only when the page is fully scrolled out of view (offset >= 1.0) // This allows the "fadeOut" to happen while the image is still zoomed.+ // Re-keying the OCR overlay is also how a stale text selection gets cleared:+ // selection state lives inside SelectionContainer and isn't reachable from here.+ var ocrClearToken by remember { mutableIntStateOf(0) } LaunchedEffect(Unit) { snapshotFlow { pageOffset }.filter { it >= 0.99f }.distinctUntilChanged().collect { if (updatedZoomState.scale > 1f) { updatedOnZoomUpdate(ZoomState()) }+ ocrClearToken+++ }+ }++ // Recognised text laid over the image so it can be selected. Loaded only for+ // the settled page: the pager keeps a neighbour composed either side, and an+ // off-screen SelectionContainer would compete for the long press.+ var ocrLayout by remember(photo.id) { mutableStateOf<OcrLayout?>(null) }+ val canHaveOcrText = photo.videoData == null && !photo.isGif+ LaunchedEffect(photo.id, isSettled, canHaveOcrText) {+ if (isSettled && canHaveOcrText) {+ ocrLayout = OcrBoxStore.layoutFor(context, photo) } } @@ -427,18 +445,21 @@ fun PhotoDetailView( } } ) {+ // Shared by the image and the OCR text overlay so the two can't drift apart.+ val zoomModifier =+ Modifier.graphicsLayer {+ scaleX = currentZoom.scale+ scaleY = currentZoom.scale+ translationX = currentZoom.offset.x+ translationY = currentZoom.offset.y+ } if (photo.videoData == null) { val imageModifier = Modifier.fillMaxSize() .onGloballyPositioned { layoutCoordinates -> size = layoutCoordinates.size }- .graphicsLayer {- scaleX = currentZoom.scale- scaleY = currentZoom.scale- translationX = currentZoom.offset.x- translationY = currentZoom.offset.y- }+ .then(zoomModifier) if (photo.isGif) { AnimatedImage( uri = photo.uri.toUri(),@@ -463,18 +484,24 @@ fun PhotoDetailView( modifier = Modifier.fillMaxSize() .onGloballyPositioned { size = it.size }- .graphicsLayer {- scaleX = currentZoom.scale- scaleY = currentZoom.scale- translationX = currentZoom.offset.x- translationY = currentZoom.offset.y- },+ .then(zoomModifier), uri = photo.uri.toUri(), isMetadataVisible = isMetadataVisible, isSettledPage = isSettled ) } + ocrLayout?.takeIf { isSettled && size != IntSize.Zero }?.let { layout ->+ key(ocrClearToken) {+ OcrTextLayer(+ layout = layout,+ containerSize = size,+ showOutlines = isMetadataVisible,+ modifier = Modifier.fillMaxSize().then(zoomModifier)+ )+ }+ }+ AnimatedVisibility( visible = isMetadataVisible, enter = fadeIn(),
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 937ee15e53..bdf4efa87b 100644--- a/photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.kt+++ b/photos/src/main/java/com/vayunmathur/photos/util/SyncWorker.kt@@ -34,6 +34,10 @@ import com.vayunmathur.photos.data.Photo import com.vayunmathur.photos.data.PhotoFace import com.vayunmathur.photos.data.PhotosRepository import com.vayunmathur.photos.data.VideoData+import com.vayunmathur.photos.data.toJson+import com.vayunmathur.photos.domain.MIN_OCR_DIM+import com.vayunmathur.photos.domain.decodeForOcr+import com.vayunmathur.photos.domain.toLayout import android.graphics.Bitmap import android.graphics.ImageDecoder import kotlinx.coroutines.CancellationException@@ -384,11 +388,15 @@ suspend fun runOCR(repository: PhotosRepository, context: Context) = coroutineSc continue } - val text = try {+ val result = try { val bitmap = decodeForOcr(context, photo.uri.toUri()) if (bitmap != null) {+ // Boxes are stored relative to this bitmap, so read its size+ // before recycling it.+ val width = bitmap.width+ val height = bitmap.height try {- ocrEngine.recognize(bitmap)+ ocrEngine.recognizeDetailed(bitmap).toLayout(width, height) } finally { bitmap.recycle() }@@ -401,7 +409,12 @@ suspend fun runOCR(repository: PhotosRepository, context: Context) = coroutineSc } // Store result and mark scanned regardless of outcome (mirrors faces).- repository.upsertAll(listOf(photo.copy(ocrText = text, ocrScanned = true)))+ val text = result?.text+ repository.upsertAll(listOf(photo.copy(+ ocrText = text,+ ocrBoxes = result?.takeIf { it.boxes.isNotEmpty() }?.toJson(),+ ocrScanned = true,+ ))) Log.i("OCRWorker", "OCR for ${photo.id}: ${text?.take(50)?.replace("\n", " ")}") // Short pause between images keeps sustained CPU/battery use low.@@ -415,31 +428,7 @@ suspend fun runOCR(repository: PhotosRepository, context: Context) = coroutineSc } } -/** Decode a downscaled software bitmap for OCR (long side capped at [OCR_DECODE_MAX]). */-private fun decodeForOcr(context: Context, uri: Uri): Bitmap? {- return try {- val source = ImageDecoder.createSource(context.contentResolver, uri)- ImageDecoder.decodeBitmap(source) { decoder, info, _ ->- decoder.allocator = ImageDecoder.ALLOCATOR_SOFTWARE- decoder.isMutableRequired = false- val maxDim = maxOf(info.size.width, info.size.height)- if (maxDim > OCR_DECODE_MAX) {- val scale = OCR_DECODE_MAX.toFloat() / maxDim- decoder.setTargetSize(- (info.size.width * scale).toInt().coerceAtLeast(1),- (info.size.height * scale).toInt().coerceAtLeast(1),- )- }- }- } catch (e: Exception) {- Log.e("OCRWorker", "Failed to decode $uri for OCR", e)- null- }-}- private const val OCR_INTER_ITEM_DELAY_MS = 250L-private const val MIN_OCR_DIM = 64-private const val OCR_DECODE_MAX = 1280 class ClipWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {