π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Adapt PersonGallerySuggestion for all people
laurenspriem47359051a138
diff --git a/mobile/lib/db/ml/base.dart b/mobile/lib/db/ml/base.dartindex 5e2879d463..0f8994192e 100644--- a/mobile/lib/db/ml/base.dart+++ b/mobile/lib/db/ml/base.dart@@ -40,6 +40,7 @@ abstract class IMLDataDB<T> {Future<Map<String, Iterable<String>>> getAllClusterIdToFaceIDs();Future<Iterable<String>> getFaceIDsForCluster(String clusterID);Future<Map<String, Map<String, Set<String>>>> getPersonToClusterIdToFaceIds();+ Future<Map<String, Set<String>>> getPersonToClusterIDs();Future<Map<String, Set<String>>> getClusterIdToFaceIdsForPerson(String personID,);diff --git a/mobile/lib/db/ml/db.dart b/mobile/lib/db/ml/db.dartindex a1d2a6ccf1..bba2a96d47 100644--- a/mobile/lib/db/ml/db.dart+++ b/mobile/lib/db/ml/db.dart@@ -103,9 +103,9 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {const String sql = '''INSERT INTO $facesTable (- $fileIDColumn, $faceIDColumn, $faceDetectionColumn, $embeddingColumn, $faceScore, $faceBlur, $isSideways, $imageHeight, $imageWidth, $mlVersionColumn+ $fileIDColumn, $faceIDColumn, $faceDetectionColumn, $embeddingColumn, $faceScore, $faceBlur, $isSideways, $imageHeight, $imageWidth, $mlVersionColumn) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)- ON CONFLICT($fileIDColumn, $faceIDColumn) DO UPDATE SET $faceIDColumn = excluded.$faceIDColumn, $faceDetectionColumn = excluded.$faceDetectionColumn, $embeddingColumn = excluded.$embeddingColumn, $faceScore = excluded.$faceScore, $faceBlur = excluded.$faceBlur, $isSideways = excluded.$isSideways, $imageHeight = excluded.$imageHeight, $imageWidth = excluded.$imageWidth, $mlVersionColumn = excluded.$mlVersionColumn+ ON CONFLICT($fileIDColumn, $faceIDColumn) DO UPDATE SET $faceIDColumn = excluded.$faceIDColumn, $faceDetectionColumn = excluded.$faceDetectionColumn, $embeddingColumn = excluded.$embeddingColumn, $faceScore = excluded.$faceScore, $faceBlur = excluded.$faceBlur, $isSideways = excluded.$isSideways, $imageHeight = excluded.$imageHeight, $imageWidth = excluded.$imageWidth, $mlVersionColumn = excluded.$mlVersionColumn''';final parameterSets = batch.map((face) {final map = mapRemoteToFaceDB(face);@@ -158,7 +158,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {final db = await instance.asyncDB;final String query = '''SELECT $fileIDColumn, $mlVersionColumn- FROM $facesTable+ FROM $facesTableWHERE $mlVersionColumn >= $minimumMlVersion''';final List<Map<String, dynamic>> maps = await db.getAll(query);@@ -267,9 +267,9 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {final Map<String, List<Uint8List>> result = {};final selectQuery = '''- SELECT fc.$clusterIDColumn, fe.$embeddingColumn- FROM $faceClustersTable fc- INNER JOIN $facesTable fe ON fc.$faceIDColumn = fe.$faceIDColumn+ SELECT fc.$clusterIDColumn, fe.$embeddingColumn+ FROM $faceClustersTable fc+ INNER JOIN $facesTable fe ON fc.$faceIDColumn = fe.$faceIDColumnWHERE fc.$clusterIDColumn IN (${List.filled(clusterIDs.length, '?').join(',')})${limit != null ? 'LIMIT ?' : ''}''';@@ -323,10 +323,10 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {final List<Map<String, dynamic>> faceMaps = await db.getAll('''- SELECT * FROM $facesTable+ SELECT * FROM $facesTableWHERE $faceIDColumn IN (- SELECT $faceIDColumn- FROM $faceClustersTable+ SELECT $faceIDColumn+ FROM $faceClustersTableWHERE $clusterIDColumn IN (${List.filled(clusterIDs.length, '?').join(',')}))AND $fileIDColumn IN (${List.filled(fileId.length, '?').join(',')})@@ -420,8 +420,8 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {final List<Map<String, dynamic>> maps = await db.getAll('''- SELECT $clusterIDColumn, $faceIDColumn- FROM $faceClustersTable+ SELECT $clusterIDColumn, $faceIDColumn+ FROM $faceClustersTableWHERE $clusterIDColumn IN (${List.filled(clusterIDs.length, '?').join(',')})''',[...clusterIDs],@@ -512,6 +512,21 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {return result;}+ @override+ Future<Map<String, Set<String>>> getPersonToClusterIDs() async {+ final db = await instance.asyncDB;+ final List<Map<String, dynamic>> maps = await db.getAll(+ 'SELECT $personIdColumn, $clusterIDColumn FROM $clusterPersonTable',+ );+ final Map<String, Set<String>> result = {};+ for (final map in maps) {+ final personID = map[personIdColumn] as String;+ final clusterID = map[clusterIDColumn] as String;+ result.putIfAbsent(personID, () => {}).add(clusterID);+ }+ return result;+ }+Future<Map<String, String>> getFaceIdToPersonIdForFaces(Iterable<String> faceIDs,) async {@@ -581,9 +596,9 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {Future<Iterable<double>> getBlurValuesForCluster(String clusterID) async {final db = await instance.asyncDB;const String query = '''- SELECT $facesTable.$faceBlur- FROM $facesTable- JOIN $faceClustersTable ON $facesTable.$faceIDColumn = $faceClustersTable.$faceIDColumn+ SELECT $facesTable.$faceBlur+ FROM $facesTable+ JOIN $faceClustersTable ON $facesTable.$faceIDColumn = $faceClustersTable.$faceIDColumnWHERE $faceClustersTable.$clusterIDColumn = ?''';// const String query2 = '''@@ -757,11 +772,11 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {while (true) {// Query a batch of rowsfinal String query = '''- SELECT $faceIDColumn, $embeddingColumn- FROM $facesTable- WHERE $faceIDColumn IN (${faceIDs.map((id) => "'$id'").join(",")})- ORDER BY $faceIDColumn DESC- LIMIT $batchSize OFFSET $offset+ SELECT $faceIDColumn, $embeddingColumn+ FROM $facesTable+ WHERE $faceIDColumn IN (${faceIDs.map((id) => "'$id'").join(",")})+ ORDER BY $faceIDColumn DESC+ LIMIT $batchSize OFFSET $offset''';final List<Map<String, dynamic>> maps = await db.getAll(query);// Break the loop if no more rows@@ -985,8 +1000,8 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {return db.then((db) async {final List<Map<String, dynamic>> maps = await db.getAll('''- SELECT $clusterIDColumn, $faceIDColumn- FROM $faceClustersTable+ SELECT $clusterIDColumn, $faceIDColumn+ FROM $faceClustersTableWHERE $clusterIDColumn IN (${List.filled(clusterIDs.length, '?').join(',')})''',[...clusterIDs],@@ -1009,7 +1024,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {final db = await instance.asyncDB;const String sql = '''- INSERT INTO $clusterSummaryTable ($clusterIDColumn, $avgColumn, $countColumn) VALUES (?, ?, ?) ON CONFLICT($clusterIDColumn) DO UPDATE SET $avgColumn = excluded.$avgColumn, $countColumn = excluded.$countColumn+ INSERT INTO $clusterSummaryTable ($clusterIDColumn, $avgColumn, $countColumn) VALUES (?, ?, ?) ON CONFLICT($clusterIDColumn) DO UPDATE SET $avgColumn = excluded.$avgColumn, $countColumn = excluded.$countColumn''';final List<List<Object?>> parameterSets = [];int batchCounter = 0;@@ -1158,7 +1173,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {final result = await db.getAll('''SELECT DISTINCT $facesTable.$fileIDColumn- FROM $faceClustersTable+ FROM $faceClustersTableJOIN $facesTable ON $faceClustersTable.$faceIDColumn = $facesTable.$faceIDColumnWHERE $faceClustersTable.$clusterIDColumn = ?''',@@ -1189,8 +1204,8 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {final notInParam = exceptClusters?.map((e) => "'$e'").join(',') ?? '';final db = await instance.asyncDB;final result = await db.getAll('''- SELECT DISTINCT $facesTable.$fileIDColumn- FROM $facesTable+ SELECT DISTINCT $facesTable.$fileIDColumn+ FROM $facesTableJOIN $faceClustersTable on $faceClustersTable.$faceIDColumn = $facesTable.$faceIDColumnWHERE $faceClustersTable.$clusterIDColumn NOT IN ($notInParam);''');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 409cb925b8..cdf0f70f5f 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@@ -21,6 +21,7 @@ import "package:photos/services/machine_learning/ml_result.dart";import "package:photos/services/search_service.dart";class ClusterSuggestion {+ final PersonEntity person;final String clusterIDToMerge;final double distancePersonToCluster;final bool usedOnlyMeanForSuggestion;@@ -28,6 +29,7 @@ class ClusterSuggestion {final List<String> faceIDsInCluster;ClusterSuggestion(+ this.person,this.clusterIDToMerge,this.distancePersonToCluster,this.usedOnlyMeanForSuggestion,@@ -102,6 +104,7 @@ class ClusterFeedbackService<T> {if (clusterIDToFiles.containsKey(clusterSuggestion.$1)) {finalSuggestions.add(ClusterSuggestion(+ person,clusterSuggestion.$1,clusterSuggestion.$2,clusterSuggestion.$3,@@ -315,39 +318,54 @@ class ClusterFeedbackService<T> {return;}- Future<List<ClusterSuggestion>> getFastSuggestionForPerson(- PersonEntity person,- ) async {- // Get the biggest cluster, to be used for quick suggestion calculation- final personClusters = await mlDataDB.getPersonClusterIDs(person.remoteID);- final allClusterIdsToCountMap = (await mlDataDB.clusterIdToFaceCount());- String biggestClusterID = '';- int biggestClusterSize = 0;- final otherPersonClusterIDs = <String>{};- for (final clusterID in personClusters) {- final clusterSize = allClusterIdsToCountMap[clusterID] ?? 0;- if (clusterSize > biggestClusterSize) {- if (biggestClusterSize > 0) {- otherPersonClusterIDs.add(biggestClusterID);+ Future<List<ClusterSuggestion>> getAllLargePersonSuggestions() async {+ final personsMap = await PersonService.instance.getPersonsMap();+ if (personsMap.isEmpty) return [];+ try {+ final allClusterIdsToCountMap = await mlDataDB.clusterIdToFaceCount();+ final personToClusterIDs = await mlDataDB.getPersonToClusterIDs();+ final personIdToBiggestCluster = <String, String>{};+ final biggestClusterToPersonID = <String, String>{};+ final personIdToOtherPersonClusterIDs = <String, Set<String>>{};+ for (final person in personsMap.values) {+ final personID = person.remoteID;+ final personClusters = personToClusterIDs[personID] ?? {};+ int biggestClusterSize = 0;+ String biggestClusterID = '';+ final Set<String> otherPersonClusterIDs = {};+ for (final clusterID in personClusters) {+ final clusterSize = allClusterIdsToCountMap[clusterID] ?? 0;+ if (clusterSize > biggestClusterSize) {+ if (biggestClusterSize > 0) {+ otherPersonClusterIDs.add(biggestClusterID);+ }+ biggestClusterID = clusterID;+ biggestClusterSize = clusterSize;+ } else {+ otherPersonClusterIDs.add(clusterID);+ }}- biggestClusterID = clusterID;- biggestClusterSize = clusterSize;- } else {- otherPersonClusterIDs.add(clusterID);+ personIdToBiggestCluster[personID] = biggestClusterID;+ biggestClusterToPersonID[biggestClusterID] = personID;+ personIdToOtherPersonClusterIDs[personID] = otherPersonClusterIDs;}- }-- try {- // Get the suggestions for the person quick check with biggest cluster and centroid- final foundSuggestions = await _getFastSuggestions(- person,- biggestClusterID,- 0.60,- extraIgnoredClusters: otherPersonClusterIDs,+ final allPersonClusters = biggestClusterToPersonID.keys.toSet();+ final allOtherPersonClustersToIgnore =+ personIdToOtherPersonClusterIDs.values.reduce((a, b) => a.union(b));+ final Map<String, Vector> clusterAvg = await _getUpdateClusterAvg(+ allClusterIdsToCountMap,+ allOtherPersonClustersToIgnore,+ minClusterSize: kMinimumClusterSizeSearchResult,+ );+ final List<(String, double, String)> foundSuggestions =+ await calcSuggestionsMeanInComputer(+ clusterAvg,+ allPersonClusters,+ allOtherPersonClustersToIgnore,+ 0.55,);// Get the files for the suggestions- final startTime = DateTime.now();final suggestionClusterIDs = foundSuggestions.map((e) => e.$1).toSet();final Map<int, Set<String>> fileIdToClusterID =await mlDataDB.getFileIdToClusterIDSetForCluster(@@ -371,11 +389,12 @@ class ClusterFeedbackService<T> {}}- final List<ClusterSuggestion> finalSuggestions = [];+ final List<ClusterSuggestion> finalSuggestions = <ClusterSuggestion>[];for (final clusterSuggestion in foundSuggestions) {if (clusterIDToFiles.containsKey(clusterSuggestion.$1)) {finalSuggestions.add(ClusterSuggestion(+ personsMap[biggestClusterToPersonID[clusterSuggestion.$3]]!,clusterSuggestion.$1,clusterSuggestion.$2,true,@@ -385,19 +404,9 @@ class ClusterFeedbackService<T> {);}}- final getFilesTime = DateTime.now();- try {- await _sortSuggestionsOnDistanceToPerson(person, finalSuggestions);- } catch (e, s) {- _logger.severe("Error in sorting suggestions", e, s);- }- _logger.info(- 'getFastSuggestionForPerson post-processing suggestions took ${DateTime.now().difference(startTime).inMilliseconds} ms, of which sorting took ${DateTime.now().difference(getFilesTime).inMilliseconds} ms and getting files took ${getFilesTime.difference(startTime).inMilliseconds} ms',- );-return finalSuggestions;} catch (e, s) {- _logger.severe("Error in getClusterFilesForPersonID", e, s);+ _logger.severe("Error in getAllLargePersonSuggestions", e, s);rethrow;}}@@ -417,7 +426,8 @@ class ClusterFeedbackService<T> {return false;}}- final List<(String, double)> suggestions = await _getFastSuggestions(+ final List<(String, double, String)> suggestions =+ await _getFastSuggestions(p,personClusterID,0.24,@@ -678,7 +688,7 @@ class ClusterFeedbackService<T> {w?.log('Calculate avg for ${clusterAvgBigClusters.length} clusters of min size $minimumSize',);- final List<(String, double)> suggestionsMeanBigClusters =+ final List<(String, double, String)> suggestionsMeanBigClusters =await calcSuggestionsMeanInComputer(clusterAvgBigClusters,personClusters,@@ -702,7 +712,7 @@ class ClusterFeedbackService<T> {);continue;}- suggestionsMean.add(suggestion);+ suggestionsMean.add((suggestion.$1, suggestion.$2));}if (suggestionsMean.isNotEmpty) {return suggestionsMean@@ -715,7 +725,7 @@ class ClusterFeedbackService<T> {// Find the other cluster candidates based on the medianfinal clusterAvg = clusterAvgBigClusters;- final List<(String, double)> moreSuggestionsMean =+ final List<(String, double, String)> moreSuggestionsMean =await calcSuggestionsMeanInComputer(clusterAvg,personClusters,@@ -835,7 +845,8 @@ class ClusterFeedbackService<T> {/// Returns a list of suggestions. For each suggestion we return a record consisting of the following elements:/// 1. clusterID: the ID of the cluster/// 2. distance: the distance between the person's cluster and the suggestion- Future<List<(String, double)>> _getFastSuggestions(+ /// 3. personClusterID: the ID of the person's cluster+ Future<List<(String, double, String)>> _getFastSuggestions(PersonEntity person,String clusterID,double threshold, {@@ -854,8 +865,8 @@ class ClusterFeedbackService<T> {);final avgCalcTime = DateTime.now();- // Find the actual closest clusters for the person- final List<(String, double)> foundSuggestions =+ // Returns a list of tuples containing the suggestion ID, distance, and personClusterID, respectively+ final List<(String, double, String)> foundSuggestions =await calcSuggestionsMeanInComputer(clusterAvg,{clusterID},@@ -997,7 +1008,7 @@ class ClusterFeedbackService<T> {return clusterAvg;}- Future<List<(String, double)>> calcSuggestionsMeanInComputer(+ Future<List<(String, double, String)>> calcSuggestionsMeanInComputer(Map<String, Vector> clusterAvg,Set<String> personClusters,Set<String> ignoredClusters,@@ -1295,8 +1306,11 @@ class ClusterFeedbackService<T> {}}-/// Returns a map of person's clusterID to map of closest clusterID to with disstance-List<(String, double)> _calcSuggestionsMean(Map<String, dynamic> args) {+/// Returns a list of suggestions for a cluster in a tuple. The values of the tuple are:+/// 1. The suggested cluster ID+/// 2. The distance between the two clusters+/// 3. The corresponding cluster ID of the person cluster+List<(String, double, String)> _calcSuggestionsMean(Map<String, dynamic> args) {// Fill in argsfinal Map<String, Vector> clusterAvg = args['clusterAvg'];final Set<String> personClusters = args['personClusters'];@@ -1352,9 +1366,14 @@ List<(String, double)> _calcSuggestionsMean(Map<String, dynamic> args) {);if (suggestions.isNotEmpty) {- final List<(String, double)> suggestClusterIds = [];- for (final List<(String, double)> suggestion in suggestions.values) {- suggestClusterIds.addAll(suggestion);+ final List<(String, double, String)> suggestClusterIds = [];+ for (final String personClusterID in suggestions.keys) {+ final suggestionss = suggestions[personClusterID]!;+ suggestClusterIds.addAll(+ suggestionss.map(+ (suggestion) => (suggestion.$1, suggestion.$2, personClusterID),+ ),+ );}suggestClusterIds.sort((a, b) => a.$2.compareTo(b.$2),@@ -1366,7 +1385,7 @@ List<(String, double)> _calcSuggestionsMean(Map<String, dynamic> args) {return suggestClusterIds.sublist(0, min(suggestClusterIds.length, 20));} else {dev.log("No suggestions found using mean");- return <(String, double)>[];+ return <(String, double, String)>[];}}diff --git a/mobile/lib/ui/viewer/people/person_gallery_suggestion.dart b/mobile/lib/ui/viewer/people/person_gallery_suggestion.dartindex 884ba7d371..4547b62a78 100644--- a/mobile/lib/ui/viewer/people/person_gallery_suggestion.dart+++ b/mobile/lib/ui/viewer/people/person_gallery_suggestion.dart@@ -18,7 +18,7 @@ import "package:photos/utils/face/face_thumbnail_cache.dart";final _logger = Logger("PersonGallerySuggestion");class PersonGallerySuggestion extends StatefulWidget {- final PersonEntity person;+ final PersonEntity? person;const PersonGallerySuggestion({required this.person,@@ -41,6 +41,10 @@ class _PersonGallerySuggestionState extends State<PersonGallerySuggestion>bool hasCurrentSuggestion = false;Map<int, Map<int, Uint8List?>> precomputedFaceCrops = {};+ PersonEntity? person;+ bool get peoplePage => widget.person != null;+ PersonEntity get relevantPerson => widget.person ?? person!;+late AnimationController _slideController;late AnimationController _fadeController;late Animation<Offset> _slideAnimation;@@ -49,6 +53,7 @@ class _PersonGallerySuggestionState extends State<PersonGallerySuggestion>@overridevoid initState() {super.initState();+ person = widget.person;_initializeAnimations();_loadInitialSuggestion();}@@ -86,8 +91,15 @@ class _PersonGallerySuggestionState extends State<PersonGallerySuggestion>Future<void> _loadInitialSuggestion() async {try {- final suggestions = await ClusterFeedbackService.instance- .getSuggestionForPerson(widget.person);+ late final List<ClusterSuggestion> suggestions;+ if (peoplePage) {+ suggestions = await ClusterFeedbackService.instance+ .getSuggestionForPerson(relevantPerson);+ } else {+ suggestions = await ClusterFeedbackService.instance+ .getAllLargePersonSuggestions();+ person = suggestions.first.person;+ }if (suggestions.isNotEmpty && mounted) {allSuggestions = suggestions;@@ -188,7 +200,7 @@ class _PersonGallerySuggestionState extends State<PersonGallerySuggestion>MaterialPageRoute(builder: (context) => ClusterPage(sortedFiles,- personID: widget.person,+ personID: relevantPerson,clusterID: currentSuggestion.clusterIDToMerge,showNamingBanner: false,),@@ -212,14 +224,14 @@ class _PersonGallerySuggestionState extends State<PersonGallerySuggestion>if (accepted) {unawaited(ClusterFeedbackService.instance.addClusterToExistingPerson(- person: widget.person,+ person: relevantPerson,clusterID: currentSuggestion.clusterIDToMerge,),);} else {unawaited(MLDataDB.instance.captureNotPersonFeedback(- personID: widget.person.remoteID,+ personID: relevantPerson.remoteID,clusterID: currentSuggestion.clusterIDToMerge,),);@@ -252,6 +264,7 @@ class _PersonGallerySuggestionState extends State<PersonGallerySuggestion>unawaited(_animateOut());try {final currentSuggestion = allSuggestions[currentSuggestionIndex];+ person = currentSuggestion.person;final clusterID = currentSuggestion.clusterIDToMerge;final someFile = currentSuggestion.filesInCluster.first;@@ -301,6 +314,7 @@ class _PersonGallerySuggestionState extends State<PersonGallerySuggestion>// Check if we have more suggestionsif (currentSuggestionIndex < allSuggestions.length) {+ person = allSuggestions[currentSuggestionIndex].person;try {// Get face crops for next suggestion (from precomputed or generate new)Map<int, Uint8List?> nextCrops;@@ -409,7 +423,7 @@ class _PersonGallerySuggestionState extends State<PersonGallerySuggestion>children: [TextSpan(text: S.of(context).areThey),TextSpan(- text: widget.person.data.name,+ text: relevantPerson.data.name,style: textTheme.bodyBold,),TextSpan(text: S.of(context).questionmark),