π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Address PR review feedback for pet recognition pipeline
Amrithesh Kakkoth Ente018c5e6a9e5f
diff --git a/mobile/apps/photos/lib/db/ml/base.dart b/mobile/apps/photos/lib/db/ml/base.dartindex d3306e658d..ab6bada38f 100644--- a/mobile/apps/photos/lib/db/ml/base.dart+++ b/mobile/apps/photos/lib/db/ml/base.dart@@ -10,7 +10,7 @@ import "package:photos/services/machine_learning/face_ml/face_clustering/face_dbabstract class IMLDataDB<T> {Future<void> bulkInsertFaces(List<Face> faces);Future<void> bulkInsertPetFaces(List<DBPetFace> petFaces);- Future<void> bulkInsertPetBodies(List<DBPetBody> petBodies);+ Future<void> bulkInsertDetectedObjects(List<DBDetectedObject> objects);Future<void> updateFaceIdToClusterId(Map<String, String> faceIDToClusterID);Future<Map<int, int>> faceIndexedFileIds({int minimumMlVersion});Future<int> getFaceIndexedFileCount({int minimumMlVersion});@@ -36,7 +36,7 @@ abstract class IMLDataDB<T> {});Future<List<Face>?> getFacesForGivenFileID(T fileUploadID);Future<List<DBPetFace>?> getPetFacesForFileID(T fileUploadID);- Future<List<DBPetBody>?> getPetBodiesForFileID(T fileUploadID);+ Future<List<DBDetectedObject>?> getDetectedObjectsForFileID(T fileUploadID);Future<Map<int, List<FaceWithoutEmbedding>>>getFileIDsToFacesWithoutEmbedding();Future<Map<String, Iterable<String>>> getClusterToFaceIDs(@@ -117,7 +117,7 @@ abstract class IMLDataDB<T> {});Future<void> updatePetFaceVectorIds(Map<String, int> petFaceIdToVectorId);- Future<void> updatePetBodyVectorIds(Map<String, int> petBodyIdToVectorId);+ Future<void> updateObjectVectorIds(Map<String, int> objectIdToVectorId);Future<List<EmbeddingVector>> getAllClipVectors();Future<Map<int, int>> clipIndexedFileWithVersion();diff --git a/mobile/apps/photos/lib/db/ml/db.dart b/mobile/apps/photos/lib/db/ml/db.dartindex 34282580e3..ec31294cba 100644--- a/mobile/apps/photos/lib/db/ml/db.dart+++ b/mobile/apps/photos/lib/db/ml/db.dart@@ -99,14 +99,12 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {createTextEmbeddingsCacheTable,createClusterCentroidVectorIdMappingTable,createPetFacesTable,- createPetBodiesTable,+ createDetectedObjectsTable,createPetFaceClustersTable,petFcClusterIDIndex,createPetClusterSummaryTable,createPetFaceVectorIdMappingTable,- createPetBodyVectorIdMappingTable,- alterPetFacesAddEmbedding,- alterPetBodiesAddEmbedding,+ createObjectVectorIdMappingTable,];static const List<String> _offlineMigrationScripts = [..._defaultMigrationScripts,@@ -196,9 +194,9 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {const String sql = '''INSERT INTO $petFacesTable (- $fileIDColumn, $petFaceIDColumn, $faceDetectionColumn, $petLandmarksColumn, $faceVectorIdColumn, $speciesColumn, $faceScore, $imageHeight, $imageWidth, $mlVersionColumn, $petFaceEmbeddingColumn- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)- ON CONFLICT($fileIDColumn, $petFaceIDColumn) DO UPDATE SET $faceDetectionColumn = excluded.$faceDetectionColumn, $petLandmarksColumn = excluded.$petLandmarksColumn, $faceVectorIdColumn = excluded.$faceVectorIdColumn, $speciesColumn = excluded.$speciesColumn, $faceScore = excluded.$faceScore, $imageHeight = excluded.$imageHeight, $imageWidth = excluded.$imageWidth, $mlVersionColumn = excluded.$mlVersionColumn, $petFaceEmbeddingColumn = excluded.$petFaceEmbeddingColumn+ $fileIDColumn, $petFaceIDColumn, $faceDetectionColumn, $faceVectorIdColumn, $speciesColumn, $faceScore, $imageHeight, $imageWidth, $mlVersionColumn, $petFaceEmbeddingColumn+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT($fileIDColumn, $petFaceIDColumn) DO UPDATE SET $faceDetectionColumn = excluded.$faceDetectionColumn, $faceVectorIdColumn = excluded.$faceVectorIdColumn, $speciesColumn = excluded.$speciesColumn, $faceScore = excluded.$faceScore, $imageHeight = excluded.$imageHeight, $imageWidth = excluded.$imageWidth, $mlVersionColumn = excluded.$mlVersionColumn, $petFaceEmbeddingColumn = excluded.$petFaceEmbeddingColumn''';final parameterSets = batch.map((petFace) {final map = petFace.toMap();@@ -206,7 +204,6 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {map[fileIDColumn],map[petFaceIDColumn],map[faceDetectionColumn],- map[petLandmarksColumn],map[faceVectorIdColumn],map[speciesColumn],map[faceScore],@@ -222,27 +219,27 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {}@override- Future<void> bulkInsertPetBodies(List<DBPetBody> petBodies) async {+ Future<void> bulkInsertDetectedObjects(List<DBDetectedObject> objects) async {final db = await asyncDB;const batchSize = 500;- final numBatches = (petBodies.length / batchSize).ceil();+ final numBatches = (objects.length / batchSize).ceil();for (int i = 0; i < numBatches; i++) {final start = i * batchSize;- final end = min((i + 1) * batchSize, petBodies.length);- final batch = petBodies.sublist(start, end);+ final end = min((i + 1) * batchSize, objects.length);+ final batch = objects.sublist(start, end);const String sql = '''- INSERT INTO $petBodiesTable (- $fileIDColumn, $petBodyIDColumn, $faceDetectionColumn, $bodyVectorIdColumn, $speciesColumn, $faceScore, $imageHeight, $imageWidth, $mlVersionColumn, $petBodyEmbeddingColumn+ INSERT INTO $detectedObjectsTable (+ $fileIDColumn, $objectIDColumn, $detectionColumn, $bodyVectorIdColumn, $speciesColumn, $faceScore, $imageHeight, $imageWidth, $mlVersionColumn, $petBodyEmbeddingColumn) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)- ON CONFLICT($fileIDColumn, $petBodyIDColumn) DO UPDATE SET $faceDetectionColumn = excluded.$faceDetectionColumn, $bodyVectorIdColumn = excluded.$bodyVectorIdColumn, $speciesColumn = excluded.$speciesColumn, $faceScore = excluded.$faceScore, $imageHeight = excluded.$imageHeight, $imageWidth = excluded.$imageWidth, $mlVersionColumn = excluded.$mlVersionColumn, $petBodyEmbeddingColumn = excluded.$petBodyEmbeddingColumn+ ON CONFLICT($fileIDColumn, $objectIDColumn) DO UPDATE SET $detectionColumn = excluded.$detectionColumn, $bodyVectorIdColumn = excluded.$bodyVectorIdColumn, $speciesColumn = excluded.$speciesColumn, $faceScore = excluded.$faceScore, $imageHeight = excluded.$imageHeight, $imageWidth = excluded.$imageWidth, $mlVersionColumn = excluded.$mlVersionColumn, $petBodyEmbeddingColumn = excluded.$petBodyEmbeddingColumn''';- final parameterSets = batch.map((petBody) {- final map = petBody.toMap();+ final parameterSets = batch.map((obj) {+ final map = obj.toMap();return [map[fileIDColumn],- map[petBodyIDColumn],- map[faceDetectionColumn],+ map[objectIDColumn],+ map[detectionColumn],map[bodyVectorIdColumn],map[speciesColumn],map[faceScore],@@ -282,13 +279,13 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {}@override- Future<void> updatePetBodyVectorIds(- Map<String, int> petBodyIdToVectorId,+ Future<void> updateObjectVectorIds(+ Map<String, int> objectIdToVectorId,) async {- if (petBodyIdToVectorId.isEmpty) return;+ if (objectIdToVectorId.isEmpty) return;final db = await asyncDB;const batchSize = 500;- final entries = petBodyIdToVectorId.entries.toList();+ final entries = objectIdToVectorId.entries.toList();final numBatches = (entries.length / batchSize).ceil();for (int i = 0; i < numBatches; i++) {final start = i * batchSize;@@ -296,15 +293,135 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {final batch = entries.sublist(start, end);const String sql = '''- UPDATE $petBodiesTable+ UPDATE $detectedObjectsTableSET $bodyVectorIdColumn = ?- WHERE $petBodyIDColumn = ?+ WHERE $objectIDColumn = ?''';final parameterSets = batch.map((e) => [e.value, e.key]).toList();await db.executeBatch(sql, parameterSets);}}+ /// 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,+ ) 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>[];+ final insertedPetFaceIds = <String>[];+ 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);+ insertedPetFaceIds.add(dbFace.petFaceId);+ }+ if (vectorIds.isNotEmpty) {+ await vdb.bulkInsertEmbeddings(+ vectorIds: vectorIds,+ embeddings: embeddings,+ );+ final updateMap = Map.fromIterables(+ insertedPetFaceIds,+ vectorIds,+ );+ await updatePetFaceVectorIds(updateMap);+ }+ }+ } catch (e, s) {+ _logger.severe("Failed to store pet face embeddings in vector DB", e, s);+ }+ }++ /// Store detected object embeddings into PetVectorDB after SQLite insert.+ /// Failure is logged but does not block indexing.+ Future<void> storeObjectEmbeddings(+ List<DBDetectedObject> dbObjects,+ List<DetectedObjectResult> objects,+ ) async {+ try {+ // Group by species (COCO class 15 = cat β species 1, 16 = dog β species 0)+ final bySpecies = <int, List<(DBDetectedObject, DetectedObjectResult)>>{};+ for (int i = 0; i < dbObjects.length; i++) {+ final species = dbObjects[i].species == 15 ? 1 : 0;+ bySpecies.putIfAbsent(species, () => []);+ bySpecies[species]!.add((dbObjects[i], objects[i]));+ }+ for (final entry in bySpecies.entries) {+ final vdb = PetVectorDB.forModel(+ species: entry.key,+ isFace: false,+ );+ final objectIds = entry.value.map((e) => e.$1.objectId).toList();+ final idMap = await vdb.getObjectVectorIdMap(+ objectIds,+ createIfMissing: true,+ );+ final vectorIds = <int>[];+ final embeddings = <Float32List>[];+ final insertedObjectIds = <String>[];+ for (final (dbObj, objResult) in entry.value) {+ final vid = idMap[dbObj.objectId];+ if (vid == null) continue;+ final emb = Float32List.fromList(objResult.embedding);+ if (emb.length != PetVectorDB.bodyDimension) {+ _logger.warning(+ "Skipping object embedding with wrong dimension ${emb.length}",+ );+ continue;+ }+ vectorIds.add(vid);+ embeddings.add(emb);+ insertedObjectIds.add(dbObj.objectId);+ }+ if (vectorIds.isNotEmpty) {+ await vdb.bulkInsertEmbeddings(+ vectorIds: vectorIds,+ embeddings: embeddings,+ );+ final updateMap = Map.fromIterables(+ insertedObjectIds,+ vectorIds,+ );+ await updateObjectVectorIds(updateMap);+ }+ }+ } catch (e, s) {+ _logger.severe(+ "Failed to store object embeddings in vector DB",+ e,+ s,+ );+ }+ }+@overrideFuture<void> updateFaceIdToClusterId(Map<String, String> faceIDToClusterID,@@ -441,11 +558,11 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {await _clusterCentroidVectorDB.deleteIndexFile();// Pet tablesawait db.execute(deletePetFacesTable);- await db.execute(deletePetBodiesTable);+ await db.execute(deleteDetectedObjectsTable);await db.execute(deletePetFaceClustersTable);await db.execute(deletePetClusterSummaryTable);await db.execute(deletePetFaceVectorIdMappingTable);- await db.execute(deletePetBodyVectorIdMappingTable);+ await db.execute(deleteObjectVectorIdMappingTable);for (final vdb in PetVectorDB.allInstances) {await vdb.deleteIndexFile();}@@ -636,10 +753,12 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {}@override- Future<List<DBPetBody>?> getPetBodiesForFileID(int fileUploadID) async {+ Future<List<DBDetectedObject>?> getDetectedObjectsForFileID(+ int fileUploadID,+ ) async {final db = await asyncDB;const String query = '''- SELECT * FROM $petBodiesTable+ SELECT * FROM $detectedObjectsTableWHERE $fileIDColumn = ?''';final List<Map<String, dynamic>> maps = await db.getAll(@@ -649,7 +768,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {if (maps.isEmpty) {return null;}- return maps.map((e) => DBPetBody.fromMap(e)).toList();+ return maps.map((e) => DBDetectedObject.fromMap(e)).toList();}@overridediff --git a/mobile/apps/photos/lib/db/ml/db_pet_model_mappers.dart b/mobile/apps/photos/lib/db/ml/db_pet_model_mappers.dartindex 75e35e96f1..ede8243c65 100644--- a/mobile/apps/photos/lib/db/ml/db_pet_model_mappers.dart+++ b/mobile/apps/photos/lib/db/ml/db_pet_model_mappers.dart@@ -10,9 +10,8 @@ class DBPetFace {final int fileId;final String petFaceId;final String detection;- final String landmarks;final int faceVectorId;- final String species;+ final int species;final double faceScore;final int imageHeight;final int imageWidth;@@ -23,7 +22,6 @@ class DBPetFace {required this.fileId,required this.petFaceId,required this.detection,- required this.landmarks,required this.faceVectorId,required this.species,required this.faceScore,@@ -38,7 +36,6 @@ class DBPetFace {fileIDColumn: fileId,petFaceIDColumn: petFaceId,faceDetectionColumn: detection,- petLandmarksColumn: landmarks,faceVectorIdColumn: faceVectorId,speciesColumn: species,'score': faceScore,@@ -54,9 +51,8 @@ class DBPetFace {fileId: map[fileIDColumn] as int,petFaceId: map[petFaceIDColumn] as String,detection: map[faceDetectionColumn] as String,- landmarks: map[petLandmarksColumn] as String,faceVectorId: map[faceVectorIdColumn] as int,- species: map[speciesColumn] as String,+ species: map[speciesColumn] as int,faceScore: parseIntOrDoubleAsDouble(map['score']) ?? 0.0,imageHeight: map['height'] as int,imageWidth: map['width'] as int,@@ -66,28 +62,28 @@ class DBPetFace {}}-// ββ Pet Body DB Mapper ββ+// ββ Detected Object DB Mapper ββ-/// Represents a row in the [petBodiesTable].-class DBPetBody {+/// Represents a row in the [detectedObjectsTable].+class DBDetectedObject {final int fileId;- final String petBodyId;+ final String objectId;final String detection;final int bodyVectorId;- final String species;- final double faceScore; // Reusing column name, but represents body score+ final int species;+ final double score;final int imageHeight;final int imageWidth;final int mlVersion;final Uint8List? embeddingBlob;- DBPetBody({+ DBDetectedObject({required this.fileId,- required this.petBodyId,+ required this.objectId,required this.detection,required this.bodyVectorId,required this.species,- required this.faceScore,+ required this.score,required this.imageHeight,required this.imageWidth,required this.mlVersion,@@ -97,11 +93,11 @@ class DBPetBody {Map<String, dynamic> toMap() {return {fileIDColumn: fileId,- petBodyIDColumn: petBodyId,- faceDetectionColumn: detection,+ objectIDColumn: objectId,+ detectionColumn: detection,bodyVectorIdColumn: bodyVectorId,speciesColumn: species,- 'score': faceScore,+ 'score': score,'height': imageHeight,'width': imageWidth,mlVersionColumn: mlVersion,@@ -109,14 +105,14 @@ class DBPetBody {};}- factory DBPetBody.fromMap(Map<String, dynamic> map) {- return DBPetBody(+ factory DBDetectedObject.fromMap(Map<String, dynamic> map) {+ return DBDetectedObject(fileId: map[fileIDColumn] as int,- petBodyId: map[petBodyIDColumn] as String,- detection: map[faceDetectionColumn] as String,+ objectId: map[objectIDColumn] as String,+ detection: map[detectionColumn] as String,bodyVectorId: map[bodyVectorIdColumn] as int,- species: map[speciesColumn] as String,- faceScore: parseIntOrDoubleAsDouble(map['score']) ?? 0.0,+ species: map[speciesColumn] as int,+ score: parseIntOrDoubleAsDouble(map['score']) ?? 0.0,imageHeight: map['height'] as int,imageWidth: map['width'] as int,mlVersion: map[mlVersionColumn] as int,diff --git a/mobile/apps/photos/lib/db/ml/pet_vector_db.dart b/mobile/apps/photos/lib/db/ml/pet_vector_db.dartindex 73d0c121a5..9af88f1a63 100644--- a/mobile/apps/photos/lib/db/ml/pet_vector_db.dart+++ b/mobile/apps/photos/lib/db/ml/pet_vector_db.dart@@ -10,7 +10,6 @@ import "package:photos/db/ml/clip_vector_db.dart" show VectorDbStats;import "package:photos/db/ml/db.dart";import "package:photos/db/ml/schema.dart";import "package:photos/src/rust/api/usearch_api.dart";-import "package:shared_preferences/shared_preferences.dart";/// Vector database for pet embeddings.///@@ -28,7 +27,6 @@ class PetVectorDB {static const int bodyDimension = 192;final String _databaseName;- final String _migrationKey;final BigInt _embeddingDimension;static Logger get logger => _logger;@@ -36,7 +34,6 @@ class PetVectorDB {// Private constructor for named instancesPetVectorDB._named(this._databaseName,- this._migrationKey,this._embeddingDimension,);@@ -44,25 +41,21 @@ class PetVectorDB {static final dogFace = PetVectorDB._named("ente.ml.vectordb.pet.dog_face.usearch",- "pet_vectordb_dog_face_migration",BigInt.from(faceDimension),);static final catFace = PetVectorDB._named("ente.ml.vectordb.pet.cat_face.usearch",- "pet_vectordb_cat_face_migration",BigInt.from(faceDimension),);static final dogBody = PetVectorDB._named("ente.ml.vectordb.pet.dog_body.usearch",- "pet_vectordb_dog_body_migration",BigInt.from(bodyDimension),);static final catBody = PetVectorDB._named("ente.ml.vectordb.pet.cat_body.usearch",- "pet_vectordb_cat_body_migration",BigInt.from(bodyDimension),);@@ -92,19 +85,10 @@ class PetVectorDB {return _vectorDbFuture!;}- bool? _migrationDone;-Future<VectorDb> _initVectorDB() async {final documentsDirectory = await getApplicationDocumentsDirectory();final String dbPath = join(documentsDirectory.path, _databaseName);_logger.info("Opening pet vectorDB: DB path $dbPath");- final indexFile = File(dbPath);- if (!await indexFile.exists() && await checkIfMigrationDone()) {- _logger.severe(- "Pet VectorDB file missing while migration is marked done. Invalidating.",- );- await invalidateMigrationState();- }late VectorDb vectorDB;try {vectorDB = VectorDb(@@ -130,26 +114,6 @@ class PetVectorDB {return vectorDB;}- Future<bool> checkIfMigrationDone() async {- if (_migrationDone != null) return _migrationDone!;- final prefs = await SharedPreferences.getInstance();- final done = prefs.getBool(_migrationKey) ?? false;- _migrationDone = done;- return done;- }-- Future<void> setMigrationDone() async {- final prefs = await SharedPreferences.getInstance();- await prefs.setBool(_migrationKey, true);- _migrationDone = true;- }-- Future<void> invalidateMigrationState() async {- final prefs = await SharedPreferences.getInstance();- await prefs.setBool(_migrationKey, false);- _migrationDone = false;- }-// ββ ID Mapping (pet_face_id string β integer for usearch) ββ/// Get or create integer vector IDs for the given pet face IDs.@@ -196,13 +160,13 @@ class PetVectorDB {return result;}- /// Get or create integer vector IDs for body embeddings.- /// Uses [petBodyVectorIdMappingTable] β separate ID space from face embeddings.- Future<Map<String, int>> getPetBodyVectorIdMap(- Iterable<String> petBodyIds, {+ /// Get or create integer vector IDs for body/object embeddings.+ /// Uses [objectVectorIdMappingTable] β separate ID space from face embeddings.+ Future<Map<String, int>> getObjectVectorIdMap(+ Iterable<String> objectIds, {bool createIfMissing = false,}) async {- final uniqueIds = petBodyIds.toSet().toList(growable: false);+ final uniqueIds = objectIds.toSet().toList(growable: false);if (uniqueIds.isEmpty) return {};final mlDataDB = MLDataDB.instance;@@ -210,7 +174,7 @@ class PetVectorDB {if (createIfMissing) {const insertSql = '''- INSERT OR IGNORE INTO $petBodyVectorIdMappingTable ($petBodyIDColumn)+ INSERT OR IGNORE INTO $objectVectorIdMappingTable ($objectIDColumn)VALUES (?)''';final insertParams = <List<Object?>>[];@@ -226,15 +190,15 @@ class PetVectorDB {final chunk = uniqueIds.sublist(i, min(i + chunkSize, uniqueIds.length));final rows = await db.getAll('''- SELECT $petBodyIDColumn, $petBodyVectorIdColumn- FROM $petBodyVectorIdMappingTable- WHERE $petBodyIDColumn IN (${List.filled(chunk.length, '?').join(',')})+ SELECT $objectIDColumn, $objectVectorIdColumn+ FROM $objectVectorIdMappingTable+ WHERE $objectIDColumn IN (${List.filled(chunk.length, '?').join(',')})''',chunk,);for (final row in rows) {- result[row[petBodyIDColumn] as String] =- row[petBodyVectorIdColumn] as int;+ result[row[objectIDColumn] as String] =+ row[objectVectorIdColumn] as int;}}return result;@@ -317,7 +281,6 @@ class PetVectorDB {/// Delete all embeddings and reset the index.Future<void> deleteAllEmbeddings() async {- await invalidateMigrationState();final db = await _vectorDB;try {await db.resetIndex();@@ -347,7 +310,6 @@ class PetVectorDB {}Future<void> deleteIndex() async {- await invalidateMigrationState();final db = await _vectorDB;try {await db.deleteIndex();@@ -368,7 +330,6 @@ class PetVectorDB {await file.delete();}_vectorDbFuture = null;- await invalidateMigrationState();} catch (e, s) {_logger.severe("Error deleting pet index file", e, s);rethrow;diff --git a/mobile/apps/photos/lib/db/ml/schema.dart b/mobile/apps/photos/lib/db/ml/schema.dartindex e0d91f0c07..ec6efb292b 100644--- a/mobile/apps/photos/lib/db/ml/schema.dart+++ b/mobile/apps/photos/lib/db/ml/schema.dart@@ -187,9 +187,9 @@ CREATE TABLE IF NOT EXISTS $offlineFileKeyMapTable (// Shared column namesconst petFaceIDColumn = 'pet_face_id';-const petBodyIDColumn = 'pet_body_id';+const objectIDColumn = 'object_id';const speciesColumn = 'species';-const petLandmarksColumn = 'landmarks';+const detectionColumn = 'detection';const faceVectorIdColumn = 'face_vector_id';const bodyVectorIdColumn = 'body_vector_id';@@ -201,38 +201,40 @@ const createPetFacesTable = '''CREATE TABLE IF NOT EXISTS $petFacesTable ($fileIDColumn INTEGER NOT NULL,$petFaceIDColumn TEXT NOT NULL UNIQUE,$faceDetectionColumn TEXT NOT NULL,- $petLandmarksColumn TEXT NOT NULL,$faceVectorIdColumn INTEGER NOT NULL,- $speciesColumn TEXT NOT NULL,+ $speciesColumn INTEGER NOT NULL,$faceScore REAL NOT NULL,$imageHeight INTEGER NOT NULL DEFAULT 0,$imageWidth INTEGER NOT NULL DEFAULT 0,$mlVersionColumn INTEGER NOT NULL DEFAULT -1,+ $petFaceEmbeddingColumn BLOB,PRIMARY KEY($fileIDColumn, $petFaceIDColumn));''';const deletePetFacesTable = 'DELETE FROM $petFacesTable';-// ββ Pet Bodies Table ββ+// ββ Detected Objects Table ββ-const petBodiesTable = 'pet_bodies';+const detectedObjectsTable = 'detected_objects';-const createPetBodiesTable = '''CREATE TABLE IF NOT EXISTS $petBodiesTable (+const createDetectedObjectsTable =+ '''CREATE TABLE IF NOT EXISTS $detectedObjectsTable ($fileIDColumn INTEGER NOT NULL,- $petBodyIDColumn TEXT NOT NULL UNIQUE,- $faceDetectionColumn TEXT NOT NULL,+ $objectIDColumn TEXT NOT NULL UNIQUE,+ $detectionColumn TEXT NOT NULL,$bodyVectorIdColumn INTEGER NOT NULL,- $speciesColumn TEXT NOT NULL,+ $speciesColumn INTEGER NOT NULL,$faceScore REAL NOT NULL,$imageHeight INTEGER NOT NULL DEFAULT 0,$imageWidth INTEGER NOT NULL DEFAULT 0,$mlVersionColumn INTEGER NOT NULL DEFAULT -1,- PRIMARY KEY($fileIDColumn, $petBodyIDColumn)+ $petBodyEmbeddingColumn BLOB,+ PRIMARY KEY($fileIDColumn, $objectIDColumn));''';-const deletePetBodiesTable = 'DELETE FROM $petBodiesTable';+const deleteDetectedObjectsTable = 'DELETE FROM $detectedObjectsTable';// ββ Clustering Tables ββ@@ -258,24 +260,18 @@ CREATE TABLE IF NOT EXISTS $petClusterSummaryTable ($clusterIDColumn TEXT NOT NULL,$avgColumn BLOB NOT NULL,$countColumn INTEGER NOT NULL,- $speciesColumn TEXT NOT NULL,+ $speciesColumn INTEGER NOT NULL,PRIMARY KEY($clusterIDColumn));''';const deletePetClusterSummaryTable = 'DELETE FROM $petClusterSummaryTable';-// ββ Embedding BLOB Columns (nullable, added via ALTER TABLE) ββ+// ββ Embedding BLOB Columns ββconst petFaceEmbeddingColumn = 'pet_face_embedding';const petBodyEmbeddingColumn = 'pet_body_embedding';-const alterPetFacesAddEmbedding =- 'ALTER TABLE $petFacesTable ADD COLUMN $petFaceEmbeddingColumn BLOB';--const alterPetBodiesAddEmbedding =- 'ALTER TABLE $petBodiesTable ADD COLUMN $petBodyEmbeddingColumn BLOB';-// ββ Vector ID Mapping Tables ββ/// Maps pet_face_id (string) β integer for face usearch index@@ -292,16 +288,16 @@ CREATE TABLE IF NOT EXISTS $petFaceVectorIdMappingTable (const deletePetFaceVectorIdMappingTable ='DELETE FROM $petFaceVectorIdMappingTable';-/// Maps pet_body_id (string) β integer for body usearch index-const petBodyVectorIdMappingTable = 'pet_body_vector_id_map';-const petBodyVectorIdColumn = 'pet_body_vector_id';+/// Maps object_id (string) β integer for body usearch index+const objectVectorIdMappingTable = 'object_vector_id_map';+const objectVectorIdColumn = 'object_vector_id';-const createPetBodyVectorIdMappingTable = '''-CREATE TABLE IF NOT EXISTS $petBodyVectorIdMappingTable (- $petBodyVectorIdColumn INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,- $petBodyIDColumn TEXT NOT NULL UNIQUE+const createObjectVectorIdMappingTable = '''+CREATE TABLE IF NOT EXISTS $objectVectorIdMappingTable (+ $objectVectorIdColumn INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ $objectIDColumn TEXT NOT NULL UNIQUE);''';-const deletePetBodyVectorIdMappingTable =- 'DELETE FROM $petBodyVectorIdMappingTable';+const deleteObjectVectorIdMappingTable =+ 'DELETE FROM $objectVectorIdMappingTable';diff --git a/mobile/apps/photos/lib/models/ml/ml_versions.dart b/mobile/apps/photos/lib/models/ml/ml_versions.dartindex 35d089178a..35cd51b769 100644--- a/mobile/apps/photos/lib/models/ml/ml_versions.dart+++ b/mobile/apps/photos/lib/models/ml/ml_versions.dart@@ -3,6 +3,7 @@ import "dart:io" show Platform;const faceMlVersion = 1;const clipMlVersion = 1;const clusterMlVersion = 1;+const petMlVersion = 1;const minimumClusterSize = 2;const embeddingFetchLimit = 200;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.dartindex a65a4d93b0..c83315fff5 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@@ -30,7 +30,7 @@ class MLIndexingIsolate extends SuperIsolate {String get isolateName => "MLIndexingIsolate";@override- bool get shouldAutomaticDispose => false;+ bool get shouldAutomaticDispose => true;bool get _shouldUseRustMl => flagService.useRustForML || isOfflineMode;diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_result.dart b/mobile/apps/photos/lib/services/machine_learning/ml_result.dartindex 422eb1a496..1f6bb9ea49 100644--- a/mobile/apps/photos/lib/services/machine_learning/ml_result.dart+++ b/mobile/apps/photos/lib/services/machine_learning/ml_result.dart@@ -13,7 +13,7 @@ class MLResult {List<FaceResult>? faces = <FaceResult>[];ClipResult? clip;List<PetFaceResult>? petFaces;- List<PetBodyResult>? petBodies;+ List<DetectedObjectResult>? detectedObjects;Dimensions decodedImageSize;@@ -26,7 +26,7 @@ class MLResult {this.faces,this.clip,this.petFaces,- this.petBodies,+ this.detectedObjects,this.decodedImageSize = const Dimensions(width: -1, height: -1),});@@ -40,7 +40,7 @@ class MLResult {'faces': faces?.map((face) => face.toJson()).toList(),'clip': clip?.toJson(),'petFaces': petFaces?.map((pf) => pf.toJson()).toList(),- 'petBodies': petBodies?.map((pb) => pb.toJson()).toList(),+ 'detectedObjects': detectedObjects?.map((obj) => obj.toJson()).toList(),'decodedImageSize': {'width': decodedImageSize.width,'height': decodedImageSize.height,@@ -67,10 +67,11 @@ class MLResult {).toList(): null,- petBodies: json['petBodies'] != null- ? (json['petBodies'] as List)+ detectedObjects: json['detectedObjects'] != null+ ? (json['detectedObjects'] as List).map(- (item) => PetBodyResult.fromJson(item as Map<String, dynamic>),+ (item) =>+ DetectedObjectResult.fromJson(item as Map<String, dynamic>),).toList(): null,@@ -235,18 +236,18 @@ class PetFaceResult {}}-class PetBodyResult {+class DetectedObjectResult {late List<double> boxXyxy;late double score;late int cocoClass;- late String petBodyId;+ late String objectId;late Embedding embedding;- PetBodyResult({+ DetectedObjectResult({required this.boxXyxy,required this.score,required this.cocoClass,- required this.petBodyId,+ required this.objectId,required this.embedding,});@@ -254,16 +255,16 @@ class PetBodyResult {'boxXyxy': boxXyxy,'score': score,'cocoClass': cocoClass,- 'petBodyId': petBodyId,+ 'objectId': objectId,'embedding': embedding,};- static PetBodyResult fromJson(Map<String, dynamic> json) {- return PetBodyResult(+ static DetectedObjectResult fromJson(Map<String, dynamic> json) {+ return DetectedObjectResult(boxXyxy: (json['boxXyxy'] as List).cast<double>(),score: json['score'],cocoClass: json['cocoClass'],- petBodyId: json['petBodyId'],+ objectId: json['objectId'],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.dartindex 21fb090788..2856a69269 100644--- a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart+++ b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart@@ -10,7 +10,6 @@ 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";@@ -632,7 +631,8 @@ class MLService {}// Pet results locally- final rustPets = result.petFaces != null || result.petBodies != null;+ final rustPets =+ result.petFaces != null || result.detectedObjects != null;if (rustPets) {if (result.petFaces != null && result.petFaces!.isNotEmpty) {final dbPetFaces = result.petFaces!.map((pf) {@@ -646,62 +646,58 @@ class MLService {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",+ species: pf.species,faceScore: pf.detection.score,imageHeight: result.decodedImageSize.height,imageWidth: result.decodedImageSize.width,- mlVersion: faceMlVersion,+ mlVersion: petMlVersion,embeddingBlob: blob,);}).toList();await mlDataDB.bulkInsertPetFaces(dbPetFaces);- await _storePetFaceEmbeddings(+ await mlDataDB.storePetFaceEmbeddings(dbPetFaces,result.petFaces!,- mlDataDB,);}- if (result.petBodies != null && result.petBodies!.isNotEmpty) {- final dbPetBodies = result.petBodies!.map((pb) {+ if (result.detectedObjects != null &&+ result.detectedObjects!.isNotEmpty) {+ final dbObjects = result.detectedObjects!.map((obj) {final detectionObj = FaceDetectionRelative(- score: pb.score,+ score: obj.score,box: [- pb.boxXyxy[0],- pb.boxXyxy[1],- pb.boxXyxy[2],- pb.boxXyxy[3],+ obj.boxXyxy[0],+ obj.boxXyxy[1],+ obj.boxXyxy[2],+ obj.boxXyxy[3],],allKeypoints: const [],);- final floatList = Float32List.fromList(pb.embedding);+ final floatList = Float32List.fromList(obj.embedding);final blob = Uint8List.view(floatList.buffer,floatList.offsetInBytes,floatList.lengthInBytes,);- return DBPetBody(+ return DBDetectedObject(fileId: result.fileId,- petBodyId: pb.petBodyId,+ objectId: obj.objectId,detection: jsonEncode(detectionObj.toJson()),bodyVectorId: -1,- species: pb.cocoClass == 15 ? "cat" : "dog",- faceScore: pb.score,+ species: obj.cocoClass,+ score: obj.score,imageHeight: result.decodedImageSize.height,imageWidth: result.decodedImageSize.width,- mlVersion: faceMlVersion,+ mlVersion: petMlVersion,embeddingBlob: blob,);}).toList();- await mlDataDB.bulkInsertPetBodies(dbPetBodies);- await _storePetBodyEmbeddings(- dbPetBodies,- result.petBodies!,- mlDataDB,+ await mlDataDB.bulkInsertDetectedObjects(dbObjects);+ await mlDataDB.storeObjectEmbeddings(+ dbObjects,+ result.detectedObjects!,);}}@@ -744,124 +740,6 @@ 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>[];- final insertedPetFaceIds = <String>[];- 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);- insertedPetFaceIds.add(dbFace.petFaceId);- }- if (vectorIds.isNotEmpty) {- await vdb.bulkInsertEmbeddings(- vectorIds: vectorIds,- embeddings: embeddings,- );- final updateMap = Map.fromIterables(- insertedPetFaceIds,- 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>[];- final insertedPetBodyIds = <String>[];- 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);- insertedPetBodyIds.add(dbBody.petBodyId);- }- if (vectorIds.isNotEmpty) {- await vdb.bulkInsertEmbeddings(- vectorIds: vectorIds,- embeddings: embeddings,- );- final updateMap = Map.fromIterables(- insertedPetBodyIds,- 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/ui/viewer/file_details/file_info_pets_item_widget.dart b/mobile/apps/photos/lib/ui/viewer/file_details/file_info_pets_item_widget.dartindex e72bf764c2..00366f2f58 100644--- a/mobile/apps/photos/lib/ui/viewer/file_details/file_info_pets_item_widget.dart+++ b/mobile/apps/photos/lib/ui/viewer/file_details/file_info_pets_item_widget.dart@@ -181,7 +181,7 @@ class _PetsItemWidgetState extends State<PetsItemWidget> {Widget _buildPetThumbnail(_PetFaceInfo info, double thumbnailWidth) {final l10n = AppLocalizations.of(context);- final speciesLabel = info.species == "dog" ? l10n.dog : l10n.cat;+ final speciesLabel = info.species == 0 ? l10n.dog : l10n.cat;return SizedBox(width: thumbnailWidth,@@ -212,7 +212,7 @@ class _PetsItemWidgetState extends State<PetsItemWidget> {class _PetFaceInfo {final String petFaceId;- final String species;+ final int species;final Uint8List faceCrop;_PetFaceInfo({diff --git a/mobile/apps/photos/lib/utils/ml_util.dart b/mobile/apps/photos/lib/utils/ml_util.dartindex 922656ea8a..f9e9906712 100644--- a/mobile/apps/photos/lib/utils/ml_util.dart+++ b/mobile/apps/photos/lib/utils/ml_util.dart@@ -820,12 +820,12 @@ Future<MLResult> analyzeImageRust(Map args) async {}if (rustResult.petBodies != null) {- result.petBodies = rustResult.petBodies!.map((body) {- return PetBodyResult(+ result.detectedObjects = rustResult.petBodies!.map((body) {+ return DetectedObjectResult(boxXyxy: body.boxXyxy.toList(growable: false),score: body.score,cocoClass: body.cocoClass,- petBodyId: body.petBodyId,+ objectId: body.petBodyId,embedding: Embedding.from(body.bodyEmbedding),);}).toList(growable: false);