Skip to content

armgit / ente

Public Imported from GitHub
0

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

Add pet recognition database schema, mappers, and vector DB

Amrithesh Kakkoth Ente1dce2e714681
diff --git a/mobile/apps/photos/lib/db/ml/base.dart b/mobile/apps/photos/lib/db/ml/base.dart
index 5bac0233d6..d3306e658d 100644
--- a/mobile/apps/photos/lib/db/ml/base.dart
+++ b/mobile/apps/photos/lib/db/ml/base.dart
@@ -1,5 +1,6 @@
import "dart:typed_data";
+import "package:photos/db/ml/db_pet_model_mappers.dart";
import "package:photos/models/ml/clip.dart";
import "package:photos/models/ml/face/face.dart";
import "package:photos/models/ml/face/face_with_embedding.dart";
@@ -8,6 +9,8 @@ import "package:photos/services/machine_learning/face_ml/face_clustering/face_db
abstract class IMLDataDB<T> {
Future<void> bulkInsertFaces(List<Face> faces);
+ Future<void> bulkInsertPetFaces(List<DBPetFace> petFaces);
+ Future<void> bulkInsertPetBodies(List<DBPetBody> petBodies);
Future<void> updateFaceIdToClusterId(Map<String, String> faceIDToClusterID);
Future<Map<int, int>> faceIndexedFileIds({int minimumMlVersion});
Future<int> getFaceIndexedFileCount({int minimumMlVersion});
@@ -32,6 +35,8 @@ abstract class IMLDataDB<T> {
String? clusterID,
});
Future<List<Face>?> getFacesForGivenFileID(T fileUploadID);
+ Future<List<DBPetFace>?> getPetFacesForFileID(T fileUploadID);
+ Future<List<DBPetBody>?> getPetBodiesForFileID(T fileUploadID);
Future<Map<int, List<FaceWithoutEmbedding>>>
getFileIDsToFacesWithoutEmbedding();
Future<Map<String, Iterable<String>>> getClusterToFaceIDs(
@@ -111,6 +116,9 @@ abstract class IMLDataDB<T> {
List<String>? exceptClusters,
});
+ Future<void> updatePetFaceVectorIds(Map<String, int> petFaceIdToVectorId);
+ Future<void> updatePetBodyVectorIds(Map<String, int> petBodyIdToVectorId);
+
Future<List<EmbeddingVector>> getAllClipVectors();
Future<Map<int, int>> clipIndexedFileWithVersion();
Future<int> getClipIndexedFileCount({int minimumMlVersion});
diff --git a/mobile/apps/photos/lib/db/ml/db.dart b/mobile/apps/photos/lib/db/ml/db.dart
index 62a1202722..e2f067c077 100644
--- a/mobile/apps/photos/lib/db/ml/db.dart
+++ b/mobile/apps/photos/lib/db/ml/db.dart
@@ -13,6 +13,8 @@ import "package:photos/db/ml/base.dart";
import "package:photos/db/ml/clip_vector_db.dart";
import "package:photos/db/ml/cluster_centroid_vector_db.dart";
import "package:photos/db/ml/db_model_mappers.dart";
+import "package:photos/db/ml/db_pet_model_mappers.dart";
+import "package:photos/db/ml/pet_vector_db.dart";
import 'package:photos/db/ml/schema.dart';
import "package:photos/events/embedding_updated_event.dart";
import "package:photos/generated/protos/ente/common/vector.pb.dart";
@@ -96,6 +98,15 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
createFaceCacheTable,
createTextEmbeddingsCacheTable,
createClusterCentroidVectorIdMappingTable,
+ createPetFacesTable,
+ createPetBodiesTable,
+ createPetFaceClustersTable,
+ petFcClusterIDIndex,
+ createPetClusterSummaryTable,
+ createPetFaceVectorIdMappingTable,
+ createPetBodyVectorIdMappingTable,
+ alterPetFacesAddEmbedding,
+ alterPetBodiesAddEmbedding,
];
static const List<String> _offlineMigrationScripts = [
..._defaultMigrationScripts,
@@ -173,6 +184,127 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
}
}
+ @override
+ Future<void> bulkInsertPetFaces(List<DBPetFace> petFaces) async {
+ final db = await asyncDB;
+ const batchSize = 500;
+ final numBatches = (petFaces.length / batchSize).ceil();
+ for (int i = 0; i < numBatches; i++) {
+ final start = i * batchSize;
+ final end = min((i + 1) * batchSize, petFaces.length);
+ final batch = petFaces.sublist(start, end);
+
+ 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
+ ''';
+ final parameterSets = batch.map((petFace) {
+ final map = petFace.toMap();
+ return [
+ map[fileIDColumn],
+ map[petFaceIDColumn],
+ map[faceDetectionColumn],
+ map[petLandmarksColumn],
+ map[faceVectorIdColumn],
+ map[speciesColumn],
+ map[faceScore],
+ map[imageHeight],
+ map[imageWidth],
+ map[mlVersionColumn],
+ map[petFaceEmbeddingColumn],
+ ];
+ }).toList();
+
+ await db.executeBatch(sql, parameterSets);
+ }
+ }
+
+ @override
+ Future<void> bulkInsertPetBodies(List<DBPetBody> petBodies) async {
+ final db = await asyncDB;
+ const batchSize = 500;
+ final numBatches = (petBodies.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);
+
+ const String sql = '''
+ INSERT INTO $petBodiesTable (
+ $fileIDColumn, $petBodyIDColumn, $faceDetectionColumn, $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
+ ''';
+ final parameterSets = batch.map((petBody) {
+ final map = petBody.toMap();
+ return [
+ map[fileIDColumn],
+ map[petBodyIDColumn],
+ map[faceDetectionColumn],
+ map[bodyVectorIdColumn],
+ map[speciesColumn],
+ map[faceScore],
+ map[imageHeight],
+ map[imageWidth],
+ map[mlVersionColumn],
+ map[petBodyEmbeddingColumn],
+ ];
+ }).toList();
+
+ await db.executeBatch(sql, parameterSets);
+ }
+ }
+
+ @override
+ Future<void> updatePetFaceVectorIds(
+ Map<String, int> petFaceIdToVectorId,
+ ) async {
+ if (petFaceIdToVectorId.isEmpty) return;
+ final db = await asyncDB;
+ const batchSize = 500;
+ final entries = petFaceIdToVectorId.entries.toList();
+ final numBatches = (entries.length / batchSize).ceil();
+ for (int i = 0; i < numBatches; i++) {
+ final start = i * batchSize;
+ final end = min((i + 1) * batchSize, entries.length);
+ final batch = entries.sublist(start, end);
+
+ const String sql = '''
+ UPDATE $petFacesTable
+ SET $faceVectorIdColumn = ?
+ WHERE $petFaceIDColumn = ?
+ ''';
+ final parameterSets = batch.map((e) => [e.value, e.key]).toList();
+ await db.executeBatch(sql, parameterSets);
+ }
+ }
+
+ @override
+ Future<void> updatePetBodyVectorIds(
+ Map<String, int> petBodyIdToVectorId,
+ ) async {
+ if (petBodyIdToVectorId.isEmpty) return;
+ final db = await asyncDB;
+ const batchSize = 500;
+ final entries = petBodyIdToVectorId.entries.toList();
+ final numBatches = (entries.length / batchSize).ceil();
+ for (int i = 0; i < numBatches; i++) {
+ final start = i * batchSize;
+ final end = min((i + 1) * batchSize, entries.length);
+ final batch = entries.sublist(start, end);
+
+ const String sql = '''
+ UPDATE $petBodiesTable
+ SET $bodyVectorIdColumn = ?
+ WHERE $petBodyIDColumn = ?
+ ''';
+ final parameterSets = batch.map((e) => [e.value, e.key]).toList();
+ await db.executeBatch(sql, parameterSets);
+ }
+ }
+
@override
Future<void> updateFaceIdToClusterId(
Map<String, String> faceIDToClusterID,
@@ -307,6 +439,16 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
await db.execute(deleteFileDataTable);
await _clipVectorDB.deleteIndexFile();
await _clusterCentroidVectorDB.deleteIndexFile();
+ // Pet tables
+ await db.execute(deletePetFacesTable);
+ await db.execute(deletePetBodiesTable);
+ await db.execute(deletePetFaceClustersTable);
+ await db.execute(deletePetClusterSummaryTable);
+ await db.execute(deletePetFaceVectorIdMappingTable);
+ await db.execute(deletePetBodyVectorIdMappingTable);
+ for (final vdb in PetVectorDB.allInstances) {
+ await vdb.deleteIndexFile();
+ }
_markClusterSummaryMutated();
}
@@ -476,6 +618,40 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
return maps.map((e) => mapRowToFace(e)).toList();
}
+ @override
+ Future<List<DBPetFace>?> getPetFacesForFileID(int fileUploadID) async {
+ final db = await asyncDB;
+ final String query = '''
+ SELECT * FROM $petFacesTable
+ WHERE $fileIDColumn = ?
+ ''';
+ final List<Map<String, dynamic>> maps = await db.getAll(
+ query,
+ [fileUploadID],
+ );
+ if (maps.isEmpty) {
+ return null;
+ }
+ return maps.map((e) => DBPetFace.fromMap(e)).toList();
+ }
+
+ @override
+ Future<List<DBPetBody>?> getPetBodiesForFileID(int fileUploadID) async {
+ final db = await asyncDB;
+ final String query = '''
+ SELECT * FROM $petBodiesTable
+ WHERE $fileIDColumn = ?
+ ''';
+ final List<Map<String, dynamic>> maps = await db.getAll(
+ query,
+ [fileUploadID],
+ );
+ if (maps.isEmpty) {
+ return null;
+ }
+ return maps.map((e) => DBPetBody.fromMap(e)).toList();
+ }
+
@override
Future<Map<int, List<FaceWithoutEmbedding>>>
getFileIDsToFacesWithoutEmbedding() async {
diff --git a/mobile/apps/photos/lib/db/ml/db_pet_model_mappers.dart b/mobile/apps/photos/lib/db/ml/db_pet_model_mappers.dart
new file mode 100644
index 0000000000..0b1304879c
--- /dev/null
+++ b/mobile/apps/photos/lib/db/ml/db_pet_model_mappers.dart
@@ -0,0 +1,207 @@
+import "dart:convert";
+import "dart:typed_data" show Uint8List;
+
+import "package:ente_pure_utils/ente_pure_utils.dart";
+import "package:photos/db/ml/schema.dart";
+import "package:photos/models/ml/face/box.dart";
+import "package:photos/models/ml/face/detection.dart";
+import "package:photos/models/ml/face/landmark.dart";
+import "package:photos/services/machine_learning/ml_result.dart";
+
+// ── Pet Face DB Mapper ──
+
+/// Represents a row in the [petFacesTable].
+class DBPetFace {
+ final int fileId;
+ final String petFaceId;
+ final String detection;
+ final String landmarks;
+ final int faceVectorId;
+ final String species;
+ final double faceScore;
+ final int imageHeight;
+ final int imageWidth;
+ final int mlVersion;
+ final Uint8List? embeddingBlob;
+
+ DBPetFace({
+ required this.fileId,
+ required this.petFaceId,
+ required this.detection,
+ required this.landmarks,
+ required this.faceVectorId,
+ required this.species,
+ required this.faceScore,
+ required this.imageHeight,
+ required this.imageWidth,
+ required this.mlVersion,
+ this.embeddingBlob,
+ });
+
+ /// Convert a [FaceResult] (from Rust) into a DB row, embedding the assigned [vectorId].
+ factory DBPetFace.fromRustResult({
+ required int fileId,
+ required FaceResult rustResult,
+ required int vectorId,
+ required int imageHeight,
+ required int imageWidth,
+ required int mlVersion,
+ required String speciesLabel,
+ }) {
+ // Mirror the human face detection JSON structure
+ final detectionObj = Detection(
+ box: FaceBox(
+ x: rustResult.detection.xMinBox,
+ y: rustResult.detection.yMinBox,
+ width: rustResult.detection.width,
+ height: rustResult.detection.height,
+ ),
+ landmarks: rustResult.detection.allKeypoints
+ .map((kp) => Landmark(x: kp[0], y: kp[1]))
+ .toList(),
+ );
+
+ return DBPetFace(
+ fileId: fileId,
+ petFaceId: rustResult.faceId,
+ detection: jsonEncode(detectionObj.toJson()),
+ landmarks: jsonEncode(rustResult.detection.allKeypoints),
+ faceVectorId: vectorId,
+ species: speciesLabel,
+ faceScore: rustResult.detection.score,
+ imageHeight: imageHeight,
+ imageWidth: imageWidth,
+ mlVersion: mlVersion,
+ );
+ }
+
+ Map<String, dynamic> toMap() {
+ return {
+ fileIDColumn: fileId,
+ petFaceIDColumn: petFaceId,
+ faceDetectionColumn: detection,
+ petLandmarksColumn: landmarks,
+ faceVectorIdColumn: faceVectorId,
+ speciesColumn: species,
+ 'score': faceScore,
+ 'height': imageHeight,
+ 'width': imageWidth,
+ mlVersionColumn: mlVersion,
+ petFaceEmbeddingColumn: embeddingBlob,
+ };
+ }
+
+ factory DBPetFace.fromMap(Map<String, dynamic> map) {
+ return 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,
+ faceScore: parseIntOrDoubleAsDouble(map['score']) ?? 0.0,
+ imageHeight: map['height'] as int,
+ imageWidth: map['width'] as int,
+ mlVersion: map[mlVersionColumn] as int,
+ embeddingBlob: map[petFaceEmbeddingColumn] as Uint8List?,
+ );
+ }
+}
+
+// ── Pet Body DB Mapper ──
+
+/// Represents a row in the [petBodiesTable].
+class DBPetBody {
+ final int fileId;
+ final String petBodyId;
+ final String detection;
+ final int bodyVectorId;
+ final String species;
+ final double faceScore; // Reusing column name, but represents body score
+ final int imageHeight;
+ final int imageWidth;
+ final int mlVersion;
+ final Uint8List? embeddingBlob;
+
+ DBPetBody({
+ required this.fileId,
+ required this.petBodyId,
+ required this.detection,
+ required this.bodyVectorId,
+ required this.species,
+ required this.faceScore,
+ required this.imageHeight,
+ required this.imageWidth,
+ required this.mlVersion,
+ this.embeddingBlob,
+ });
+
+ /// Convert to DB row given the bounding box, class, and assigned [vectorId].
+ /// boxXyxy: [xMin, yMin, xMax, yMax]
+ factory DBPetBody.fromRustResult({
+ required int fileId,
+ required String petBodyId,
+ required List<double> boxXyxy,
+ required double score,
+ required int vectorId,
+ required int imageHeight,
+ required int imageWidth,
+ required int mlVersion,
+ required String speciesLabel,
+ }) {
+ final width = boxXyxy[2] - boxXyxy[0];
+ final height = boxXyxy[3] - boxXyxy[1];
+
+ final detectionObj = Detection(
+ box: FaceBox(
+ x: boxXyxy[0],
+ y: boxXyxy[1],
+ width: width,
+ height: height,
+ ),
+ landmarks: const [], // Bodies don't have landmarks
+ );
+
+ return DBPetBody(
+ fileId: fileId,
+ petBodyId: petBodyId,
+ detection: jsonEncode(detectionObj.toJson()),
+ bodyVectorId: vectorId,
+ species: speciesLabel,
+ faceScore: score,
+ imageHeight: imageHeight,
+ imageWidth: imageWidth,
+ mlVersion: mlVersion,
+ );
+ }
+
+ Map<String, dynamic> toMap() {
+ return {
+ fileIDColumn: fileId,
+ petBodyIDColumn: petBodyId,
+ faceDetectionColumn: detection,
+ bodyVectorIdColumn: bodyVectorId,
+ speciesColumn: species,
+ 'score': faceScore,
+ 'height': imageHeight,
+ 'width': imageWidth,
+ mlVersionColumn: mlVersion,
+ petBodyEmbeddingColumn: embeddingBlob,
+ };
+ }
+
+ factory DBPetBody.fromMap(Map<String, dynamic> map) {
+ return DBPetBody(
+ fileId: map[fileIDColumn] as int,
+ petBodyId: map[petBodyIDColumn] as String,
+ detection: map[faceDetectionColumn] as String,
+ bodyVectorId: map[bodyVectorIdColumn] as int,
+ species: map[speciesColumn] as String,
+ faceScore: parseIntOrDoubleAsDouble(map['score']) ?? 0.0,
+ imageHeight: map['height'] as int,
+ imageWidth: map['width'] as int,
+ mlVersion: map[mlVersionColumn] as int,
+ embeddingBlob: map[petBodyEmbeddingColumn] as Uint8List?,
+ );
+ }
+}
diff --git a/mobile/apps/photos/lib/db/ml/pet_vector_db.dart b/mobile/apps/photos/lib/db/ml/pet_vector_db.dart
new file mode 100644
index 0000000000..73d0c121a5
--- /dev/null
+++ b/mobile/apps/photos/lib/db/ml/pet_vector_db.dart
@@ -0,0 +1,377 @@
+import "dart:io" show File;
+import "dart:math" show min;
+import "dart:typed_data" show Float32List;
+
+import "package:flutter_rust_bridge/flutter_rust_bridge.dart" show Uint64List;
+import "package:logging/logging.dart";
+import "package:path/path.dart";
+import "package:path_provider/path_provider.dart";
+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.
+///
+/// **Each embedding model gets its own vector space** because embeddings from
+/// different models (dog face BYOL vs cat body, etc.) are not comparable.
+/// Face embeddings are 128-d, body embeddings are 192-d.
+///
+/// Uses usearch (via Rust FFI) for approximate nearest-neighbor search.
+/// Pet face IDs are strings, so they are mapped to auto-incrementing integers
+/// via [petFaceVectorIdMappingTable] before being stored as usearch keys.
+class PetVectorDB {
+ static final Logger _logger = Logger("PetVectorDB");
+
+ static const int faceDimension = 128;
+ static const int bodyDimension = 192;
+
+ final String _databaseName;
+ final String _migrationKey;
+ final BigInt _embeddingDimension;
+
+ static Logger get logger => _logger;
+
+ // Private constructor for named instances
+ PetVectorDB._named(
+ this._databaseName,
+ this._migrationKey,
+ this._embeddingDimension,
+ );
+
+ // ── 4 separate vector spaces, one per model ──
+
+ 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),
+ );
+
+ /// All 4 vector DB instances for iteration.
+ static final List<PetVectorDB> allInstances = [
+ dogFace,
+ catFace,
+ dogBody,
+ catBody,
+ ];
+
+ /// Get the correct vector DB for a species + embedding type.
+ /// [species]: 0 = dog, 1 = cat
+ /// [isFace]: true = face embedding, false = body embedding
+ static PetVectorDB forModel({required int species, required bool isFace}) {
+ if (species == 0) {
+ return isFace ? dogFace : dogBody;
+ } else {
+ return isFace ? catFace : catBody;
+ }
+ }
+
+ Future<VectorDb>? _vectorDbFuture;
+
+ Future<VectorDb> get _vectorDB async {
+ _vectorDbFuture ??= _initVectorDB();
+ 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(
+ filePath: dbPath,
+ dimensions: _embeddingDimension,
+ );
+ } catch (e, s) {
+ _logger.severe("Could not open Pet VectorDB at $dbPath", e, s);
+ _logger.severe("Deleting the index file and trying again");
+ await deleteIndexFile();
+ try {
+ vectorDB = VectorDb(
+ filePath: dbPath,
+ dimensions: _embeddingDimension,
+ );
+ } catch (e, s) {
+ _logger.severe("Still can't open Pet VectorDB at $dbPath", e, s);
+ rethrow;
+ }
+ }
+ final stats = await getIndexStats(vectorDB);
+ _logger.info("Pet VectorDB opened with stats: ${stats.toString()}");
+ 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.
+ /// Returns a map of petFaceId β†’ integer vectorId.
+ Future<Map<String, int>> getPetFaceVectorIdMap(
+ Iterable<String> petFaceIds, {
+ bool createIfMissing = false,
+ }) async {
+ final uniqueIds = petFaceIds.toSet().toList(growable: false);
+ if (uniqueIds.isEmpty) return {};
+
+ final mlDataDB = MLDataDB.instance;
+ final db = await mlDataDB.asyncDB;
+
+ if (createIfMissing) {
+ const insertSql = '''
+ INSERT OR IGNORE INTO $petFaceVectorIdMappingTable ($petFaceIDColumn)
+ VALUES (?)
+ ''';
+ final insertParams = <List<Object?>>[];
+ for (final id in uniqueIds) {
+ insertParams.add([id]);
+ }
+ await db.executeBatch(insertSql, insertParams);
+ }
+
+ final result = <String, int>{};
+ const chunkSize = 800;
+ for (int i = 0; i < uniqueIds.length; i += chunkSize) {
+ final chunk = uniqueIds.sublist(i, min(i + chunkSize, uniqueIds.length));
+ final rows = await db.getAll(
+ '''
+ SELECT $petFaceIDColumn, $petFaceVectorIdColumn
+ FROM $petFaceVectorIdMappingTable
+ WHERE $petFaceIDColumn IN (${List.filled(chunk.length, '?').join(',')})
+ ''',
+ chunk,
+ );
+ for (final row in rows) {
+ result[row[petFaceIDColumn] as String] =
+ row[petFaceVectorIdColumn] as int;
+ }
+ }
+ 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, {
+ bool createIfMissing = false,
+ }) async {
+ final uniqueIds = petBodyIds.toSet().toList(growable: false);
+ if (uniqueIds.isEmpty) return {};
+
+ final mlDataDB = MLDataDB.instance;
+ final db = await mlDataDB.asyncDB;
+
+ if (createIfMissing) {
+ const insertSql = '''
+ INSERT OR IGNORE INTO $petBodyVectorIdMappingTable ($petBodyIDColumn)
+ VALUES (?)
+ ''';
+ final insertParams = <List<Object?>>[];
+ for (final id in uniqueIds) {
+ insertParams.add([id]);
+ }
+ await db.executeBatch(insertSql, insertParams);
+ }
+
+ final result = <String, int>{};
+ const chunkSize = 800;
+ for (int i = 0; i < uniqueIds.length; i += chunkSize) {
+ 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(',')})
+ ''',
+ chunk,
+ );
+ for (final row in rows) {
+ result[row[petBodyIDColumn] as String] =
+ row[petBodyVectorIdColumn] as int;
+ }
+ }
+ return result;
+ }
+
+ // ── Vector Operations ──
+
+ /// Insert a single pet face embedding into the vector DB.
+ Future<void> insertEmbedding({
+ required int vectorId,
+ required List<double> embedding,
+ }) async {
+ final db = await _vectorDB;
+ try {
+ await db.addVector(key: BigInt.from(vectorId), vector: embedding);
+ } catch (e, s) {
+ _logger.severe("Error inserting pet embedding", e, s);
+ rethrow;
+ }
+ }
+
+ /// Bulk insert pet face embeddings.
+ Future<void> bulkInsertEmbeddings({
+ required List<int> vectorIds,
+ required List<Float32List> embeddings,
+ }) async {
+ final db = await _vectorDB;
+ final bigKeys = Uint64List.fromList(vectorIds);
+ try {
+ await db.bulkAddVectors(keys: bigKeys, vectors: embeddings);
+ } catch (e, s) {
+ _logger.severe("Error bulk inserting pet embeddings", e, s);
+ rethrow;
+ }
+ }
+
+ /// Get embeddings by their vector IDs.
+ Future<List<Float32List>> getEmbeddings(List<int> vectorIds) async {
+ final db = await _vectorDB;
+ try {
+ final keys = Uint64List.fromList(vectorIds);
+ return await db.bulkGetVectors(keys: keys);
+ } catch (e, s) {
+ _logger.severe("Error getting pet embeddings", e, s);
+ rethrow;
+ }
+ }
+
+ /// Delete embeddings by their vector IDs.
+ Future<void> deleteEmbeddings(List<int> vectorIds) async {
+ final db = await _vectorDB;
+ try {
+ final deletedCount =
+ await db.bulkRemoveVectors(keys: Uint64List.fromList(vectorIds));
+ _logger.info("Deleted $deletedCount pet embeddings");
+ } catch (e, s) {
+ _logger.severe("Error deleting pet embeddings", e, s);
+ rethrow;
+ }
+ }
+
+ /// Search for the closest pet face embeddings to a query.
+ Future<(Uint64List, Float32List)> searchClosestVectors(
+ List<double> query,
+ int count, {
+ bool exact = false,
+ }) async {
+ final db = await _vectorDB;
+ try {
+ return await db.searchVectors(
+ query: query,
+ count: BigInt.from(count),
+ exact: exact,
+ );
+ } catch (e, s) {
+ _logger.severe("Error searching pet vectors", e, s);
+ rethrow;
+ }
+ }
+
+ /// Delete all embeddings and reset the index.
+ Future<void> deleteAllEmbeddings() async {
+ await invalidateMigrationState();
+ final db = await _vectorDB;
+ try {
+ await db.resetIndex();
+ } catch (e, s) {
+ _logger.severe("Error deleting all pet embeddings", e, s);
+ rethrow;
+ }
+ }
+
+ Future<VectorDbStats> getIndexStats([VectorDb? db]) async {
+ db ??= await _vectorDB;
+ try {
+ final stats = await db.getIndexStats();
+ return VectorDbStats(
+ size: stats.$1.toInt(),
+ capacity: stats.$2.toInt(),
+ dimensions: stats.$3.toInt(),
+ fileSize: stats.$4.toInt(),
+ memoryUsage: stats.$5.toInt(),
+ expansionAdd: stats.$6.toInt(),
+ expansionSearch: stats.$7.toInt(),
+ );
+ } catch (e, s) {
+ _logger.severe("Error getting pet index stats", e, s);
+ rethrow;
+ }
+ }
+
+ Future<void> deleteIndex() async {
+ await invalidateMigrationState();
+ final db = await _vectorDB;
+ try {
+ await db.deleteIndex();
+ _vectorDbFuture = null;
+ } catch (e, s) {
+ _logger.severe("Error deleting pet index", e, s);
+ rethrow;
+ }
+ }
+
+ Future<void> deleteIndexFile() async {
+ try {
+ final documentsDirectory = await getApplicationDocumentsDirectory();
+ final String dbPath = join(documentsDirectory.path, _databaseName);
+ _logger.info("Delete pet index file: $dbPath");
+ final file = File(dbPath);
+ if (await file.exists()) {
+ 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.dart
index ff67113477..e0d91f0c07 100644
--- a/mobile/apps/photos/lib/db/ml/schema.dart
+++ b/mobile/apps/photos/lib/db/ml/schema.dart
@@ -182,3 +182,126 @@ CREATE TABLE IF NOT EXISTS $offlineFileKeyMapTable (
$offlineFileKeyLocalIdColumn TEXT NOT NULL UNIQUE
);
''';
+
+// ── PET RECOGNITION TABLES ─────────────────────────────────────────────
+
+// Shared column names
+const petFaceIDColumn = 'pet_face_id';
+const petBodyIDColumn = 'pet_body_id';
+const speciesColumn = 'species';
+const petLandmarksColumn = 'landmarks';
+const faceVectorIdColumn = 'face_vector_id';
+const bodyVectorIdColumn = 'body_vector_id';
+
+// ── Pet Faces Table ──
+
+const petFacesTable = 'pet_faces';
+
+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,
+ $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, $petFaceIDColumn)
+);
+''';
+
+const deletePetFacesTable = 'DELETE FROM $petFacesTable';
+
+// ── Pet Bodies Table ──
+
+const petBodiesTable = 'pet_bodies';
+
+const createPetBodiesTable = '''CREATE TABLE IF NOT EXISTS $petBodiesTable (
+ $fileIDColumn INTEGER NOT NULL,
+ $petBodyIDColumn TEXT NOT NULL UNIQUE,
+ $faceDetectionColumn TEXT NOT NULL,
+ $bodyVectorIdColumn INTEGER NOT NULL,
+ $speciesColumn TEXT 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)
+);
+''';
+
+const deletePetBodiesTable = 'DELETE FROM $petBodiesTable';
+
+// ── Clustering Tables ──
+
+const petFaceClustersTable = 'pet_face_clusters';
+
+const createPetFaceClustersTable = '''
+CREATE TABLE IF NOT EXISTS $petFaceClustersTable (
+ $petFaceIDColumn TEXT NOT NULL,
+ $clusterIDColumn TEXT NOT NULL,
+ PRIMARY KEY($petFaceIDColumn)
+);
+''';
+
+const petFcClusterIDIndex =
+ '''CREATE INDEX IF NOT EXISTS idx_petFcClusterID ON $petFaceClustersTable($clusterIDColumn);''';
+
+const deletePetFaceClustersTable = 'DELETE FROM $petFaceClustersTable';
+
+const petClusterSummaryTable = 'pet_cluster_summary';
+
+const createPetClusterSummaryTable = '''
+CREATE TABLE IF NOT EXISTS $petClusterSummaryTable (
+ $clusterIDColumn TEXT NOT NULL,
+ $avgColumn BLOB NOT NULL,
+ $countColumn INTEGER NOT NULL,
+ $speciesColumn TEXT NOT NULL,
+ PRIMARY KEY($clusterIDColumn)
+);
+''';
+
+const deletePetClusterSummaryTable = 'DELETE FROM $petClusterSummaryTable';
+
+// ── Embedding BLOB Columns (nullable, added via ALTER TABLE) ──
+
+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
+const petFaceVectorIdMappingTable = 'pet_face_vector_id_map';
+const petFaceVectorIdColumn = 'pet_face_vector_id';
+
+const createPetFaceVectorIdMappingTable = '''
+CREATE TABLE IF NOT EXISTS $petFaceVectorIdMappingTable (
+ $petFaceVectorIdColumn INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
+ $petFaceIDColumn TEXT NOT NULL UNIQUE
+);
+''';
+
+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';
+
+const createPetBodyVectorIdMappingTable = '''
+CREATE TABLE IF NOT EXISTS $petBodyVectorIdMappingTable (
+ $petBodyVectorIdColumn INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
+ $petBodyIDColumn TEXT NOT NULL UNIQUE
+);
+''';
+
+const deletePetBodyVectorIdMappingTable =
+ 'DELETE FROM $petBodyVectorIdMappingTable';