Skip to content

armgit / ente

Public Imported from GitHub
0

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

Integrate pet recognition into ML indexing pipeline with feature flag

Amrithesh Kakkoth Ente2668b3db2bf2
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart b/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart
index ec0952fe31..f2d057c962 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart
@@ -8,6 +8,7 @@ import 'package:photos/services/machine_learning/face_ml/face_detection/face_det
import 'package:photos/services/machine_learning/face_ml/face_embedding/face_embedding_service.dart';
import "package:photos/services/machine_learning/ml_models_overview.dart";
import 'package:photos/services/machine_learning/ml_result.dart';
+import "package:photos/services/machine_learning/pet_ml/pet_model_services.dart";
import "package:photos/services/machine_learning/semantic_search/clip/clip_image_encoder.dart";
import "package:photos/services/remote_assets_service.dart";
import "package:photos/utils/isolate/isolate_operations.dart";
@@ -29,7 +30,7 @@ class MLIndexingIsolate extends SuperIsolate {
String get isolateName => "MLIndexingIsolate";
@override
- bool get shouldAutomaticDispose => true;
+ bool get shouldAutomaticDispose => false;
bool get _shouldUseRustMl => flagService.useRustForML || isOfflineMode;
@@ -87,6 +88,7 @@ class MLIndexingIsolate extends SuperIsolate {
"useRustMl": useRustMl,
"runFaces": instruction.shouldRunFaces,
"runClip": instruction.shouldRunClip,
+ "runPets": useRustMl && flagService.petEnabled,
...rustRuntimeArgs,
"faceDetectionAddress": FaceDetectionService.instance.sessionAddress,
"faceEmbeddingAddress": FaceEmbeddingService.instance.sessionAddress,
@@ -175,11 +177,24 @@ class MLIndexingIsolate extends SuperIsolate {
return;
}
_logger.info('Downloading models');
- await Future.wait([
+ final modelsToDownload = <Future<void>>[
FaceDetectionService.instance.downloadModel(forceRefresh),
FaceEmbeddingService.instance.downloadModel(forceRefresh),
ClipImageEncoder.instance.downloadModel(forceRefresh),
- ]);
+ ];
+
+ if (flagService.petEnabled) {
+ modelsToDownload.addAll([
+ PetFaceDetectionService.instance.downloadModel(forceRefresh),
+ PetFaceEmbeddingDogService.instance.downloadModel(forceRefresh),
+ PetFaceEmbeddingCatService.instance.downloadModel(forceRefresh),
+ PetBodyDetectionService.instance.downloadModel(forceRefresh),
+ PetBodyEmbeddingDogService.instance.downloadModel(forceRefresh),
+ PetBodyEmbeddingCatService.instance.downloadModel(forceRefresh),
+ ]);
+ }
+
+ await Future.wait(modelsToDownload);
areModelsDownloaded = true;
_logger.info('Downloaded models');
});
@@ -348,13 +363,42 @@ class MLIndexingIsolate extends SuperIsolate {
final faceEmbedding =
await FaceEmbeddingService.instance.getModelNameAndPath();
final clipImage = await ClipImageEncoder.instance.getModelNameAndPath();
+
+ String petFaceDetectionPath = "";
+ String petFaceEmbeddingDogPath = "";
+ String petFaceEmbeddingCatPath = "";
+ String petBodyDetectionPath = "";
+ String petBodyEmbeddingDogPath = "";
+ String petBodyEmbeddingCatPath = "";
+
+ if (flagService.petEnabled) {
+ petFaceDetectionPath =
+ (await PetFaceDetectionService.instance.getModelNameAndPath()).$2;
+ petFaceEmbeddingDogPath =
+ (await PetFaceEmbeddingDogService.instance.getModelNameAndPath()).$2;
+ petFaceEmbeddingCatPath =
+ (await PetFaceEmbeddingCatService.instance.getModelNameAndPath()).$2;
+ petBodyDetectionPath =
+ (await PetBodyDetectionService.instance.getModelNameAndPath()).$2;
+ petBodyEmbeddingDogPath =
+ (await PetBodyEmbeddingDogService.instance.getModelNameAndPath()).$2;
+ petBodyEmbeddingCatPath =
+ (await PetBodyEmbeddingCatService.instance.getModelNameAndPath()).$2;
+ }
+
return {
"faceDetectionModelPath": faceDetection.$2,
"faceEmbeddingModelPath": faceEmbedding.$2,
"clipImageModelPath": clipImage.$2,
+ "petFaceDetectionModelPath": petFaceDetectionPath,
+ "petFaceEmbeddingDogModelPath": petFaceEmbeddingDogPath,
+ "petFaceEmbeddingCatModelPath": petFaceEmbeddingCatPath,
+ "petBodyDetectionModelPath": petBodyDetectionPath,
+ "petBodyEmbeddingDogModelPath": petBodyEmbeddingDogPath,
+ "petBodyEmbeddingCatModelPath": petBodyEmbeddingCatPath,
"preferCoreml": Platform.isIOS,
- "preferNnapi": Platform.isAndroid,
- "preferXnnpack": Platform.isAndroid,
+ "preferNnapi": false,
+ "preferXnnpack": false,
"allowCpuFallback": true,
};
}
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_models_overview.dart b/mobile/apps/photos/lib/services/machine_learning/ml_models_overview.dart
index bb1ec97d30..f1ca929a84 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_models_overview.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_models_overview.dart
@@ -1,6 +1,7 @@
import "package:photos/services/machine_learning/face_ml/face_detection/face_detection_service.dart";
import "package:photos/services/machine_learning/face_ml/face_embedding/face_embedding_service.dart";
import "package:photos/services/machine_learning/ml_model.dart";
+import "package:photos/services/machine_learning/pet_ml/pet_model_services.dart";
import "package:photos/services/machine_learning/semantic_search/clip/clip_image_encoder.dart";
import "package:photos/services/machine_learning/semantic_search/clip/clip_text_encoder.dart";
@@ -9,6 +10,12 @@ enum MLModels {
faceEmbedding,
clipImageEncoder,
clipTextEncoder,
+ petFaceDetection,
+ petFaceEmbeddingDog,
+ petFaceEmbeddingCat,
+ petBodyDetection,
+ petBodyEmbeddingDog,
+ petBodyEmbeddingCat,
}
extension MLModelsExtension on MLModels {
@@ -22,6 +29,18 @@ extension MLModelsExtension on MLModels {
return ClipImageEncoder.instance;
case MLModels.clipTextEncoder:
return ClipTextEncoder.instance;
+ case MLModels.petFaceDetection:
+ return PetFaceDetectionService.instance;
+ case MLModels.petFaceEmbeddingDog:
+ return PetFaceEmbeddingDogService.instance;
+ case MLModels.petFaceEmbeddingCat:
+ return PetFaceEmbeddingCatService.instance;
+ case MLModels.petBodyDetection:
+ return PetBodyDetectionService.instance;
+ case MLModels.petBodyEmbeddingDog:
+ return PetBodyEmbeddingDogService.instance;
+ case MLModels.petBodyEmbeddingCat:
+ return PetBodyEmbeddingCatService.instance;
}
}
@@ -30,6 +49,12 @@ extension MLModelsExtension on MLModels {
case MLModels.faceDetection:
case MLModels.faceEmbedding:
case MLModels.clipImageEncoder:
+ case MLModels.petFaceDetection:
+ case MLModels.petFaceEmbeddingDog:
+ case MLModels.petFaceEmbeddingCat:
+ case MLModels.petBodyDetection:
+ case MLModels.petBodyEmbeddingDog:
+ case MLModels.petBodyEmbeddingCat:
return true;
case MLModels.clipTextEncoder:
return false;
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_result.dart b/mobile/apps/photos/lib/services/machine_learning/ml_result.dart
index 920cf1b83b..422eb1a496 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_result.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_result.dart
@@ -12,6 +12,8 @@ class MLResult {
List<FaceResult>? faces = <FaceResult>[];
ClipResult? clip;
+ List<PetFaceResult>? petFaces;
+ List<PetBodyResult>? petBodies;
Dimensions decodedImageSize;
@@ -23,6 +25,8 @@ class MLResult {
this.fileId = -1,
this.faces,
this.clip,
+ this.petFaces,
+ this.petBodies,
this.decodedImageSize = const Dimensions(width: -1, height: -1),
});
@@ -35,6 +39,8 @@ class MLResult {
'fileId': fileId,
'faces': faces?.map((face) => face.toJson()).toList(),
'clip': clip?.toJson(),
+ 'petFaces': petFaces?.map((pf) => pf.toJson()).toList(),
+ 'petBodies': petBodies?.map((pb) => pb.toJson()).toList(),
'decodedImageSize': {
'width': decodedImageSize.width,
'height': decodedImageSize.height,
@@ -54,6 +60,20 @@ class MLResult {
clip: json['clip'] != null
? ClipResult.fromJson(json['clip'] as Map<String, dynamic>)
: null,
+ petFaces: json['petFaces'] != null
+ ? (json['petFaces'] as List)
+ .map(
+ (item) => PetFaceResult.fromJson(item as Map<String, dynamic>),
+ )
+ .toList()
+ : null,
+ petBodies: json['petBodies'] != null
+ ? (json['petBodies'] as List)
+ .map(
+ (item) => PetBodyResult.fromJson(item as Map<String, dynamic>),
+ )
+ .toList()
+ : null,
decodedImageSize: json['decodedImageSize'] != null
? Dimensions(
width: json['decodedImageSize']['width'],
@@ -176,3 +196,75 @@ int? tryGetFileIdFromFaceId(String faceId) {
return null;
}
}
+
+class PetFaceResult {
+ late FaceDetectionRelative detection;
+ late AlignmentResult alignment;
+ late int species;
+ late Embedding embedding;
+ late int fileId;
+ late String petFaceId;
+
+ PetFaceResult({
+ required this.fileId,
+ required this.petFaceId,
+ required this.detection,
+ required this.alignment,
+ required this.species,
+ required this.embedding,
+ });
+
+ Map<String, dynamic> toJson() => {
+ 'detection': detection.toJson(),
+ 'alignment': alignment.toJson(),
+ 'species': species,
+ 'embedding': embedding,
+ 'fileId': fileId,
+ 'petFaceId': petFaceId,
+ };
+
+ static PetFaceResult fromJson(Map<String, dynamic> json) {
+ return PetFaceResult(
+ detection: FaceDetectionRelative.fromJson(json['detection']),
+ alignment: AlignmentResult.fromJson(json['alignment']),
+ species: json['species'],
+ embedding: Embedding.from(json['embedding']),
+ fileId: json['fileId'],
+ petFaceId: json['petFaceId'],
+ );
+ }
+}
+
+class PetBodyResult {
+ late List<double> boxXyxy;
+ late double score;
+ late int cocoClass;
+ late String petBodyId;
+ late Embedding embedding;
+
+ PetBodyResult({
+ required this.boxXyxy,
+ required this.score,
+ required this.cocoClass,
+ required this.petBodyId,
+ required this.embedding,
+ });
+
+ Map<String, dynamic> toJson() => {
+ 'boxXyxy': boxXyxy,
+ 'score': score,
+ 'cocoClass': cocoClass,
+ 'petBodyId': petBodyId,
+ 'embedding': embedding,
+ };
+
+ static PetBodyResult fromJson(Map<String, dynamic> json) {
+ return PetBodyResult(
+ boxXyxy: (json['boxXyxy'] as List).cast<double>(),
+ score: json['score'],
+ cocoClass: json['cocoClass'],
+ petBodyId: json['petBodyId'],
+ embedding: Embedding.from(json['embedding']),
+ );
+ }
+}
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
index aa833142bd..7bab2d7d7b 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
@@ -1,13 +1,16 @@
import "dart:async";
+import "dart:convert" show jsonEncode;
import "dart:io" show Platform;
import "dart:math" show min;
-import "dart:typed_data" show Uint8List;
+import "dart:typed_data" show Float32List, Uint8List;
import "package:flutter/foundation.dart" show kDebugMode;
import "package:logging/logging.dart";
import "package:photos/core/event_bus.dart";
import "package:photos/db/files_db.dart";
import "package:photos/db/ml/db.dart";
+import "package:photos/db/ml/db_pet_model_mappers.dart";
+import "package:photos/db/ml/pet_vector_db.dart";
import "package:photos/db/offline_files_db.dart";
import "package:photos/events/compute_control_event.dart";
import "package:photos/events/people_changed_event.dart";
@@ -18,6 +21,7 @@ import "package:photos/service_locator.dart";
import "package:photos/services/filedata/model/file_data.dart";
import 'package:photos/services/machine_learning/face_ml/face_clustering/face_clustering_service.dart';
import "package:photos/services/machine_learning/face_ml/face_clustering/face_db_info_for_clustering.dart";
+import "package:photos/services/machine_learning/face_ml/face_detection/detection.dart";
import "package:photos/services/machine_learning/face_ml/person/person_service.dart";
import "package:photos/services/machine_learning/ml_indexing_isolate.dart";
import 'package:photos/services/machine_learning/ml_result.dart';
@@ -46,6 +50,7 @@ class MLService {
bool get showClusteringIsHappening => _clusteringIsHappening;
bool debugIndexingDisabled = false;
+ bool debugPetOnlyMode = false;
bool _clusteringIsHappening = false;
bool _mlControllerStatus = false;
bool _isIndexingOrClusteringRunning = false;
@@ -268,7 +273,11 @@ class MLService {
await MLIndexingIsolate.instance.ensureDownloadedModels();
}
final Stream<List<FileMLInstruction>> instructionStream =
- fetchEmbeddingsAndInstructions(fileDownloadMlLimit, mode: mode);
+ fetchEmbeddingsAndInstructions(
+ fileDownloadMlLimit,
+ mode: mode,
+ forceAll: debugPetOnlyMode || flagService.petEnabled,
+ );
int fileAnalyzedCount = 0;
final Stopwatch stopwatch = Stopwatch()..start();
@@ -532,6 +541,12 @@ class MLService {
Future<bool> processImage(FileMLInstruction instruction) async {
bool actuallyRanML = false;
+ // In pet-only mode, skip faces and clip to only run pet recognition
+ if (debugPetOnlyMode) {
+ instruction.shouldRunFaces = false;
+ instruction.shouldRunClip = false;
+ }
+
final mlDataDB = _dbForMode(instruction.mode);
try {
final String filePath = await getImagePathForML(instruction.file);
@@ -626,6 +641,81 @@ class MLService {
);
}
}
+
+ // Pet results locally
+ final rustPets = result.petFaces != null || result.petBodies != null;
+ if (rustPets) {
+ if (result.petFaces != null && result.petFaces!.isNotEmpty) {
+ final dbPetFaces = result.petFaces!.map((pf) {
+ final floatList = Float32List.fromList(pf.embedding);
+ final blob = Uint8List.view(
+ floatList.buffer,
+ floatList.offsetInBytes,
+ floatList.lengthInBytes,
+ );
+ return DBPetFace(
+ fileId: result.fileId,
+ petFaceId: pf.petFaceId,
+ detection: jsonEncode(pf.detection.toJson()),
+ landmarks: jsonEncode(
+ pf.detection.allKeypoints.map((kp) => [kp[0], kp[1]]).toList(),
+ ),
+ faceVectorId: -1,
+ species: pf.species == 0 ? "dog" : "cat",
+ faceScore: pf.detection.score,
+ imageHeight: result.decodedImageSize.height,
+ imageWidth: result.decodedImageSize.width,
+ mlVersion: faceMlVersion,
+ embeddingBlob: blob,
+ );
+ }).toList();
+ await mlDataDB.bulkInsertPetFaces(dbPetFaces);
+ await _storePetFaceEmbeddings(
+ dbPetFaces,
+ result.petFaces!,
+ mlDataDB,
+ );
+ }
+
+ if (result.petBodies != null && result.petBodies!.isNotEmpty) {
+ final dbPetBodies = result.petBodies!.map((pb) {
+ final detectionObj = FaceDetectionRelative(
+ score: pb.score,
+ box: [
+ pb.boxXyxy[0],
+ pb.boxXyxy[1],
+ pb.boxXyxy[2],
+ pb.boxXyxy[3],
+ ],
+ allKeypoints: const [],
+ );
+ final floatList = Float32List.fromList(pb.embedding);
+ final blob = Uint8List.view(
+ floatList.buffer,
+ floatList.offsetInBytes,
+ floatList.lengthInBytes,
+ );
+ return DBPetBody(
+ fileId: result.fileId,
+ petBodyId: pb.petBodyId,
+ detection: jsonEncode(detectionObj.toJson()),
+ bodyVectorId: -1,
+ species: pb.cocoClass == 15 ? "cat" : "dog",
+ faceScore: pb.score,
+ imageHeight: result.decodedImageSize.height,
+ imageWidth: result.decodedImageSize.width,
+ mlVersion: faceMlVersion,
+ embeddingBlob: blob,
+ );
+ }).toList();
+ await mlDataDB.bulkInsertPetBodies(dbPetBodies);
+ await _storePetBodyEmbeddings(
+ dbPetBodies,
+ result.petBodies!,
+ mlDataDB,
+ );
+ }
+ }
_logger.info("ML result for fileID ${result.fileId} stored remote+local");
return actuallyRanML;
} catch (e, s) {
@@ -665,6 +755,120 @@ class MLService {
}
}
+ /// Store pet face embeddings into PetVectorDB after SQLite insert.
+ /// Failure is logged but does not block indexing.
+ Future<void> _storePetFaceEmbeddings(
+ List<DBPetFace> dbPetFaces,
+ List<PetFaceResult> petFaces,
+ MLDataDB mlDataDB,
+ ) async {
+ try {
+ // Group by species
+ final bySpecies = <int, List<(DBPetFace, PetFaceResult)>>{};
+ for (int i = 0; i < dbPetFaces.length; i++) {
+ final species = petFaces[i].species;
+ bySpecies.putIfAbsent(species, () => []);
+ bySpecies[species]!.add((dbPetFaces[i], petFaces[i]));
+ }
+ for (final entry in bySpecies.entries) {
+ final vdb = PetVectorDB.forModel(
+ species: entry.key,
+ isFace: true,
+ );
+ final petFaceIds = entry.value.map((e) => e.$1.petFaceId).toList();
+ final idMap = await vdb.getPetFaceVectorIdMap(
+ petFaceIds,
+ createIfMissing: true,
+ );
+ final vectorIds = <int>[];
+ final embeddings = <Float32List>[];
+ for (final (dbFace, pfResult) in entry.value) {
+ final vid = idMap[dbFace.petFaceId];
+ if (vid == null) continue;
+ final emb = Float32List.fromList(pfResult.embedding);
+ if (emb.length != PetVectorDB.faceDimension) {
+ _logger.warning(
+ "Skipping pet face embedding with wrong dimension ${emb.length}",
+ );
+ continue;
+ }
+ vectorIds.add(vid);
+ embeddings.add(emb);
+ }
+ if (vectorIds.isNotEmpty) {
+ await vdb.bulkInsertEmbeddings(
+ vectorIds: vectorIds,
+ embeddings: embeddings,
+ );
+ final updateMap = Map.fromIterables(
+ entry.value.map((e) => e.$1.petFaceId),
+ vectorIds,
+ );
+ await mlDataDB.updatePetFaceVectorIds(updateMap);
+ }
+ }
+ } catch (e, s) {
+ _logger.severe("Failed to store pet face embeddings in vector DB", e, s);
+ }
+ }
+
+ /// Store pet body embeddings into PetVectorDB after SQLite insert.
+ /// Failure is logged but does not block indexing.
+ Future<void> _storePetBodyEmbeddings(
+ List<DBPetBody> dbPetBodies,
+ List<PetBodyResult> petBodies,
+ MLDataDB mlDataDB,
+ ) async {
+ try {
+ // Group by species
+ final bySpecies = <int, List<(DBPetBody, PetBodyResult)>>{};
+ for (int i = 0; i < dbPetBodies.length; i++) {
+ final species = petBodies[i].cocoClass == 15 ? 1 : 0;
+ bySpecies.putIfAbsent(species, () => []);
+ bySpecies[species]!.add((dbPetBodies[i], petBodies[i]));
+ }
+ for (final entry in bySpecies.entries) {
+ final vdb = PetVectorDB.forModel(
+ species: entry.key,
+ isFace: false,
+ );
+ final petBodyIds = entry.value.map((e) => e.$1.petBodyId).toList();
+ final idMap = await vdb.getPetBodyVectorIdMap(
+ petBodyIds,
+ createIfMissing: true,
+ );
+ final vectorIds = <int>[];
+ final embeddings = <Float32List>[];
+ for (final (dbBody, pbResult) in entry.value) {
+ final vid = idMap[dbBody.petBodyId];
+ if (vid == null) continue;
+ final emb = Float32List.fromList(pbResult.embedding);
+ if (emb.length != PetVectorDB.bodyDimension) {
+ _logger.warning(
+ "Skipping pet body embedding with wrong dimension ${emb.length}",
+ );
+ continue;
+ }
+ vectorIds.add(vid);
+ embeddings.add(emb);
+ }
+ if (vectorIds.isNotEmpty) {
+ await vdb.bulkInsertEmbeddings(
+ vectorIds: vectorIds,
+ embeddings: embeddings,
+ );
+ final updateMap = Map.fromIterables(
+ entry.value.map((e) => e.$1.petBodyId),
+ vectorIds,
+ );
+ await mlDataDB.updatePetBodyVectorIds(updateMap);
+ }
+ }
+ } catch (e, s) {
+ _logger.severe("Failed to store pet body embeddings in vector DB", e, s);
+ }
+ }
+
bool _canRunMLFunction({required String function}) {
if (kDebugMode && Platform.isIOS && !_isIndexingOrClusteringRunning) {
return true;
diff --git a/mobile/apps/photos/lib/services/machine_learning/pet_ml/pet_model_services.dart b/mobile/apps/photos/lib/services/machine_learning/pet_ml/pet_model_services.dart
new file mode 100644
index 0000000000..4557cf662d
--- /dev/null
+++ b/mobile/apps/photos/lib/services/machine_learning/pet_ml/pet_model_services.dart
@@ -0,0 +1,123 @@
+import 'package:logging/logging.dart';
+import "package:photos/services/machine_learning/ml_model.dart";
+
+/// Pet face detection model (YOLOv5-face with 3 keypoints).
+/// Model: yolov5n_petface_v2.onnx β€” detects pet faces with left_eye, right_eye, nose landmarks.
+class PetFaceDetectionService extends MlModel {
+ static const kRemoteBucketModelPath = "yolov5s_pet_face_fp16.onnx";
+ static const _modelName = "YOLOv5PetFace";
+
+ @override
+ String get modelRemotePath => kModelBucketEndpoint + kRemoteBucketModelPath;
+
+ @override
+ Logger get logger => _logger;
+ static final _logger = Logger('PetFaceDetectionService');
+
+ @override
+ String get modelName => _modelName;
+
+ PetFaceDetectionService._privateConstructor();
+ static final instance = PetFaceDetectionService._privateConstructor();
+ factory PetFaceDetectionService() => instance;
+}
+
+/// Dog face embedding model (BYOL 128-d).
+class PetFaceEmbeddingDogService extends MlModel {
+ static const kRemoteBucketModelPath = "dog_face_embedding128.onnx";
+ static const _modelName = "DogFaceByol128";
+
+ @override
+ String get modelRemotePath => kModelBucketEndpoint + kRemoteBucketModelPath;
+
+ @override
+ Logger get logger => _logger;
+ static final _logger = Logger('PetFaceEmbeddingDogService');
+
+ @override
+ String get modelName => _modelName;
+
+ PetFaceEmbeddingDogService._privateConstructor();
+ static final instance = PetFaceEmbeddingDogService._privateConstructor();
+ factory PetFaceEmbeddingDogService() => instance;
+}
+
+/// Cat face embedding model (BYOL 128-d).
+class PetFaceEmbeddingCatService extends MlModel {
+ static const kRemoteBucketModelPath = "cat_face_embedding128.onnx";
+ static const _modelName = "CatFaceByol128";
+
+ @override
+ String get modelRemotePath => kModelBucketEndpoint + kRemoteBucketModelPath;
+
+ @override
+ Logger get logger => _logger;
+ static final _logger = Logger('PetFaceEmbeddingCatService');
+
+ @override
+ String get modelName => _modelName;
+
+ PetFaceEmbeddingCatService._privateConstructor();
+ static final instance = PetFaceEmbeddingCatService._privateConstructor();
+ factory PetFaceEmbeddingCatService() => instance;
+}
+
+/// Pet body detection model (YOLOv5s β€” COCO classes 15=cat, 16=dog).
+class PetBodyDetectionService extends MlModel {
+ static const kRemoteBucketModelPath = "yolov5s_object_fp16.onnx";
+ static const _modelName = "YOLOv5sPetBody";
+
+ @override
+ String get modelRemotePath => kModelBucketEndpoint + kRemoteBucketModelPath;
+
+ @override
+ Logger get logger => _logger;
+ static final _logger = Logger('PetBodyDetectionService');
+
+ @override
+ String get modelName => _modelName;
+
+ PetBodyDetectionService._privateConstructor();
+ static final instance = PetBodyDetectionService._privateConstructor();
+ factory PetBodyDetectionService() => instance;
+}
+
+/// Dog body embedding model.
+class PetBodyEmbeddingDogService extends MlModel {
+ static const kRemoteBucketModelPath = "dog_body_embedding192.onnx";
+ static const _modelName = "DogBody";
+
+ @override
+ String get modelRemotePath => kModelBucketEndpoint + kRemoteBucketModelPath;
+
+ @override
+ Logger get logger => _logger;
+ static final _logger = Logger('PetBodyEmbeddingDogService');
+
+ @override
+ String get modelName => _modelName;
+
+ PetBodyEmbeddingDogService._privateConstructor();
+ static final instance = PetBodyEmbeddingDogService._privateConstructor();
+ factory PetBodyEmbeddingDogService() => instance;
+}
+
+/// Cat body embedding model.
+class PetBodyEmbeddingCatService extends MlModel {
+ static const kRemoteBucketModelPath = "cat_body_embedding192.onnx";
+ static const _modelName = "CatBody";
+
+ @override
+ String get modelRemotePath => kModelBucketEndpoint + kRemoteBucketModelPath;
+
+ @override
+ Logger get logger => _logger;
+ static final _logger = Logger('PetBodyEmbeddingCatService');
+
+ @override
+ String get modelName => _modelName;
+
+ PetBodyEmbeddingCatService._privateConstructor();
+ static final instance = PetBodyEmbeddingCatService._privateConstructor();
+ factory PetBodyEmbeddingCatService() => instance;
+}
diff --git a/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart b/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart
index 9a4c6be837..274b6bc805 100644
--- a/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart
@@ -16,6 +16,7 @@ import "package:photos/models/ml/ml_versions.dart";
import "package:photos/service_locator.dart";
import "package:photos/services/collections_service.dart";
import "package:photos/services/machine_learning/ml_computer.dart";
+import "package:photos/services/machine_learning/ml_service.dart";
import "package:photos/services/machine_learning/ml_result.dart";
import "package:photos/services/machine_learning/semantic_search/clip/clip_image_encoder.dart";
import "package:photos/services/machine_learning/semantic_search/query_result.dart";
@@ -327,6 +328,10 @@ class SemanticSearchService {
}
Future<void> _loadTextModel({bool delay = false}) async {
+ if (MLService.instance.debugPetOnlyMode) {
+ _logger.info("Skipping ClipText load (debugPetOnlyMode)");
+ return;
+ }
_logger.info("Initializing ClipText");
try {
if (delay) await Future.delayed(const Duration(seconds: 5));
diff --git a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
index c2c7a63b29..824e4d8faa 100644
--- a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
+++ b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
@@ -292,6 +292,16 @@ Future<void> _ensureRustRuntimePrepared(Map<String, dynamic> args) async {
faceDetection: (args["faceDetectionModelPath"] as String?) ?? "",
faceEmbedding: (args["faceEmbeddingModelPath"] as String?) ?? "",
clipImage: (args["clipImageModelPath"] as String?) ?? "",
+ petFaceDetection: (args["petFaceDetectionModelPath"] as String?) ?? "",
+ petFaceEmbeddingDog:
+ (args["petFaceEmbeddingDogModelPath"] as String?) ?? "",
+ petFaceEmbeddingCat:
+ (args["petFaceEmbeddingCatModelPath"] as String?) ?? "",
+ petBodyDetection: (args["petBodyDetectionModelPath"] as String?) ?? "",
+ petBodyEmbeddingDog:
+ (args["petBodyEmbeddingDogModelPath"] as String?) ?? "",
+ petBodyEmbeddingCat:
+ (args["petBodyEmbeddingCatModelPath"] as String?) ?? "",
);
final providerPolicy = rust_ml.RustExecutionProviderPolicy(
preferCoreml: args["preferCoreml"] as bool? ?? true,
diff --git a/mobile/apps/photos/lib/utils/ml_util.dart b/mobile/apps/photos/lib/utils/ml_util.dart
index a02cc0a976..ade612d5d8 100644
--- a/mobile/apps/photos/lib/utils/ml_util.dart
+++ b/mobile/apps/photos/lib/utils/ml_util.dart
@@ -15,6 +15,7 @@ import "package:photos/models/file/file_type.dart";
import "package:photos/models/ml/clip.dart";
import "package:photos/models/ml/face/dimension.dart";
import "package:photos/models/ml/face/face.dart";
+import "package:photos/models/ml/ml_typedefs.dart";
import "package:photos/models/ml/ml_versions.dart";
import "package:photos/service_locator.dart";
import "package:photos/services/filedata/model/file_data.dart";
@@ -95,7 +96,9 @@ Future<IndexStatus> getIndexStatus() async {
int _lastFetchTimeForOthersIndexed = 0;
/// Return a list of file instructions for files that should be indexed for ML
-Future<List<FileMLInstruction>> getFilesForMlIndexing() async {
+Future<List<FileMLInstruction>> getFilesForMlIndexing({
+ bool forceAll = false,
+}) async {
_logger.info('getFilesForMlIndexing called');
final mlDataDB = MLDataDB.instance;
final time = DateTime.now();
@@ -127,9 +130,9 @@ Future<List<FileMLInstruction>> getFilesForMlIndexing() async {
}
queuedFiledIDs.add(enteFile.uploadedFileID!);
- final shouldRunFaces =
+ final shouldRunFaces = forceAll ||
_shouldRunIndexing(enteFile, faceIndexedFileIDs, faceMlVersion);
- final shouldRunClip =
+ final shouldRunClip = forceAll ||
_shouldRunIndexing(enteFile, clipIndexedFileIDs, clipMlVersion);
if (!shouldRunFaces && !shouldRunClip) {
continue;
@@ -157,9 +160,9 @@ Future<List<FileMLInstruction>> getFilesForMlIndexing() async {
continue;
}
queuedFiledIDs.add(enteFile.uploadedFileID!);
- final shouldRunFaces =
+ final shouldRunFaces = forceAll ||
_shouldRunIndexing(enteFile, faceIndexedFileIDs, faceMlVersion);
- final shouldRunClip =
+ final shouldRunClip = forceAll ||
_shouldRunIndexing(enteFile, clipIndexedFileIDs, clipMlVersion);
if (!shouldRunFaces && !shouldRunClip) {
continue;
@@ -203,7 +206,9 @@ Future<List<FileMLInstruction>> getFilesForMlIndexing() async {
return [...splitResult.matched, ...splitResult.unmatched];
}
-Future<List<FileMLInstruction>> getOfflineFilesForMlIndexing() async {
+Future<List<FileMLInstruction>> getOfflineFilesForMlIndexing({
+ bool forceAll = false,
+}) async {
_logger.info('getOfflineFilesForMlIndexing called');
final mlDataDB = MLDataDB.offlineInstance;
final Map<int, int> faceIndexedFileIDs = await mlDataDB.faceIndexedFileIds();
@@ -242,16 +247,18 @@ Future<List<FileMLInstruction>> getOfflineFilesForMlIndexing() async {
continue;
}
queuedFileIDs.add(localIntId);
- final shouldRunFaces = _shouldRunIndexingWithFileId(
- localIntId,
- faceIndexedFileIDs,
- faceMlVersion,
- );
- final shouldRunClip = _shouldRunIndexingWithFileId(
- localIntId,
- clipIndexedFileIDs,
- clipMlVersion,
- );
+ final shouldRunFaces = forceAll ||
+ _shouldRunIndexingWithFileId(
+ localIntId,
+ faceIndexedFileIDs,
+ faceMlVersion,
+ );
+ final shouldRunClip = forceAll ||
+ _shouldRunIndexingWithFileId(
+ localIntId,
+ clipIndexedFileIDs,
+ clipMlVersion,
+ );
if (!shouldRunFaces && !shouldRunClip) {
continue;
}
@@ -274,10 +281,12 @@ Future<List<FileMLInstruction>> getOfflineFilesForMlIndexing() async {
Stream<List<FileMLInstruction>> fetchEmbeddingsAndInstructions(
int yieldSize, {
required MLMode mode,
+ bool forceAll = false,
}) async* {
- if (mode == MLMode.offline) {
- final List<FileMLInstruction> filesToIndex =
- await getOfflineFilesForMlIndexing();
+ if (mode == MLMode.offline || forceAll) {
+ final List<FileMLInstruction> filesToIndex = mode == MLMode.offline
+ ? await getOfflineFilesForMlIndexing(forceAll: forceAll)
+ : await getFilesForMlIndexing(forceAll: forceAll);
final List<List<FileMLInstruction>> chunks = filesToIndex.chunks(yieldSize);
for (final batch in chunks) {
yield batch;
@@ -601,11 +610,24 @@ Future<MLResult> analyzeImageRust(Map args) async {
final String imagePath = args["filePath"] as String;
final bool runFaces = args["runFaces"] as bool;
final bool runClip = args["runClip"] as bool;
+ final bool runPets = args["runPets"] as bool? ?? false;
final String? faceDetectionModelPath =
args["faceDetectionModelPath"] as String?;
final String? faceEmbeddingModelPath =
args["faceEmbeddingModelPath"] as String?;
final String? clipImageModelPath = args["clipImageModelPath"] as String?;
+ final String? petFaceDetectionModelPath =
+ args["petFaceDetectionModelPath"] as String?;
+ final String? petFaceEmbeddingDogModelPath =
+ args["petFaceEmbeddingDogModelPath"] as String?;
+ final String? petFaceEmbeddingCatModelPath =
+ args["petFaceEmbeddingCatModelPath"] as String?;
+ final String? petBodyDetectionModelPath =
+ args["petBodyDetectionModelPath"] as String?;
+ final String? petBodyEmbeddingDogModelPath =
+ args["petBodyEmbeddingDogModelPath"] as String?;
+ final String? petBodyEmbeddingCatModelPath =
+ args["petBodyEmbeddingCatModelPath"] as String?;
final bool preferCoreml = args["preferCoreml"] as bool? ?? true;
final bool preferNnapi = args["preferNnapi"] as bool? ?? true;
final bool preferXnnpack = args["preferXnnpack"] as bool? ?? false;
@@ -625,6 +647,26 @@ Future<MLResult> analyzeImageRust(Map args) async {
if (runClip && isMissingModelPath(clipImageModelPath)) {
missingModelPaths.add("clipImageModelPath");
}
+ if (runPets) {
+ if (isMissingModelPath(petFaceDetectionModelPath)) {
+ missingModelPaths.add("petFaceDetectionModelPath");
+ }
+ if (isMissingModelPath(petFaceEmbeddingDogModelPath)) {
+ missingModelPaths.add("petFaceEmbeddingDogModelPath");
+ }
+ if (isMissingModelPath(petFaceEmbeddingCatModelPath)) {
+ missingModelPaths.add("petFaceEmbeddingCatModelPath");
+ }
+ if (isMissingModelPath(petBodyDetectionModelPath)) {
+ missingModelPaths.add("petBodyDetectionModelPath");
+ }
+ if (isMissingModelPath(petBodyEmbeddingDogModelPath)) {
+ missingModelPaths.add("petBodyEmbeddingDogModelPath");
+ }
+ if (isMissingModelPath(petBodyEmbeddingCatModelPath)) {
+ missingModelPaths.add("petBodyEmbeddingCatModelPath");
+ }
+ }
if (missingModelPaths.isNotEmpty) {
throw Exception(
"RustMLMissingModelPath: Missing required model paths: ${missingModelPaths.join(', ')}",
@@ -635,6 +677,12 @@ Future<MLResult> analyzeImageRust(Map args) async {
faceDetection: faceDetectionModelPath ?? "",
faceEmbedding: faceEmbeddingModelPath ?? "",
clipImage: clipImageModelPath ?? "",
+ petFaceDetection: petFaceDetectionModelPath ?? "",
+ petFaceEmbeddingDog: petFaceEmbeddingDogModelPath ?? "",
+ petFaceEmbeddingCat: petFaceEmbeddingCatModelPath ?? "",
+ petBodyDetection: petBodyDetectionModelPath ?? "",
+ petBodyEmbeddingDog: petBodyEmbeddingDogModelPath ?? "",
+ petBodyEmbeddingCat: petBodyEmbeddingCatModelPath ?? "",
);
final providerPolicy = rust_ml.RustExecutionProviderPolicy(
preferCoreml: preferCoreml,
@@ -652,6 +700,7 @@ Future<MLResult> analyzeImageRust(Map args) async {
imagePath: analyzePath,
runFaces: runFaces,
runClip: runClip,
+ runPets: runPets,
modelPaths: modelPaths,
providerPolicy: providerPolicy,
),
@@ -751,6 +800,46 @@ Future<MLResult> analyzeImageRust(Map args) async {
);
}
+ if (runPets) {
+ if (rustResult.petFaces != null) {
+ result.petFaces = rustResult.petFaces!.map((face) {
+ final detection = FaceDetectionRelative(
+ score: face.detection.score,
+ box: face.detection.boxXyxy.toList(growable: false),
+ allKeypoints: face.detection.keypoints
+ .map((point) => point.toList(growable: false))
+ .toList(growable: false),
+ );
+ final alignment = AlignmentResult(
+ affineMatrix: [],
+ center: face.alignment.center.toList(growable: false),
+ size: face.alignment.cropSize,
+ rotation: face.alignment.angle,
+ );
+ return PetFaceResult(
+ fileId: enteFileID,
+ petFaceId: face.petFaceId,
+ detection: detection,
+ alignment: alignment,
+ species: face.species,
+ embedding: Embedding.from(face.faceEmbedding),
+ );
+ }).toList(growable: false);
+ }
+
+ if (rustResult.petBodies != null) {
+ result.petBodies = rustResult.petBodies!.map((body) {
+ return PetBodyResult(
+ boxXyxy: body.boxXyxy.toList(growable: false),
+ score: body.score,
+ cocoClass: body.cocoClass,
+ petBodyId: body.petBodyId,
+ embedding: Embedding.from(body.bodyEmbedding),
+ );
+ }).toList(growable: false);
+ }
+ }
+
return result;
} catch (e, s) {
_logger.severe("Could not analyze image with Rust pipeline", e, s);
diff --git a/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart b/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart
index 2309a58c2e..4d13509077 100644
--- a/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart
+++ b/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart
@@ -106,6 +106,8 @@ class FlagService {
bool get useRustForFaceThumbnails => internalUser;
+ bool get petEnabled => internalUser;
+
Future<void> tryRefreshFlags() async {
try {
await _fetch();