Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[mob][photos] Add OcrService with Rust and Vision backends

laurenspriem5e156dd1f363
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_model_assets.dart b/mobile/apps/photos/lib/services/machine_learning/ml_model_assets.dart
index 5e875dc204..2ca02bf2e7 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_model_assets.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_model_assets.dart
@@ -155,3 +155,63 @@ class PetBodyEmbeddingCatModel extends MlModelAsset {
@override
String get modelSha256 => _sha256;
}
+
+class OcrDetectionModel extends MlModelAsset {
+ static const remoteFileName = "PP-OCRv5/det.onnx";
+ static const _sha256 =
+ "d7fe3ea74652890722c0f4d02458b7261d9f5ae6c92904d05707c9eb155c7924";
+
+ OcrDetectionModel._();
+ static final instance = OcrDetectionModel._();
+
+ @override
+ String get modelRemotePath => kModelBucketEndpoint + remoteFileName;
+
+ @override
+ String get modelSha256 => _sha256;
+}
+
+class OcrClassificationModel extends MlModelAsset {
+ static const remoteFileName = "PP-OCRv5/cls.onnx";
+ static const _sha256 =
+ "f4bb53707100c5f3d59ba834eb05bb400369f20aed35d4b26807b1bfadd2a70e";
+
+ OcrClassificationModel._();
+ static final instance = OcrClassificationModel._();
+
+ @override
+ String get modelRemotePath => kModelBucketEndpoint + remoteFileName;
+
+ @override
+ String get modelSha256 => _sha256;
+}
+
+class OcrRecognitionModel extends MlModelAsset {
+ static const remoteFileName = "PP-OCRv5/rec.onnx";
+ static const _sha256 =
+ "bf66820f48fa99f779974c4df78e5274a9d8e0458c4137e8c5357e40e2c3faf2";
+
+ OcrRecognitionModel._();
+ static final instance = OcrRecognitionModel._();
+
+ @override
+ String get modelRemotePath => kModelBucketEndpoint + remoteFileName;
+
+ @override
+ String get modelSha256 => _sha256;
+}
+
+class OcrDictionaryAsset extends MlModelAsset {
+ static const remoteFileName = "PP-OCRv5/ppocrv5_dict.txt";
+ static const _sha256 =
+ "d1979e9f794c464c0d2e0b70a7fe14dd978e9dc644c0e71f14158cdf8342af1b";
+
+ OcrDictionaryAsset._();
+ static final instance = OcrDictionaryAsset._();
+
+ @override
+ String get modelRemotePath => kModelBucketEndpoint + remoteFileName;
+
+ @override
+ String get modelSha256 => _sha256;
+}
diff --git a/mobile/apps/photos/lib/services/machine_learning/ocr/legacy_mobile_ocr_backend.dart b/mobile/apps/photos/lib/services/machine_learning/ocr/legacy_mobile_ocr_backend.dart
new file mode 100644
index 0000000000..27746dee51
--- /dev/null
+++ b/mobile/apps/photos/lib/services/machine_learning/ocr/legacy_mobile_ocr_backend.dart
@@ -0,0 +1,102 @@
+import "package:mobile_ocr/mobile_ocr.dart" as legacy;
+import "package:photos/services/machine_learning/ocr/ocr_backend.dart";
+import "package:photos/services/machine_learning/ocr/ocr_models.dart";
+
+class LegacyMobileOcrBackend implements OcrBackend {
+ final legacy.MobileOcr _ocr = legacy.MobileOcr();
+
+ @override
+ Future<ModelPreparationStatus> prepareModels(
+ Set<OcrModelComponent> components,
+ ) {
+ return _translate(() async {
+ final status = await _ocr.prepareModels(
+ components: components
+ .map(
+ (component) =>
+ legacy.OcrModelComponent.values.byName(component.name),
+ )
+ .toSet(),
+ );
+ return ModelPreparationStatus(
+ isReady: status.isReady,
+ version: status.version,
+ modelPath: status.modelPath,
+ );
+ });
+ }
+
+ @override
+ Future<TextDetectionResult> detectText({
+ required String imagePath,
+ bool includeAllConfidenceScores = false,
+ String? requestId,
+ }) {
+ return _translate(() async {
+ final result = await _ocr.detectText(
+ imagePath: imagePath,
+ includeAllConfidenceScores: includeAllConfidenceScores,
+ requestId: requestId,
+ );
+ return TextDetectionResult(
+ blocks: result.blocks.map(_toTextBlock).toList(growable: false),
+ imageSize: result.imageSize,
+ );
+ });
+ }
+
+ @override
+ Future<TextRegionDetectionResult> detectTextRegions({
+ required String imagePath,
+ String? requestId,
+ }) {
+ return _translate(() async {
+ final result = await _ocr.detectTextRegions(
+ imagePath: imagePath,
+ requestId: requestId,
+ );
+ return TextRegionDetectionResult(
+ regions: result.regions.map(_toTextRegion).toList(growable: false),
+ imageSize: result.imageSize,
+ );
+ });
+ }
+
+ @override
+ Future<void> cancelRequest(String requestId) {
+ return _translate(() => _ocr.cancelRequest(requestId));
+ }
+
+ @override
+ Future<String> ensureDisplayablePath(String imagePath) {
+ return legacy.DisplayImageHelper.ensureDisplayablePath(imagePath);
+ }
+
+ Future<T> _translate<T>(Future<T> Function() operation) async {
+ try {
+ return await operation();
+ } on legacy.OcrException catch (error) {
+ throw OcrException(
+ code: error.code,
+ message: error.message,
+ details: error.details,
+ );
+ }
+ }
+
+ TextBlock _toTextBlock(legacy.TextBlock block) => TextBlock(
+ text: block.text,
+ confidence: block.confidence,
+ points: block.points,
+ characters: block.characters.map(_toCharacterBox).toList(growable: false),
+ );
+
+ CharacterBox _toCharacterBox(legacy.CharacterBox character) => CharacterBox(
+ text: character.text,
+ confidence: character.confidence,
+ points: character.points,
+ );
+
+ TextRegion _toTextRegion(legacy.TextRegion region) =>
+ TextRegion(confidence: region.confidence, points: region.points);
+}
diff --git a/mobile/apps/photos/lib/services/machine_learning/ocr/ocr_backend.dart b/mobile/apps/photos/lib/services/machine_learning/ocr/ocr_backend.dart
new file mode 100644
index 0000000000..8904e2ba98
--- /dev/null
+++ b/mobile/apps/photos/lib/services/machine_learning/ocr/ocr_backend.dart
@@ -0,0 +1,22 @@
+import "package:photos/services/machine_learning/ocr/ocr_models.dart";
+
+abstract class OcrBackend {
+ Future<ModelPreparationStatus> prepareModels(
+ Set<OcrModelComponent> components,
+ );
+
+ Future<TextDetectionResult> detectText({
+ required String imagePath,
+ bool includeAllConfidenceScores = false,
+ String? requestId,
+ });
+
+ Future<TextRegionDetectionResult> detectTextRegions({
+ required String imagePath,
+ String? requestId,
+ });
+
+ Future<void> cancelRequest(String requestId);
+
+ Future<String> ensureDisplayablePath(String imagePath);
+}
diff --git a/mobile/apps/photos/lib/services/machine_learning/ocr/ocr_models.dart b/mobile/apps/photos/lib/services/machine_learning/ocr/ocr_models.dart
new file mode 100644
index 0000000000..9a6bc281f2
--- /dev/null
+++ b/mobile/apps/photos/lib/services/machine_learning/ocr/ocr_models.dart
@@ -0,0 +1,211 @@
+import "dart:ui";
+
+enum OcrModelComponent { detector, recognizer }
+
+class ModelPreparationStatus {
+ final bool isReady;
+ final String? version;
+ final String? modelPath;
+
+ const ModelPreparationStatus({
+ required this.isReady,
+ this.version,
+ this.modelPath,
+ });
+}
+
+class OcrException implements Exception {
+ final String code;
+ final String message;
+ final Object? details;
+
+ const OcrException({required this.code, required this.message, this.details});
+
+ @override
+ String toString() => "OcrException($code, $message)";
+}
+
+class TextBlock {
+ final String text;
+ final double confidence;
+ final List<Offset> points;
+ final List<CharacterBox> characters;
+
+ const TextBlock({
+ required this.text,
+ required this.confidence,
+ required this.points,
+ required this.characters,
+ });
+
+ Rect get boundingBox => _boundingBoxOf(points);
+
+ Offset get center => boundingBox.center;
+
+ factory TextBlock.fromMap(Map<dynamic, dynamic> map) {
+ final pointsList = map["points"] as List?;
+ final points = (pointsList == null || pointsList.isEmpty)
+ ? _fallbackPointsFromRect(map)
+ : _pointsFromList(pointsList);
+ final charactersList = map["characters"] as List?;
+ final characters = charactersList == null
+ ? const <CharacterBox>[]
+ : charactersList
+ .whereType<Map<dynamic, dynamic>>()
+ .map(CharacterBox.fromMap)
+ .toList(growable: false);
+ return TextBlock(
+ text: map["text"] as String? ?? "",
+ confidence: (map["confidence"] as num?)?.toDouble() ?? 0.0,
+ points: points,
+ characters: characters,
+ );
+ }
+
+ Map<String, dynamic> toMap() => {
+ "text": text,
+ "confidence": confidence,
+ "points": _pointsToList(points),
+ "characters": characters
+ .map((character) => character.toMap())
+ .toList(growable: false),
+ };
+
+ static List<Offset> _fallbackPointsFromRect(Map<dynamic, dynamic> map) {
+ final x = map["x"] as num?;
+ final y = map["y"] as num?;
+ final width = map["width"] as num?;
+ final height = map["height"] as num?;
+ if (x == null || y == null || width == null || height == null) {
+ throw ArgumentError(
+ "TextBlock map is missing polygon points and fallback rectangle.",
+ );
+ }
+ final left = x.toDouble();
+ final top = y.toDouble();
+ final right = left + width.toDouble();
+ final bottom = top + height.toDouble();
+ return <Offset>[
+ Offset(left, top),
+ Offset(right, top),
+ Offset(right, bottom),
+ Offset(left, bottom),
+ ];
+ }
+}
+
+class CharacterBox {
+ final String text;
+ final double confidence;
+ final List<Offset> points;
+
+ const CharacterBox({
+ required this.text,
+ required this.confidence,
+ required this.points,
+ });
+
+ Rect get boundingBox => _boundingBoxOf(points);
+
+ factory CharacterBox.fromMap(Map<dynamic, dynamic> map) {
+ return CharacterBox(
+ text: map["text"] as String? ?? "",
+ confidence: (map["confidence"] as num?)?.toDouble() ?? 0.0,
+ points: _pointsFromList(map["points"] as List?),
+ );
+ }
+
+ Map<String, dynamic> toMap() => {
+ "text": text,
+ "confidence": confidence,
+ "points": _pointsToList(points),
+ };
+}
+
+class TextRegion {
+ final double confidence;
+ final List<Offset> points;
+
+ const TextRegion({required this.confidence, required this.points});
+
+ Rect get boundingBox => _boundingBoxOf(points);
+
+ factory TextRegion.fromMap(Map<dynamic, dynamic> map) {
+ return TextRegion(
+ confidence: (map["confidence"] as num?)?.toDouble() ?? 0,
+ points: _pointsFromList(map["points"] as List?),
+ );
+ }
+}
+
+class TextDetectionResult {
+ final List<TextBlock> blocks;
+ final Size imageSize;
+
+ const TextDetectionResult({required this.blocks, required this.imageSize});
+
+ factory TextDetectionResult.fromMap(Map<dynamic, dynamic> map) {
+ final blocks = (map["blocks"] as List? ?? const [])
+ .whereType<Map<dynamic, dynamic>>()
+ .map(TextBlock.fromMap)
+ .toList(growable: false);
+ return TextDetectionResult(blocks: blocks, imageSize: _imageSizeOf(map));
+ }
+}
+
+class TextRegionDetectionResult {
+ final List<TextRegion> regions;
+ final Size imageSize;
+
+ const TextRegionDetectionResult({
+ required this.regions,
+ required this.imageSize,
+ });
+
+ factory TextRegionDetectionResult.fromMap(Map<dynamic, dynamic> map) {
+ final regions = (map["regions"] as List? ?? const [])
+ .whereType<Map<dynamic, dynamic>>()
+ .map(TextRegion.fromMap)
+ .toList(growable: false);
+ return TextRegionDetectionResult(
+ regions: regions,
+ imageSize: _imageSizeOf(map),
+ );
+ }
+}
+
+Size _imageSizeOf(Map<dynamic, dynamic> map) => Size(
+ (map["imageWidth"] as num?)?.toDouble() ?? 0,
+ (map["imageHeight"] as num?)?.toDouble() ?? 0,
+);
+
+List<Offset> _pointsFromList(List? pointsList) => (pointsList ?? const [])
+ .whereType<Map<dynamic, dynamic>>()
+ .map(
+ (point) => Offset(
+ (point["x"] as num).toDouble(),
+ (point["y"] as num).toDouble(),
+ ),
+ )
+ .toList(growable: false);
+
+List<Map<String, double>> _pointsToList(List<Offset> points) => points
+ .map((point) => {"x": point.dx, "y": point.dy})
+ .toList(growable: false);
+
+Rect _boundingBoxOf(List<Offset> points) {
+ if (points.isEmpty) {
+ return Rect.zero;
+ }
+ var left = points.first.dx;
+ var top = points.first.dy;
+ var right = left;
+ var bottom = top;
+ for (final point in points.skip(1)) {
+ if (point.dx < left) left = point.dx;
+ if (point.dy < top) top = point.dy;
+ if (point.dx > right) right = point.dx;
+ if (point.dy > bottom) bottom = point.dy;
+ }
+ return Rect.fromLTRB(left, top, right, bottom);
+}
diff --git a/mobile/apps/photos/lib/services/machine_learning/ocr/rust_ocr_backend.dart b/mobile/apps/photos/lib/services/machine_learning/ocr/rust_ocr_backend.dart
new file mode 100644
index 0000000000..cebad3c7ea
--- /dev/null
+++ b/mobile/apps/photos/lib/services/machine_learning/ocr/rust_ocr_backend.dart
@@ -0,0 +1,354 @@
+import "dart:convert";
+import "dart:io";
+import "dart:ui";
+
+import "package:crypto/crypto.dart";
+import "package:logging/logging.dart";
+import "package:path/path.dart" as p;
+import "package:path_provider/path_provider.dart";
+import "package:photos/services/machine_learning/ml_model_assets.dart";
+import "package:photos/services/machine_learning/ocr/ocr_backend.dart";
+import "package:photos/services/machine_learning/ocr/ocr_models.dart";
+import "package:photos/src/rust/api/image_processing_api.dart"
+ show decodeToJpeg;
+import "package:photos/src/rust/api/ocr_api.dart";
+import "package:synchronized/synchronized.dart";
+
+class RustOcrBackend implements OcrBackend {
+ static final _logger = Logger("RustOcrBackend");
+ static const _modelVersion = "pp-ocrv5";
+ static const _transcodableExtensions = {"heic", "heif", "heics", "avif"};
+ static const _displayCacheDirectoryName = "ocr_display";
+ static const _displayCacheMaxEntries = 32;
+ static const _displayCacheMaxBytes = 256 * 1024 * 1024;
+ static const _displayJpegQuality = 95;
+ static const _noModelPaths = RustOcrModelPaths(
+ detection: "",
+ classification: "",
+ recognition: "",
+ dictionary: "",
+ );
+
+ final _engineLock = Lock();
+ OcrEngine? _engine;
+ RustOcrModelPaths _enginePaths = _noModelPaths;
+ final Map<String, String> _displayCache = {};
+ final Map<String, Future<String>> _displayInFlight = {};
+
+ @override
+ Future<ModelPreparationStatus> prepareModels(
+ Set<OcrModelComponent> components,
+ ) {
+ return _engineLock.synchronized(() async {
+ final paths = await _downloadModels(
+ includeRecognizer: components.contains(OcrModelComponent.recognizer),
+ );
+ await _ensureEngine(paths);
+ return ModelPreparationStatus(
+ isReady: true,
+ version: _modelVersion,
+ modelPath: File(paths.detection).parent.path,
+ );
+ });
+ }
+
+ Future<RustOcrModelPaths> _downloadModels({
+ required bool includeRecognizer,
+ }) async {
+ if (!includeRecognizer) {
+ final detection = await OcrDetectionModel.instance.downloadModel();
+ return RustOcrModelPaths(
+ detection: detection,
+ classification: _enginePaths.classification,
+ recognition: _enginePaths.recognition,
+ dictionary: _enginePaths.dictionary,
+ );
+ }
+ final paths = await Future.wait([
+ OcrDetectionModel.instance.downloadModel(),
+ OcrClassificationModel.instance.downloadModel(),
+ OcrRecognitionModel.instance.downloadModel(),
+ OcrDictionaryAsset.instance.downloadModel(),
+ ]);
+ return RustOcrModelPaths(
+ detection: paths[0],
+ classification: paths[1],
+ recognition: paths[2],
+ dictionary: paths[3],
+ );
+ }
+
+ Future<void> _ensureEngine(RustOcrModelPaths paths) async {
+ if (_engine != null && paths == _enginePaths) {
+ return;
+ }
+ try {
+ _engine = await OcrEngine.create(paths: paths);
+ _enginePaths = paths;
+ final loadedModels = paths.recognition.isEmpty
+ ? "detector only"
+ : "detector, classifier and recognizer";
+ _logger.info("Created Rust OCR engine ($loadedModels)");
+ } on RustOcrError catch (error) {
+ _logger.severe("Could not create the Rust OCR engine: $error");
+ throw OcrException(
+ code: "MODEL_PREP_ERROR",
+ message: _rustOcrErrorMessage(error),
+ details: error,
+ );
+ }
+ }
+
+ @override
+ Future<TextDetectionResult> detectText({
+ required String imagePath,
+ bool includeAllConfidenceScores = false,
+ String? requestId,
+ }) async {
+ final engine = _requireEngine();
+ try {
+ final result = await engine.detectText(
+ imagePath: imagePath,
+ includeAllConfidenceScores: includeAllConfidenceScores,
+ requestId: requestId,
+ );
+ return textDetectionResultFromRust(result);
+ } on RustOcrError catch (error) {
+ throw _failure(
+ error,
+ imagePath: imagePath,
+ otherCode: "RECOGNITION_ERROR",
+ );
+ }
+ }
+
+ @override
+ Future<TextRegionDetectionResult> detectTextRegions({
+ required String imagePath,
+ String? requestId,
+ }) async {
+ final engine = _requireEngine();
+ try {
+ final result = await engine.detectTextRegions(
+ imagePath: imagePath,
+ requestId: requestId,
+ );
+ return textRegionDetectionResultFromRust(result);
+ } on RustOcrError catch (error) {
+ throw _failure(error, imagePath: imagePath, otherCode: "DETECTION_ERROR");
+ }
+ }
+
+ @override
+ Future<void> cancelRequest(String requestId) async {
+ _engine?.cancel(requestId: requestId);
+ }
+
+ @override
+ Future<String> ensureDisplayablePath(String imagePath) {
+ if (!_needsTranscode(imagePath)) {
+ return Future.value(imagePath);
+ }
+ final inFlight = _displayInFlight[imagePath];
+ if (inFlight != null) {
+ return inFlight;
+ }
+ final future = _displayablePath(imagePath).whenComplete(() {
+ _displayInFlight.remove(imagePath);
+ });
+ _displayInFlight[imagePath] = future;
+ return future;
+ }
+
+ OcrEngine _requireEngine() {
+ final engine = _engine;
+ if (engine == null) {
+ throw const OcrException(
+ code: "MODEL_NOT_READY",
+ message: "OCR models have not been prepared",
+ );
+ }
+ return engine;
+ }
+
+ OcrException _failure(
+ RustOcrError error, {
+ required String imagePath,
+ required String otherCode,
+ }) {
+ final exception = ocrExceptionFromRustError(
+ error,
+ imagePath: imagePath,
+ otherCode: otherCode,
+ );
+ if (error is RustOcrError_CorruptModel) {
+ _logger.severe("Rust OCR reported a corrupt model: ${error.message}");
+ } else {
+ _logger.warning("Rust OCR failed: $exception");
+ }
+ return exception;
+ }
+
+ bool _needsTranscode(String imagePath) {
+ final extension = p.extension(imagePath).toLowerCase();
+ return extension.isNotEmpty &&
+ _transcodableExtensions.contains(extension.substring(1));
+ }
+
+ Future<String> _displayablePath(String imagePath) async {
+ try {
+ final stat = await File(imagePath).stat();
+ if (stat.type == FileSystemEntityType.notFound) {
+ return imagePath;
+ }
+ final cacheDirectory = Directory(
+ p.join(
+ (await getTemporaryDirectory()).path,
+ _displayCacheDirectoryName,
+ ),
+ );
+ final cacheFile = File(
+ p.join(cacheDirectory.path, "${_displayCacheKey(imagePath, stat)}.jpg"),
+ );
+ final cached = _displayCache.remove(imagePath);
+ if (cached == cacheFile.path && await cacheFile.exists()) {
+ _displayCache[imagePath] = cached!;
+ await cacheFile.setLastModified(DateTime.now());
+ return cached;
+ }
+ await cacheDirectory.create(recursive: true);
+ final jpeg = await decodeToJpeg(
+ imagePath: imagePath,
+ quality: _displayJpegQuality,
+ );
+ await cacheFile.writeAsBytes(jpeg, flush: true);
+ _displayCache[imagePath] = cacheFile.path;
+ if (_displayCache.length > _displayCacheMaxEntries) {
+ _displayCache.remove(_displayCache.keys.first);
+ }
+ await _trimDisplayCache(cacheDirectory);
+ return cacheFile.path;
+ } catch (e, s) {
+ _logger.warning("Could not transcode $imagePath for display", e, s);
+ return imagePath;
+ }
+ }
+
+ String _displayCacheKey(String imagePath, FileStat stat) {
+ final modified = stat.modified.millisecondsSinceEpoch;
+ return md5
+ .convert(utf8.encode("$imagePath:$modified:${stat.size}"))
+ .toString();
+ }
+
+ Future<void> _trimDisplayCache(Directory cacheDirectory) async {
+ final files = <(File, FileStat)>[];
+ await for (final entity in cacheDirectory.list()) {
+ if (entity is File) {
+ files.add((entity, await entity.stat()));
+ }
+ }
+ files.sort((a, b) => b.$2.modified.compareTo(a.$2.modified));
+ var retainedBytes = 0;
+ for (final (index, (file, stat)) in files.indexed) {
+ final retain =
+ index < _displayCacheMaxEntries &&
+ retainedBytes + stat.size <= _displayCacheMaxBytes;
+ if (retain) {
+ retainedBytes += stat.size;
+ } else {
+ await file.delete();
+ }
+ }
+ _displayCache.removeWhere(
+ (_, cachedPath) => !File(cachedPath).existsSync(),
+ );
+ }
+}
+
+TextDetectionResult textDetectionResultFromRust(
+ RustTextDetectionResult result,
+) {
+ return TextDetectionResult(
+ blocks: result.blocks
+ .map(
+ (block) => TextBlock(
+ text: block.text,
+ confidence: block.confidence,
+ points: _offsetsFromRust(block.points),
+ characters: block.characters
+ .map(
+ (character) => CharacterBox(
+ text: character.text,
+ confidence: character.confidence,
+ points: _offsetsFromRust(character.points),
+ ),
+ )
+ .toList(growable: false),
+ ),
+ )
+ .toList(growable: false),
+ imageSize: Size(
+ result.imageWidth.toDouble(),
+ result.imageHeight.toDouble(),
+ ),
+ );
+}
+
+TextRegionDetectionResult textRegionDetectionResultFromRust(
+ RustTextRegionDetectionResult result,
+) {
+ return TextRegionDetectionResult(
+ regions: result.regions
+ .map(
+ (region) => TextRegion(
+ confidence: region.confidence,
+ points: _offsetsFromRust(region.points),
+ ),
+ )
+ .toList(growable: false),
+ imageSize: Size(
+ result.imageWidth.toDouble(),
+ result.imageHeight.toDouble(),
+ ),
+ );
+}
+
+OcrException ocrExceptionFromRustError(
+ RustOcrError error, {
+ required String imagePath,
+ required String otherCode,
+}) {
+ final message = _rustOcrErrorMessage(error);
+ return switch (error) {
+ RustOcrError_ImageNotFound() => OcrException(
+ code: "IMAGE_NOT_FOUND",
+ message: "Image file does not exist at path: $imagePath",
+ details: message,
+ ),
+ RustOcrError_InvalidImage() => OcrException(
+ code: "IMAGE_DECODE_ERROR",
+ message: "Failed to decode image: $message",
+ ),
+ RustOcrError_Cancelled() => OcrException(
+ code: "CANCELLED",
+ message: message,
+ ),
+ RustOcrError_CorruptModel() => OcrException(
+ code: "MODEL_PREP_ERROR",
+ message: message,
+ ),
+ RustOcrError_Other() => OcrException(code: otherCode, message: message),
+ };
+}
+
+String _rustOcrErrorMessage(RustOcrError error) => switch (error) {
+ RustOcrError_Cancelled() => "OCR request was cancelled",
+ RustOcrError_ImageNotFound(:final message) ||
+ RustOcrError_InvalidImage(:final message) ||
+ RustOcrError_CorruptModel(:final message) ||
+ RustOcrError_Other(:final message) => message,
+};
+
+List<Offset> _offsetsFromRust(List<RustOcrPoint> points) =>
+ points.map((point) => Offset(point.x, point.y)).toList(growable: false);
diff --git a/mobile/apps/photos/lib/services/machine_learning/ocr/vision_ocr_backend.dart b/mobile/apps/photos/lib/services/machine_learning/ocr/vision_ocr_backend.dart
new file mode 100644
index 0000000000..4873fcb8a2
--- /dev/null
+++ b/mobile/apps/photos/lib/services/machine_learning/ocr/vision_ocr_backend.dart
@@ -0,0 +1,76 @@
+import "package:ente_vision/ente_vision.dart";
+import "package:flutter/services.dart";
+import "package:photos/services/machine_learning/ocr/ocr_backend.dart";
+import "package:photos/services/machine_learning/ocr/ocr_models.dart";
+
+class VisionOcrBackend implements OcrBackend {
+ VisionOcrBackend({VisionTextRecognizer? recognizer})
+ : _recognizer = recognizer ?? VisionTextRecognizer.instance;
+
+ static const _status = ModelPreparationStatus(
+ isReady: true,
+ version: "iOS-Vision",
+ modelPath: "system",
+ );
+
+ final VisionTextRecognizer _recognizer;
+
+ @override
+ Future<ModelPreparationStatus> prepareModels(
+ Set<OcrModelComponent> components,
+ ) async {
+ return _status;
+ }
+
+ @override
+ Future<TextDetectionResult> detectText({
+ required String imagePath,
+ bool includeAllConfidenceScores = false,
+ String? requestId,
+ }) {
+ return _translate(() async {
+ final result = await _recognizer.detectText(
+ imagePath: imagePath,
+ includeAllConfidenceScores: includeAllConfidenceScores,
+ requestId: requestId,
+ );
+ return TextDetectionResult.fromMap(result);
+ });
+ }
+
+ @override
+ Future<TextRegionDetectionResult> detectTextRegions({
+ required String imagePath,
+ String? requestId,
+ }) {
+ return _translate(() async {
+ final result = await _recognizer.detectTextRegions(
+ imagePath: imagePath,
+ requestId: requestId,
+ );
+ return TextRegionDetectionResult.fromMap(result);
+ });
+ }
+
+ @override
+ Future<void> cancelRequest(String requestId) {
+ return _translate(() => _recognizer.cancelRequest(requestId));
+ }
+
+ @override
+ Future<String> ensureDisplayablePath(String imagePath) async {
+ return imagePath;
+ }
+
+ Future<T> _translate<T>(Future<T> Function() operation) async {
+ try {
+ return await operation();
+ } on PlatformException catch (error) {
+ throw OcrException(
+ code: error.code,
+ message: error.message ?? "OCR operation failed",
+ details: error.details,
+ );
+ }
+ }
+}
diff --git a/mobile/apps/photos/lib/services/machine_learning/ocr_service.dart b/mobile/apps/photos/lib/services/machine_learning/ocr_service.dart
new file mode 100644
index 0000000000..2ea49cafa9
--- /dev/null
+++ b/mobile/apps/photos/lib/services/machine_learning/ocr_service.dart
@@ -0,0 +1,118 @@
+import "dart:io";
+
+import "package:logging/logging.dart";
+import "package:photos/service_locator.dart";
+import "package:photos/services/machine_learning/ocr/legacy_mobile_ocr_backend.dart";
+import "package:photos/services/machine_learning/ocr/ocr_backend.dart";
+import "package:photos/services/machine_learning/ocr/ocr_models.dart";
+import "package:photos/services/machine_learning/ocr/rust_ocr_backend.dart";
+import "package:photos/services/machine_learning/ocr/vision_ocr_backend.dart";
+
+enum OcrBackendKind { legacy, rust, vision }
+
+class OcrService {
+ OcrService({
+ required bool Function() rustOcrEnabled,
+ required bool isAndroid,
+ required bool isIOS,
+ OcrBackend Function()? createLegacyBackend,
+ OcrBackend Function()? createRustBackend,
+ OcrBackend Function()? createVisionBackend,
+ }) : _rustOcrEnabled = rustOcrEnabled,
+ _isAndroid = isAndroid,
+ _isIOS = isIOS,
+ _createLegacyBackend = createLegacyBackend ?? LegacyMobileOcrBackend.new,
+ _createRustBackend = createRustBackend ?? RustOcrBackend.new,
+ _createVisionBackend = createVisionBackend ?? VisionOcrBackend.new;
+
+ static final instance = OcrService(
+ rustOcrEnabled: () => flagService.rustOcr,
+ isAndroid: Platform.isAndroid,
+ isIOS: Platform.isIOS,
+ );
+
+ static final _logger = Logger("OcrService");
+
+ final bool Function() _rustOcrEnabled;
+ final bool _isAndroid;
+ final bool _isIOS;
+ final OcrBackend Function() _createLegacyBackend;
+ final OcrBackend Function() _createRustBackend;
+ final OcrBackend Function() _createVisionBackend;
+ final Map<OcrBackendKind, OcrBackend> _backends = {};
+ OcrBackendKind? _activeKind;
+
+ OcrBackendKind get backendKind {
+ if (!_rustOcrEnabled()) {
+ return OcrBackendKind.legacy;
+ }
+ if (_isAndroid) {
+ return OcrBackendKind.rust;
+ }
+ if (_isIOS) {
+ return OcrBackendKind.vision;
+ }
+ return OcrBackendKind.legacy;
+ }
+
+ Future<ModelPreparationStatus> prepareModels({
+ Set<OcrModelComponent>? components,
+ }) {
+ return _backend.prepareModels(
+ components ?? OcrModelComponent.values.toSet(),
+ );
+ }
+
+ Future<TextDetectionResult> detectText({
+ required String imagePath,
+ bool includeAllConfidenceScores = false,
+ String? requestId,
+ }) async {
+ _ensureImageExists(imagePath);
+ return _backend.detectText(
+ imagePath: imagePath,
+ includeAllConfidenceScores: includeAllConfidenceScores,
+ requestId: requestId,
+ );
+ }
+
+ Future<TextRegionDetectionResult> detectTextRegions({
+ required String imagePath,
+ String? requestId,
+ }) async {
+ _ensureImageExists(imagePath);
+ return _backend.detectTextRegions(
+ imagePath: imagePath,
+ requestId: requestId,
+ );
+ }
+
+ Future<void> cancelRequest(String requestId) {
+ return _backend.cancelRequest(requestId);
+ }
+
+ Future<String> ensureDisplayablePath(String imagePath) {
+ return _backend.ensureDisplayablePath(imagePath);
+ }
+
+ OcrBackend get _backend {
+ final kind = backendKind;
+ if (kind != _activeKind) {
+ _logger.info("Using the ${kind.name} OCR backend");
+ _activeKind = kind;
+ }
+ return _backends.putIfAbsent(kind, () => _createBackend(kind));
+ }
+
+ OcrBackend _createBackend(OcrBackendKind kind) => switch (kind) {
+ OcrBackendKind.legacy => _createLegacyBackend(),
+ OcrBackendKind.rust => _createRustBackend(),
+ OcrBackendKind.vision => _createVisionBackend(),
+ };
+
+ void _ensureImageExists(String imagePath) {
+ if (!File(imagePath).existsSync()) {
+ throw ArgumentError("Image file does not exist at path: $imagePath");
+ }
+ }
+}
diff --git a/mobile/apps/photos/lib/ui/viewer/file/ocr/inline_text_detection.dart b/mobile/apps/photos/lib/ui/viewer/file/ocr/inline_text_detection.dart
index 26df81209f..2aa0b0bd83 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/ocr/inline_text_detection.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/ocr/inline_text_detection.dart
@@ -6,16 +6,13 @@ import "package:flutter/material.dart";
import "package:flutter/rendering.dart";
import "package:flutter/services.dart";
import "package:logging/logging.dart";
-import "package:mobile_ocr/mobile_ocr.dart"
- show
- DisplayImageHelper,
- MobileOcr,
- OcrModelComponent,
- TextRegionDetectionResult;
import "package:photos/models/file/extensions/file_props.dart";
import "package:photos/models/file/file.dart";
import "package:photos/models/file/file_type.dart";
import "package:photos/module/download/file.dart";
+import "package:photos/services/machine_learning/ocr/ocr_models.dart"
+ show OcrModelComponent, TextRegionDetectionResult;
+import "package:photos/services/machine_learning/ocr_service.dart";
import "package:photos/states/detail_page_state.dart";
import "package:photos/ui/viewer/file/ocr/ocr_dot_wave_overlay.dart";
import "package:photos/ui/viewer/file/ocr/text_detector_widget.dart";
@@ -68,7 +65,7 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
static const double _textRegionHitSlop = 8.0;
static final Map<String, _RegionCacheEntry> _regionCache = {};
final Logger _logger = Logger("InlineTextDetection");
- final MobileOcr _mobileOcr = MobileOcr();
+ final OcrService _ocrService = OcrService.instance;
final TextDetectorController _detectorController = TextDetectorController();
bool _isEligible = false;
@@ -189,7 +186,7 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
final requestId = _activeRegionRequestId;
_activeRegionRequestId = null;
if (requestId != null) {
- unawaited(_mobileOcr.cancelRequest(requestId).catchError((_) {}));
+ unawaited(_ocrService.cancelRequest(requestId).catchError((_) {}));
}
}
@@ -252,7 +249,7 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
setState(() {
_localFilePath = localFile.path;
});
- final detectorStatus = await _mobileOcr.prepareModels(
+ final detectorStatus = await _ocrService.prepareModels(
components: {OcrModelComponent.detector},
);
if (!mounted || generation != _evaluationGeneration) return;
@@ -264,14 +261,14 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
_activeRegionRequestId = regionRequestId;
late final TextRegionDetectionResult result;
try {
- result = await _mobileOcr
+ result = await _ocrService
.detectTextRegions(
imagePath: localFile.path,
requestId: regionRequestId,
)
.timeout(_regionDetectionTimeout);
} on TimeoutException {
- await _mobileOcr.cancelRequest(regionRequestId);
+ await _ocrService.cancelRequest(regionRequestId);
rethrow;
} finally {
if (_activeRegionRequestId == regionRequestId) {
@@ -350,9 +347,7 @@ class _InlineTextDetectionState extends State<InlineTextDetection> {
}
try {
- final displayPath = await DisplayImageHelper.ensureDisplayablePath(
- localPath,
- );
+ final displayPath = await _ocrService.ensureDisplayablePath(localPath);
final imageSize = await getImageSize(FileImage(File(displayPath)));
if (!mounted ||
requestId != _imageSizeRequestId ||
diff --git a/mobile/apps/photos/lib/ui/viewer/file/ocr/text_detector_widget.dart b/mobile/apps/photos/lib/ui/viewer/file/ocr/text_detector_widget.dart
index 1c2dd46b33..72617f0ec2 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/ocr/text_detector_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/ocr/text_detector_widget.dart
@@ -3,8 +3,9 @@ import 'dart:io';
import 'package:ente_strings/ente_strings.dart';
import 'package:flutter/material.dart';
-import 'package:mobile_ocr/mobile_ocr.dart'
- show DisplayImageHelper, MobileOcr, TextBlock;
+import 'package:photos/services/machine_learning/ocr/ocr_models.dart'
+ show TextBlock;
+import 'package:photos/services/machine_learning/ocr_service.dart';
import 'package:photos/theme/colors.dart';
import 'package:photos/theme/ente_theme.dart';
import 'package:photos/ui/viewer/file/ocr/text_overlay_widget.dart';
@@ -88,7 +89,7 @@ class TextDetectorWidget extends StatefulWidget {
}
class _TextDetectorWidgetState extends State<TextDetectorWidget> {
- final MobileOcr _ocr = MobileOcr();
+ final OcrService _ocr = OcrService.instance;
final TextOverlayController _textOverlayController = TextOverlayController();
List<TextBlock>? _detectedTextBlocks;
bool _isProcessing = false;
@@ -146,9 +147,7 @@ class _TextDetectorWidgetState extends State<TextDetectorWidget> {
});
try {
- final resolvedPath = await DisplayImageHelper.ensureDisplayablePath(
- requestedPath,
- );
+ final resolvedPath = await _ocr.ensureDisplayablePath(requestedPath);
if (!mounted || widget.imagePath != requestedPath) {
return;
}
diff --git a/mobile/apps/photos/lib/ui/viewer/file/ocr/text_overlay_widget.dart b/mobile/apps/photos/lib/ui/viewer/file/ocr/text_overlay_widget.dart
index c940e8ddee..7e062b1d93 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/ocr/text_overlay_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/ocr/text_overlay_widget.dart
@@ -5,7 +5,8 @@ import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
-import 'package:mobile_ocr/mobile_ocr.dart' show CharacterBox, TextBlock;
+import 'package:photos/services/machine_learning/ocr/ocr_models.dart'
+ show CharacterBox, TextBlock;
import 'package:photos/theme/colors.dart';
import 'package:photos/theme/ente_theme.dart';
import 'package:photos/ui/viewer/file/ocr/text_reading_order.dart';
diff --git a/mobile/apps/photos/lib/ui/viewer/file/ocr/text_region_hit_test.dart b/mobile/apps/photos/lib/ui/viewer/file/ocr/text_region_hit_test.dart
index e068029bc6..0fa062976f 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/ocr/text_region_hit_test.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/ocr/text_region_hit_test.dart
@@ -1,5 +1,5 @@
import "package:flutter/widgets.dart";
-import "package:mobile_ocr/models/text_region.dart";
+import "package:photos/services/machine_learning/ocr/ocr_models.dart";
bool shouldCaptureOcrGesture({
required bool pointOnInteractiveSelectionUi,
diff --git a/mobile/apps/photos/test/services/machine_learning/ocr/ocr_models_test.dart b/mobile/apps/photos/test/services/machine_learning/ocr/ocr_models_test.dart
new file mode 100644
index 0000000000..fae6e3458d
--- /dev/null
+++ b/mobile/apps/photos/test/services/machine_learning/ocr/ocr_models_test.dart
@@ -0,0 +1,180 @@
+import "package:flutter/widgets.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:photos/services/machine_learning/ocr/ocr_models.dart";
+
+void main() {
+ const quad = [
+ {"x": 1, "y": 2},
+ {"x": 11, "y": 2},
+ {"x": 11, "y": 8.5},
+ {"x": 1, "y": 8.5},
+ ];
+
+ group("TextBlock.fromMap", () {
+ test("parses points and characters", () {
+ final block = TextBlock.fromMap({
+ "text": "hello",
+ "confidence": 0.93,
+ "points": quad,
+ "characters": [
+ {
+ "text": "h",
+ "confidence": 0.9,
+ "points": [
+ {"x": 1, "y": 2},
+ {"x": 3, "y": 2},
+ {"x": 3, "y": 8.5},
+ {"x": 1, "y": 8.5},
+ ],
+ },
+ "not a map",
+ ],
+ });
+
+ expect(block.text, "hello");
+ expect(block.confidence, 0.93);
+ expect(block.points, const [
+ Offset(1, 2),
+ Offset(11, 2),
+ Offset(11, 8.5),
+ Offset(1, 8.5),
+ ]);
+ expect(block.characters, hasLength(1));
+ expect(block.characters.single.text, "h");
+ expect(block.characters.single.confidence, 0.9);
+ expect(
+ block.characters.single.boundingBox,
+ const Rect.fromLTRB(1, 2, 3, 8.5),
+ );
+ expect(block.boundingBox, const Rect.fromLTRB(1, 2, 11, 8.5));
+ expect(block.center, const Offset(6, 5.25));
+ });
+
+ test("falls back to the rectangle when points are missing", () {
+ final block = TextBlock.fromMap({
+ "text": "rect",
+ "x": 10,
+ "y": 20,
+ "width": 30,
+ "height": 5,
+ });
+
+ expect(block.points, const [
+ Offset(10, 20),
+ Offset(40, 20),
+ Offset(40, 25),
+ Offset(10, 25),
+ ]);
+ expect(block.characters, isEmpty);
+ expect(block.confidence, 0);
+ });
+
+ test("falls back to the rectangle when points are empty", () {
+ final block = TextBlock.fromMap({
+ "points": <Object?>[],
+ "x": 0,
+ "y": 0,
+ "width": 4,
+ "height": 4,
+ });
+
+ expect(block.boundingBox, const Rect.fromLTRB(0, 0, 4, 4));
+ expect(block.text, "");
+ });
+
+ test("rejects a map without points or rectangle", () {
+ expect(() => TextBlock.fromMap({"text": "x"}), throwsArgumentError);
+ });
+
+ test("round trips through toMap", () {
+ final block = TextBlock.fromMap({
+ "text": "hello",
+ "confidence": 0.5,
+ "points": quad,
+ "characters": [
+ {"text": "h", "confidence": 0.4, "points": quad},
+ ],
+ });
+
+ final copy = TextBlock.fromMap(block.toMap());
+
+ expect(copy.text, block.text);
+ expect(copy.confidence, block.confidence);
+ expect(copy.points, block.points);
+ expect(copy.characters.single.text, "h");
+ expect(copy.characters.single.points, block.characters.single.points);
+ });
+ });
+
+ test("CharacterBox.fromMap tolerates missing fields", () {
+ final character = CharacterBox.fromMap(const {});
+
+ expect(character.text, "");
+ expect(character.confidence, 0);
+ expect(character.points, isEmpty);
+ expect(character.boundingBox, Rect.zero);
+ });
+
+ test("TextRegion.fromMap parses confidence and points", () {
+ final region = TextRegion.fromMap({"confidence": 0.75, "points": quad});
+
+ expect(region.confidence, 0.75);
+ expect(region.points, hasLength(4));
+ expect(region.boundingBox, const Rect.fromLTRB(1, 2, 11, 8.5));
+ });
+
+ test("TextDetectionResult.fromMap parses blocks and image size", () {
+ final result = TextDetectionResult.fromMap({
+ "blocks": [
+ {"text": "a", "confidence": 1, "points": quad},
+ "ignored",
+ ],
+ "imageWidth": 640,
+ "imageHeight": 480.0,
+ });
+
+ expect(result.blocks.single.text, "a");
+ expect(result.imageSize, const Size(640, 480));
+ });
+
+ test("TextDetectionResult.fromMap tolerates missing keys", () {
+ final result = TextDetectionResult.fromMap(const {});
+
+ expect(result.blocks, isEmpty);
+ expect(result.imageSize, Size.zero);
+ });
+
+ test("TextRegionDetectionResult.fromMap parses regions and size", () {
+ final result = TextRegionDetectionResult.fromMap({
+ "regions": [
+ {"confidence": 0.6, "points": quad},
+ ],
+ "imageWidth": 320,
+ "imageHeight": 240,
+ });
+
+ expect(result.regions.single.confidence, 0.6);
+ expect(result.imageSize, const Size(320, 240));
+ });
+
+ test("TextRegionDetectionResult.fromMap tolerates missing keys", () {
+ final result = TextRegionDetectionResult.fromMap(const {});
+
+ expect(result.regions, isEmpty);
+ expect(result.imageSize, Size.zero);
+ });
+
+ test("OcrException prints its code and message", () {
+ const exception = OcrException(
+ code: "IMAGE_NOT_FOUND",
+ message: "Image file does not exist",
+ details: 42,
+ );
+
+ expect(
+ exception.toString(),
+ "OcrException(IMAGE_NOT_FOUND, Image file does not exist)",
+ );
+ expect(exception.details, 42);
+ });
+}
diff --git a/mobile/apps/photos/test/services/machine_learning/ocr/ocr_service_test.dart b/mobile/apps/photos/test/services/machine_learning/ocr/ocr_service_test.dart
new file mode 100644
index 0000000000..ed773b51ba
--- /dev/null
+++ b/mobile/apps/photos/test/services/machine_learning/ocr/ocr_service_test.dart
@@ -0,0 +1,214 @@
+import "dart:io";
+
+import "package:flutter/widgets.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:photos/services/machine_learning/ocr/ocr_backend.dart";
+import "package:photos/services/machine_learning/ocr/ocr_models.dart";
+import "package:photos/services/machine_learning/ocr_service.dart";
+
+class _FakeBackend implements OcrBackend {
+ _FakeBackend(this.name);
+
+ final String name;
+ final List<String> calls = [];
+ Set<OcrModelComponent>? preparedComponents;
+
+ @override
+ Future<ModelPreparationStatus> prepareModels(
+ Set<OcrModelComponent> components,
+ ) async {
+ calls.add("prepareModels");
+ preparedComponents = components;
+ return ModelPreparationStatus(isReady: true, version: name);
+ }
+
+ @override
+ Future<TextDetectionResult> detectText({
+ required String imagePath,
+ bool includeAllConfidenceScores = false,
+ String? requestId,
+ }) async {
+ calls.add("detectText:$requestId:$includeAllConfidenceScores");
+ return const TextDetectionResult(blocks: [], imageSize: Size(1, 1));
+ }
+
+ @override
+ Future<TextRegionDetectionResult> detectTextRegions({
+ required String imagePath,
+ String? requestId,
+ }) async {
+ calls.add("detectTextRegions:$requestId");
+ return const TextRegionDetectionResult(regions: [], imageSize: Size(1, 1));
+ }
+
+ @override
+ Future<void> cancelRequest(String requestId) async {
+ calls.add("cancelRequest:$requestId");
+ }
+
+ @override
+ Future<String> ensureDisplayablePath(String imagePath) async {
+ calls.add("ensureDisplayablePath");
+ return "$name:$imagePath";
+ }
+}
+
+class _Harness {
+ _Harness({
+ required bool rustOcr,
+ required bool isAndroid,
+ required bool isIOS,
+ }) : rustOcr = rustOcr {
+ service = OcrService(
+ rustOcrEnabled: () => this.rustOcr,
+ isAndroid: isAndroid,
+ isIOS: isIOS,
+ createLegacyBackend: () => _create(legacy),
+ createRustBackend: () => _create(rust),
+ createVisionBackend: () => _create(vision),
+ );
+ }
+
+ bool rustOcr;
+ late final OcrService service;
+ final legacy = _FakeBackend("legacy");
+ final rust = _FakeBackend("rust");
+ final vision = _FakeBackend("vision");
+ final created = <String>[];
+
+ OcrBackend _create(_FakeBackend backend) {
+ created.add(backend.name);
+ return backend;
+ }
+}
+
+void main() {
+ late Directory tempDirectory;
+ late String imagePath;
+
+ setUp(() async {
+ tempDirectory = await Directory.systemTemp.createTemp("ocr_service_test");
+ imagePath = "${tempDirectory.path}/photo.jpg";
+ await File(imagePath).writeAsBytes(const [1, 2, 3]);
+ });
+
+ tearDown(() async {
+ await tempDirectory.delete(recursive: true);
+ });
+
+ test("uses the Rust backend on Android when the flag is on", () async {
+ final harness = _Harness(rustOcr: true, isAndroid: true, isIOS: false);
+
+ expect(harness.service.backendKind, OcrBackendKind.rust);
+ final status = await harness.service.prepareModels();
+ expect(status.version, "rust");
+ expect(harness.rust.preparedComponents, OcrModelComponent.values.toSet());
+ expect(harness.created, ["rust"]);
+ });
+
+ test("uses the Vision backend on iOS when the flag is on", () async {
+ final harness = _Harness(rustOcr: true, isAndroid: false, isIOS: true);
+
+ expect(harness.service.backendKind, OcrBackendKind.vision);
+ final status = await harness.service.prepareModels(
+ components: {OcrModelComponent.detector},
+ );
+ expect(status.version, "vision");
+ expect(harness.vision.preparedComponents, {OcrModelComponent.detector});
+ expect(harness.created, ["vision"]);
+ });
+
+ test("uses the legacy backend when the flag is off", () async {
+ for (final (isAndroid, isIOS) in const [(true, false), (false, true)]) {
+ final harness = _Harness(
+ rustOcr: false,
+ isAndroid: isAndroid,
+ isIOS: isIOS,
+ );
+
+ expect(harness.service.backendKind, OcrBackendKind.legacy);
+ await harness.service.cancelRequest("r");
+ expect(harness.legacy.calls, ["cancelRequest:r"]);
+ expect(harness.created, ["legacy"]);
+ }
+ });
+
+ test("uses the legacy backend on other platforms even with the flag on", () {
+ final harness = _Harness(rustOcr: true, isAndroid: false, isIOS: false);
+
+ expect(harness.service.backendKind, OcrBackendKind.legacy);
+ });
+
+ test("creates each backend once and follows flag changes per call", () async {
+ final harness = _Harness(rustOcr: false, isAndroid: true, isIOS: false);
+
+ await harness.service.cancelRequest("a");
+ harness.rustOcr = true;
+ await harness.service.cancelRequest("b");
+ await harness.service.cancelRequest("c");
+ harness.rustOcr = false;
+ await harness.service.cancelRequest("d");
+
+ expect(harness.legacy.calls, ["cancelRequest:a", "cancelRequest:d"]);
+ expect(harness.rust.calls, ["cancelRequest:b", "cancelRequest:c"]);
+ expect(harness.created, ["legacy", "rust"]);
+ });
+
+ test("detectText forwards to the backend for an existing image", () async {
+ final harness = _Harness(rustOcr: true, isAndroid: true, isIOS: false);
+
+ final result = await harness.service.detectText(
+ imagePath: imagePath,
+ includeAllConfidenceScores: true,
+ requestId: "r1",
+ );
+
+ expect(result.imageSize, const Size(1, 1));
+ expect(harness.rust.calls, ["detectText:r1:true"]);
+ });
+
+ test(
+ "detectTextRegions forwards to the backend for an existing image",
+ () async {
+ final harness = _Harness(rustOcr: true, isAndroid: false, isIOS: true);
+
+ await harness.service.detectTextRegions(
+ imagePath: imagePath,
+ requestId: "r2",
+ );
+
+ expect(harness.vision.calls, ["detectTextRegions:r2"]);
+ },
+ );
+
+ test("rejects a missing image before reaching the backend", () async {
+ final harness = _Harness(rustOcr: true, isAndroid: true, isIOS: false);
+ final missingPath = "${tempDirectory.path}/missing.jpg";
+
+ await expectLater(
+ harness.service.detectText(imagePath: missingPath),
+ throwsA(
+ isA<ArgumentError>().having(
+ (e) => e.message,
+ "message",
+ "Image file does not exist at path: $missingPath",
+ ),
+ ),
+ );
+ await expectLater(
+ harness.service.detectTextRegions(imagePath: missingPath),
+ throwsArgumentError,
+ );
+ expect(harness.rust.calls, isEmpty);
+ expect(harness.created, isEmpty);
+ });
+
+ test("ensureDisplayablePath goes through the selected backend", () async {
+ final harness = _Harness(rustOcr: true, isAndroid: true, isIOS: false);
+
+ expect(
+ await harness.service.ensureDisplayablePath("/tmp/photo.heic"),
+ "rust:/tmp/photo.heic",
+ );
+ });
+}
diff --git a/mobile/apps/photos/test/services/machine_learning/ocr/rust_ocr_backend_test.dart b/mobile/apps/photos/test/services/machine_learning/ocr/rust_ocr_backend_test.dart
new file mode 100644
index 0000000000..80bcf0b13d
--- /dev/null
+++ b/mobile/apps/photos/test/services/machine_learning/ocr/rust_ocr_backend_test.dart
@@ -0,0 +1,177 @@
+import "package:flutter/widgets.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:photos/services/machine_learning/ocr/ocr_models.dart";
+import "package:photos/services/machine_learning/ocr/rust_ocr_backend.dart";
+import "package:photos/src/rust/api/ocr_api.dart";
+
+void main() {
+ const quad = [
+ RustOcrPoint(x: 1, y: 2),
+ RustOcrPoint(x: 11, y: 2),
+ RustOcrPoint(x: 11, y: 8.5),
+ RustOcrPoint(x: 1, y: 8.5),
+ ];
+ const offsets = [
+ Offset(1, 2),
+ Offset(11, 2),
+ Offset(11, 8.5),
+ Offset(1, 8.5),
+ ];
+
+ test("converts a Rust text detection result", () {
+ const rustResult = RustTextDetectionResult(
+ blocks: [
+ RustTextBlock(
+ text: "hello",
+ confidence: 0.91,
+ points: quad,
+ characters: [
+ RustCharacterBox(text: "h", confidence: 0.8, points: quad),
+ ],
+ ),
+ ],
+ imageWidth: 640,
+ imageHeight: 480,
+ );
+
+ final result = textDetectionResultFromRust(rustResult);
+
+ expect(result.imageSize, const Size(640, 480));
+ final block = result.blocks.single;
+ expect(block.text, "hello");
+ expect(block.confidence, 0.91);
+ expect(block.points, offsets);
+ expect(block.characters.single.text, "h");
+ expect(block.characters.single.confidence, 0.8);
+ expect(block.characters.single.points, offsets);
+ });
+
+ test("converts a Rust text region detection result", () {
+ const rustResult = RustTextRegionDetectionResult(
+ regions: [RustTextRegion(confidence: 0.7, points: quad)],
+ imageWidth: 320,
+ imageHeight: 240,
+ );
+
+ final result = textRegionDetectionResultFromRust(rustResult);
+
+ expect(result.imageSize, const Size(320, 240));
+ expect(result.regions.single.confidence, 0.7);
+ expect(result.regions.single.points, offsets);
+ });
+
+ group("RustOcrError mapping", () {
+ const imagePath = "/tmp/photo.jpg";
+ OcrException map(RustOcrError error, {String otherCode = "OTHER"}) =>
+ ocrExceptionFromRustError(
+ error,
+ imagePath: imagePath,
+ otherCode: otherCode,
+ );
+
+ test("maps each variant to the legacy code and message", () {
+ expect(
+ map(const RustOcrError.imageNotFound(message: "image not found: a")),
+ isA<OcrException>()
+ .having((e) => e.code, "code", "IMAGE_NOT_FOUND")
+ .having(
+ (e) => e.message,
+ "message",
+ "Image file does not exist at path: $imagePath",
+ )
+ .having((e) => e.details, "details", "image not found: a"),
+ );
+ expect(
+ map(const RustOcrError.invalidImage(message: "bad bytes")),
+ isA<OcrException>()
+ .having((e) => e.code, "code", "IMAGE_DECODE_ERROR")
+ .having(
+ (e) => e.message,
+ "message",
+ "Failed to decode image: bad bytes",
+ ),
+ );
+ expect(
+ map(const RustOcrError.cancelled()),
+ isA<OcrException>()
+ .having((e) => e.code, "code", "CANCELLED")
+ .having((e) => e.message, "message", isNotEmpty),
+ );
+ expect(
+ map(const RustOcrError.corruptModel(message: "vocab mismatch")),
+ isA<OcrException>()
+ .having((e) => e.code, "code", "MODEL_PREP_ERROR")
+ .having((e) => e.message, "message", "vocab mismatch"),
+ );
+ });
+
+ test("maps other errors to the code of the failing operation", () {
+ const error = RustOcrError.other(message: "ort failure");
+
+ expect(
+ map(error, otherCode: "RECOGNITION_ERROR").code,
+ "RECOGNITION_ERROR",
+ );
+ expect(map(error, otherCode: "DETECTION_ERROR").code, "DETECTION_ERROR");
+ expect(map(error, otherCode: "DETECTION_ERROR").message, "ort failure");
+ });
+
+ test("messages carry the phrases the text detector widget matches", () {
+ final missing = map(
+ const RustOcrError.imageNotFound(message: "image not found: a"),
+ ).toString().toLowerCase();
+ final undecodable = map(
+ const RustOcrError.invalidImage(message: "bad bytes"),
+ ).toString().toLowerCase();
+
+ expect(missing, contains("image"));
+ expect(missing, contains("not"));
+ expect(missing, contains("exist"));
+ expect(undecodable, contains("failed to decode"));
+ });
+ });
+
+ group("without a prepared engine", () {
+ final backend = RustOcrBackend();
+
+ test("detectText throws MODEL_NOT_READY", () {
+ expect(
+ backend.detectText(imagePath: "/tmp/photo.jpg"),
+ throwsA(
+ isA<OcrException>().having((e) => e.code, "code", "MODEL_NOT_READY"),
+ ),
+ );
+ });
+
+ test("detectTextRegions throws MODEL_NOT_READY", () {
+ expect(
+ backend.detectTextRegions(imagePath: "/tmp/photo.jpg"),
+ throwsA(
+ isA<OcrException>().having((e) => e.code, "code", "MODEL_NOT_READY"),
+ ),
+ );
+ });
+
+ test("cancelRequest completes", () async {
+ await backend.cancelRequest("request");
+ });
+
+ test("ensureDisplayablePath leaves non-HEIC paths untouched", () async {
+ expect(
+ await backend.ensureDisplayablePath("/tmp/photo.JPG"),
+ "/tmp/photo.JPG",
+ );
+ expect(await backend.ensureDisplayablePath("/tmp/photo"), "/tmp/photo");
+ });
+
+ test(
+ "ensureDisplayablePath returns a missing HEIC path unchanged",
+ () async {
+ expect(
+ await backend.ensureDisplayablePath("/tmp/does-not-exist.heic"),
+ "/tmp/does-not-exist.heic",
+ );
+ },
+ );
+ });
+}
diff --git a/mobile/apps/photos/test/services/machine_learning/ocr/vision_ocr_backend_test.dart b/mobile/apps/photos/test/services/machine_learning/ocr/vision_ocr_backend_test.dart
new file mode 100644
index 0000000000..bb78038145
--- /dev/null
+++ b/mobile/apps/photos/test/services/machine_learning/ocr/vision_ocr_backend_test.dart
@@ -0,0 +1,166 @@
+import "package:ente_vision/ente_vision.dart";
+import "package:flutter/services.dart";
+import "package:flutter/widgets.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:photos/services/machine_learning/ocr/ocr_models.dart";
+import "package:photos/services/machine_learning/ocr/vision_ocr_backend.dart";
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ const channel = MethodChannel("io.ente.photos.vision/text_recognition");
+ final backend = VisionOcrBackend(
+ recognizer: VisionTextRecognizer(methodChannel: channel),
+ );
+ final calls = <MethodCall>[];
+ Future<Object?> Function(MethodCall call) reply = (_) async => null;
+
+ setUp(() {
+ calls.clear();
+ reply = (_) async => null;
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(channel, (call) {
+ calls.add(call);
+ return reply(call);
+ });
+ });
+
+ tearDown(() {
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(channel, null);
+ });
+
+ test("prepareModels is ready without downloading anything", () async {
+ final status = await backend.prepareModels(
+ OcrModelComponent.values.toSet(),
+ );
+
+ expect(status.isReady, isTrue);
+ expect(status.version, "iOS-Vision");
+ expect(status.modelPath, "system");
+ expect(calls, isEmpty);
+ });
+
+ test("detectText forwards its arguments and parses the result", () async {
+ reply = (_) async => {
+ "blocks": [
+ {
+ "text": "hello",
+ "confidence": 0.9,
+ "points": [
+ {"x": 1.0, "y": 2.0},
+ {"x": 10.0, "y": 2.0},
+ {"x": 10.0, "y": 8.0},
+ {"x": 1.0, "y": 8.0},
+ ],
+ "characters": <Object?>[],
+ },
+ ],
+ "imageWidth": 640,
+ "imageHeight": 480,
+ };
+
+ final result = await backend.detectText(
+ imagePath: "/tmp/photo.jpg",
+ includeAllConfidenceScores: true,
+ requestId: "request-1",
+ );
+
+ expect(calls.single.method, "textRecognition.detectText");
+ expect(calls.single.arguments, {
+ "imagePath": "/tmp/photo.jpg",
+ "includeAllConfidenceScores": true,
+ "requestId": "request-1",
+ });
+ expect(result.blocks.single.text, "hello");
+ expect(result.blocks.single.boundingBox, const Rect.fromLTRB(1, 2, 10, 8));
+ expect(result.imageSize, const Size(640, 480));
+ });
+
+ test(
+ "detectTextRegions forwards its arguments and parses the result",
+ () async {
+ reply = (_) async => {
+ "regions": [
+ {
+ "confidence": 0.75,
+ "points": [
+ {"x": 0.0, "y": 0.0},
+ {"x": 5.0, "y": 0.0},
+ {"x": 5.0, "y": 3.0},
+ {"x": 0.0, "y": 3.0},
+ ],
+ },
+ ],
+ "imageWidth": 320,
+ "imageHeight": 240,
+ };
+
+ final result = await backend.detectTextRegions(
+ imagePath: "/tmp/photo.jpg",
+ requestId: "request-2",
+ );
+
+ expect(calls.single.method, "textRecognition.detectTextRegions");
+ expect(calls.single.arguments, {
+ "imagePath": "/tmp/photo.jpg",
+ "requestId": "request-2",
+ });
+ expect(result.regions.single.confidence, 0.75);
+ expect(result.imageSize, const Size(320, 240));
+ },
+ );
+
+ test("an empty native result becomes an empty detection", () async {
+ final result = await backend.detectText(imagePath: "/tmp/photo.jpg");
+
+ expect(result.blocks, isEmpty);
+ expect(result.imageSize, Size.zero);
+ });
+
+ test("cancelRequest forwards the request id", () async {
+ await backend.cancelRequest("request-3");
+
+ expect(calls.single.method, "textRecognition.cancelRequest");
+ expect(calls.single.arguments, {"requestId": "request-3"});
+ });
+
+ test("platform exceptions become OcrExceptions", () async {
+ reply = (_) async => throw PlatformException(
+ code: "IMAGE_DECODE_ERROR",
+ message: "Failed to decode image",
+ details: {"path": "/tmp/photo.jpg"},
+ );
+
+ await expectLater(
+ backend.detectText(imagePath: "/tmp/photo.jpg"),
+ throwsA(
+ isA<OcrException>()
+ .having((e) => e.code, "code", "IMAGE_DECODE_ERROR")
+ .having((e) => e.message, "message", "Failed to decode image")
+ .having((e) => e.details, "details", {"path": "/tmp/photo.jpg"}),
+ ),
+ );
+ });
+
+ test("a platform exception without a message gets a default one", () async {
+ reply = (_) async => throw PlatformException(code: "CANCELLED");
+
+ await expectLater(
+ backend.detectTextRegions(imagePath: "/tmp/photo.jpg"),
+ throwsA(
+ isA<OcrException>()
+ .having((e) => e.code, "code", "CANCELLED")
+ .having((e) => e.message, "message", "OCR operation failed"),
+ ),
+ );
+ });
+
+ test("ensureDisplayablePath returns the path unchanged", () async {
+ expect(
+ await backend.ensureDisplayablePath("/tmp/photo.heic"),
+ "/tmp/photo.heic",
+ );
+ expect(calls, isEmpty);
+ });
+}
diff --git a/mobile/apps/photos/test/ui/viewer/file/ocr/text_region_hit_test_test.dart b/mobile/apps/photos/test/ui/viewer/file/ocr/text_region_hit_test_test.dart
index 2900683e3b..b2d17b7f30 100644
--- a/mobile/apps/photos/test/ui/viewer/file/ocr/text_region_hit_test_test.dart
+++ b/mobile/apps/photos/test/ui/viewer/file/ocr/text_region_hit_test_test.dart
@@ -1,6 +1,6 @@
import "package:flutter/widgets.dart";
import "package:flutter_test/flutter_test.dart";
-import "package:mobile_ocr/models/text_region.dart";
+import "package:photos/services/machine_learning/ocr/ocr_models.dart";
import "package:photos/ui/viewer/file/ocr/text_region_hit_test.dart";
void main() {
diff --git a/mobile/packages/feature_flag/lib/src/flag_service.dart b/mobile/packages/feature_flag/lib/src/flag_service.dart
index df1199071b..8dd44c3758 100644
--- a/mobile/packages/feature_flag/lib/src/flag_service.dart
+++ b/mobile/packages/feature_flag/lib/src/flag_service.dart
@@ -117,6 +117,8 @@ class FlagService {
bool get ocrOverlayEnabled => true;
+ bool get rustOcr => internalUser;
+
bool get enableBgLocalUploadPriority => internalUser;
bool get syncRecoveryDiagnostics => internalUser;