Skip to content

armgit / ente

Public Imported from GitHub
0

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

Refactor face thumbnail caching logic

laurenspriem3f212aa1d159
diff --git a/mobile/lib/db/ml/db.dart b/mobile/lib/db/ml/db.dart
index 0186ead274..322bb90303 100644
--- a/mobile/lib/db/ml/db.dart
+++ b/mobile/lib/db/ml/db.dart
@@ -35,6 +35,8 @@ import 'package:sqlite_async/sqlite_async.dart';
///
/// [clipTable] - Stores the embeddings of the CLIP model
/// [fileDataTable] - Stores data about the files that are already processed by the ML models
+///
+/// [faceCacheTable] - Stores a all the mappings from personID or clusterID to the faceID that has been used as cover face.
class MLDataDB with SqlDbBase implements IMLDataDB<int> {
static final Logger _logger = Logger("MLDataDB");
@@ -57,6 +59,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
fcClusterIDIndex,
createClipEmbeddingsTable,
createFileDataTable,
+ createFaceCacheTable,
];
// only have a single app-wide reference to the database
@@ -471,6 +474,22 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
return maps.map((e) => e[faceIDColumn] as String).toSet();
}
+ Future<List<String>> getFaceIDsForClusterOrderedByScore(
+ String clusterID, {
+ int limit = 10,
+ }) async {
+ final db = await instance.asyncDB;
+ final faceIdsResult = await db.getAll(
+ 'SELECT $facesTable.$faceIDColumn FROM $facesTable '
+ 'JOIN $faceClustersTable ON $facesTable.$faceIDColumn = $faceClustersTable.$faceIDColumn '
+ 'WHERE $faceClustersTable.$clusterIDColumn = ? '
+ 'ORDER BY $facesTable.$faceScore DESC '
+ 'LIMIT ?',
+ [clusterID, limit],
+ );
+ return faceIdsResult.map((e) => e[faceIDColumn] as String).toList();
+ }
+
// Get Map of personID to Map of clusterID to faceIDs
@override
Future<Map<String, Map<String, Set<String>>>>
@@ -541,6 +560,23 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
return faceIdsResult.map((e) => e[faceIDColumn] as String).toSet();
}
+ Future<List<String>> getFaceIDsForPersonOrderedByScore(
+ String personID, {
+ int limit = 10,
+ }) async {
+ final db = await instance.asyncDB;
+ final faceIdsResult = await db.getAll(
+ 'SELECT $facesTable.$faceIDColumn FROM $facesTable '
+ 'JOIN $faceClustersTable ON $facesTable.$faceIDColumn = $faceClustersTable.$faceIDColumn '
+ 'JOIN $clusterPersonTable ON $faceClustersTable.$clusterIDColumn = $clusterPersonTable.$clusterIDColumn '
+ 'WHERE $clusterPersonTable.$personIdColumn = ? '
+ 'ORDER BY $facesTable.$faceScore DESC '
+ 'LIMIT ?',
+ [personID, limit],
+ );
+ return faceIdsResult.map((e) => e[faceIDColumn] as String).toList();
+ }
+
@override
Future<Iterable<double>> getBlurValuesForCluster(String clusterID) async {
final db = await instance.asyncDB;
@@ -1249,4 +1285,47 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
embedding.version,
];
}
+
+ Future<void> putFaceIdCachedForPersonOrCluster(
+ String personOrClusterId,
+ String faceID,
+ ) async {
+ final db = await instance.asyncDB;
+ await db.execute(
+ '''
+ INSERT OR REPLACE INTO $faceCacheTable ($personOrClusterIdColumn, $faceIDColumn)
+ VALUES (?, ?)
+ ''',
+ [personOrClusterId, faceID],
+ );
+ }
+
+ Future<String?> getFaceIdUsedForPersonOrCluster(
+ String personOrClusterId,
+ ) async {
+ final db = await instance.asyncDB;
+ final List<Map<String, dynamic>> maps = await db.getAll(
+ '''
+ SELECT $faceIDColumn FROM $faceCacheTable
+ WHERE $personOrClusterIdColumn = ?
+ ''',
+ [personOrClusterId],
+ );
+ if (maps.isNotEmpty) {
+ return maps.first[faceIDColumn] as String;
+ }
+ return null;
+ }
+
+ Future<void> removeFaceIdCachedForPersonOrCluster(
+ String personOrClusterID,
+ ) async {
+ final db = await instance.asyncDB;
+ const String sql = '''
+ DELETE FROM $faceCacheTable
+ WHERE $personOrClusterIdColumn = ?'
+ ''';
+ final List<Object?> params = [personOrClusterID];
+ await db.execute(sql, params);
+ }
}
diff --git a/mobile/lib/db/ml/schema.dart b/mobile/lib/db/ml/schema.dart
index 5968215cf5..3db7d42820 100644
--- a/mobile/lib/db/ml/schema.dart
+++ b/mobile/lib/db/ml/schema.dart
@@ -15,6 +15,7 @@ const imageHeight = 'height';
const mlVersionColumn = 'ml_version';
const personIdColumn = 'person_id';
const clusterIDColumn = 'cluster_id';
+const personOrClusterIdColumn = 'person_or_cluster_id';
const createFacesTable = '''CREATE TABLE IF NOT EXISTS $facesTable (
$fileIDColumn INTEGER NOT NULL,
@@ -123,3 +124,16 @@ CREATE TABLE IF NOT EXISTS $fileDataTable (
''';
const deleteFileDataTable = 'DELETE FROM $fileDataTable';
+
+// ## FACE CACHE TABLE
+const faceCacheTable = 'face_cache';
+
+const createFaceCacheTable = '''
+CREATE TABLE IF NOT EXISTS $faceCacheTable (
+ $personOrClusterIdColumn TEXT NOT NULL UNIQUE,
+ $faceIDColumn TEXT NOT NULL UNIQUE,
+ PRIMARY KEY ($personOrClusterIdColumn),
+);
+''';
+
+const deleteFaceCacheTable = 'DELETE FROM $faceCacheTable';
diff --git a/mobile/lib/services/machine_learning/face_ml/person/person_service.dart b/mobile/lib/services/machine_learning/face_ml/person/person_service.dart
index d9d2cc7b02..f195d43518 100644
--- a/mobile/lib/services/machine_learning/face_ml/person/person_service.dart
+++ b/mobile/lib/services/machine_learning/face_ml/person/person_service.dart
@@ -16,6 +16,7 @@ import "package:photos/service_locator.dart";
import "package:photos/services/entity_service.dart";
import "package:photos/services/machine_learning/ml_result.dart";
import "package:photos/services/search_service.dart";
+import "package:photos/utils/face/face_box_crop.dart";
import "package:shared_preferences/shared_preferences.dart";
class PersonService {
@@ -445,9 +446,21 @@ class PersonService {
data: person.data.copyWith(avatarFaceId: face.faceID),
);
await updatePerson(updatedPerson);
+ await faceMLDataDB.putFaceIdCachedForPersonOrCluster(
+ p.remoteID,
+ face.faceID,
+ );
return updatedPerson;
}
+ Future<PersonEntity> removeAvatar(PersonEntity p) async {
+ final person = (await getPerson(p.remoteID))!;
+ person.data.avatarFaceID = null;
+ await updatePerson(person);
+ await checkRemoveCachedFaceIDForPersonOrClusterId(p.remoteID);
+ return person;
+ }
+
Future<PersonEntity> updateAttributes(
String id, {
String? name,
diff --git a/mobile/lib/ui/viewer/people/file_face_widget.dart b/mobile/lib/ui/viewer/people/file_face_widget.dart
index e37e6b2e2c..b024057d69 100644
--- a/mobile/lib/ui/viewer/people/file_face_widget.dart
+++ b/mobile/lib/ui/viewer/people/file_face_widget.dart
@@ -51,7 +51,7 @@ class _FileFaceWidgetState extends State<FileFaceWidget> {
super.dispose();
if (widget.faceCrop == null) {
checkStopTryingToGenerateFaceThumbnails(
- widget.file,
+ widget.file.uploadedFileID!,
useFullFile: widget.useFullFile,
);
}
diff --git a/mobile/lib/ui/viewer/people/person_face_widget.dart b/mobile/lib/ui/viewer/people/person_face_widget.dart
index 62c18ec618..0c9e0f96d3 100644
--- a/mobile/lib/ui/viewer/people/person_face_widget.dart
+++ b/mobile/lib/ui/viewer/people/person_face_widget.dart
@@ -12,31 +12,22 @@ import "package:photos/services/machine_learning/ml_result.dart";
import "package:photos/services/search_service.dart";
import "package:photos/theme/ente_theme.dart";
import "package:photos/ui/common/loading_widget.dart";
-import "package:photos/ui/viewer/file/thumbnail_widget.dart";
import "package:photos/utils/face/face_box_crop.dart";
final _logger = Logger("PersonFaceWidget");
class PersonFaceWidget extends StatefulWidget {
- final EnteFile file;
final String? personId;
final String? clusterID;
final bool useFullFile;
- final bool thumbnailFallback;
- final bool cannotTrustFile;
- final Uint8List? faceCrop;
final VoidCallback? onErrorCallback;
// PersonFaceWidget constructor checks that both personId and clusterID are not null
// and that the file is not null
- const PersonFaceWidget(
- this.file, {
+ const PersonFaceWidget({
this.personId,
this.clusterID,
this.useFullFile = true,
- this.thumbnailFallback = false,
- this.cannotTrustFile = false,
- this.faceCrop,
this.onErrorCallback,
super.key,
}) : assert(
@@ -50,23 +41,25 @@ class PersonFaceWidget extends StatefulWidget {
class _PersonFaceWidgetState extends State<PersonFaceWidget> {
Future<Uint8List?>? faceCropFuture;
- late final mlDataDB = MLDataDB.instance;
+ EnteFile? fileForFaceCrop;
+
+ bool get isPerson => widget.personId != null;
@override
void initState() {
super.initState();
- faceCropFuture = widget.faceCrop != null
- ? Future.value(widget.faceCrop)
- : _getFaceCrop();
+ faceCropFuture = _getFaceCrop();
}
@override
void dispose() {
super.dispose();
- checkStopTryingToGenerateFaceThumbnails(
- widget.file,
- useFullFile: widget.useFullFile,
- );
+ if (fileForFaceCrop != null) {
+ checkStopTryingToGenerateFaceThumbnails(
+ fileForFaceCrop!.uploadedFileID!,
+ useFullFile: widget.useFullFile,
+ );
+ }
}
@override
@@ -88,14 +81,14 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget> {
} else {
if (snapshot.hasError) {
_logger.severe(
- "Error getting cover face for person: ${snapshot.error} ${snapshot.stackTrace}}",
+ "Error getting cover face for person",
+ snapshot.error,
+ snapshot.stackTrace,
);
}
- return widget.thumbnailFallback
- ? ThumbnailWidget(widget.file)
- : EnteLoadingWidget(
- color: getEnteColorScheme(context).fillMuted,
- );
+ return EnteLoadingWidget(
+ color: getEnteColorScheme(context).fillMuted,
+ );
}
},
);
@@ -103,80 +96,108 @@ class _PersonFaceWidgetState extends State<PersonFaceWidget> {
Future<Uint8List?> _getFaceCrop() async {
try {
- EnteFile? fileForFaceCrop = widget.file;
- String? personAvatarFaceID;
- Iterable<String>? allFaces;
- if (widget.personId != null) {
- final PersonEntity? personEntity =
- await PersonService.instance.getPerson(widget.personId!);
- if (personEntity != null) {
- personAvatarFaceID = personEntity.data.avatarFaceID;
- if (personAvatarFaceID != null) {
- final tryCache =
- await checkGetCachedCropForFaceID(personAvatarFaceID);
- if (tryCache != null) return tryCache;
- }
- if (personAvatarFaceID == null && widget.cannotTrustFile) {
- allFaces = await mlDataDB.getFaceIDsForPerson(widget.personId!);
+ final String personOrClusterId = widget.personId ?? widget.clusterID!;
+ final tryInMemoryCachedCrop =
+ checkInMemoryCachedCropForPersonOrClusterID(personOrClusterId);
+ if (tryInMemoryCachedCrop != null) return tryInMemoryCachedCrop;
+ String? fixedFaceID;
+ PersonEntity? personEntity;
+ if (isPerson) {
+ personEntity = await PersonService.instance.getPerson(widget.personId!);
+ if (personEntity == null) {
+ _logger.severe(
+ "Person with ID ${widget.personId} not found, cannot get cover face.",
+ );
+ return null;
+ }
+ fixedFaceID = personEntity.data.avatarFaceID;
+ }
+ fixedFaceID ??=
+ await checkUsedFaceIDForPersonOrClusterId(personOrClusterId);
+ final hiddenFileIDs = await SearchService.instance
+ .getHiddenFiles()
+ .then((onValue) => onValue.map((e) => e.uploadedFileID));
+ EnteFile? fileForFaceCrop;
+ if (fixedFaceID != null) {
+ final fileID = getFileIdFromFaceId<int>(fixedFaceID);
+ final fileInDB = await FilesDB.instance.getAnyUploadedFile(fileID);
+ if (fileInDB == null) {
+ if (personEntity?.data.avatarFaceID != null) {
+ await PersonService.instance.removeAvatar(personEntity!);
+ _logger.severe(
+ "Removed avatar for person ${widget.personId} as the file was not found in DB.",
+ );
+ } else {
+ _logger.severe(
+ "File with ID $fileID not found in DB, cannot get cover face.",
+ );
+ await checkRemoveCachedFaceIDForPersonOrClusterId(
+ personOrClusterId,
+ );
}
+ } else if (hiddenFileIDs.contains(fileInDB.uploadedFileID)) {
+ _logger.info(
+ "File with ID $fileID is hidden, skipping it for face crop.",
+ );
+ await checkRemoveCachedFaceIDForPersonOrClusterId(
+ personOrClusterId,
+ );
+ } else {
+ fileForFaceCrop = fileInDB;
}
- } else if (widget.clusterID != null && widget.cannotTrustFile) {
- allFaces = await mlDataDB.getFaceIDsForCluster(widget.clusterID!);
}
- if (allFaces != null) {
- final allFileIDs =
- allFaces.map((e) => getFileIdFromFaceId<int>(e)).toSet();
- final hiddenFileIDs = await SearchService.instance
- .getHiddenFiles()
- .then((onValue) => onValue.map((e) => e.uploadedFileID));
- final acceptableFileIDs = allFileIDs.difference(hiddenFileIDs.toSet());
- final fileIDToCreationTime =
- await FilesDB.instance.getFileIDToCreationTime();
- // Get the file with the most recent creation time
- final recentFileID = acceptableFileIDs.reduce((a, b) {
- final aTime = fileIDToCreationTime[a];
- final bTime = fileIDToCreationTime[b];
- if (aTime == null) {
- return b;
+ if (fileForFaceCrop == null) {
+ final List<String> allFaces = isPerson
+ ? await MLDataDB.instance
+ .getFaceIDsForPersonOrderedByScore(widget.personId!)
+ : await MLDataDB.instance
+ .getFaceIDsForClusterOrderedByScore(widget.clusterID!);
+ for (final faceID in allFaces) {
+ final fileID = getFileIdFromFaceId<int>(faceID);
+ if (hiddenFileIDs.contains(fileID)) {
+ _logger.info(
+ "File with ID $fileID is hidden, skipping it for face crop.",
+ );
+ continue;
}
- if (bTime == null) {
- return a;
+ fileForFaceCrop = await FilesDB.instance.getAnyUploadedFile(fileID);
+ if (fileForFaceCrop != null) {
+ _logger.info(
+ "Using file ID $fileID for face crop for person: ${widget.personId} or cluster: ${widget.clusterID}",
+ );
+ fixedFaceID = faceID;
+ break;
}
- return (aTime >= bTime) ? a : b;
- });
- if (fileForFaceCrop.uploadedFileID != recentFileID) {
- fileForFaceCrop =
- await FilesDB.instance.getAnyUploadedFile(recentFileID);
- if (fileForFaceCrop == null) return null;
+ }
+ if (fileForFaceCrop == null) {
+ _logger.severe(
+ "No suitable file found for face crop for person: ${widget.personId} or cluster: ${widget.clusterID}",
+ );
+ return null;
}
}
-
- final Face? face = await mlDataDB.getCoverFaceForPerson(
+ final Face? face = await MLDataDB.instance.getCoverFaceForPerson(
recentFileID: fileForFaceCrop.uploadedFileID!,
- avatarFaceId: personAvatarFaceID,
+ avatarFaceId: fixedFaceID,
personID: widget.personId,
clusterID: widget.clusterID,
);
if (face == null) {
debugPrint(
- "No cover face for person: ${widget.personId} and cluster ${widget.clusterID} and recentFile ${widget.file.uploadedFileID}",
+ "No cover face for person: ${widget.personId} or cluster ${widget.clusterID} and fileID ${fileForFaceCrop.uploadedFileID!}",
);
return null;
}
- if (face.fileID != fileForFaceCrop.uploadedFileID!) {
- fileForFaceCrop =
- await FilesDB.instance.getAnyUploadedFile(face.fileID);
- if (fileForFaceCrop == null) return null;
- }
final cropMap = await getCachedFaceCrops(
fileForFaceCrop,
[face],
useFullFile: widget.useFullFile,
+ personOrClusterID: personOrClusterId,
);
return cropMap?[face.faceID];
} catch (e, s) {
_logger.severe(
- "Error getting cover face for person: ${widget.personId} and cluster ${widget.clusterID}",
+ "Error getting cover face for person: ${widget.personId} or cluster ${widget.clusterID}",
e,
s,
);
diff --git a/mobile/lib/utils/face/face_box_crop.dart b/mobile/lib/utils/face/face_box_crop.dart
index ced0c84d08..74fe92e22a 100644
--- a/mobile/lib/utils/face/face_box_crop.dart
+++ b/mobile/lib/utils/face/face_box_crop.dart
@@ -22,6 +22,9 @@ final _logger = Logger("FaceCropUtils");
const int _retryLimit = 3;
final LRUMap<String, Uint8List?> _faceCropCache = LRUMap(1000);
final LRUMap<String, Uint8List?> _faceCropThumbnailCache = LRUMap(1000);
+
+final LRUMap<String, String> _personOrClusterIdToCachedFaceID = LRUMap(1000);
+
TaskQueue _queueFullFileFaceGenerations = TaskQueue<String>(
maxConcurrentTasks: 5,
taskTimeout: const Duration(minutes: 1),
@@ -33,36 +36,83 @@ TaskQueue _queueThumbnailFaceGenerations = TaskQueue<String>(
maxQueueSize: 100,
);
-Future<Uint8List?> checkGetCachedCropForFaceID(String faceID) async {
+Uint8List? checkInMemoryCachedCropForPersonOrClusterID(
+ String personOrClusterID,
+) {
+ final String? faceID =
+ _personOrClusterIdToCachedFaceID.get(personOrClusterID);
+ if (faceID == null) return null;
final Uint8List? cachedCover = _faceCropCache.get(faceID);
return cachedCover;
}
-Future<void> putCachedCropForFaceID(
- String faceID,
- Uint8List data,
+Uint8List? _checkInMemoryCachedCropForFaceID(String faceID) {
+ final Uint8List? cachedCover = _faceCropCache.get(faceID);
+ return cachedCover;
+}
+
+Future<String?> checkUsedFaceIDForPersonOrClusterId(
+ String personOrClusterID,
) async {
+ final String? cachedFaceID =
+ _personOrClusterIdToCachedFaceID.get(personOrClusterID);
+ if (cachedFaceID != null) return cachedFaceID;
+ final String? faceIDFromDB = await MLDataDB.instance
+ .getFaceIdUsedForPersonOrCluster(personOrClusterID);
+ if (faceIDFromDB != null) {
+ _personOrClusterIdToCachedFaceID.put(personOrClusterID, faceIDFromDB);
+ }
+ return faceIDFromDB;
+}
+
+Future<void> _putCachedCropForFaceID(
+ String faceID,
+ Uint8List data, [
+ String? personOrClusterID,
+]) async {
_faceCropCache.put(faceID, data);
+ if (personOrClusterID != null) {
+ await MLDataDB.instance.putFaceIdCachedForPersonOrCluster(
+ personOrClusterID,
+ faceID,
+ );
+ _personOrClusterIdToCachedFaceID.put(personOrClusterID, faceID);
+ }
+}
+
+Future<void> checkRemoveCachedFaceIDForPersonOrClusterId(
+ String personOrClusterID,
+) async {
+ final String? cachedFaceID = await MLDataDB.instance
+ .getFaceIdUsedForPersonOrCluster(personOrClusterID);
+ if (cachedFaceID != null) {
+ _personOrClusterIdToCachedFaceID.remove(personOrClusterID);
+ await MLDataDB.instance
+ .removeFaceIdCachedForPersonOrCluster(personOrClusterID);
+ }
}
+/// Careful to only use [personOrClusterID] if all [faces] are from the same person or cluster.
Future<Map<String, Uint8List>?> getCachedFaceCrops(
EnteFile enteFile,
Iterable<Face> faces, {
int fetchAttempt = 1,
bool useFullFile = true,
+ String? personOrClusterID,
}) async {
try {
final faceIdToCrop = <String, Uint8List>{};
final facesWithoutCrops = <String, FaceBox>{};
for (final face in faces) {
- final Uint8List? cachedFace = _faceCropCache.get(face.faceID);
+ final Uint8List? cachedFace =
+ _checkInMemoryCachedCropForFaceID(face.faceID);
if (cachedFace != null) {
faceIdToCrop[face.faceID] = cachedFace;
} else {
final faceCropCacheFile = cachedFaceCropPath(face.faceID);
if ((await faceCropCacheFile.exists())) {
final data = await faceCropCacheFile.readAsBytes();
- _faceCropCache.put(face.faceID, data);
+ await _putCachedCropForFaceID(face.faceID, data, personOrClusterID);
faceIdToCrop[face.faceID] = data;
} else {
facesWithoutCrops[face.faceID] = face.detection.box;
@@ -102,7 +152,11 @@ Future<Map<String, Uint8List>?> getCachedFaceCrops(
if (computedCrop != null) {
faceIdToCrop[entry.key] = computedCrop;
if (useFullFile) {
- _faceCropCache.put(entry.key, computedCrop);
+ await _putCachedCropForFaceID(
+ entry.key,
+ computedCrop,
+ personOrClusterID,
+ );
final faceCropCacheFile = cachedFaceCropPath(entry.key);
faceCropCacheFile.writeAsBytes(computedCrop).ignore();
} else {
@@ -191,11 +245,10 @@ Future<Uint8List?> precomputeClusterFaceCrop(
}
void checkStopTryingToGenerateFaceThumbnails(
- EnteFile file, {
+ int fileID, {
bool useFullFile = true,
}) {
- final taskId =
- [file.uploadedFileID!, useFullFile ? "-full" : "-thumbnail"].join();
+ final taskId = [fileID, useFullFile ? "-full" : "-thumbnail"].join();
if (useFullFile) {
_queueFullFileFaceGenerations.removeTask(taskId);
} else {