Skip to content

armgit / ente

Public Imported from GitHub
0

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

[mob][photos] small refactor

laurensprieme47b4169ed17
diff --git a/mobile/lib/models/ml/ml_versions.dart b/mobile/lib/models/ml/ml_versions.dart
index d22c4c0670..a52982fb23 100644
--- a/mobile/lib/models/ml/ml_versions.dart
+++ b/mobile/lib/models/ml/ml_versions.dart
@@ -2,3 +2,6 @@ const faceMlVersion = 1;
const clipMlVersion = 1;
const clusterMlVersion = 1;
const minimumClusterSize = 2;
+
+const embeddingFetchLimit = 200;
+const fileDownloadMlLimit = 10;
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.dart
index f639520df3..8b3bb7eda1 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
@@ -5,17 +5,8 @@ import "dart:ui" show Image;
import "package:logging/logging.dart";
import "package:photos/core/event_bus.dart";
-import "package:photos/db/ml/clip_db.dart";
-import "package:photos/db/ml/db.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/models/ml/clip.dart";
-import "package:photos/models/ml/face/face.dart";
-import "package:photos/models/ml/ml_versions.dart";
-import "package:photos/service_locator.dart";
-import "package:photos/services/filedata/filedata_service.dart";
-import "package:photos/services/filedata/model/file_data.dart";
import "package:photos/services/machine_learning/face_ml/face_detection/detection.dart";
import "package:photos/services/machine_learning/face_ml/face_detection/face_detection_service.dart";
import "package:photos/services/machine_learning/face_ml/face_embedding/face_embedding_service.dart";
@@ -23,7 +14,6 @@ import "package:photos/services/machine_learning/face_ml/person/person_service.d
import "package:photos/services/machine_learning/ml_exceptions.dart";
import "package:photos/services/machine_learning/ml_result.dart";
import "package:photos/utils/image_ml_util.dart";
-import "package:photos/utils/ml_util.dart";
class FaceRecognitionService {
final _logger = Logger("FaceRecognitionService");
@@ -40,8 +30,6 @@ class FaceRecognitionService {
bool _shouldSyncPeople = false;
bool _isSyncing = false;
- static const _embeddingFetchLimit = 200;
-
Future<void> init() async {
if (_isInitialized) {
return;
@@ -80,101 +68,6 @@ class FaceRecognitionService {
_isSyncing = false;
}
- Stream<List<FileMLInstruction>> syncEmbeddings({
- int yieldSize = 10,
- }) async* {
- final List<FileMLInstruction> filesToIndex = await getFilesForMlIndexing();
- final List<List<FileMLInstruction>> chunks =
- filesToIndex.chunks(_embeddingFetchLimit);
- List<FileMLInstruction> batchToYield = [];
-
- for (final chunk in chunks) {
- if (!localSettings.remoteFetchEnabled) {
- _logger.warning("remoteFetchEnabled is false, skiping embedding fetch");
- yield chunk;
- }
- final Set<int> ids = {};
- final Map<int, FileMLInstruction> pendingIndex = {};
- for (final instruction in chunk) {
- ids.add(instruction.file.uploadedFileID!);
- pendingIndex[instruction.file.uploadedFileID!] = instruction;
- }
- _logger.info("fetching embeddings for ${ids.length} files");
- final res = await FileDataService.instance.getFilesData(ids);
- _logger.info("embeddingResponse ${res.debugLog()}");
- final List<Face> faces = [];
- final List<ClipEmbedding> clipEmbeddings = [];
- for (FileDataEntity fileMl in res.data.values) {
- final existingInstruction = pendingIndex[fileMl.fileID]!;
- final facesFromRemoteEmbedding = _getFacesFromRemoteEmbedding(fileMl);
- //Note: Always do null check, empty value means no face was found.
- if (facesFromRemoteEmbedding != null) {
- faces.addAll(facesFromRemoteEmbedding);
- existingInstruction.shouldRunFaces = false;
- }
- if (fileMl.clipEmbedding != null &&
- fileMl.clipEmbedding!.version >= clipMlVersion) {
- clipEmbeddings.add(
- ClipEmbedding(
- fileID: fileMl.fileID,
- embedding: fileMl.clipEmbedding!.embedding,
- version: fileMl.clipEmbedding!.version,
- ),
- );
- existingInstruction.shouldRunClip = false;
- }
- if (!existingInstruction.pendingML) {
- pendingIndex.remove(fileMl.fileID);
- } else {
- existingInstruction.existingRemoteFileML = fileMl;
- pendingIndex[fileMl.fileID] = existingInstruction;
- }
- }
- for (final fileID in pendingIndex.keys) {
- final instruction = pendingIndex[fileID]!;
- if (instruction.pendingML) {
- batchToYield.add(instruction);
- if (batchToYield.length == yieldSize) {
- _logger.info("queueing indexing for $yieldSize");
- yield batchToYield;
- batchToYield = [];
- }
- }
- }
- await MLDataDB.instance.bulkInsertFaces(faces);
- await MLDataDB.instance.putMany(clipEmbeddings);
- }
- // Yield any remaining instructions
- if (batchToYield.isNotEmpty) {
- _logger.info("queueing indexing for ${batchToYield.length}");
- yield batchToYield;
- }
- }
-
- // Returns a list of faces from the given remote fileML. null if the version is less than the current version
- // or if the remote faceEmbedding is null.
- List<Face>? _getFacesFromRemoteEmbedding(FileDataEntity fileMl) {
- final RemoteFaceEmbedding? remoteFaceEmbedding = fileMl.faceEmbedding;
- if (shouldDiscardRemoteEmbedding(fileMl)) {
- return null;
- }
- final List<Face> faces = [];
- if (remoteFaceEmbedding!.faces.isEmpty) {
- faces.add(
- Face.empty(fileMl.fileID),
- );
- } else {
- for (final f in remoteFaceEmbedding.faces) {
- f.fileInfo = FileInfo(
- imageHeight: remoteFaceEmbedding.height,
- imageWidth: remoteFaceEmbedding.width,
- );
- faces.add(f);
- }
- }
- return faces;
- }
-
static Future<List<FaceResult>> runFacesPipeline(
int enteFileID,
Image image,
diff --git a/mobile/lib/services/machine_learning/ml_service.dart b/mobile/lib/services/machine_learning/ml_service.dart
index 9321c3f96a..d54d45000c 100644
--- a/mobile/lib/services/machine_learning/ml_service.dart
+++ b/mobile/lib/services/machine_learning/ml_service.dart
@@ -58,7 +58,6 @@ class MLService {
bool _isRunningML = false;
bool _shouldPauseIndexingAndClustering = false;
- static const int _fileDownloadLimit = 10;
static const _kForceClusteringFaceCount = 8000;
/// Only call this function once at app startup, after that you can directly call [runAllML]
@@ -142,7 +141,9 @@ class MLService {
}
void triggerML() {
- if (_mlControllerStatus && !_isIndexingOrClusteringRunning && !_isRunningML) {
+ if (_mlControllerStatus &&
+ !_isIndexingOrClusteringRunning &&
+ !_isRunningML) {
unawaited(runAllML());
}
}
@@ -169,8 +170,7 @@ class MLService {
_isIndexingOrClusteringRunning = true;
_logger.info('starting image indexing');
final Stream<List<FileMLInstruction>> instructionStream =
- FaceRecognitionService.instance
- .syncEmbeddings(yieldSize: _fileDownloadLimit);
+ fetchEmbeddingsAndInstructions();
int fileAnalyzedCount = 0;
final Stopwatch stopwatch = Stopwatch()..start();
diff --git a/mobile/lib/utils/ml_util.dart b/mobile/lib/utils/ml_util.dart
index 33d30711c0..c30872c4bf 100644
--- a/mobile/lib/utils/ml_util.dart
+++ b/mobile/lib/utils/ml_util.dart
@@ -7,11 +7,16 @@ import "package:photos/core/configuration.dart";
import "package:photos/db/files_db.dart";
import "package:photos/db/ml/clip_db.dart";
import "package:photos/db/ml/db.dart";
+import "package:photos/extensions/list.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/clip.dart";
import "package:photos/models/ml/face/dimension.dart";
+import "package:photos/models/ml/face/face.dart";
import "package:photos/models/ml/ml_versions.dart";
+import "package:photos/service_locator.dart";
+import "package:photos/services/filedata/filedata_service.dart";
import "package:photos/services/filedata/model/file_data.dart";
import "package:photos/services/machine_learning/face_ml/face_recognition_service.dart";
import "package:photos/services/machine_learning/ml_exceptions.dart";
@@ -68,6 +73,7 @@ Future<IndexStatus> getIndexStatus() async {
}
}
+/// Return a list of file instructions for files that should be indexed for ML
Future<List<FileMLInstruction>> getFilesForMlIndexing() async {
_logger.info('getFilesForMlIndexing called');
final time = DateTime.now();
@@ -146,7 +152,106 @@ Future<List<FileMLInstruction>> getFilesForMlIndexing() async {
return sortedBylocalID;
}
-bool shouldDiscardRemoteEmbedding(FileDataEntity fileML) {
+Stream<List<FileMLInstruction>> fetchEmbeddingsAndInstructions({
+ int yieldSize = fileDownloadMlLimit,
+}) async* {
+ final List<FileMLInstruction> filesToIndex = await getFilesForMlIndexing();
+ final List<List<FileMLInstruction>> chunks =
+ filesToIndex.chunks(embeddingFetchLimit);
+ List<FileMLInstruction> batchToYield = [];
+
+ for (final chunk in chunks) {
+ if (!localSettings.remoteFetchEnabled) {
+ _logger.warning("remoteFetchEnabled is false, skiping embedding fetch");
+ final batches = chunk.chunks(yieldSize);
+ for (final batch in batches) {
+ yield batch;
+ }
+ continue;
+ }
+ final Set<int> ids = {};
+ final Map<int, FileMLInstruction> pendingIndex = {};
+ for (final instruction in chunk) {
+ ids.add(instruction.file.uploadedFileID!);
+ pendingIndex[instruction.file.uploadedFileID!] = instruction;
+ }
+ _logger.info("fetching embeddings for ${ids.length} files");
+ final res = await FileDataService.instance.getFilesData(ids);
+ _logger.info("embeddingResponse ${res.debugLog()}");
+ final List<Face> faces = [];
+ final List<ClipEmbedding> clipEmbeddings = [];
+ for (FileDataEntity fileMl in res.data.values) {
+ final existingInstruction = pendingIndex[fileMl.fileID]!;
+ final facesFromRemoteEmbedding = _getFacesFromRemoteEmbedding(fileMl);
+ //Note: Always do null check, empty value means no face was found.
+ if (facesFromRemoteEmbedding != null) {
+ faces.addAll(facesFromRemoteEmbedding);
+ existingInstruction.shouldRunFaces = false;
+ }
+ if (fileMl.clipEmbedding != null &&
+ fileMl.clipEmbedding!.version >= clipMlVersion) {
+ clipEmbeddings.add(
+ ClipEmbedding(
+ fileID: fileMl.fileID,
+ embedding: fileMl.clipEmbedding!.embedding,
+ version: fileMl.clipEmbedding!.version,
+ ),
+ );
+ existingInstruction.shouldRunClip = false;
+ }
+ if (!existingInstruction.pendingML) {
+ pendingIndex.remove(fileMl.fileID);
+ } else {
+ existingInstruction.existingRemoteFileML = fileMl;
+ pendingIndex[fileMl.fileID] = existingInstruction;
+ }
+ }
+ for (final fileID in pendingIndex.keys) {
+ final instruction = pendingIndex[fileID]!;
+ if (instruction.pendingML) {
+ batchToYield.add(instruction);
+ if (batchToYield.length == yieldSize) {
+ _logger.info("queueing indexing for $yieldSize");
+ yield batchToYield;
+ batchToYield = [];
+ }
+ }
+ }
+ await MLDataDB.instance.bulkInsertFaces(faces);
+ await MLDataDB.instance.putMany(clipEmbeddings);
+ }
+ // Yield any remaining instructions
+ if (batchToYield.isNotEmpty) {
+ _logger.info("queueing indexing for ${batchToYield.length}");
+ yield batchToYield;
+ }
+}
+
+// Returns a list of faces from the given remote fileML. null if the version is less than the current version
+// or if the remote faceEmbedding is null.
+List<Face>? _getFacesFromRemoteEmbedding(FileDataEntity fileMl) {
+ final RemoteFaceEmbedding? remoteFaceEmbedding = fileMl.faceEmbedding;
+ if (_shouldDiscardRemoteEmbedding(fileMl)) {
+ return null;
+ }
+ final List<Face> faces = [];
+ if (remoteFaceEmbedding!.faces.isEmpty) {
+ faces.add(
+ Face.empty(fileMl.fileID),
+ );
+ } else {
+ for (final f in remoteFaceEmbedding.faces) {
+ f.fileInfo = FileInfo(
+ imageHeight: remoteFaceEmbedding.height,
+ imageWidth: remoteFaceEmbedding.width,
+ );
+ faces.add(f);
+ }
+ }
+ return faces;
+}
+
+bool _shouldDiscardRemoteEmbedding(FileDataEntity fileML) {
final fileID = fileML.fileID;
final RemoteFaceEmbedding? faceEmbedding = fileML.faceEmbedding;
if (faceEmbedding == null || faceEmbedding.version < faceMlVersion) {