π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mob][photos] Breakup cluster function
laurenspriemb78a65dc51e6
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 c84059e392..122c3ec963 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@@ -44,10 +44,15 @@ enum ClusterOperation { linearIncrementalClustering, dbscanClustering }class ClusteringResult {final Map<String, int> newFaceIdToCluster;+ final Map<int, List<String>>? newClusterIdToFaceIds;final Map<int, (Uint8List, int)>? newClusterSummaries;++ bool get isEmpty => newFaceIdToCluster.isEmpty;+ClusteringResult({required this.newFaceIdToCluster,- required this.newClusterSummaries,+ this.newClusterSummaries,+ this.newClusterIdToFaceIds,});}@@ -316,7 +321,7 @@ class FaceClusteringService {/// 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<Map<String, int>> predictCompleteComputer(+ Future<ClusteringResult> predictCompleteComputer(Map<String, Uint8List> input, {Map<int, int>? fileIDToCreationTime,double distanceThreshold = kRecommendedDistanceThreshold,@@ -326,7 +331,7 @@ class FaceClusteringService {_logger.warning("Complete Clustering dataset of embeddings is empty, returning empty list.",);- return {};+ return ClusteringResult(newFaceIdToCluster: {});}// Clustering inside the isolate@@ -336,7 +341,7 @@ class FaceClusteringService {try {final startTime = DateTime.now();- final faceIdToCluster = await _computer.compute(+ final clusteringResult = await _computer.compute(runCompleteClustering,param: {"input": input,@@ -345,19 +350,19 @@ class FaceClusteringService {"mergeThreshold": mergeThreshold,},taskName: "createImageEmbedding",- ) as Map<String, int>;+ ) as ClusteringResult;final endTime = DateTime.now();_logger.info("Complete Clustering took: ${endTime.difference(startTime).inMilliseconds}ms",);- return faceIdToCluster;+ return clusteringResult;} catch (e, s) {_logger.severe(e, s);rethrow;}}- Future<Map<String, int>?> predictWithinClusterComputer(+ Future<ClusteringResult?> predictWithinClusterComputer(Map<String, Uint8List> input, {Map<int, int>? fileIDToCreationTime,double distanceThreshold = kRecommendedDistanceThreshold,@@ -366,16 +371,19 @@ class FaceClusteringService {'`predictWithinClusterComputer` called with ${input.length} faces and distance threshold $distanceThreshold',);try {- if (input.length < 10) {- final mergeThreshold = distanceThreshold + 0.06;+ if (input.length < 500) {+ final mergeThreshold = distanceThreshold + 0.08;_logger.info('Running complete clustering on ${input.length} faces with distance threshold $mergeThreshold',);- return predictCompleteComputer(+ final result = await predictCompleteComputer(input,fileIDToCreationTime: fileIDToCreationTime,+ distanceThreshold: distanceThreshold,mergeThreshold: mergeThreshold,);+ if (result.newFaceIdToCluster.isEmpty) return null;+ return result;} else {_logger.info('Running linear clustering on ${input.length} faces with distance threshold $distanceThreshold',@@ -385,7 +393,7 @@ class FaceClusteringService {fileIDToCreationTime: fileIDToCreationTime,distanceThreshold: distanceThreshold,);- return clusterResult?.newFaceIdToCluster;+ return clusterResult;}} catch (e, s) {_logger.severe(e, s);@@ -750,7 +758,7 @@ class FaceClusteringService {);}- static Map<String, int> runCompleteClustering(Map args) {+ 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;@@ -792,7 +800,7 @@ class FaceClusteringService {}if (faceInfos.isEmpty) {- return {};+ ClusteringResult(newFaceIdToCluster: {});}final int totalFaces = faceInfos.length;@@ -920,12 +928,31 @@ class FaceClusteringService {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];+ }+ }++ final newClusterSummaries = FaceClusteringService.updateClusterSummaries(+ oldSummary: <int, (Uint8List, int)>{},+ newFaceInfos: faceInfos,+ );+stopwatchClustering.stop();log(' [CompleteClustering] ${DateTime.now()} Clustering for ${faceInfos.length} embeddings executed in ${stopwatchClustering.elapsedMilliseconds}ms',);- return newFaceIdToCluster;+ return ClusteringResult(+ newFaceIdToCluster: newFaceIdToCluster,+ newClusterSummaries: newClusterSummaries,+ newClusterIdToFaceIds: clusterIdToFaceIds,+ );}static List<List<String>> _runDbscanClustering(Map args) {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 2a4ca787f4..70375ed5ff 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@@ -151,18 +151,21 @@ class ClusterFeedbackService {await FilesDB.instance.getFileIDToCreationTime();// Re-cluster within the deleted faces- final newFaceIdToClusterID =+ final clusterResult =await FaceClusteringService.instance.predictWithinClusterComputer(embeddings,fileIDToCreationTime: fileIDToCreationTime,distanceThreshold: 0.20,);- if (newFaceIdToClusterID == null || newFaceIdToClusterID.isEmpty) {+ if (clusterResult == null || clusterResult.isEmpty) {return;}+ final newFaceIdToClusterID = clusterResult.newFaceIdToCluster;// Update the deleted facesawait FaceMLDataDB.instance.forceUpdateClusterIds(newFaceIdToClusterID);+ await FaceMLDataDB.instance+ .clusterSummaryUpdate(clusterResult.newClusterSummaries!);// Make sure the deleted faces don't get suggested in the futurefinal notClusterIdToPersonId = <int, String>{};@@ -200,18 +203,21 @@ class ClusterFeedbackService {await FilesDB.instance.getFileIDToCreationTime();// Re-cluster within the deleted faces- final newFaceIdToClusterID =+ final clusterResult =await FaceClusteringService.instance.predictWithinClusterComputer(embeddings,fileIDToCreationTime: fileIDToCreationTime,distanceThreshold: 0.20,);- if (newFaceIdToClusterID == null || newFaceIdToClusterID.isEmpty) {+ if (clusterResult == null || clusterResult.isEmpty) {return;}+ final newFaceIdToClusterID = clusterResult.newFaceIdToCluster;// Update the deleted facesawait FaceMLDataDB.instance.forceUpdateClusterIds(newFaceIdToClusterID);+ await FaceMLDataDB.instance+ .clusterSummaryUpdate(clusterResult.newClusterSummaries!);Bus.instance.fire(PeopleChangedEvent(@@ -310,7 +316,7 @@ class ClusterFeedbackService {}// TODO: iterate over this method to find sweet spot- Future<Map<int, List<String>>> breakUpCluster(+ Future<ClusteringResult> breakUpCluster(int clusterID, {bool useDbscan = false,}) async {@@ -327,54 +333,20 @@ class ClusterFeedbackService {final fileIDToCreationTime =await FilesDB.instance.getFileIDToCreationTime();- final Map<int, List<String>> clusterIdToFaceIds = {};- if (useDbscan) {- final dbscanClusters = await FaceClusteringService.instance.predictDbscan(- embeddings,- fileIDToCreationTime: fileIDToCreationTime,- eps: 0.30,- minPts: 8,- );-- if (dbscanClusters.isEmpty) {- return {};- }-- int maxClusterID = DateTime.now().millisecondsSinceEpoch;-- for (final List<String> cluster in dbscanClusters) {- final faceIds = cluster;- clusterIdToFaceIds[maxClusterID] = faceIds;- maxClusterID++;- }- } else {- final faceIdToCluster =- await FaceClusteringService.instance.predictWithinClusterComputer(- embeddings,- fileIDToCreationTime: fileIDToCreationTime,- distanceThreshold: 0.22,- );-- if (faceIdToCluster == null || faceIdToCluster.isEmpty) {- _logger.info('No clusters found');- return {};- } else {- _logger.info(- 'Broke up cluster $clusterID into ${faceIdToCluster.values.toSet().length} clusters',- );- }+ final clusterResult =+ await FaceClusteringService.instance.predictWithinClusterComputer(+ embeddings,+ fileIDToCreationTime: fileIDToCreationTime,+ distanceThreshold: 0.14,+ );- for (final entry in faceIdToCluster.entries) {- final clusterID = entry.value;- if (clusterIdToFaceIds.containsKey(clusterID)) {- clusterIdToFaceIds[clusterID]!.add(entry.key);- } else {- clusterIdToFaceIds[clusterID] = [entry.key];- }- }+ if (clusterResult == null || clusterResult.isEmpty) {+ _logger.info('No clusters found');+ return ClusteringResult(newFaceIdToCluster: {});}- final clusterIdToCount = clusterIdToFaceIds.map((key, value) {+ final clusterIdToCount =+ clusterResult.newClusterIdToFaceIds!.map((key, value) {return MapEntry(key, value.length);});final amountOfNewClusters = clusterIdToCount.length;@@ -383,28 +355,16 @@ class ClusterFeedbackService {'Broke up cluster $clusterID into $amountOfNewClusters clusters \n ${clusterIdToCount.toString()}',);- final clusterIdToDisplayNames = <int, List<String>>{};if (kDebugMode) {- for (final entry in clusterIdToFaceIds.entries) {- final faceIDs = entry.value;- final fileIDs = faceIDs.map((e) => getFileIdFromFaceId(e)).toList();- final files = await FilesDB.instance.getFilesFromIDs(fileIDs);- final displayNames = files.values.map((e) => e.displayName).toList();- clusterIdToDisplayNames[entry.key] = displayNames;+ final Set allClusteredFaceIDsSet = {};+ for (final List<String> value+ in clusterResult.newClusterIdToFaceIds!.values) {+ allClusteredFaceIDsSet.addAll(value);}+ assert((originalFaceIDsSet.difference(allClusteredFaceIDsSet)).isEmpty);}- final Set allClusteredFaceIDsSet = {};- for (final List<String> value in clusterIdToFaceIds.values) {- allClusteredFaceIDsSet.addAll(value);- }- final clusterIDToNoiseFaceID =- originalFaceIDsSet.difference(allClusteredFaceIDsSet);- if (clusterIDToNoiseFaceID.isNotEmpty) {- clusterIdToFaceIds[-1] = clusterIDToNoiseFaceID.toList();- }-- return clusterIdToFaceIds;+ return clusterResult;}/// WARNING: this method is purely for debugging purposes, never use in productiondiff --git a/mobile/lib/ui/viewer/people/cluster_app_bar.dart b/mobile/lib/ui/viewer/people/cluster_app_bar.dartindex 769291d718..668894c120 100644--- a/mobile/lib/ui/viewer/people/cluster_app_bar.dart+++ b/mobile/lib/ui/viewer/people/cluster_app_bar.dart@@ -7,10 +7,12 @@ import "package:ml_linalg/linalg.dart";import 'package:photos/core/configuration.dart';import 'package:photos/core/event_bus.dart';import "package:photos/db/files_db.dart";+import "package:photos/events/people_changed_event.dart";import 'package:photos/events/subscription_purchased_event.dart';import "package:photos/face/db.dart";import "package:photos/face/model/person.dart";import "package:photos/generated/protos/ente/common/vector.pb.dart";+import "package:photos/models/file/file.dart";import 'package:photos/models/gallery_type.dart';import 'package:photos/models/selected_files.dart';import 'package:photos/services/collections_service.dart';@@ -20,6 +22,7 @@ import "package:photos/services/machine_learning/face_ml/feedback/cluster_feedbaimport 'package:photos/ui/actions/collection/collection_sharing_actions.dart';import "package:photos/ui/common/popup_item.dart";import "package:photos/ui/viewer/people/cluster_breakup_page.dart";+import "package:photos/ui/viewer/people/cluster_page.dart";import "package:photos/utils/dialog_util.dart";class ClusterAppBar extends StatefulWidget {@@ -115,7 +118,7 @@ class _AppBarWidgetState extends State<ClusterAppBar> {icon: Icons.hide_image_outlined,),EntePopupMenuItem(- "Break up cluster",+ "Mixed grouping?",value: ClusterPopupAction.breakupCluster,icon: Icons.analytics_outlined,),@@ -217,34 +220,111 @@ class _AppBarWidgetState extends State<ClusterAppBar> {}Future<void> _breakUpCluster(BuildContext context) async {- final newClusterIDToFaceIDs =- await ClusterFeedbackService.instance.breakUpCluster(widget.clusterID);+ if (!kDebugMode) {+ bool userConfirmed = false;+ List<EnteFile> biggestClusterFiles = [];+ int biggestClusterID = -1;+ await showChoiceDialog(+ context,+ title: "Does this grouping contain multiple people?",+ body:+ "We will automatically analyze the grouping again to determine if there are multiple people in the grouping, and separate them out again. This may take a few seconds.",+ firstButtonLabel: "Yes, confirm",+ firstButtonOnTap: () async {+ try {+ final breakupResult = await ClusterFeedbackService.instance+ .breakUpCluster(widget.clusterID);+ final Map<int, List<String>> newClusterIDToFaceIDs =+ breakupResult.newClusterIdToFaceIds!;+ final Map<String, int> newFaceIdToClusterID =+ breakupResult.newFaceIdToCluster;- final allFileIDs = newClusterIDToFaceIDs.values- .expand((e) => e)- .map((e) => getFileIdFromFaceId(e))- .toList();+ // Update to delete the old clusters and save the new clusters+ await FaceMLDataDB.instance.deleteClusterSummary(widget.clusterID);+ await FaceMLDataDB.instance+ .clusterSummaryUpdate(breakupResult.newClusterSummaries!);+ await FaceMLDataDB.instance+ .updateFaceIdToClusterId(newFaceIdToClusterID);- final fileIDtoFile = await FilesDB.instance.getFilesFromIDs(- allFileIDs,- );+ // Find the biggest cluster+ biggestClusterID = -1;+ int biggestClusterSize = 0;+ for (final MapEntry<int, List<String>> clusterToFaces+ in newClusterIDToFaceIDs.entries) {+ if (clusterToFaces.value.length > biggestClusterSize) {+ biggestClusterSize = clusterToFaces.value.length;+ biggestClusterID = clusterToFaces.key;+ }+ }+ // Get the files for the biggest new cluster+ final biggestClusterFileIDs =+ newClusterIDToFaceIDs[biggestClusterID]!+ .map((e) => getFileIdFromFaceId(e))+ .toList();+ biggestClusterFiles = await FilesDB.instance+ .getFilesFromIDs(+ biggestClusterFileIDs,+ )+ .then((mapping) => mapping.values.toList());+ // Sort the files to prevent issues with the order of the files in gallery+ biggestClusterFiles+ .sort((a, b) => b.creationTime!.compareTo(a.creationTime!));- final newClusterIDToFiles = newClusterIDToFaceIDs.map(- (key, value) => MapEntry(- key,- value- .map((faceId) => fileIDtoFile[getFileIdFromFaceId(faceId)]!)- .toList(),- ),- );+ userConfirmed = true;+ } catch (e, s) {+ _logger.severe('Breakup cluster failed', e, s);+ // await showGenericErrorDialog(context: context, error: e);+ }+ },+ );+ if (userConfirmed) {+ // Close the old cluster page+ Navigator.of(context).pop();++ // Push the new cluster page+ await Navigator.of(context).push(+ MaterialPageRoute(+ builder: (context) => ClusterPage(+ biggestClusterFiles,+ clusterID: biggestClusterID,+ ),+ ),+ );+ Bus.instance.fire(PeopleChangedEvent());+ }+ } else {+ final breakupResult = await ClusterFeedbackService.instance+ .breakUpCluster(widget.clusterID);++ final Map<int, List<String>> newClusterIDToFaceIDs =+ breakupResult.newClusterIdToFaceIds!;++ final allFileIDs = newClusterIDToFaceIDs.values+ .expand((e) => e)+ .map((e) => getFileIdFromFaceId(e))+ .toList();- await Navigator.of(context).push(- MaterialPageRoute(- builder: (context) => ClusterBreakupPage(- newClusterIDToFiles,- "(Analysis)",+ final fileIDtoFile = await FilesDB.instance.getFilesFromIDs(+ allFileIDs,+ );++ final newClusterIDToFiles = newClusterIDToFaceIDs.map(+ (key, value) => MapEntry(+ key,+ value+ .map((faceId) => fileIDtoFile[getFileIdFromFaceId(faceId)]!)+ .toList(),),- ),- );+ );++ await Navigator.of(context).push(+ MaterialPageRoute(+ builder: (context) => ClusterBreakupPage(+ newClusterIDToFiles,+ "(Analysis)",+ ),+ ),+ );+ }}}