π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mob][photos] Decouple face embedding fetch from indexing
laurenspriemfd6c5216492a
diff --git a/mobile/lib/db/embeddings_db.dart b/mobile/lib/db/embeddings_db.dartindex 0d98314d8c..66b91b5070 100644--- a/mobile/lib/db/embeddings_db.dart+++ b/mobile/lib/db/embeddings_db.dart@@ -6,6 +6,7 @@ import 'package:path_provider/path_provider.dart';import "package:photos/core/event_bus.dart";import "package:photos/events/embedding_updated_event.dart";import "package:photos/models/embedding.dart";+import "package:photos/models/ml/ml_versions.dart";import "package:sqlite_async/sqlite_async.dart";class EmbeddingsDB {@@ -62,14 +63,16 @@ class EmbeddingsDB {return _convertToEmbeddings(results);}- // Get FileIDs for a specific model- Future<Set<int>> getFileIDs() async {+ // Get indexed FileIDs+ Future<Map<int, int>> getIndexedFileIds() async {final db = await _database;- final results = await db.getAll('SELECT $columnFileID FROM $tableName');- if (results.isEmpty) {- return <int>{};+ final maps = await db.getAll('SELECT $columnFileID FROM $tableName');+ final Map<int, int> result = {};+ for (final map in maps) {+ result[map[columnFileID] as int] =+ clipMlVersion; // TODO: Add an actual column for version}- return results.map((e) => e[columnFileID] as int).toSet();+ return result;}Future<void> put(Embedding embedding) async {diff --git a/mobile/lib/models/ml/ml_versions.dart b/mobile/lib/models/ml/ml_versions.dartindex 857bef33c5..315f6c74b5 100644--- a/mobile/lib/models/ml/ml_versions.dart+++ b/mobile/lib/models/ml/ml_versions.dart@@ -1,3 +1,4 @@const faceMlVersion = 1;+const clipMlVersion = 2;const clusterMlVersion = 1;-const minimumClusterSize = 2;\ No newline at end of file+const minimumClusterSize = 2;diff --git a/mobile/lib/services/machine_learning/face_ml/face_ml_service.dart b/mobile/lib/services/machine_learning/face_ml/face_ml_service.dartindex 473f911ada..6e2a9c470d 100644--- a/mobile/lib/services/machine_learning/face_ml/face_ml_service.dart+++ b/mobile/lib/services/machine_learning/face_ml/face_ml_service.dart@@ -22,10 +22,7 @@ import "package:photos/face/model/box.dart";import "package:photos/face/model/detection.dart" as face_detection;import "package:photos/face/model/face.dart";import "package:photos/face/model/landmark.dart";-import "package:photos/models/file/extensions/file_props.dart";import "package:photos/models/file/file.dart";-import "package:photos/models/file/file_type.dart";-import "package:photos/models/ml/ml_versions.dart";import "package:photos/service_locator.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";@@ -39,7 +36,6 @@ import "package:photos/services/machine_learning/face_ml/person/person_service.dimport 'package:photos/services/machine_learning/file_ml/file_ml.dart';import 'package:photos/services/machine_learning/file_ml/remote_fileml_service.dart';import 'package:photos/services/machine_learning/ml_exceptions.dart';-import "package:photos/services/search_service.dart";import "package:photos/utils/image_ml_util.dart";import "package:photos/utils/local_settings.dart";import "package:photos/utils/ml_util.dart";@@ -92,7 +88,6 @@ class FaceMlService {bool _shouldPauseIndexingAndClustering = false;static const int _fileDownloadLimit = 10;- static const _embeddingFetchLimit = 200;static const _kForceClusteringFaceCount = 8000;/// Only call this function once at app startup, after that you can directly call [runAllFaceML]@@ -136,13 +131,17 @@ class FaceMlService {_logger.info('init done');}+ Future<void> sync() async {+ await FaceRecognitionService.instance.sync();+ }+Future<void> runAllFaceML({bool force = false}) async {if (force) {_mlControllerStatus = true;}if (_cannotRunMLFunction() && !force) return;- await FaceRecognitionService.instance.sync();+ await sync();final int unclusteredFacesCount =await FaceMLDataDB.instance.getUnclusteredFaceCount();@@ -165,162 +164,47 @@ class FaceMlService {/// Analyzes all the images in the database with the latest ml version and stores the results in the database.////// This function first checks if the image has already been analyzed with the lastest faceMlVersion and stored in the database. If so, it skips the image.- Future<void> indexAllImages({int retryFetchCount = 10}) async {+ Future<void> indexAllImages() async {if (_cannotRunMLFunction()) return;try {_isIndexingOrClusteringRunning = true;_logger.info('starting image indexing');- // Get indexed fileIDs, all regular files, and all hidden files- final Map<int, int> alreadyIndexedFiles =- await FaceMLDataDB.instance.getIndexedFileIds();- final List<EnteFile> enteFiles =- await SearchService.instance.getAllFiles();- final List<EnteFile> hiddenFiles =- await SearchService.instance.getHiddenFiles();+ final filesToIndex = await getFilesForMlIndexing();++ final List<List<FileMLInstruction>> chunks =+ filesToIndex.chunks(_fileDownloadLimit);- // Sort out what should be indexed and in what orderint fileAnalyzedCount = 0;- int fileSkippedCount = 0;- final stopwatch = Stopwatch()..start();- final List<EnteFile> filesWithLocalID = <EnteFile>[];- final List<EnteFile> filesWithoutLocalID = <EnteFile>[];- final List<EnteFile> hiddenFilesToIndex = <EnteFile>[];- for (final EnteFile enteFile in enteFiles) {- if (_skipAnalysisEnteFile(enteFile, alreadyIndexedFiles)) {- fileSkippedCount++;- continue;- }- if ((enteFile.localID ?? '').isEmpty) {- filesWithoutLocalID.add(enteFile);- } else {- filesWithLocalID.add(enteFile);- }- }- for (final EnteFile enteFile in hiddenFiles) {- if (_skipAnalysisEnteFile(enteFile, alreadyIndexedFiles)) {- fileSkippedCount++;- continue;- }- hiddenFilesToIndex.add(enteFile);- }- final sortedBylocalID = <EnteFile>[];- sortedBylocalID.addAll(filesWithLocalID);- sortedBylocalID.addAll(filesWithoutLocalID);- sortedBylocalID.addAll(hiddenFilesToIndex);- final List<List<EnteFile>> chunks =- sortedBylocalID.chunks(_embeddingFetchLimit); // Chunks of 200-- int fetchedCount = 0;+ final Stopwatch stopwatch = Stopwatch()..start();outerLoop:for (final chunk in chunks) {- // Fetching and storing remote embeddings- if (LocalSettings.instance.remoteFetchEnabled) {- try {- final fileIds = chunk.map((file) => file.uploadedFileID!).toSet();- _logger.info('starting remote fetch for ${fileIds.length} files');- final res =- await RemoteFileMLService.instance.getFilessEmbedding(fileIds);- _logger.info('fetched ${res.mlData.length} embeddings');- fetchedCount += res.mlData.length;- final List<Face> faces = [];- final remoteFileIdToVersion = <int, int>{};- for (FileMl fileMl in res.mlData.values) {- if (shouldDiscardRemoteEmbedding(fileMl)) continue;- if (fileMl.faceEmbedding.faces.isEmpty) {- faces.add(- Face.empty(- fileMl.fileID,- ),- );- } else {- for (final f in fileMl.faceEmbedding.faces) {- f.fileInfo = FileInfo(- imageHeight: fileMl.height,- imageWidth: fileMl.width,- );- faces.add(f);- }- }- remoteFileIdToVersion[fileMl.fileID] =- fileMl.faceEmbedding.version;- }- if (res.noEmbeddingFileIDs.isNotEmpty) {- _logger.info(- 'No embeddings found for ${res.noEmbeddingFileIDs.length} files',- );- for (final fileID in res.noEmbeddingFileIDs) {- faces.add(Face.empty(fileID, error: false));- remoteFileIdToVersion[fileID] = faceMlVersion;- }- }-- await FaceMLDataDB.instance.bulkInsertFaces(faces);- _logger.info('stored embeddings');- for (final entry in remoteFileIdToVersion.entries) {- alreadyIndexedFiles[entry.key] = entry.value;- }- _logger- .info('already indexed files ${remoteFileIdToVersion.length}');- } catch (e, s) {- _logger.severe("err while getting files embeddings", e, s);- if (retryFetchCount < 1000) {- Future.delayed(Duration(seconds: retryFetchCount), () {- unawaited(indexAllImages(retryFetchCount: retryFetchCount * 2));- });- return;- } else {- _logger.severe(- "Failed to fetch embeddings for files after multiple retries",- e,- s,- );- rethrow;- }- }- } else {- _logger.warning(- 'Not fetching embeddings because user manually disabled it in debug options',+ if (!await canUseHighBandwidth()) {+ _logger.info(+ 'stopping indexing because user is not connected to wifi',);+ break outerLoop;}-- final smallerChunks = chunk.chunks(_fileDownloadLimit);- for (final smallestChunk in smallerChunks) {- final futures = <Future<bool>>[];- if (!await canUseHighBandwidth()) {- _logger.info(- 'stopping indexing because user is not connected to wifi',- );+ final futures = <Future<bool>>[];+ for (final instruction in chunk) {+ if (_shouldPauseIndexingAndClustering) {+ _logger.info("indexAllImages() was paused, stopping");break outerLoop;}- for (final enteFile in smallestChunk) {- if (_shouldPauseIndexingAndClustering) {- _logger.info("indexAllImages() was paused, stopping");- break outerLoop;- }- if (_skipAnalysisEnteFile(- enteFile,- alreadyIndexedFiles,- )) {- fileSkippedCount++;- continue;- }- await _ensureReadyForInference();- futures.add(processImage(enteFile));- }- final awaitedFutures = await Future.wait(futures);- final sumFutures = awaitedFutures.fold<int>(- 0,- (previousValue, element) => previousValue + (element ? 1 : 0),- );- fileAnalyzedCount += sumFutures;+ await _ensureReadyForInference();+ futures.add(processImage(instruction.enteFile));}+ final awaitedFutures = await Future.wait(futures);+ final sumFutures = awaitedFutures.fold<int>(+ 0,+ (previousValue, element) => previousValue + (element ? 1 : 0),+ );+ fileAnalyzedCount += sumFutures;}- stopwatch.stop();_logger.info(- "`indexAllImages()` finished. Fetched $fetchedCount and analyzed $fileAnalyzedCount images, in ${stopwatch.elapsed.inSeconds} seconds (avg of ${stopwatch.elapsed.inSeconds / fileAnalyzedCount} seconds per image, skipped $fileSkippedCount images)",+ "`indexAllImages()` finished. Analyzed $fileAnalyzedCount images, in ${stopwatch.elapsed.inSeconds} seconds (avg of ${stopwatch.elapsed.inSeconds / fileAnalyzedCount} seconds per image)",);_logStatus();} catch (e, s) {@@ -1024,22 +908,6 @@ class FaceMlService {}}- bool _skipAnalysisEnteFile(EnteFile enteFile, Map<int, int> indexedFileIds) {- // Skip if the file is not uploaded or not owned by the user- if (!enteFile.isUploaded || enteFile.isOwner == false) {- return true;- }- // I don't know how motionPhotos and livePhotos work, so I'm also just skipping them for now- if (enteFile.fileType == FileType.other) {- return true;- }- // Skip if the file is already analyzed with the latest ml version- final id = enteFile.uploadedFileID!;-- return indexedFileIds.containsKey(id) &&- indexedFileIds[id]! >= faceMlVersion;- }-bool _cannotRunMLFunction({String function = ""}) {if (_isIndexingOrClusteringRunning) {_logger.info(diff --git a/mobile/lib/services/machine_learning/face_ml/face_recognition_service.dart b/mobile/lib/services/machine_learning/face_ml/face_recognition_service.dartindex 7563f3d9ca..c141c0eb10 100644--- a/mobile/lib/services/machine_learning/face_ml/face_recognition_service.dart+++ b/mobile/lib/services/machine_learning/face_ml/face_recognition_service.dart@@ -4,7 +4,15 @@ import "package:logging/logging.dart";import "package:photos/core/event_bus.dart";import "package:photos/events/diff_sync_complete_event.dart";import "package:photos/events/people_changed_event.dart";+import "package:photos/extensions/list.dart";+import "package:photos/face/db.dart";+import "package:photos/face/model/face.dart";+import "package:photos/models/ml/ml_versions.dart";import "package:photos/services/machine_learning/face_ml/person/person_service.dart";+import "package:photos/services/machine_learning/file_ml/file_ml.dart";+import "package:photos/services/machine_learning/file_ml/remote_fileml_service.dart";+import "package:photos/utils/local_settings.dart";+import "package:photos/utils/ml_util.dart";class FaceRecognitionService {final _logger = Logger("FaceRecognitionService");@@ -21,6 +29,8 @@ class FaceRecognitionService {bool _shouldSyncPeople = false;bool _isSyncing = false;+ static const _embeddingFetchLimit = 200;+Future<void> init() async {if (_isInitialized) {return;@@ -29,7 +39,7 @@ class FaceRecognitionService {// Listen on DiffSyncBus.instance.on<DiffSyncCompleteEvent>().listen((event) async {- unawaited(sync());+ unawaited(_syncPersonFeedback());});// Listen on PeopleChanged@@ -43,6 +53,17 @@ class FaceRecognitionService {}Future<void> sync() async {+ await _syncPersonFeedback();+ if (LocalSettings.instance.remoteFetchEnabled) {+ await _syncFaceEmbeddings();+ } else {+ _logger.severe(+ 'Not fetching embeddings because user manually disabled it in debug options',+ );+ }+ }++ Future<void> _syncPersonFeedback() async {if (_isSyncing) {return;}@@ -54,4 +75,79 @@ class FaceRecognitionService {}_isSyncing = false;}++ Future<void> _syncFaceEmbeddings({int retryFetchCount = 10}) async {+ final filesToIndex = await getFilesForMlIndexing();++ final List<List<FileMLInstruction>> chunks =+ filesToIndex.chunks(_embeddingFetchLimit); // Chunks of 200++ int fetchedCount = 0;+ for (final chunk in chunks) {+ // Fetching and storing remote embeddings+ try {+ final fileIds = chunk+ .map((instruction) => instruction.enteFile.uploadedFileID!)+ .toSet();+ _logger.info('starting remote fetch for ${fileIds.length} files');+ final res =+ await RemoteFileMLService.instance.getFilessEmbedding(fileIds);+ _logger.info('fetched ${res.mlData.length} embeddings');+ fetchedCount += res.mlData.length;+ final List<Face> faces = [];+ final remoteFileIdToVersion = <int, int>{};+ for (FileMl fileMl in res.mlData.values) {+ if (shouldDiscardRemoteEmbedding(fileMl)) continue;+ if (fileMl.faceEmbedding.faces.isEmpty) {+ faces.add(+ Face.empty(+ fileMl.fileID,+ ),+ );+ } else {+ for (final f in fileMl.faceEmbedding.faces) {+ f.fileInfo = FileInfo(+ imageHeight: fileMl.height,+ imageWidth: fileMl.width,+ );+ faces.add(f);+ }+ }+ remoteFileIdToVersion[fileMl.fileID] = fileMl.faceEmbedding.version;+ }+ if (res.noEmbeddingFileIDs.isNotEmpty) {+ _logger.info(+ 'No embeddings found for ${res.noEmbeddingFileIDs.length} files',+ );+ for (final fileID in res.noEmbeddingFileIDs) {+ faces.add(Face.empty(fileID, error: false));+ remoteFileIdToVersion[fileID] = faceMlVersion;+ }+ }++ await FaceMLDataDB.instance.bulkInsertFaces(faces);+ _logger.info(+ 'stored embeddings, already indexed files ${remoteFileIdToVersion.length}',+ );+ } catch (e, s) {+ _logger.severe("err while getting files embeddings", e, s);+ if (retryFetchCount < 1000) {+ Future.delayed(Duration(seconds: retryFetchCount), () {+ unawaited(+ _syncFaceEmbeddings(retryFetchCount: retryFetchCount * 2),+ );+ });+ return;+ } else {+ _logger.severe(+ "Failed to fetch embeddings for files after multiple retries",+ e,+ s,+ );+ rethrow;+ }+ }+ }+ _logger.info('Fetched $fetchedCount embeddings');+ }}diff --git a/mobile/lib/utils/ml_util.dart b/mobile/lib/utils/ml_util.dartindex cc783ad1db..fdb578d7d4 100644--- a/mobile/lib/utils/ml_util.dart+++ b/mobile/lib/utils/ml_util.dart@@ -4,10 +4,15 @@ import "dart:math" as math show sqrt;import "package:flutter/services.dart" show PlatformException;import "package:logging/logging.dart";import "package:photos/core/configuration.dart";+import "package:photos/db/embeddings_db.dart";import "package:photos/db/files_db.dart";+import "package:photos/face/db.dart";+import "package:photos/models/file/extensions/file_props.dart";import "package:photos/models/file/file.dart";import "package:photos/models/file/file_type.dart";+import "package:photos/models/ml/ml_versions.dart";import "package:photos/services/machine_learning/ml_exceptions.dart";+import "package:photos/services/search_service.dart";import "package:photos/utils/file_util.dart";import "package:photos/utils/thumbnail_util.dart";@@ -15,6 +20,80 @@ final _logger = Logger("MlUtil");enum FileDataForML { thumbnailData, fileData }+class FileMLInstruction {+ final EnteFile enteFile;++ final bool shouldRunFaces;+ final bool shouldRunClip;++ FileMLInstruction({+ required this.enteFile,+ required this.shouldRunFaces,+ required this.shouldRunClip,+ });+}++Future<List<FileMLInstruction>> getFilesForMlIndexing() async {+ _logger.info('getFilesForMlIndexing called');+ final time = DateTime.now();+ // Get indexed fileIDs for each ML service+ final Map<int, int> faceIndexedFileIDs =+ await FaceMLDataDB.instance.getIndexedFileIds();+ final Map<int, int> clipIndexedFileIDs =+ await EmbeddingsDB.instance.getIndexedFileIds();++ // Get all regular files and all hidden files+ final enteFiles = await SearchService.instance.getAllFiles();+ final hiddenFiles = await SearchService.instance.getHiddenFiles();++ // Sort out what should be indexed and in what order+ final List<FileMLInstruction> filesWithLocalID = [];+ final List<FileMLInstruction> filesWithoutLocalID = [];+ final List<FileMLInstruction> hiddenFilesToIndex = [];+ for (final EnteFile enteFile in enteFiles) {+ final skip = _skipAnalysisEnteFile(enteFile);+ final shouldRunFaces = _shouldRunIndexing(enteFile, faceIndexedFileIDs);+ final shouldRunClip = _shouldRunIndexing(enteFile, clipIndexedFileIDs);+ if (skip && !shouldRunFaces && !shouldRunClip) {+ continue;+ }+ final instruction = FileMLInstruction(+ enteFile: enteFile,+ shouldRunFaces: shouldRunFaces,+ shouldRunClip: shouldRunClip,+ );+ if ((enteFile.localID ?? '').isEmpty) {+ filesWithoutLocalID.add(instruction);+ } else {+ filesWithLocalID.add(instruction);+ }+ }+ for (final EnteFile enteFile in hiddenFiles) {+ final skip = _skipAnalysisEnteFile(enteFile);+ final shouldRunFaces = _shouldRunIndexing(enteFile, faceIndexedFileIDs);+ final shouldRunClip = _shouldRunIndexing(enteFile, clipIndexedFileIDs);+ if (skip && !shouldRunFaces && !shouldRunClip) {+ continue;+ }+ final instruction = FileMLInstruction(+ enteFile: enteFile,+ shouldRunFaces: shouldRunFaces,+ shouldRunClip: shouldRunClip,+ );+ hiddenFilesToIndex.add(instruction);+ }+ final sortedBylocalID = <FileMLInstruction>[+ ...filesWithLocalID,+ ...filesWithoutLocalID,+ ...hiddenFilesToIndex,+ ];+ _logger.info(+ "Getting list of files to index for ML took ${DateTime.now().difference(time).inMilliseconds} ms",+ );++ return sortedBylocalID;+}+Future<Set<int>> getIndexableFileIDs() async {final fileIDs = await FilesDB.instance.getOwnedFileIDs(Configuration.instance.getUserID()!);@@ -91,6 +170,23 @@ Future<String> getImagePathForML(return imagePath;}+bool _skipAnalysisEnteFile(EnteFile enteFile) {+ // Skip if the file is not uploaded or not owned by the user+ if (!enteFile.isUploaded || enteFile.isOwner == false) {+ return true;+ }+ // I don't know how motionPhotos and livePhotos work, so I'm also just skipping them for now+ if (enteFile.fileType == FileType.other) {+ return true;+ }+ return false;+}++bool _shouldRunIndexing(EnteFile enteFile, Map<int, int> indexedFileIds) {+ final id = enteFile.uploadedFileID!;+ return !indexedFileIds.containsKey(id) || indexedFileIds[id]! < faceMlVersion;+}+void normalizeEmbedding(List<double> embedding) {double normalization = 0;for (int i = 0; i < embedding.length; i++) {