π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mob][photos] Small refactor FaceClusteringService
laurenspriem979730d74049
diff --git a/mobile/lib/services/machine_learning/face_ml/face_clustering/face_clustering_service.dart b/mobile/lib/services/machine_learning/face_ml/face_clustering/face_clustering_service.dartindex 35a25748ac..84b180eb8b 100644--- a/mobile/lib/services/machine_learning/face_ml/face_clustering/face_clustering_service.dart+++ b/mobile/lib/services/machine_learning/face_ml/face_clustering/face_clustering_service.dart@@ -40,18 +40,24 @@ enum ClusterOperation { linearIncrementalClustering }class ClusteringResult {final Map<String, int> newFaceIdToCluster;- final Map<int, List<String>>? newClusterIdToFaceIds;- final Map<int, (Uint8List, int)>? newClusterSummaries;+ final Map<int, List<String>> newClusterIdToFaceIds;+ final Map<int, (Uint8List, int)> newClusterSummaries;bool get isEmpty => newFaceIdToCluster.isEmpty;-- bool get hasAllResults => newClusterSummaries != null && newClusterIdToFaceIds != null;-+ClusteringResult({required this.newFaceIdToCluster,- this.newClusterSummaries,- this.newClusterIdToFaceIds,+ required this.newClusterSummaries,+ required this.newClusterIdToFaceIds,});++ factory ClusteringResult.empty() {+ return ClusteringResult(+ newFaceIdToCluster: {},+ newClusterIdToFaceIds: {},+ newClusterSummaries: {},+ );+ }}class FaceClusteringService {@@ -59,7 +65,7 @@ class FaceClusteringService {final _computer = Computer.shared();Timer? _inactivityTimer;- final Duration _inactivityDuration = const Duration(minutes: 3);+ final Duration _inactivityDuration = const Duration(minutes: 2);int _activeTasks = 0;final _initLock = Lock();@@ -82,7 +88,7 @@ class FaceClusteringService {static final instance = FaceClusteringService._privateConstructor();factory FaceClusteringService() => instance;- Future<void> init() async {+ Future<void> _initIsolate() async {return _initLock.synchronized(() async {if (isSpawned) return;@@ -104,9 +110,9 @@ class FaceClusteringService {});}- Future<void> ensureSpawned() async {+ Future<void> _ensureSpawnedIsolate() async {if (!isSpawned) {- await init();+ await _initIsolate();}}@@ -124,7 +130,7 @@ class FaceClusteringService {try {switch (function) {case ClusterOperation.linearIncrementalClustering:- final result = FaceClusteringService.runLinearClustering(args);+ final ClusteringResult result = _runLinearClustering(args);sendPort.send(result);break;}@@ -138,7 +144,7 @@ class FaceClusteringService {Future<dynamic> _runInIsolate((ClusterOperation, Map<String, dynamic>) message,) async {- await ensureSpawned();+ await _ensureSpawnedIsolate();_resetInactivityTimer();final completer = Completer<dynamic>();final answerPort = ReceivePort();@@ -178,13 +184,13 @@ class FaceClusteringService {_logger.info('Clustering Isolate has been inactive for ${_inactivityDuration.inSeconds} seconds with no tasks running. Killing isolate.',);- dispose();+ _dispose();}});}/// Disposes the isolate worker.- void dispose() {+ void _dispose() {if (!isSpawned) return;isSpawned = false;@@ -193,10 +199,10 @@ class FaceClusteringService {_inactivityTimer?.cancel();}- /// Runs the clustering algorithm [runLinearClustering] on the given [input], in an isolate.+ /// Runs the clustering algorithm [_runLinearClustering] on the given [input], in an isolate.////// Returns the clustering result, which is a list of clusters, where each cluster is a list of indices of the dataset.- Future<ClusteringResult?> predictLinear(+ Future<ClusteringResult?> predictLinearIsolate(Set<FaceInfoForClustering> input, {Map<int, int>? fileIDToCreationTime,double distanceThreshold = kRecommendedDistanceThreshold,@@ -225,7 +231,7 @@ class FaceClusteringService {final stopwatchClustering = Stopwatch()..start();// final Map<String, int> faceIdToCluster =// await _runLinearClusteringInComputer(input);- final ClusteringResult? faceIdToCluster = await _runInIsolate(+ final ClusteringResult faceIdToCluster = await _runInIsolate((ClusterOperation.linearIncrementalClustering,{@@ -253,8 +259,49 @@ class FaceClusteringService {}}- /// Runs the clustering algorithm [runLinearClustering] on the given [input], in computer, without any dynamic thresholding- Future<ClusteringResult?> predictLinearComputer(+ Future<ClusteringResult> predictWithinClusterComputer(+ Map<String, Uint8List> input, {+ Map<int, int>? fileIDToCreationTime,+ Map<int, (Uint8List, int)> oldClusterSummaries = const <int, (Uint8List, int)>{},+ double distanceThreshold = kRecommendedDistanceThreshold,+ }) async {+ _logger.info(+ '`predictWithinClusterComputer` called with ${input.length} faces and distance threshold $distanceThreshold',+ );+ try {+ if (input.length < 500) {+ final mergeThreshold = distanceThreshold;+ _logger.info(+ 'Running complete clustering on ${input.length} faces with distance threshold $mergeThreshold',+ );+ final ClusteringResult clusterResult = await predictCompleteComputer(+ input,+ fileIDToCreationTime: fileIDToCreationTime,+ oldClusterSummaries: oldClusterSummaries,+ distanceThreshold: distanceThreshold - 0.08,+ mergeThreshold: mergeThreshold,+ );+ return clusterResult;+ } else {+ _logger.info(+ 'Running linear clustering on ${input.length} faces with distance threshold $distanceThreshold',+ );+ final ClusteringResult clusterResult = await predictLinearComputer(+ input,+ fileIDToCreationTime: fileIDToCreationTime,+ oldClusterSummaries: oldClusterSummaries,+ distanceThreshold: distanceThreshold,+ );+ return clusterResult;+ }+ } catch (e, s) {+ _logger.severe(e, s);+ rethrow;+ }+ }++ /// Runs the clustering algorithm [_runLinearClustering] on the given [input], in computer, without any dynamic thresholding+ Future<ClusteringResult> predictLinearComputer(Map<String, Uint8List> input, {Map<int, int>? fileIDToCreationTime,required Map<int, (Uint8List, int)> oldClusterSummaries,@@ -264,7 +311,7 @@ class FaceClusteringService {_logger.warning("Linear Clustering dataset of embeddings is empty, returning empty list.",);- return null;+ return ClusteringResult.empty();}// Clustering inside the isolate@@ -289,7 +336,7 @@ class FaceClusteringService {.toSet();final startTime = DateTime.now();final faceIdToCluster = await _computer.compute(- runLinearClustering,+ _runLinearClustering,param: {"input": clusteringInput,"fileIDToCreationTime": fileIDToCreationTime,@@ -311,7 +358,7 @@ class FaceClusteringService {}}- /// Runs the clustering algorithm [runCompleteClustering] on the given [input], in computer.+ /// Runs the clustering algorithm [_runCompleteClustering] on the given [input], in computer.////// WARNING: Only use on small datasets, as it is not optimized for large datasets.Future<ClusteringResult> predictCompleteComputer(@@ -325,7 +372,7 @@ class FaceClusteringService {_logger.warning("Complete Clustering dataset of embeddings is empty, returning empty list.",);- return ClusteringResult(newFaceIdToCluster: {});+ return ClusteringResult.empty();}// Clustering inside the isolate@@ -336,7 +383,7 @@ class FaceClusteringService {try {final startTime = DateTime.now();final clusteringResult = await _computer.compute(- runCompleteClustering,+ _runCompleteClustering,param: {"input": input,"fileIDToCreationTime": fileIDToCreationTime,@@ -356,521 +403,367 @@ class FaceClusteringService {rethrow;}}+}- Future<ClusteringResult?> predictWithinClusterComputer(- Map<String, Uint8List> input, {- Map<int, int>? fileIDToCreationTime,- Map<int, (Uint8List, int)> oldClusterSummaries = const <int, (Uint8List, int)>{},- double distanceThreshold = kRecommendedDistanceThreshold,- }) async {- _logger.info(- '`predictWithinClusterComputer` called with ${input.length} faces and distance threshold $distanceThreshold',+ClusteringResult _runLinearClustering(Map args) {+ // final input = args['input'] as Map<String, (int?, Uint8List)>;+ final input = args['input'] as Set<FaceInfoForClustering>;+ final fileIDToCreationTime = args['fileIDToCreationTime'] as Map<int, int>?;+ final distanceThreshold = args['distanceThreshold'] as double;+ final conservativeDistanceThreshold = args['conservativeDistanceThreshold'] as double;+ final useDynamicThreshold = args['useDynamicThreshold'] as bool;+ final offset = args['offset'] as int?;+ final oldClusterSummaries = args['oldClusterSummaries'] as Map<int, (Uint8List, int)>?;++ log(+ "[ClusterIsolate] ${DateTime.now()} Copied to isolate ${input.length} faces",+ );++ // Organize everything into a list of FaceInfo objects+ final List<FaceInfo> faceInfos = [];+ for (final face in input) {+ faceInfos.add(+ FaceInfo(+ faceID: face.faceID,+ faceScore: face.faceScore,+ blurValue: face.blurValue,+ badFace: face.faceScore < kMinimumQualityFaceScore ||+ face.blurValue < kLaplacianSoftThreshold ||+ (face.blurValue < kLaplacianVerySoftThreshold &&+ face.faceScore < kMediumQualityFaceScore) ||+ face.isSideways,+ vEmbedding: Vector.fromList(+ EVector.fromBuffer(face.embeddingBytes).values,+ dtype: DType.float32,+ ),+ clusterId: face.clusterId,+ fileCreationTime: fileIDToCreationTime?[getFileIdFromFaceId(face.faceID)],+ ),);- try {- if (input.length < 500) {- final mergeThreshold = distanceThreshold;- _logger.info(- 'Running complete clustering on ${input.length} faces with distance threshold $mergeThreshold',- );- final result = await predictCompleteComputer(- input,- fileIDToCreationTime: fileIDToCreationTime,- oldClusterSummaries: oldClusterSummaries,- distanceThreshold: distanceThreshold - 0.08,- mergeThreshold: mergeThreshold,- );- if (result.newFaceIdToCluster.isEmpty) return null;- return result;- } else {- _logger.info(- 'Running linear clustering on ${input.length} faces with distance threshold $distanceThreshold',- );- final clusterResult = await predictLinearComputer(- input,- fileIDToCreationTime: fileIDToCreationTime,- oldClusterSummaries: oldClusterSummaries,- distanceThreshold: distanceThreshold,- );- return clusterResult;- }- } catch (e, s) {- _logger.severe(e, s);- rethrow;- }}- static ClusteringResult? runLinearClustering(Map args) {- // final input = args['input'] as Map<String, (int?, Uint8List)>;- final input = args['input'] as Set<FaceInfoForClustering>;- final fileIDToCreationTime = args['fileIDToCreationTime'] as Map<int, int>?;- final distanceThreshold = args['distanceThreshold'] as double;- final conservativeDistanceThreshold = args['conservativeDistanceThreshold'] as double;- final useDynamicThreshold = args['useDynamicThreshold'] as bool;- final offset = args['offset'] as int?;- final oldClusterSummaries = args['oldClusterSummaries'] as Map<int, (Uint8List, int)>?;-- log(- "[ClusterIsolate] ${DateTime.now()} Copied to isolate ${input.length} faces",- );-- // Organize everything into a list of FaceInfo objects- final List<FaceInfo> faceInfos = [];- for (final face in input) {- faceInfos.add(- FaceInfo(- faceID: face.faceID,- faceScore: face.faceScore,- blurValue: face.blurValue,- badFace: face.faceScore < kMinimumQualityFaceScore ||- face.blurValue < kLaplacianSoftThreshold ||- (face.blurValue < kLaplacianVerySoftThreshold &&- face.faceScore < kMediumQualityFaceScore) ||- face.isSideways,- vEmbedding: Vector.fromList(- EVector.fromBuffer(face.embeddingBytes).values,- dtype: DType.float32,- ),- clusterId: face.clusterId,- fileCreationTime: fileIDToCreationTime?[getFileIdFromFaceId(face.faceID)],- ),- );- }-- // Assert that the embeddings are normalized- for (final faceInfo in faceInfos) {- if (faceInfo.vEmbedding != null) {- final norm = faceInfo.vEmbedding!.norm();- assert((norm - 1.0).abs() < 1e-5);- }- }-- if (fileIDToCreationTime != null) {- _sortFaceInfosOnCreationTime(faceInfos);- }-- // Sort the faceInfos such that the ones with null clusterId are at the end- final List<FaceInfo> facesWithClusterID = <FaceInfo>[];- final List<FaceInfo> facesWithoutClusterID = <FaceInfo>[];- for (final FaceInfo faceInfo in faceInfos) {- if (faceInfo.clusterId == null) {- facesWithoutClusterID.add(faceInfo);- } else {- facesWithClusterID.add(faceInfo);- }+ // Assert that the embeddings are normalized+ for (final faceInfo in faceInfos) {+ if (faceInfo.vEmbedding != null) {+ final norm = faceInfo.vEmbedding!.norm();+ assert((norm - 1.0).abs() < 1e-5);}- final alreadyClusteredCount = facesWithClusterID.length;- final sortedFaceInfos = <FaceInfo>[];- sortedFaceInfos.addAll(facesWithClusterID);- sortedFaceInfos.addAll(facesWithoutClusterID);-- log(- "[ClusterIsolate] ${DateTime.now()} Clustering ${facesWithoutClusterID.length} new faces without clusterId, and $alreadyClusteredCount faces with clusterId",- );-- // Make sure the first face has a clusterId- final int totalFaces = sortedFaceInfos.length;- int dynamicThresholdCount = 0;+ }- if (sortedFaceInfos.isEmpty) {- return null;- }+ if (fileIDToCreationTime != null) {+ _sortFaceInfosOnCreationTime(faceInfos);+ }- // Start actual clustering- log(- "[ClusterIsolate] ${DateTime.now()} Processing $totalFaces faces in total in this round ${offset != null ? "on top of ${offset + facesWithClusterID.length} earlier processed faces" : ""}",- );- // set current epoch time as clusterID- int clusterID = DateTime.now().microsecondsSinceEpoch;- if (facesWithClusterID.isEmpty) {- // assign a clusterID to the first face- sortedFaceInfos[0].clusterId = clusterID;- clusterID++;+ // Sort the faceInfos such that the ones with null clusterId are at the end+ final List<FaceInfo> facesWithClusterID = <FaceInfo>[];+ final List<FaceInfo> facesWithoutClusterID = <FaceInfo>[];+ for (final FaceInfo faceInfo in faceInfos) {+ if (faceInfo.clusterId == null) {+ facesWithoutClusterID.add(faceInfo);+ } else {+ facesWithClusterID.add(faceInfo);}- final stopwatchClustering = Stopwatch()..start();- for (int i = 1; i < totalFaces; i++) {- // Incremental clustering, so we can skip faces that already have a clusterId- if (sortedFaceInfos[i].clusterId != null) {- clusterID = max(clusterID, sortedFaceInfos[i].clusterId!);- continue;- }+ }+ final alreadyClusteredCount = facesWithClusterID.length;+ final sortedFaceInfos = <FaceInfo>[];+ sortedFaceInfos.addAll(facesWithClusterID);+ sortedFaceInfos.addAll(facesWithoutClusterID);- int closestIdx = -1;- double closestDistance = double.infinity;- late double thresholdValue;- if (useDynamicThreshold) {- thresholdValue =- sortedFaceInfos[i].badFace! ? conservativeDistanceThreshold : distanceThreshold;- if (sortedFaceInfos[i].badFace!) dynamicThresholdCount++;- } else {- thresholdValue = distanceThreshold;- }- if (i % 250 == 0) {- log("[ClusterIsolate] ${DateTime.now()} Processed ${offset != null ? i + offset : i} faces");- }- // WARNING: The loop below is now O(n^2) so be very careful with anything you put in there!- for (int j = i - 1; j >= 0; j--) {- final double distance =- 1 - sortedFaceInfos[i].vEmbedding!.dot(sortedFaceInfos[j].vEmbedding!);- if (distance < closestDistance) {- if (sortedFaceInfos[j].badFace! && distance > conservativeDistanceThreshold) {- continue;- }- closestDistance = distance;- closestIdx = j;- }- }+ log(+ "[ClusterIsolate] ${DateTime.now()} Clustering ${facesWithoutClusterID.length} new faces without clusterId, and $alreadyClusteredCount faces with clusterId",+ );- if (closestDistance < thresholdValue) {- if (sortedFaceInfos[closestIdx].clusterId == null) {- // Ideally this should never happen, but just in case log it- log(- " [ClusterIsolate] [WARNING] ${DateTime.now()} Found new cluster $clusterID",- );- clusterID++;- sortedFaceInfos[closestIdx].clusterId = clusterID;- }- sortedFaceInfos[i].clusterId = sortedFaceInfos[closestIdx].clusterId;- } else {- clusterID++;- sortedFaceInfos[i].clusterId = clusterID;- }- }+ // Make sure the first face has a clusterId+ final int totalFaces = sortedFaceInfos.length;+ int dynamicThresholdCount = 0;- // Finally, assign the new clusterId to the faces- final Map<String, int> newFaceIdToCluster = {};- final newClusteredFaceInfos = sortedFaceInfos.sublist(alreadyClusteredCount);- for (final faceInfo in newClusteredFaceInfos) {- newFaceIdToCluster[faceInfo.faceID] = faceInfo.clusterId!;- }+ if (sortedFaceInfos.isEmpty) {+ return ClusteringResult.empty();+ }- // Create a map of clusterId to faceIds- final Map<int, List<String>> clusterIdToFaceIds = {};- for (final entry in newFaceIdToCluster.entries) {- final clusterID = entry.value;- if (clusterIdToFaceIds.containsKey(clusterID)) {- clusterIdToFaceIds[clusterID]!.add(entry.key);- } else {- clusterIdToFaceIds[clusterID] = [entry.key];- }+ // Start actual clustering+ log(+ "[ClusterIsolate] ${DateTime.now()} Processing $totalFaces faces in total in this round ${offset != null ? "on top of ${offset + facesWithClusterID.length} earlier processed faces" : ""}",+ );+ // set current epoch time as clusterID+ int clusterID = DateTime.now().microsecondsSinceEpoch;+ if (facesWithClusterID.isEmpty) {+ // assign a clusterID to the first face+ sortedFaceInfos[0].clusterId = clusterID;+ clusterID++;+ }+ final stopwatchClustering = Stopwatch()..start();+ for (int i = 1; i < totalFaces; i++) {+ // Incremental clustering, so we can skip faces that already have a clusterId+ if (sortedFaceInfos[i].clusterId != null) {+ clusterID = max(clusterID, sortedFaceInfos[i].clusterId!);+ continue;}- stopwatchClustering.stop();- log(- ' [ClusterIsolate] ${DateTime.now()} Clustering for ${sortedFaceInfos.length} embeddings executed in ${stopwatchClustering.elapsedMilliseconds}ms',- );+ int closestIdx = -1;+ double closestDistance = double.infinity;+ late double thresholdValue;if (useDynamicThreshold) {- log(- "[ClusterIsolate] ${DateTime.now()} Dynamic thresholding: $dynamicThresholdCount faces had a low face score or low blur clarity",- );- }-- // Now calculate the mean of the embeddings for each cluster and update the cluster summaries- Map<int, (Uint8List, int)>? newClusterSummaries;- if (oldClusterSummaries != null) {- newClusterSummaries = FaceClusteringService.updateClusterSummaries(- oldSummary: oldClusterSummaries,- newFaceInfos: newClusteredFaceInfos,- );- }-- // analyze the results- // FaceClusteringService._analyzeClusterResults(sortedFaceInfos);-- return ClusteringResult(- newFaceIdToCluster: newFaceIdToCluster,- newClusterSummaries: newClusterSummaries,- newClusterIdToFaceIds: clusterIdToFaceIds,- );- }-- static Map<int, (Uint8List, int)> updateClusterSummaries({- required Map<int, (Uint8List, int)> oldSummary,- required List<FaceInfo> newFaceInfos,- }) {- final calcSummariesStart = DateTime.now();- final Map<int, List<FaceInfo>> newClusterIdToFaceInfos = {};- for (final faceInfo in newFaceInfos) {- if (newClusterIdToFaceInfos.containsKey(faceInfo.clusterId!)) {- newClusterIdToFaceInfos[faceInfo.clusterId!]!.add(faceInfo);- } else {- newClusterIdToFaceInfos[faceInfo.clusterId!] = [faceInfo];+ thresholdValue =+ sortedFaceInfos[i].badFace! ? conservativeDistanceThreshold : distanceThreshold;+ if (sortedFaceInfos[i].badFace!) dynamicThresholdCount++;+ } else {+ thresholdValue = distanceThreshold;+ }+ if (i % 250 == 0) {+ log("[ClusterIsolate] ${DateTime.now()} Processed ${offset != null ? i + offset : i} faces");+ }+ // WARNING: The loop below is now O(n^2) so be very careful with anything you put in there!+ for (int j = i - 1; j >= 0; j--) {+ final double distance =+ 1 - sortedFaceInfos[i].vEmbedding!.dot(sortedFaceInfos[j].vEmbedding!);+ if (distance < closestDistance) {+ if (sortedFaceInfos[j].badFace! && distance > conservativeDistanceThreshold) {+ continue;+ }+ closestDistance = distance;+ closestIdx = j;}}- final Map<int, (Uint8List, int)> newClusterSummaries = {};- for (final clusterId in newClusterIdToFaceInfos.keys) {- final List<Vector> newEmbeddings =- newClusterIdToFaceInfos[clusterId]!.map((faceInfo) => faceInfo.vEmbedding!).toList();- final newCount = newEmbeddings.length;- if (oldSummary.containsKey(clusterId)) {- final oldMean = Vector.fromList(- EVector.fromBuffer(oldSummary[clusterId]!.$1).values,- dtype: DType.float32,- );- final oldCount = oldSummary[clusterId]!.$2;- final oldEmbeddings = oldMean * oldCount;- newEmbeddings.add(oldEmbeddings);- final newMeanVector = newEmbeddings.reduce((a, b) => a + b) / (oldCount + newCount);- final newMeanVectorNormalized = newMeanVector / newMeanVector.norm();- newClusterSummaries[clusterId] = (- EVector(values: newMeanVectorNormalized.toList()).writeToBuffer(),- oldCount + newCount+ if (closestDistance < thresholdValue) {+ if (sortedFaceInfos[closestIdx].clusterId == null) {+ // Ideally this should never happen, but just in case log it+ log(+ " [ClusterIsolate] [WARNING] ${DateTime.now()} Found new cluster $clusterID",);- } else {- final newMeanVector = newEmbeddings.reduce((a, b) => a + b);- final newMeanVectorNormalized = newMeanVector / newMeanVector.norm();- newClusterSummaries[clusterId] =- (EVector(values: newMeanVectorNormalized.toList()).writeToBuffer(), newCount);+ clusterID++;+ sortedFaceInfos[closestIdx].clusterId = clusterID;}+ sortedFaceInfos[i].clusterId = sortedFaceInfos[closestIdx].clusterId;+ } else {+ clusterID++;+ sortedFaceInfos[i].clusterId = clusterID;}- log(- "[ClusterIsolate] ${DateTime.now()} Calculated cluster summaries in ${DateTime.now().difference(calcSummariesStart).inMilliseconds}ms",- );-- return newClusterSummaries;}- static void _analyzeClusterResults(List<FaceInfo> sortedFaceInfos) {- if (!kDebugMode) return;- final stopwatch = Stopwatch()..start();-- final Map<String, int> faceIdToCluster = {};- for (final faceInfo in sortedFaceInfos) {- faceIdToCluster[faceInfo.faceID] = faceInfo.clusterId!;- }-- // Find faceIDs that are part of a cluster which is larger than 5 and are new faceIDs- final Map<int, int> clusterIdToSize = {};- faceIdToCluster.forEach((key, value) {- if (clusterIdToSize.containsKey(value)) {- clusterIdToSize[value] = clusterIdToSize[value]! + 1;- } else {- clusterIdToSize[value] = 1;- }- });+ // Finally, assign the new clusterId to the faces+ final Map<String, int> newFaceIdToCluster = {};+ final newClusteredFaceInfos = sortedFaceInfos.sublist(alreadyClusteredCount);+ for (final faceInfo in newClusteredFaceInfos) {+ newFaceIdToCluster[faceInfo.faceID] = faceInfo.clusterId!;+ }- // print top 10 cluster ids and their sizes based on the internal cluster id- final clusterIds = faceIdToCluster.values.toSet();- final clusterSizes = clusterIds.map((clusterId) {- return faceIdToCluster.values.where((id) => id == clusterId).length;- }).toList();- clusterSizes.sort();- // find clusters whose size is greater than 1- int oneClusterCount = 0;- int moreThan5Count = 0;- int moreThan10Count = 0;- int moreThan20Count = 0;- int moreThan50Count = 0;- int moreThan100Count = 0;-- for (int i = 0; i < clusterSizes.length; i++) {- if (clusterSizes[i] > 100) {- moreThan100Count++;- } else if (clusterSizes[i] > 50) {- moreThan50Count++;- } else if (clusterSizes[i] > 20) {- moreThan20Count++;- } else if (clusterSizes[i] > 10) {- moreThan10Count++;- } else if (clusterSizes[i] > 5) {- moreThan5Count++;- } else if (clusterSizes[i] == 1) {- oneClusterCount++;- }+ // Create a map of clusterId to faceIds+ final Map<int, List<String>> clusterIdToFaceIds = {};+ for (final entry in newFaceIdToCluster.entries) {+ final clusterID = entry.value;+ if (clusterIdToFaceIds.containsKey(clusterID)) {+ clusterIdToFaceIds[clusterID]!.add(entry.key);+ } else {+ clusterIdToFaceIds[clusterID] = [entry.key];}+ }- // print the metrics- log(- "[ClusterIsolate] Total clusters ${clusterIds.length}: \n oneClusterCount $oneClusterCount \n moreThan5Count $moreThan5Count \n moreThan10Count $moreThan10Count \n moreThan20Count $moreThan20Count \n moreThan50Count $moreThan50Count \n moreThan100Count $moreThan100Count",- );- stopwatch.stop();+ stopwatchClustering.stop();+ log(+ ' [ClusterIsolate] ${DateTime.now()} Clustering for ${sortedFaceInfos.length} embeddings executed in ${stopwatchClustering.elapsedMilliseconds}ms',+ );+ if (useDynamicThreshold) {log(- "[ClusterIsolate] Clustering additional analysis took ${stopwatch.elapsedMilliseconds} ms",+ "[ClusterIsolate] ${DateTime.now()} Dynamic thresholding: $dynamicThresholdCount faces had a low face score or low blur clarity",);}- static ClusteringResult runCompleteClustering(Map args) {- final input = args['input'] as Map<String, Uint8List>;- final fileIDToCreationTime = args['fileIDToCreationTime'] as Map<int, int>?;- final distanceThreshold = args['distanceThreshold'] as double;- final mergeThreshold = args['mergeThreshold'] as double;- final oldClusterSummaries = args['oldClusterSummaries'] as Map<int, (Uint8List, int)>?;-- log(- "[CompleteClustering] ${DateTime.now()} Copied to isolate ${input.length} faces for clustering",+ // Now calculate the mean of the embeddings for each cluster and update the cluster summaries+ final newClusterSummaries = _updateClusterSummaries(+ newFaceInfos: newClusteredFaceInfos,+ oldSummary: oldClusterSummaries,);- // Organize everything into a list of FaceInfo objects- final List<FaceInfo> faceInfos = [];- for (final entry in input.entries) {- faceInfos.add(- FaceInfo(- faceID: entry.key,- vEmbedding: Vector.fromList(- EVector.fromBuffer(entry.value).values,- dtype: DType.float32,- ),- fileCreationTime: fileIDToCreationTime?[getFileIdFromFaceId(entry.key)],- ),- );- }-- if (fileIDToCreationTime != null) {- _sortFaceInfosOnCreationTime(faceInfos);- }+ // analyze the results+ // FaceClusteringService._analyzeClusterResults(sortedFaceInfos);- if (faceInfos.isEmpty) {- ClusteringResult(newFaceIdToCluster: {});- }- final int totalFaces = faceInfos.length;+ return ClusteringResult(+ newFaceIdToCluster: newFaceIdToCluster,+ newClusterSummaries: newClusterSummaries,+ newClusterIdToFaceIds: clusterIdToFaceIds,+ );+}- // Start actual clustering- log(- "[CompleteClustering] ${DateTime.now()} Processing $totalFaces faces in one single round of complete clustering",+ClusteringResult _runCompleteClustering(Map args) {+ final input = args['input'] as Map<String, Uint8List>;+ final fileIDToCreationTime = args['fileIDToCreationTime'] as Map<int, int>?;+ final distanceThreshold = args['distanceThreshold'] as double;+ final mergeThreshold = args['mergeThreshold'] as double;+ final oldClusterSummaries = args['oldClusterSummaries'] as Map<int, (Uint8List, int)>?;++ log(+ "[CompleteClustering] ${DateTime.now()} Copied to isolate ${input.length} faces for clustering",+ );++ // Organize everything into a list of FaceInfo objects+ final List<FaceInfo> faceInfos = [];+ for (final entry in input.entries) {+ faceInfos.add(+ FaceInfo(+ faceID: entry.key,+ vEmbedding: Vector.fromList(+ EVector.fromBuffer(entry.value).values,+ dtype: DType.float32,+ ),+ fileCreationTime: fileIDToCreationTime?[getFileIdFromFaceId(entry.key)],+ ),);+ }- // set current epoch time as clusterID- int clusterID = DateTime.now().microsecondsSinceEpoch;-- // Start actual clustering- final Map<String, int> newFaceIdToCluster = {};- final stopwatchClustering = Stopwatch()..start();- for (int i = 0; i < totalFaces; i++) {- if ((i + 1) % 250 == 0) {- log("[CompleteClustering] ${DateTime.now()} Processed ${i + 1} faces");- }- if (faceInfos[i].clusterId != null) continue;- int closestIdx = -1;- double closestDistance = double.infinity;- for (int j = 0; j < totalFaces; j++) {- if (i == j) continue;- final double distance = 1 - faceInfos[i].vEmbedding!.dot(faceInfos[j].vEmbedding!);- if (distance < closestDistance) {- closestDistance = distance;- closestIdx = j;- }- }+ if (fileIDToCreationTime != null) {+ _sortFaceInfosOnCreationTime(faceInfos);+ }- if (closestDistance < distanceThreshold) {- if (faceInfos[closestIdx].clusterId == null) {- clusterID++;- faceInfos[closestIdx].clusterId = clusterID;- }- faceInfos[i].clusterId = faceInfos[closestIdx].clusterId!;- } else {- clusterID++;- faceInfos[i].clusterId = clusterID;+ if (faceInfos.isEmpty) {+ ClusteringResult.empty();+ }+ final int totalFaces = faceInfos.length;++ // Start actual clustering+ log(+ "[CompleteClustering] ${DateTime.now()} Processing $totalFaces faces in one single round of complete clustering",+ );++ // set current epoch time as clusterID+ int clusterID = DateTime.now().microsecondsSinceEpoch;++ // Start actual clustering+ final Map<String, int> newFaceIdToCluster = {};+ final stopwatchClustering = Stopwatch()..start();+ for (int i = 0; i < totalFaces; i++) {+ if ((i + 1) % 250 == 0) {+ log("[CompleteClustering] ${DateTime.now()} Processed ${i + 1} faces");+ }+ if (faceInfos[i].clusterId != null) continue;+ int closestIdx = -1;+ double closestDistance = double.infinity;+ for (int j = 0; j < totalFaces; j++) {+ if (i == j) continue;+ final double distance = 1 - faceInfos[i].vEmbedding!.dot(faceInfos[j].vEmbedding!);+ if (distance < closestDistance) {+ closestDistance = distance;+ closestIdx = j;}}- // Now calculate the mean of the embeddings for each cluster- final Map<int, List<FaceInfo>> clusterIdToFaceInfos = {};- for (final faceInfo in faceInfos) {- if (clusterIdToFaceInfos.containsKey(faceInfo.clusterId)) {- clusterIdToFaceInfos[faceInfo.clusterId]!.add(faceInfo);- } else {- clusterIdToFaceInfos[faceInfo.clusterId!] = [faceInfo];+ if (closestDistance < distanceThreshold) {+ if (faceInfos[closestIdx].clusterId == null) {+ clusterID++;+ faceInfos[closestIdx].clusterId = clusterID;}+ faceInfos[i].clusterId = faceInfos[closestIdx].clusterId!;+ } else {+ clusterID++;+ faceInfos[i].clusterId = clusterID;}- final Map<int, (Vector, int)> clusterIdToMeanEmbeddingAndWeight = {};- for (final clusterId in clusterIdToFaceInfos.keys) {- final List<Vector> embeddings =- clusterIdToFaceInfos[clusterId]!.map((faceInfo) => faceInfo.vEmbedding!).toList();- final count = clusterIdToFaceInfos[clusterId]!.length;- final Vector meanEmbedding = embeddings.reduce((a, b) => a + b) / count;- final Vector meanEmbeddingNormalized = meanEmbedding / meanEmbedding.norm();- clusterIdToMeanEmbeddingAndWeight[clusterId] = (meanEmbeddingNormalized, count);- }+ }- // Now merge the clusters that are close to each other, based on mean embedding- final List<(int, int)> mergedClustersList = [];- final List<int> clusterIds = clusterIdToMeanEmbeddingAndWeight.keys.toList();- log(' [CompleteClustering] ${DateTime.now()} ${clusterIds.length} clusters found, now checking for merges');- while (true) {- if (clusterIds.length < 2) break;- double distance = double.infinity;- (int, int) clusterIDsToMerge = (-1, -1);- for (int i = 0; i < clusterIds.length; i++) {- for (int j = 0; j < clusterIds.length; j++) {- if (i == j) continue;- final double newDistance = 1 -- clusterIdToMeanEmbeddingAndWeight[clusterIds[i]]!- .$1- .dot(clusterIdToMeanEmbeddingAndWeight[clusterIds[j]]!.$1);- if (newDistance < distance) {- distance = newDistance;- clusterIDsToMerge = (clusterIds[i], clusterIds[j]);- }- }- }- if (distance < mergeThreshold) {- mergedClustersList.add(clusterIDsToMerge);- final clusterID1 = clusterIDsToMerge.$1;- final clusterID2 = clusterIDsToMerge.$2;- final mean1 = clusterIdToMeanEmbeddingAndWeight[clusterID1]!.$1;- final mean2 = clusterIdToMeanEmbeddingAndWeight[clusterID2]!.$1;- final count1 = clusterIdToMeanEmbeddingAndWeight[clusterID1]!.$2;- final count2 = clusterIdToMeanEmbeddingAndWeight[clusterID2]!.$2;- final weight1 = count1 / (count1 + count2);- final weight2 = count2 / (count1 + count2);- final weightedMean = mean1 * weight1 + mean2 * weight2;- final weightedMeanNormalized = weightedMean / weightedMean.norm();- clusterIdToMeanEmbeddingAndWeight[clusterID1] = (- weightedMeanNormalized,- count1 + count2,- );- clusterIdToMeanEmbeddingAndWeight.remove(clusterID2);- clusterIds.remove(clusterID2);- } else {- break;- }+ // Now calculate the mean of the embeddings for each cluster+ final Map<int, List<FaceInfo>> clusterIdToFaceInfos = {};+ for (final faceInfo in faceInfos) {+ if (clusterIdToFaceInfos.containsKey(faceInfo.clusterId)) {+ clusterIdToFaceInfos[faceInfo.clusterId]!.add(faceInfo);+ } else {+ clusterIdToFaceInfos[faceInfo.clusterId!] = [faceInfo];}- log(' [CompleteClustering] ${DateTime.now()} ${mergedClustersList.length} clusters merged');+ }+ final Map<int, (Vector, int)> clusterIdToMeanEmbeddingAndWeight = {};+ for (final clusterId in clusterIdToFaceInfos.keys) {+ final List<Vector> embeddings =+ clusterIdToFaceInfos[clusterId]!.map((faceInfo) => faceInfo.vEmbedding!).toList();+ final count = clusterIdToFaceInfos[clusterId]!.length;+ final Vector meanEmbedding = embeddings.reduce((a, b) => a + b) / count;+ final Vector meanEmbeddingNormalized = meanEmbedding / meanEmbedding.norm();+ clusterIdToMeanEmbeddingAndWeight[clusterId] = (meanEmbeddingNormalized, count);+ }- // Now assign the new clusterId to the faces- for (final faceInfo in faceInfos) {- for (final mergedClusters in mergedClustersList) {- if (faceInfo.clusterId == mergedClusters.$2) {- faceInfo.clusterId = mergedClusters.$1;+ // Now merge the clusters that are close to each other, based on mean embedding+ final List<(int, int)> mergedClustersList = [];+ final List<int> clusterIds = clusterIdToMeanEmbeddingAndWeight.keys.toList();+ log(' [CompleteClustering] ${DateTime.now()} ${clusterIds.length} clusters found, now checking for merges');+ while (true) {+ if (clusterIds.length < 2) break;+ double distance = double.infinity;+ (int, int) clusterIDsToMerge = (-1, -1);+ for (int i = 0; i < clusterIds.length; i++) {+ for (int j = 0; j < clusterIds.length; j++) {+ if (i == j) continue;+ final double newDistance = 1 -+ clusterIdToMeanEmbeddingAndWeight[clusterIds[i]]!+ .$1+ .dot(clusterIdToMeanEmbeddingAndWeight[clusterIds[j]]!.$1);+ if (newDistance < distance) {+ distance = newDistance;+ clusterIDsToMerge = (clusterIds[i], clusterIds[j]);}}}-- // Finally, assign the new clusterId to the faces- for (final faceInfo in faceInfos) {- newFaceIdToCluster[faceInfo.faceID] = faceInfo.clusterId!;+ if (distance < mergeThreshold) {+ mergedClustersList.add(clusterIDsToMerge);+ final clusterID1 = clusterIDsToMerge.$1;+ final clusterID2 = clusterIDsToMerge.$2;+ final mean1 = clusterIdToMeanEmbeddingAndWeight[clusterID1]!.$1;+ final mean2 = clusterIdToMeanEmbeddingAndWeight[clusterID2]!.$1;+ final count1 = clusterIdToMeanEmbeddingAndWeight[clusterID1]!.$2;+ final count2 = clusterIdToMeanEmbeddingAndWeight[clusterID2]!.$2;+ final weight1 = count1 / (count1 + count2);+ final weight2 = count2 / (count1 + count2);+ final weightedMean = mean1 * weight1 + mean2 * weight2;+ final weightedMeanNormalized = weightedMean / weightedMean.norm();+ clusterIdToMeanEmbeddingAndWeight[clusterID1] = (+ weightedMeanNormalized,+ count1 + count2,+ );+ clusterIdToMeanEmbeddingAndWeight.remove(clusterID2);+ clusterIds.remove(clusterID2);+ } else {+ break;}+ }+ log(' [CompleteClustering] ${DateTime.now()} ${mergedClustersList.length} clusters merged');- final Map<int, List<String>> clusterIdToFaceIds = {};- for (final entry in newFaceIdToCluster.entries) {- final clusterID = entry.value;- if (clusterIdToFaceIds.containsKey(clusterID)) {- clusterIdToFaceIds[clusterID]!.add(entry.key);- } else {- clusterIdToFaceIds[clusterID] = [entry.key];+ // Now assign the new clusterId to the faces+ for (final faceInfo in faceInfos) {+ for (final mergedClusters in mergedClustersList) {+ if (faceInfo.clusterId == mergedClusters.$2) {+ faceInfo.clusterId = mergedClusters.$1;}}+ }- // Now calculate the mean of the embeddings for each cluster and update the cluster summaries- Map<int, (Uint8List, int)>? newClusterSummaries;- if (oldClusterSummaries != null) {- newClusterSummaries = FaceClusteringService.updateClusterSummaries(- oldSummary: oldClusterSummaries,- newFaceInfos: faceInfos,- );+ // Finally, assign the new clusterId to the faces+ for (final faceInfo in faceInfos) {+ newFaceIdToCluster[faceInfo.faceID] = faceInfo.clusterId!;+ }++ final Map<int, List<String>> clusterIdToFaceIds = {};+ for (final entry in newFaceIdToCluster.entries) {+ final clusterID = entry.value;+ if (clusterIdToFaceIds.containsKey(clusterID)) {+ clusterIdToFaceIds[clusterID]!.add(entry.key);+ } else {+ clusterIdToFaceIds[clusterID] = [entry.key];}+ }- stopwatchClustering.stop();- log(- ' [CompleteClustering] ${DateTime.now()} Clustering for ${faceInfos.length} embeddings executed in ${stopwatchClustering.elapsedMilliseconds}ms',+ // Now calculate the mean of the embeddings for each cluster and update the cluster summaries+ final newClusterSummaries = _updateClusterSummaries(+ newFaceInfos: faceInfos,+ oldSummary: oldClusterSummaries,);- return ClusteringResult(- newFaceIdToCluster: newFaceIdToCluster,- newClusterSummaries: newClusterSummaries,- newClusterIdToFaceIds: clusterIdToFaceIds,- );- }+ stopwatchClustering.stop();+ log(+ ' [CompleteClustering] ${DateTime.now()} Clustering for ${faceInfos.length} embeddings executed in ${stopwatchClustering.elapsedMilliseconds}ms',+ );++ return ClusteringResult(+ newFaceIdToCluster: newFaceIdToCluster,+ newClusterSummaries: newClusterSummaries,+ newClusterIdToFaceIds: clusterIdToFaceIds,+ );}/// Sort the faceInfos based on fileCreationTime, in descending order, so newest faces are first@@ -889,3 +782,107 @@ void _sortFaceInfosOnCreationTime(}});}++Map<int, (Uint8List, int)> _updateClusterSummaries({+ required List<FaceInfo> newFaceInfos,+ Map<int, (Uint8List, int)>? oldSummary,+}) {+ final calcSummariesStart = DateTime.now();+ final Map<int, List<FaceInfo>> newClusterIdToFaceInfos = {};+ for (final faceInfo in newFaceInfos) {+ if (newClusterIdToFaceInfos.containsKey(faceInfo.clusterId!)) {+ newClusterIdToFaceInfos[faceInfo.clusterId!]!.add(faceInfo);+ } else {+ newClusterIdToFaceInfos[faceInfo.clusterId!] = [faceInfo];+ }+ }++ final Map<int, (Uint8List, int)> newClusterSummaries = {};+ for (final clusterId in newClusterIdToFaceInfos.keys) {+ final List<Vector> newEmbeddings =+ newClusterIdToFaceInfos[clusterId]!.map((faceInfo) => faceInfo.vEmbedding!).toList();+ final newCount = newEmbeddings.length;+ if (oldSummary != null && oldSummary.containsKey(clusterId)) {+ final oldMean = Vector.fromList(+ EVector.fromBuffer(oldSummary[clusterId]!.$1).values,+ dtype: DType.float32,+ );+ final oldCount = oldSummary[clusterId]!.$2;+ final oldEmbeddings = oldMean * oldCount;+ newEmbeddings.add(oldEmbeddings);+ final newMeanVector = newEmbeddings.reduce((a, b) => a + b) / (oldCount + newCount);+ final newMeanVectorNormalized = newMeanVector / newMeanVector.norm();+ newClusterSummaries[clusterId] =+ (EVector(values: newMeanVectorNormalized.toList()).writeToBuffer(), oldCount + newCount);+ } else {+ final newMeanVector = newEmbeddings.reduce((a, b) => a + b);+ final newMeanVectorNormalized = newMeanVector / newMeanVector.norm();+ newClusterSummaries[clusterId] =+ (EVector(values: newMeanVectorNormalized.toList()).writeToBuffer(), newCount);+ }+ }+ log(+ "[ClusterIsolate] ${DateTime.now()} Calculated cluster summaries in ${DateTime.now().difference(calcSummariesStart).inMilliseconds}ms",+ );++ return newClusterSummaries;+}++void _analyzeClusterResults(List<FaceInfo> sortedFaceInfos) {+ if (!kDebugMode) return;+ final stopwatch = Stopwatch()..start();++ final Map<String, int> faceIdToCluster = {};+ for (final faceInfo in sortedFaceInfos) {+ faceIdToCluster[faceInfo.faceID] = faceInfo.clusterId!;+ }++ // Find faceIDs that are part of a cluster which is larger than 5 and are new faceIDs+ final Map<int, int> clusterIdToSize = {};+ faceIdToCluster.forEach((key, value) {+ if (clusterIdToSize.containsKey(value)) {+ clusterIdToSize[value] = clusterIdToSize[value]! + 1;+ } else {+ clusterIdToSize[value] = 1;+ }+ });++ // print top 10 cluster ids and their sizes based on the internal cluster id+ final clusterIds = faceIdToCluster.values.toSet();+ final clusterSizes = clusterIds.map((clusterId) {+ return faceIdToCluster.values.where((id) => id == clusterId).length;+ }).toList();+ clusterSizes.sort();+ // find clusters whose size is greater than 1+ int oneClusterCount = 0;+ int moreThan5Count = 0;+ int moreThan10Count = 0;+ int moreThan20Count = 0;+ int moreThan50Count = 0;+ int moreThan100Count = 0;++ for (int i = 0; i < clusterSizes.length; i++) {+ if (clusterSizes[i] > 100) {+ moreThan100Count++;+ } else if (clusterSizes[i] > 50) {+ moreThan50Count++;+ } else if (clusterSizes[i] > 20) {+ moreThan20Count++;+ } else if (clusterSizes[i] > 10) {+ moreThan10Count++;+ } else if (clusterSizes[i] > 5) {+ moreThan5Count++;+ } else if (clusterSizes[i] == 1) {+ oneClusterCount++;+ }+ }++ // print the metrics+ log(+ "[ClusterIsolate] Total clusters ${clusterIds.length}: \n oneClusterCount $oneClusterCount \n moreThan5Count $moreThan5Count \n moreThan10Count $moreThan10Count \n moreThan20Count $moreThan20Count \n moreThan50Count $moreThan50Count \n moreThan100Count $moreThan100Count",+ );+ stopwatch.stop();+ log(+ "[ClusterIsolate] Clustering additional analysis took ${stopwatch.elapsedMilliseconds} ms",+ );+}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 1297f4cac0..de4287465e 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@@ -164,8 +164,7 @@ class FaceMlService {pauseIndexingAndClustering();}});- if (Platform.isIOS &&- MachineLearningController.instance.isDeviceHealthy) {+ if (Platform.isIOS && MachineLearningController.instance.isDeviceHealthy) {_logger.info("Starting face indexing and clustering on iOS from init");unawaited(indexAndClusterAll());}@@ -270,8 +269,7 @@ class FaceMlService {switch (function) {case FaceMlOperation.analyzeImage:final time = DateTime.now();- final FaceMlResult result =- await FaceMlService.analyzeImageSync(args);+ final FaceMlResult result = await FaceMlService.analyzeImageSync(args);dev.log("`analyzeImageSync` function executed in ${DateTime.now().difference(time).inMilliseconds} ms",);@@ -284,8 +282,7 @@ class FaceMlService {error: e,stackTrace: stackTrace,);- sendPort- .send({'error': e.toString(), 'stackTrace': stackTrace.toString()});+ sendPort.send({'error': e.toString(), 'stackTrace': stackTrace.toString()});}});}@@ -369,8 +366,7 @@ class FaceMlService {await sync(forceSync: _shouldSyncPeople);- final int unclusteredFacesCount =- await FaceMLDataDB.instance.getUnclusteredFaceCount();+ final int unclusteredFacesCount = await FaceMLDataDB.instance.getUnclusteredFaceCount();if (unclusteredFacesCount > _kForceClusteringFaceCount) {_logger.info("There are $unclusteredFacesCount unclustered faces, doing clustering first",@@ -397,13 +393,10 @@ class FaceMlService {_isIndexingOrClusteringRunning = true;_logger.info('starting image indexing');- final w = (kDebugMode ? EnteWatch('prepare indexing files') : null)- ?..start();- final Map<int, int> alreadyIndexedFiles =- await FaceMLDataDB.instance.getIndexedFileIds();+ final w = (kDebugMode ? EnteWatch('prepare indexing files') : null)?..start();+ final Map<int, int> alreadyIndexedFiles = await FaceMLDataDB.instance.getIndexedFileIds();w?.log('getIndexedFileIds');- final List<EnteFile> enteFiles =- await SearchService.instance.getAllFiles();+ final List<EnteFile> enteFiles = await SearchService.instance.getAllFiles();w?.log('getAllFiles');// Make sure the image conversion isolate is spawned@@ -430,8 +423,7 @@ class FaceMlService {}}w?.log('sifting through all normal files');- final List<EnteFile> hiddenFiles =- await SearchService.instance.getHiddenFiles();+ final List<EnteFile> hiddenFiles = await SearchService.instance.getHiddenFiles();w?.log('getHiddenFiles: ${hiddenFiles.length} hidden files');for (final EnteFile enteFile in hiddenFiles) {if (_skipAnalysisEnteFile(enteFile, alreadyIndexedFiles)) {@@ -447,8 +439,7 @@ class FaceMlService {sortedBylocalID.addAll(filesWithoutLocalID);sortedBylocalID.addAll(hiddenFilesToIndex);w?.log('preparing all files to index');- final List<List<EnteFile>> chunks =- sortedBylocalID.chunks(_embeddingFetchLimit);+ final List<List<EnteFile>> chunks = sortedBylocalID.chunks(_embeddingFetchLimit);int fetchedCount = 0;outerLoop:for (final chunk in chunks) {@@ -456,15 +447,13 @@ class FaceMlService {if (LocalSettings.instance.remoteFetchEnabled) {try {- final Set<int> fileIds =- {}; // if there are duplicates here server returns 400+ final Set<int> fileIds = {}; // if there are duplicates here server returns 400// Try to find embeddings on the remote serverfor (final f in chunk) {fileIds.add(f.uploadedFileID!);}_logger.info('starting remote fetch for ${fileIds.length} files');- final res =- await RemoteFileMLService.instance.getFilessEmbedding(fileIds);+ final res = await RemoteFileMLService.instance.getFilessEmbedding(fileIds);_logger.info('fetched ${res.mlData.length} embeddings');fetchedCount += res.mlData.length;final List<Face> faces = [];@@ -486,8 +475,7 @@ class FaceMlService {faces.add(f);}}- remoteFileIdToVersion[fileMl.fileID] =- fileMl.faceEmbedding.version;+ remoteFileIdToVersion[fileMl.fileID] = fileMl.faceEmbedding.version;}if (res.noEmbeddingFileIDs.isNotEmpty) {_logger.info(@@ -504,8 +492,7 @@ class FaceMlService {for (final entry in remoteFileIdToVersion.entries) {alreadyIndexedFiles[entry.key] = entry.value;}- _logger- .info('already indexed files ${remoteFileIdToVersion.length}');+ _logger.info('already indexed files ${remoteFileIdToVersion.length}');} catch (e, s) {_logger.severe("err while getting files embeddings", e, s);if (retryFetchCount < 1000) {@@ -586,10 +573,9 @@ class FaceMlService {try {// Get a sense of the total number of faces in the database- final int totalFaces = await FaceMLDataDB.instance- .getTotalFaceCount(minFaceScore: minFaceScore);- final fileIDToCreationTime =- await FilesDB.instance.getFileIDToCreationTime();+ final int totalFaces =+ await FaceMLDataDB.instance.getTotalFaceCount(minFaceScore: minFaceScore);+ final fileIDToCreationTime = await FilesDB.instance.getFileIDToCreationTime();final startEmbeddingFetch = DateTime.now();// read all embeddingsfinal result = await FaceMLDataDB.instance.getFaceInfoForClustering(@@ -607,8 +593,7 @@ class FaceMlService {}// sort the embeddings based on file creation time, newest firstallFaceInfoForClustering.sort((b, a) {- return fileIDToCreationTime[a.fileID]!- .compareTo(fileIDToCreationTime[b.fileID]!);+ return fileIDToCreationTime[a.fileID]!.compareTo(fileIDToCreationTime[b.fileID]!);});_logger.info('Getting and sorting embeddings took ${DateTime.now().difference(startEmbeddingFetch).inMilliseconds} ms for ${allFaceInfoForClustering.length} embeddings'@@ -664,8 +649,7 @@ class FaceMlService {}}- final clusteringResult =- await FaceClusteringService.instance.predictLinear(+ final clusteringResult = await FaceClusteringService.instance.predictLinearIsolate(faceInfoForClustering.toSet(),fileIDToCreationTime: fileIDToCreationTime,offset: offset,@@ -676,17 +660,13 @@ class FaceMlService {return;}- await FaceMLDataDB.instance- .updateFaceIdToClusterId(clusteringResult.newFaceIdToCluster);- await FaceMLDataDB.instance- .clusterSummaryUpdate(clusteringResult.newClusterSummaries!);+ await FaceMLDataDB.instance.updateFaceIdToClusterId(clusteringResult.newFaceIdToCluster);+ await FaceMLDataDB.instance.clusterSummaryUpdate(clusteringResult.newClusterSummaries!);Bus.instance.fire(PeopleChangedEvent());for (final faceInfo in faceInfoForClustering) {- faceInfo.clusterId ??=- clusteringResult.newFaceIdToCluster[faceInfo.faceID];+ faceInfo.clusterId ??= clusteringResult.newFaceIdToCluster[faceInfo.faceID];}- for (final clusterUpdate- in clusteringResult.newClusterSummaries!.entries) {+ for (final clusterUpdate in clusteringResult.newClusterSummaries!.entries) {oldClusterSummaries[clusterUpdate.key] = clusterUpdate.value;}_logger.info(@@ -702,8 +682,7 @@ class FaceMlService {} else {final clusterStartTime = DateTime.now();// Cluster the embeddings using the linear clustering algorithm, returning a map from faceID to clusterID- final clusteringResult =- await FaceClusteringService.instance.predictLinear(+ final clusteringResult = await FaceClusteringService.instance.predictLinearIsolate(allFaceInfoForClustering.toSet(),fileIDToCreationTime: fileIDToCreationTime,oldClusterSummaries: oldClusterSummaries,@@ -721,10 +700,8 @@ class FaceMlService {_logger.info('Updating ${clusteringResult.newFaceIdToCluster.length} FaceIDs with clusterIDs in the DB',);- await FaceMLDataDB.instance- .updateFaceIdToClusterId(clusteringResult.newFaceIdToCluster);- await FaceMLDataDB.instance- .clusterSummaryUpdate(clusteringResult.newClusterSummaries!);+ await FaceMLDataDB.instance.updateFaceIdToClusterId(clusteringResult.newFaceIdToCluster);+ await FaceMLDataDB.instance.clusterSummaryUpdate(clusteringResult.newClusterSummaries!);Bus.instance.fire(PeopleChangedEvent());_logger.info('Done updating FaceIDs with clusterIDs in the DB, in ''${DateTime.now().difference(clusterDoneTime).inSeconds} seconds');@@ -756,8 +733,7 @@ class FaceMlService {allLandmarksEqual = false;break;}- if (face.detection.landmarks- .any((landmark) => landmark.x != landmark.y)) {+ if (face.detection.landmarks.any((landmark) => landmark.x != landmark.y)) {allLandmarksEqual = false;break;}@@ -766,10 +742,7 @@ class FaceMlService {debugPrint("Discarding remote embedding for fileID ${fileMl.fileID} ""because landmarks are equal");debugPrint(- fileMl.faceEmbedding.faces- .map((e) => e.detection.landmarks.toString())- .toList()- .toString(),+ fileMl.faceEmbedding.faces.map((e) => e.detection.landmarks.toString()).toList().toString(),);return true;}@@ -807,11 +780,9 @@ class FaceMlService {Face.empty(result.fileId, error: result.errorOccured),);} else {- if (result.decodedImageSize.width == -1 ||- result.decodedImageSize.height == -1) {- _logger- .severe("decodedImageSize is not stored correctly for image with "- "ID: ${enteFile.uploadedFileID}");+ if (result.decodedImageSize.width == -1 || result.decodedImageSize.height == -1) {+ _logger.severe("decodedImageSize is not stored correctly for image with "+ "ID: ${enteFile.uploadedFileID}");_logger.info("Using aligned image size for image with ID: ${enteFile.uploadedFileID}. This size is ${result.decodedImageSize.width}x${result.decodedImageSize.height} compared to size of ${enteFile.width}x${enteFile.height} in the metadata",);@@ -896,8 +867,7 @@ class FaceMlService {_checkEnteFileForID(enteFile);await ensureInitialized();- final String? filePath =- await _getImagePathForML(enteFile, typeOfData: FileDataForML.fileData);+ final String? filePath = await _getImagePathForML(enteFile, typeOfData: FileDataForML.fileData);if (filePath == null) {_logger.severe(@@ -916,10 +886,8 @@ class FaceMlService {{"enteFileID": enteFile.uploadedFileID ?? -1,"filePath": filePath,- "faceDetectionAddress":- FaceDetectionService.instance.sessionAddress,- "faceEmbeddingAddress":- FaceEmbeddingService.instance.sessionAddress,+ "faceDetectionAddress": FaceDetectionService.instance.sessionAddress,+ "faceEmbeddingAddress": FaceEmbeddingService.instance.sessionAddress,}),) as String?;@@ -973,8 +941,7 @@ class FaceMlService {stopwatch.reset();// Get the faces- final List<FaceDetectionRelative> faceDetectionResult =- await FaceMlService.detectFacesSync(+ final List<FaceDetectionRelative> faceDetectionResult = await FaceMlService.detectFacesSync(image,imgByteData,faceDetectionAddress,@@ -995,8 +962,7 @@ class FaceMlService {stopwatch.reset();// Align the faces- final Float32List faceAlignmentResult =- await FaceMlService.alignFacesSync(+ final Float32List faceAlignmentResult = await FaceMlService.alignFacesSync(image,imgByteData,faceDetectionResult,@@ -1108,8 +1074,7 @@ class FaceMlService {}) async {try {// Get the bounding boxes of the faces- final (List<FaceDetectionRelative> faces, dataSize) =- await FaceDetectionService.predictSync(+ final (List<FaceDetectionRelative> faces, dataSize) = await FaceDetectionService.predictSync(image,imageByteData,interpreterAddress,@@ -1219,8 +1184,7 @@ class FaceMlService {}bool _skipAnalysisEnteFile(EnteFile enteFile, Map<int, int> indexedFileIds) {- if (_isIndexingOrClusteringRunning == false ||- _mlControllerStatus == false) {+ if (_isIndexingOrClusteringRunning == false || _mlControllerStatus == false) {return true;}// Skip if the file is not uploaded or not owned by the user@@ -1234,8 +1198,7 @@ class FaceMlService {// Skip if the file is already analyzed with the latest ml versionfinal id = enteFile.uploadedFileID!;- return indexedFileIds.containsKey(id) &&- indexedFileIds[id]! >= faceMlVersion;+ return indexedFileIds.containsKey(id) && indexedFileIds[id]! >= faceMlVersion;}bool _cannotRunMLFunction({String function = ""}) {diff --git a/mobile/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart b/mobile/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dartindex 5a41a60df7..af6f07a1ab 100644--- a/mobile/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart+++ b/mobile/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart@@ -40,8 +40,7 @@ class ClusterFeedbackService {final _computer = Computer.shared();ClusterFeedbackService._privateConstructor();- static final ClusterFeedbackService instance =- ClusterFeedbackService._privateConstructor();+ static final ClusterFeedbackService instance = ClusterFeedbackService._privateConstructor();static int lastViewedClusterID = -1;static setLastViewedClusterID(int clusterID) {@@ -68,8 +67,7 @@ class ClusterFeedbackService {try {// Get the suggestions for the person using centroids and medianfinal startTime = DateTime.now();- final List<(int, double, bool)> foundSuggestions =- await _getSuggestions(person);+ final List<(int, double, bool)> foundSuggestions = await _getSuggestions(person);final findSuggestionsTime = DateTime.now();_logger.info('getSuggestionForPerson `_getSuggestions`: Found ${foundSuggestions.length} suggestions in ${findSuggestionsTime.difference(startTime).inMilliseconds} ms',@@ -143,36 +141,32 @@ class ClusterFeedbackService {final fileID = getFileIdFromFaceId(faceID);return files.any((file) => file.uploadedFileID == fileID);});- final embeddings =- await FaceMLDataDB.instance.getFaceEmbeddingMapForFaces(faceIDs);+ final embeddings = await FaceMLDataDB.instance.getFaceEmbeddingMapForFaces(faceIDs);- final fileIDToCreationTime =- await FilesDB.instance.getFileIDToCreationTime();+ final fileIDToCreationTime = await FilesDB.instance.getFileIDToCreationTime();// Re-cluster within the deleted faces- final clusterResult =- await FaceClusteringService.instance.predictWithinClusterComputer(+ final clusterResult = await FaceClusteringService.instance.predictWithinClusterComputer(embeddings,fileIDToCreationTime: fileIDToCreationTime,distanceThreshold: 0.20,);- if (clusterResult == null || clusterResult.isEmpty) {+ if (clusterResult.isEmpty) {+ _logger.warning('No clusters found or something went wrong');return;}final newFaceIdToClusterID = clusterResult.newFaceIdToCluster;// Update the deleted facesawait FaceMLDataDB.instance.forceUpdateClusterIds(newFaceIdToClusterID);- await FaceMLDataDB.instance- .clusterSummaryUpdate(clusterResult.newClusterSummaries!);+ await FaceMLDataDB.instance.clusterSummaryUpdate(clusterResult.newClusterSummaries);// Make sure the deleted faces don't get suggested in the futurefinal notClusterIdToPersonId = <int, String>{};for (final clusterId in newFaceIdToClusterID.values.toSet()) {notClusterIdToPersonId[clusterId] = p.remoteID;}- await FaceMLDataDB.instance- .bulkCaptureNotPersonFeedback(notClusterIdToPersonId);+ await FaceMLDataDB.instance.bulkCaptureNotPersonFeedback(notClusterIdToPersonId);Bus.instance.fire(PeopleChangedEvent());return;@@ -195,28 +189,24 @@ class ClusterFeedbackService {final fileID = getFileIdFromFaceId(faceID);return files.any((file) => file.uploadedFileID == fileID);});- final embeddings =- await FaceMLDataDB.instance.getFaceEmbeddingMapForFaces(faceIDs);+ final embeddings = await FaceMLDataDB.instance.getFaceEmbeddingMapForFaces(faceIDs);- final fileIDToCreationTime =- await FilesDB.instance.getFileIDToCreationTime();+ final fileIDToCreationTime = await FilesDB.instance.getFileIDToCreationTime();// Re-cluster within the deleted faces- final clusterResult =- await FaceClusteringService.instance.predictWithinClusterComputer(+ final clusterResult = await FaceClusteringService.instance.predictWithinClusterComputer(embeddings,fileIDToCreationTime: fileIDToCreationTime,distanceThreshold: 0.20,);- if (clusterResult == null || clusterResult.isEmpty) {+ if (clusterResult.isEmpty) {return;}final newFaceIdToClusterID = clusterResult.newFaceIdToCluster;// Update the deleted facesawait FaceMLDataDB.instance.forceUpdateClusterIds(newFaceIdToClusterID);- await FaceMLDataDB.instance- .clusterSummaryUpdate(clusterResult.newClusterSummaries!);+ await FaceMLDataDB.instance.clusterSummaryUpdate(clusterResult.newClusterSummaries);Bus.instance.fire(PeopleChangedEvent(@@ -319,14 +309,12 @@ class ClusterFeedbackService {final allClusterToFaceCount = await faceMlDb.clusterIdToFaceCount();final clustersToInspect = <int>[];for (final clusterID in allClusterToFaceCount.keys) {- if (allClusterToFaceCount[clusterID]! > 20 &&- allClusterToFaceCount[clusterID]! < 500) {+ if (allClusterToFaceCount[clusterID]! > 20 && allClusterToFaceCount[clusterID]! < 500) {clustersToInspect.add(clusterID);}}- final fileIDToCreationTime =- await FilesDB.instance.getFileIDToCreationTime();+ final fileIDToCreationTime = await FilesDB.instance.getFileIDToCreationTime();final susClusters = <(int, int)>[];@@ -337,24 +325,20 @@ class ClusterFeedbackService {final embeddings = await faceMlDb.getFaceEmbeddingMapForFaces(faceIDs);- final clusterResult =- await FaceClusteringService.instance.predictWithinClusterComputer(+ final clusterResult = await FaceClusteringService.instance.predictWithinClusterComputer(embeddings,fileIDToCreationTime: fileIDToCreationTime,distanceThreshold: 0.22,);- if (clusterResult == null ||- clusterResult.newClusterIdToFaceIds == null ||- clusterResult.isEmpty) {+ if (clusterResult.isEmpty) {_logger.warning('[CheckMixedClusters] Clustering did not seem to work for cluster $clusterID of size ${allClusterToFaceCount[clusterID]}',);continue;}- final newClusterIdToCount =- clusterResult.newClusterIdToFaceIds!.map((key, value) {+ final newClusterIdToCount = clusterResult.newClusterIdToFaceIds.map((key, value) {return MapEntry(key, value.length);});final amountOfNewClusters = newClusterIdToCount.length;@@ -375,15 +359,12 @@ class ClusterFeedbackService {final int secondBiggestClusterID = clusterIDs.reduce((a, b) {return newClusterIdToCount[a]! > newClusterIdToCount[b]! ? a : b;});- final int secondBiggestSize =- newClusterIdToCount[secondBiggestClusterID]!;+ final int secondBiggestSize = newClusterIdToCount[secondBiggestClusterID]!;final secondBiggestRatio = secondBiggestSize / originalClusterSize;if (biggestRatio < 0.5 || secondBiggestRatio > 0.2) {- final faceIdsOfCluster =- await faceMlDb.getFaceIDsForCluster(clusterID);- final uniqueFileIDs =- faceIdsOfCluster.map(getFileIdFromFaceId).toSet();+ final faceIdsOfCluster = await faceMlDb.getFaceIDsForCluster(clusterID);+ final uniqueFileIDs = faceIdsOfCluster.map(getFileIdFromFaceId).toSet();susClusters.add((clusterID, uniqueFileIDs.length));_logger.info('[CheckMixedClusters] Detected that cluster $clusterID with size ${uniqueFileIDs.length} might be mixed',@@ -423,25 +404,25 @@ class ClusterFeedbackService {final embeddings = await faceMlDb.getFaceEmbeddingMapForFaces(faceIDs);- final fileIDToCreationTime =- await FilesDB.instance.getFileIDToCreationTime();+ if (embeddings.isEmpty) {+ _logger.warning('No embeddings found for cluster $clusterID');+ return ClusteringResult.empty();+ }++ final fileIDToCreationTime = await FilesDB.instance.getFileIDToCreationTime();- final clusterResult =- await FaceClusteringService.instance.predictWithinClusterComputer(+ final clusterResult = await FaceClusteringService.instance.predictWithinClusterComputer(embeddings,fileIDToCreationTime: fileIDToCreationTime,distanceThreshold: 0.22,);- if (clusterResult == null ||- !clusterResult.hasAllResults ||- clusterResult.isEmpty) {+ if (clusterResult.isEmpty) {_logger.warning('No clusters found or something went wrong');- return ClusteringResult(newFaceIdToCluster: {});+ return ClusteringResult.empty();}- final clusterIdToCount =- clusterResult.newClusterIdToFaceIds!.map((key, value) {+ final clusterIdToCount = clusterResult.newClusterIdToFaceIds.map((key, value) {return MapEntry(key, value.length);});final amountOfNewClusters = clusterIdToCount.length;@@ -452,8 +433,7 @@ class ClusterFeedbackService {if (kDebugMode) {final Set allClusteredFaceIDsSet = {};- for (final List<String> value- in clusterResult.newClusterIdToFaceIds!.values) {+ for (final List<String> value in clusterResult.newClusterIdToFaceIds.values) {allClusteredFaceIDsSet.addAll(value);}assert((originalFaceIDsSet.difference(allClusteredFaceIDsSet)).isEmpty);@@ -467,16 +447,14 @@ class ClusterFeedbackService {try {// Delete old clustersawait FaceMLDataDB.instance.dropClustersAndPersonTable();- final List<PersonEntity> persons =- await PersonService.instance.getPersons();+ final List<PersonEntity> persons = await PersonService.instance.getPersons();for (final PersonEntity p in persons) {await PersonService.instance.deletePerson(p.remoteID);}// Create new fake clusters based on blur value. One for values between 0 and 10, one for 10-20, etc till 200final int startClusterID = DateTime.now().microsecondsSinceEpoch;- final faceIDsToBlurValues =- await FaceMLDataDB.instance.getFaceIDsToBlurValues(200);+ final faceIDsToBlurValues = await FaceMLDataDB.instance.getFaceIDsToBlurValues(200);final faceIdToCluster = <String, int>{};for (final entry in faceIDsToBlurValues.entries) {final faceID = entry.key;@@ -549,46 +527,40 @@ class ClusterFeedbackService {_logger.info('L2 norm of current mean: $currentL2Norm',);- final trueDistance =- biggestMean.distanceTo(currentMean, distance: Distance.cosine);+ final trueDistance = biggestMean.distanceTo(currentMean, distance: Distance.cosine);_logger.info('True distance between the two means: $trueDistance');// Median distanceconst sampleSize = 100;- final Iterable<Uint8List> biggestEmbeddings = await FaceMLDataDB- .instance- .getFaceEmbeddingsForCluster(biggestClusterID);- final List<Uint8List> biggestSampledEmbeddingsProto =- _randomSampleWithoutReplacement(+ final Iterable<Uint8List> biggestEmbeddings =+ await FaceMLDataDB.instance.getFaceEmbeddingsForCluster(biggestClusterID);+ final List<Uint8List> biggestSampledEmbeddingsProto = _randomSampleWithoutReplacement(biggestEmbeddings,sampleSize,);- final List<Vector> biggestSampledEmbeddings =- biggestSampledEmbeddingsProto- .map(- (embedding) => Vector.fromList(- EVector.fromBuffer(embedding).values,- dtype: DType.float32,- ),- )- .toList(growable: false);+ final List<Vector> biggestSampledEmbeddings = biggestSampledEmbeddingsProto+ .map(+ (embedding) => Vector.fromList(+ EVector.fromBuffer(embedding).values,+ dtype: DType.float32,+ ),+ )+ .toList(growable: false);final Iterable<Uint8List> currentEmbeddings =await FaceMLDataDB.instance.getFaceEmbeddingsForCluster(clusterID);- final List<Uint8List> currentSampledEmbeddingsProto =- _randomSampleWithoutReplacement(+ final List<Uint8List> currentSampledEmbeddingsProto = _randomSampleWithoutReplacement(currentEmbeddings,sampleSize,);- final List<Vector> currentSampledEmbeddings =- currentSampledEmbeddingsProto- .map(- (embedding) => Vector.fromList(- EVector.fromBuffer(embedding).values,- dtype: DType.float32,- ),- )- .toList(growable: false);+ final List<Vector> currentSampledEmbeddings = currentSampledEmbeddingsProto+ .map(+ (embedding) => Vector.fromList(+ EVector.fromBuffer(embedding).values,+ dtype: DType.float32,+ ),+ )+ .toList(growable: false);// Calculate distances and find the medianfinal List<double> distances = [];@@ -607,8 +579,7 @@ class ClusterFeedbackService {distances.sort();trueDistances.sort();final double medianDistance = distances[distances.length ~/ 2];- final double trueMedianDistance =- trueDistances[trueDistances.length ~/ 2];+ final double trueMedianDistance = trueDistances[trueDistances.length ~/ 2];_logger.info("Median distance between biggest cluster and current cluster: $medianDistance (using sample of $sampleSize)",);@@ -623,8 +594,7 @@ class ClusterFeedbackService {final List<double> blurValues = await FaceMLDataDB.instance.getBlurValuesForCluster(clusterID).then((value) => value.toList());- final blurValuesIntegers =- blurValues.map((value) => value.round()).toList();+ final blurValuesIntegers = blurValues.map((value) => value.round()).toList();blurValuesIntegers.sort();_logger.info("Blur values for cluster $clusterID${clusterSize != null ? ' with $clusterSize photos' : ''}: $blurValuesIntegers",@@ -652,14 +622,12 @@ class ClusterFeedbackService {final allClusterIdsToCountMap = await faceMlDb.clusterIdToFaceCount();final ignoredClusters = await faceMlDb.getPersonIgnoredClusters(p.remoteID);final personClusters = await faceMlDb.getPersonClusterIDs(p.remoteID);- final personFaceIDs =- await FaceMLDataDB.instance.getFaceIDsForPerson(p.remoteID);+ final personFaceIDs = await FaceMLDataDB.instance.getFaceIDsForPerson(p.remoteID);final personFileIDs = personFaceIDs.map(getFileIdFromFaceId).toSet();w?.log('${p.data.name} has ${personClusters.length} existing clusters, getting all database data done',);- final allClusterIdToFaceIDs =- await FaceMLDataDB.instance.getAllClusterIdToFaceIDs();+ final allClusterIdToFaceIDs = await FaceMLDataDB.instance.getAllClusterIdToFaceIDs();w?.log('getAllClusterIdToFaceIDs done');// First only do a simple check on the big clusters, if the person does not have small clusters yet@@ -670,8 +638,7 @@ class ClusterFeedbackService {late Map<int, Vector> clusterAvgBigClusters;final List<(int, double)> suggestionsMean = [];for (final minimumSize in checkSizes.toSet()) {- if (smallestPersonClusterSize >=- min(minimumSize, kMinimumClusterSizeSearchResult)) {+ if (smallestPersonClusterSize >= min(minimumSize, kMinimumClusterSizeSearchResult)) {clusterAvgBigClusters = await _getUpdateClusterAvg(allClusterIdsToCountMap,ignoredClusters,@@ -680,8 +647,7 @@ class ClusterFeedbackService {w?.log('Calculate avg for ${clusterAvgBigClusters.length} clusters of min size $minimumSize',);- final List<(int, double)> suggestionsMeanBigClusters =- await calcSuggestionsMeanInComputer(+ final List<(int, double)> suggestionsMeanBigClusters = await calcSuggestionsMeanInComputer(clusterAvgBigClusters,personClusters,ignoredClusters,@@ -696,8 +662,7 @@ class ClusterFeedbackService {.map((faceID) => getFileIdFromFaceId(faceID)).toSet();final overlap = personFileIDs.intersection(suggestionSet);- if (overlap.isNotEmpty &&- ((overlap.length / suggestionSet.length) > 0.5)) {+ if (overlap.isNotEmpty && ((overlap.length / suggestionSet.length) > 0.5)) {await FaceMLDataDB.instance.captureNotPersonFeedback(personID: p.remoteID,clusterID: suggestion.$1,@@ -707,9 +672,7 @@ class ClusterFeedbackService {suggestionsMean.add(suggestion);}if (suggestionsMean.isNotEmpty) {- return suggestionsMean- .map((e) => (e.$1, e.$2, true))- .toList(growable: false);+ return suggestionsMean.map((e) => (e.$1, e.$2, true)).toList(growable: false);}}}@@ -717,16 +680,14 @@ class ClusterFeedbackService {// Find the other cluster candidates based on the medianfinal clusterAvg = clusterAvgBigClusters;- final List<(int, double)> moreSuggestionsMean =- await calcSuggestionsMeanInComputer(+ final List<(int, double)> moreSuggestionsMean = await calcSuggestionsMeanInComputer(clusterAvg,personClusters,ignoredClusters,maxMeanDistance,);if (moreSuggestionsMean.isEmpty) {- _logger- .info("No suggestions found using mean, even with higher threshold");+ _logger.info("No suggestions found using mean, even with higher threshold");return [];}@@ -748,8 +709,7 @@ class ClusterFeedbackService {await FaceMLDataDB.instance.getFaceEmbeddingsForCluster(clusterID);personEmbeddingsProto.addAll(embeddings);}- final List<Uint8List> sampledEmbeddingsProto =- _randomSampleWithoutReplacement(+ final List<Uint8List> sampledEmbeddingsProto = _randomSampleWithoutReplacement(personEmbeddingsProto,sampleSize,);@@ -893,8 +853,7 @@ class ClusterFeedbackService {// get clusterIDs sorted by count in descending orderfinal sortedClusterIDs = allClusterIds.toList();sortedClusterIDs.sort(- (a, b) =>- allClusterIdsToCountMap[b]!.compareTo(allClusterIdsToCountMap[a]!),+ (a, b) => allClusterIdsToCountMap[b]!.compareTo(allClusterIdsToCountMap[a]!),);int indexedInCurrentRun = 0;w?.reset();@@ -909,8 +868,7 @@ class ClusterFeedbackService {currentPendingRead = allClusterIdsToCountMap[clusterID] ?? 0;clusterIdsToRead.add(clusterID);} else {- if ((currentPendingRead + allClusterIdsToCountMap[clusterID]!) <- maxEmbeddingToRead) {+ if ((currentPendingRead + allClusterIdsToCountMap[clusterID]!) < maxEmbeddingToRead) {clusterIdsToRead.add(clusterID);currentPendingRead += allClusterIdsToCountMap[clusterID]!;} else {@@ -919,9 +877,8 @@ class ClusterFeedbackService {}}- final Map<int, Iterable<Uint8List>> clusterEmbeddings = await FaceMLDataDB- .instance- .getFaceEmbeddingsForClusters(clusterIdsToRead);+ final Map<int, Iterable<Uint8List>> clusterEmbeddings =+ await FaceMLDataDB.instance.getFaceEmbeddingsForClusters(clusterIdsToRead);w?.logAndReset('read $currentPendingRead embeddings for ${clusterEmbeddings.length} clusters',@@ -938,8 +895,7 @@ class ClusterFeedbackService {final avg = vectors.reduce((a, b) => a + b) / vectors.length;final avgNormalized = avg / avg.norm();final avgEmbeddingBuffer = EVector(values: avgNormalized).writeToBuffer();- updatesForClusterSummary[clusterID] =- (avgEmbeddingBuffer, embeddings.length);+ updatesForClusterSummary[clusterID] = (avgEmbeddingBuffer, embeddings.length);// store the intermediate updatesindexedInCurrentRun++;if (updatesForClusterSummary.length > 100) {@@ -1042,9 +998,8 @@ class ClusterFeedbackService {// Calculate the avg embedding of the personfinal w = (kDebugMode ? EnteWatch('sortSuggestions') : null)?..start();- final personEmbeddingsCount = personClusters- .map((e) => personClusterToSummary[e]!.$2)- .reduce((a, b) => a + b);+ final personEmbeddingsCount =+ personClusters.map((e) => personClusterToSummary[e]!.$2).reduce((a, b) => a + b);Vector personAvg = Vector.filled(192, 0);for (final personClusterID in personClusters) {final personClusterBlob = personClusterToSummary[personClusterID]!.$1;@@ -1052,8 +1007,7 @@ class ClusterFeedbackService {EVector.fromBuffer(personClusterBlob).values,dtype: DType.float32,);- final clusterWeight =- personClusterToSummary[personClusterID]!.$2 / personEmbeddingsCount;+ final clusterWeight = personClusterToSummary[personClusterID]!.$2 / personEmbeddingsCount;personAvg += personClusterAvg * clusterWeight;}w?.log('calculated person avg');@@ -1084,8 +1038,7 @@ class ClusterFeedbackService {);final fileIdToDistanceMap = {};for (final entry in faceIdToVectorMap.entries) {- fileIdToDistanceMap[getFileIdFromFaceId(entry.key)] =- 1 - personAvg.dot(entry.value);+ fileIdToDistanceMap[getFileIdFromFaceId(entry.key)] = 1 - personAvg.dot(entry.value);}w?.log('calculated distances for cluster $clusterID');suggestion.filesInCluster.sort((b, a) {@@ -1150,9 +1103,7 @@ List<(int, double)> _calcSuggestionsMean(Map<String, dynamic> args) {}}if (nearestPersonCluster != null && minDistance != null) {- suggestions- .putIfAbsent(nearestPersonCluster, () => [])- .add((otherClusterID, minDistance));+ suggestions.putIfAbsent(nearestPersonCluster, () => []).add((otherClusterID, minDistance));suggestionCount++;}if (suggestionCount >= suggestionMax) {@@ -1182,8 +1133,7 @@ List<(int, double)> _calcSuggestionsMean(Map<String, dynamic> args) {}}-Future<(Map<int, Vector>, Set<int>, int, int, int)>- checkAndSerializeCurrentClusterMeans(+Future<(Map<int, Vector>, Set<int>, int, int, int)> checkAndSerializeCurrentClusterMeans(Map args,) async {final Map<int, int> allClusterIdsToCountMap = args['allClusterIdsToCountMap'];diff --git a/mobile/lib/ui/viewer/people/cluster_app_bar.dart b/mobile/lib/ui/viewer/people/cluster_app_bar.dartindex 8b95d4247e..e2b3c10824 100644--- a/mobile/lib/ui/viewer/people/cluster_app_bar.dart+++ b/mobile/lib/ui/viewer/people/cluster_app_bar.dart@@ -191,14 +191,14 @@ class _AppBarWidgetState extends State<ClusterAppBar> {final breakupResult = await ClusterFeedbackService.instance.breakUpCluster(widget.clusterID);final Map<int, List<String>> newClusterIDToFaceIDs =- breakupResult.newClusterIdToFaceIds!;+ breakupResult.newClusterIdToFaceIds;final Map<String, int> newFaceIdToClusterID =breakupResult.newFaceIdToCluster;// Update to delete the old clusters and save the new clustersawait FaceMLDataDB.instance.deleteClusterSummary(widget.clusterID);await FaceMLDataDB.instance- .clusterSummaryUpdate(breakupResult.newClusterSummaries!);+ .clusterSummaryUpdate(breakupResult.newClusterSummaries);await FaceMLDataDB.instance.updateFaceIdToClusterId(newFaceIdToClusterID);@@ -254,7 +254,7 @@ class _AppBarWidgetState extends State<ClusterAppBar> {await ClusterFeedbackService.instance.breakUpCluster(widget.clusterID);final Map<int, List<String>> newClusterIDToFaceIDs =- breakupResult.newClusterIdToFaceIds!;+ breakupResult.newClusterIdToFaceIds;final allFileIDs = newClusterIDToFaceIDs.values.expand((e) => e)