Skip to content

armgit / ente

Public Imported from GitHub
0

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

Split smart memories calculators by domain

laurenspriemad8e1b8b666c
diff --git a/mobile/apps/photos/lib/services/smart_memories_clip_calculator.dart b/mobile/apps/photos/lib/services/smart_memories_clip_calculator.dart
new file mode 100644
index 0000000000..1d1d9633e9
--- /dev/null
+++ b/mobile/apps/photos/lib/services/smart_memories_clip_calculator.dart
@@ -0,0 +1,150 @@
+part of "smart_memories_service.dart";
+
+class ClipMemoriesCalculator {
+ static Future<List<ClipMemory>> compute(
+ Iterable<EnteFile> allFiles,
+ DateTime currentTime,
+ List<ClipShownLog> shownClip, {
+ bool surfaceAll = false,
+ required bool isOfflineMode,
+ required Map<int, int> seenTimes,
+ required Map<int, EmbeddingVector> fileIDToImageEmbedding,
+ required Map<ClipMemoryType, Vector> clipMemoryTypeVectors,
+ }) async {
+ final w = (kDebugMode ? EnteWatch('getClipResults') : null)?..start();
+ final List<ClipMemory> clipResults = [];
+ if (allFiles.isEmpty) return [];
+ final nowInMicroseconds = currentTime.microsecondsSinceEpoch;
+ final windowEnd =
+ currentTime.add(kMemoriesUpdateFrequency).microsecondsSinceEpoch;
+ w?.log('allFiles setup');
+
+ ClipMemory? buildClipMemory(ClipMemoryType clipMemoryType) {
+ final Vector? activityVector = clipMemoryTypeVectors[clipMemoryType];
+ if (activityVector == null) {
+ dev.log("No vector for clipMemoryType $clipMemoryType");
+ return null;
+ }
+ final Map<int, double> similarities = {};
+ for (final entry in fileIDToImageEmbedding.entries) {
+ similarities[entry.key] = entry.value.vector.dot(activityVector);
+ }
+ w?.log(
+ 'comparing embeddings for clipMemoryType $clipMemoryType',
+ );
+ final List<EnteFile> clipFiles = [];
+ for (final file in allFiles) {
+ final memoryFileID = SmartMemoriesService._memoryFileId(
+ file,
+ isOfflineMode: isOfflineMode,
+ );
+ if (memoryFileID == null) continue;
+ final similarity = similarities[memoryFileID];
+ if (similarity == null) continue;
+ if (similarity > SmartMemoriesService._clipMemoryTypeQueryThreshold) {
+ clipFiles.add(file);
+ }
+ }
+ if (clipFiles.length < 10) return null;
+ clipFiles.sort((a, b) {
+ final int bFileID = SmartMemoriesService._memoryFileId(
+ b,
+ isOfflineMode: isOfflineMode,
+ )!;
+ final int aFileID = SmartMemoriesService._memoryFileId(
+ a,
+ isOfflineMode: isOfflineMode,
+ )!;
+ return similarities[bFileID]!.compareTo(similarities[aFileID]!);
+ });
+ final int limit = min(clipFiles.length, 50);
+ final List<EnteFile> topCandidates = clipFiles.take(limit).toList();
+ topCandidates.shuffle(Random());
+ final List<EnteFile> selected = [];
+ final selectedFileIDs = <int>[];
+ final selectedCreationTimes = <int>[];
+ int skipped = 0;
+ for (final file in topCandidates) {
+ if (selected.length >= 10) break;
+ final fileID = SmartMemoriesService._memoryFileId(
+ file,
+ isOfflineMode: isOfflineMode,
+ );
+ if (fileID == null) continue;
+ final creationTime = file.creationTime;
+ if (SmartMemoriesService._isTooCloseInTime(
+ creationTime,
+ selectedCreationTimes,
+ )) {
+ skipped++;
+ continue;
+ }
+ if (SmartMemoriesService._isNearDuplicate(
+ fileID,
+ selectedFileIDs,
+ fileIDToImageEmbedding,
+ ) &&
+ (topCandidates.length - skipped) > 10) {
+ skipped++;
+ continue;
+ }
+ selected.add(file);
+ selectedFileIDs.add(fileID);
+ if (creationTime != null) {
+ selectedCreationTimes.add(creationTime);
+ }
+ }
+ selected.sort((a, b) {
+ final int bFileID = SmartMemoriesService._memoryFileId(
+ b,
+ isOfflineMode: isOfflineMode,
+ )!;
+ final int aFileID = SmartMemoriesService._memoryFileId(
+ a,
+ isOfflineMode: isOfflineMode,
+ )!;
+ return similarities[bFileID]!.compareTo(similarities[aFileID]!);
+ });
+ return ClipMemory(
+ selected.map((f) => Memory.fromFile(f, seenTimes)).toList(),
+ nowInMicroseconds,
+ windowEnd,
+ clipMemoryType,
+ );
+ }
+
+ if (surfaceAll) {
+ for (final clipMemoryType in ClipMemoryType.values) {
+ final clipMemory = buildClipMemory(clipMemoryType);
+ if (clipMemory != null) clipResults.add(clipMemory);
+ }
+ return clipResults;
+ }
+
+ final List<ClipMemoryType> rotationOrder = [...ClipMemoryType.values]
+ ..shuffle();
+ final List<ClipMemoryType> eligibleClipTypes = [];
+
+ clipMemoriesLoop:
+ for (final clipMemoryType in rotationOrder) {
+ for (final shownLog in shownClip) {
+ if (shownLog.clipMemoryType != clipMemoryType) continue;
+ final shownDate =
+ DateTime.fromMicrosecondsSinceEpoch(shownLog.lastTimeShown);
+ final bool seenRecently =
+ currentTime.difference(shownDate) < kClipShowTimeout;
+ if (seenRecently) continue clipMemoriesLoop;
+ }
+ eligibleClipTypes.add(clipMemoryType);
+ }
+
+ for (final clipMemoryType in eligibleClipTypes) {
+ final clipMemory = buildClipMemory(clipMemoryType);
+ if (clipMemory == null) continue;
+ clipResults.add(clipMemory);
+ break;
+ }
+
+ return clipResults;
+ }
+}
diff --git a/mobile/apps/photos/lib/services/smart_memories_people_calculator.dart b/mobile/apps/photos/lib/services/smart_memories_people_calculator.dart
new file mode 100644
index 0000000000..d5e45a4f3c
--- /dev/null
+++ b/mobile/apps/photos/lib/services/smart_memories_people_calculator.dart
@@ -0,0 +1,524 @@
+part of "smart_memories_service.dart";
+
+class PeopleMemoriesCalculator {
+ static Future<List<PeopleMemory>> compute(
+ Iterable<EnteFile> allFiles,
+ Map<int, EnteFile> allFileIdsToFile,
+ DateTime currentTime,
+ List<PeopleShownLog> shownPeople, {
+ bool surfaceAll = false,
+ required Map<int, int> seenTimes,
+ required List<PersonEntity> persons,
+ required bool isOfflineMode,
+ required bool canUseUnnamedFallback,
+ String? currentUserEmail,
+ required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
+ required Map<String, int> clusterIdToFaceCount,
+ required Map<String, Iterable<String>> clusterIdToFaceIDs,
+ required Set<String> assignedClusterIDs,
+ required Map<int, EmbeddingVector> fileIDToImageEmbedding,
+ required Vector clipPositiveTextVector,
+ required Map<PeopleActivity, Vector> clipPeopleActivityVectors,
+ }) async {
+ final w = (kDebugMode ? EnteWatch('getPeopleResults') : null)?..start();
+ final List<PeopleMemory> memoryResults = [];
+ if (allFiles.isEmpty) return [];
+ final nowInMicroseconds = currentTime.microsecondsSinceEpoch;
+ final windowEnd =
+ currentTime.add(kMemoriesUpdateFrequency).microsecondsSinceEpoch;
+ w?.log('allFiles setup');
+
+ final personIdToPerson = <String, PersonEntity>{};
+ final personIdToFaceIDs = <String, Set<String>>{};
+ final personIdToFileIDs = <String, Set<int>>{};
+ for (final person in persons) {
+ final personID = person.remoteID;
+ personIdToPerson[personID] = person;
+ personIdToFaceIDs[personID] = {};
+ personIdToFileIDs[personID] = {};
+ for (final cluster in person.data.assigned) {
+ if (cluster.faces.isEmpty) continue;
+ personIdToFaceIDs[personID]!.addAll(cluster.faces);
+ personIdToFileIDs[personID]!
+ .addAll(cluster.faces.map((faceID) => getFileIdFromFaceId(faceID)));
+ }
+ }
+ final List<String> orderedImportantPersonsID = persons
+ .where((person) => !isOfflineMode && !person.data.isIgnored)
+ .map((p) => p.remoteID)
+ .toList();
+ orderedImportantPersonsID.shuffle(Random());
+ final amountOfPersons = orderedImportantPersonsID.length;
+ final shownPersonTimeout = Duration(
+ days: min(
+ kPersonShowTimeout.inDays,
+ max(1, amountOfPersons) * kMemoriesUpdateFrequencyDays,
+ ),
+ );
+ w?.log('orderedImportantPersonsID setup');
+
+ String? meID;
+ for (final personEntity in persons) {
+ if (personEntity.data.email == currentUserEmail) {
+ meID = personEntity.remoteID;
+ break;
+ }
+ }
+ final bool isMeAssigned = meID != null;
+ Set<int>? meFileIDs;
+ if (isMeAssigned) meFileIDs = personIdToFileIDs[meID]!;
+
+ Future<List<Memory>> selectPeopleMemories(List<Memory> memories) {
+ return SmartMemoriesService._bestSelectionPeople(
+ memories,
+ isOfflineMode: isOfflineMode,
+ fileIDToImageEmbedding: fileIDToImageEmbedding,
+ clipPositiveTextVector: clipPositiveTextVector,
+ );
+ }
+
+ final unnamedClusterCandidates =
+ SmartMemoriesService._buildUnnamedClusterCandidates(
+ clusterIdToFaceCount: clusterIdToFaceCount,
+ clusterIdToFaceIDs: clusterIdToFaceIDs,
+ assignedClusterIDs: assignedClusterIDs,
+ allFileIdsToFile: allFileIdsToFile,
+ fileIdToFaces: fileIdToFaces,
+ meFileIDs: meFileIDs,
+ isMeAssigned: isMeAssigned,
+ seenTimes: seenTimes,
+ nowInMicroseconds: nowInMicroseconds,
+ windowEnd: windowEnd,
+ isOfflineMode: isOfflineMode,
+ selectionBuilder: selectPeopleMemories,
+ );
+ final randomizedUnnamedClusterCandidates =
+ SmartMemoriesService._orderUnnamedCandidatesByRecencyAndRandom(
+ candidates: unnamedClusterCandidates,
+ shownPeople: shownPeople,
+ currentTime: currentTime,
+ shownPersonTimeout: shownPersonTimeout,
+ );
+ w?.log('unnamed cluster candidates setup');
+
+ if (kDebugMode && SmartMemoriesService._debugForceUnnamedClustersOnly) {
+ for (final candidate in randomizedUnnamedClusterCandidates) {
+ final memory = await candidate.realize();
+ if (memory == null) continue;
+ memoryResults.add(memory);
+ if (!surfaceAll) break;
+ }
+ return memoryResults;
+ }
+
+ final Map<String, Map<PeopleMemoryType, List<PeopleMemoryCandidate>>>
+ personToCandidates = {};
+ for (final personID in orderedImportantPersonsID) {
+ final personFileIDs = personIdToFileIDs[personID]!;
+ final personName = personIdToPerson[personID]!.data.name;
+ w?.log('start with new person $personName');
+ w?.log('personFilesToFaces setup');
+
+ final spotlightFiles = <EnteFile>[];
+ for (final fileID in personFileIDs) {
+ final int personsPresent = fileIdToFaces[fileID]?.length ?? 10;
+ if (personsPresent > 1) continue;
+ final file = allFileIdsToFile[fileID];
+ if (file != null) {
+ spotlightFiles.add(file);
+ }
+ }
+ if (spotlightFiles.length > SmartMemoriesService.minimumMemoryLength) {
+ final spotlightMemories = spotlightFiles
+ .map((f) => Memory.fromFile(f, seenTimes))
+ .toList(growable: false);
+ final spotlightList =
+ personToCandidates.putIfAbsent(personID, () => {}).putIfAbsent(
+ PeopleMemoryType.spotlight,
+ () => <PeopleMemoryCandidate>[],
+ );
+ spotlightList.add(
+ PeopleMemoryCandidate(
+ personID: personID,
+ personName: (isMeAssigned && meID == personID) ? null : personName,
+ type: PeopleMemoryType.spotlight,
+ rawMemories: spotlightMemories,
+ firstDateToShow: nowInMicroseconds,
+ lastDateToShow: windowEnd,
+ selectionBuilder: selectPeopleMemories,
+ ),
+ );
+ }
+ w?.log('spotlight setup');
+
+ if (isMeAssigned && meID != personID) {
+ final youAndThemFiles = <EnteFile>[];
+ for (final fileID in personFileIDs) {
+ final bool mePresent = meFileIDs!.contains(fileID);
+ final personFaces = fileIdToFaces[fileID] ?? [];
+ if (!mePresent || personFaces.length != 2) continue;
+ final file = allFileIdsToFile[fileID];
+ if (file != null) {
+ youAndThemFiles.add(file);
+ }
+ }
+ if (youAndThemFiles.length > SmartMemoriesService.minimumMemoryLength) {
+ final youAndThemMemories = youAndThemFiles
+ .map((f) => Memory.fromFile(f, seenTimes))
+ .toList(growable: false);
+ final youAndThemList =
+ personToCandidates.putIfAbsent(personID, () => {}).putIfAbsent(
+ PeopleMemoryType.youAndThem,
+ () => <PeopleMemoryCandidate>[],
+ );
+ youAndThemList.add(
+ PeopleMemoryCandidate(
+ personID: personID,
+ personName: personName,
+ type: PeopleMemoryType.youAndThem,
+ rawMemories: youAndThemMemories,
+ firstDateToShow: nowInMicroseconds,
+ lastDateToShow: windowEnd,
+ selectionBuilder: selectPeopleMemories,
+ ),
+ );
+ }
+ w?.log('youAndThem setup');
+ }
+
+ if (isMeAssigned && meID != personID) {
+ final vectors = SmartMemoriesService._getEmbeddingsForFileIDs(
+ fileIDToImageEmbedding,
+ personFileIDs,
+ );
+ w?.log('getting clip vectors for doingSomethingTogether');
+ final activityFiles = <EnteFile>[];
+ for (final activity in PeopleActivity.values) {
+ activityFiles.clear();
+ final Vector? activityVector = clipPeopleActivityVectors[activity];
+ if (activityVector == null) {
+ dev.log("No vector for activity $activity");
+ continue;
+ }
+ final Map<int, double> similarities = {};
+ for (final embedding in vectors) {
+ similarities[embedding.fileID] =
+ embedding.vector.dot(activityVector);
+ }
+ w?.log(
+ 'comparing embeddings for doingSomethingTogether and $activity',
+ );
+ for (final fileID in personFileIDs) {
+ final similarity = similarities[fileID];
+ if (similarity == null) continue;
+ if (similarity > SmartMemoriesService._clipActivityQueryThreshold) {
+ final file = allFileIdsToFile[fileID];
+ if (file != null) {
+ activityFiles.add(file);
+ }
+ }
+ }
+ if (activityFiles.length > SmartMemoriesService.minimumMemoryLength) {
+ final activityMemories = activityFiles
+ .map((f) => Memory.fromFile(f, seenTimes))
+ .toList(growable: false);
+ final activityList =
+ personToCandidates.putIfAbsent(personID, () => {}).putIfAbsent(
+ PeopleMemoryType.doingSomethingTogether,
+ () => <PeopleMemoryCandidate>[],
+ );
+ activityList.add(
+ PeopleMemoryCandidate(
+ personID: personID,
+ personName: personName,
+ type: PeopleMemoryType.doingSomethingTogether,
+ rawMemories: activityMemories,
+ firstDateToShow: nowInMicroseconds,
+ lastDateToShow: windowEnd,
+ activity: activity,
+ selectionBuilder: selectPeopleMemories,
+ ),
+ );
+ }
+ }
+
+ w?.log('doingSomethingTogether setup');
+ }
+
+ final lastTimeYouSawThemFiles = <EnteFile>[];
+ int lastCreationTime = 0;
+ bool longAgo = true;
+ for (final fileID in personFileIDs) {
+ final file = allFileIdsToFile[fileID];
+ if (file != null && file.creationTime != null) {
+ final creationTime = file.creationTime!;
+ final creationDateTime =
+ DateTime.fromMicrosecondsSinceEpoch(creationTime);
+ if (currentTime.difference(creationDateTime).inDays < 365) {
+ longAgo = false;
+ break;
+ }
+ if (creationTime > lastCreationTime - microSecondsInDay) {
+ final lastDateTime =
+ DateTime.fromMicrosecondsSinceEpoch(lastCreationTime);
+ if (creationDateTime.difference(lastDateTime).inHours > 24) {
+ lastTimeYouSawThemFiles.clear();
+ }
+ if (creationTime > lastCreationTime) {
+ lastCreationTime = creationTime;
+ }
+ lastTimeYouSawThemFiles.add(file);
+ }
+ }
+ }
+ if (longAgo && lastTimeYouSawThemFiles.length >= 2 && meID != personID) {
+ final lastTimeMemories = lastTimeYouSawThemFiles
+ .map((f) => Memory.fromFile(f, seenTimes))
+ .toList();
+ lastTimeMemories.sort(
+ (a, b) => a.file.creationTime!.compareTo(b.file.creationTime!),
+ );
+ final filteredLastTimeMemories =
+ SmartMemoriesService._filterNearDuplicates(
+ lastTimeMemories,
+ fileIDToImageEmbedding,
+ minKeep: 2,
+ isOfflineMode: isOfflineMode,
+ );
+ final spacedLastTimeMemories =
+ SmartMemoriesService._filterByTimeSpacing(
+ filteredLastTimeMemories,
+ );
+ final lastTimeList =
+ personToCandidates.putIfAbsent(personID, () => {}).putIfAbsent(
+ PeopleMemoryType.lastTimeYouSawThem,
+ () => <PeopleMemoryCandidate>[],
+ );
+ lastTimeList.add(
+ PeopleMemoryCandidate(
+ personID: personID,
+ personName: personName,
+ type: PeopleMemoryType.lastTimeYouSawThem,
+ rawMemories: spacedLastTimeMemories,
+ firstDateToShow: nowInMicroseconds,
+ lastDateToShow: windowEnd,
+ lastCreationTime: lastCreationTime,
+ requiresSelection: false,
+ ),
+ );
+ }
+ w?.log('lastTimeYouSawThem setup');
+ }
+
+ if (surfaceAll) {
+ for (final personCandidates in personToCandidates.values) {
+ for (final candidateList in personCandidates.values) {
+ for (final candidate in candidateList) {
+ final memory = await candidate.realize();
+ if (memory != null) {
+ memoryResults.add(memory);
+ }
+ }
+ }
+ }
+ for (final candidate in unnamedClusterCandidates) {
+ final memory = await candidate.realize();
+ if (memory != null) {
+ memoryResults.add(memory);
+ }
+ }
+ return memoryResults;
+ }
+
+ for (final personID in orderedImportantPersonsID) {
+ final personCandidates = personToCandidates[personID];
+ if (personCandidates == null) continue;
+ final person = personIdToPerson[personID]!;
+
+ final lastMetCandidate =
+ personCandidates[PeopleMemoryType.lastTimeYouSawThem]?.first;
+ if (lastMetCandidate != null &&
+ lastMetCandidate.lastCreationTime != null) {
+ final lastMetTime = DateTime.fromMicrosecondsSinceEpoch(
+ lastMetCandidate.lastCreationTime!,
+ ).copyWith(year: currentTime.year);
+ final daysSinceLastMet = lastMetTime.difference(currentTime).inDays;
+ if (daysSinceLastMet < 7 && daysSinceLastMet >= 0) {
+ final lastMetMemory = await lastMetCandidate.realize();
+ if (lastMetMemory != null) {
+ memoryResults.add(lastMetMemory);
+ }
+ }
+ }
+
+ final birthdate = DateTime.tryParse(person.data.birthDate ?? "");
+ if (birthdate != null) {
+ final thisBirthday =
+ DateTime(currentTime.year, birthdate.month, birthdate.day);
+ final daysTillBirthday = thisBirthday.difference(currentTime).inDays;
+ if (daysTillBirthday < 6 && daysTillBirthday >= 0) {
+ final int newAge = currentTime.year - birthdate.year;
+ final spotlightCandidate =
+ personCandidates[PeopleMemoryType.spotlight]?.first;
+ if (spotlightCandidate != null &&
+ spotlightCandidate.personName != null) {
+ final spotlightMem = await spotlightCandidate.realize();
+ if (spotlightMem != null) {
+ final thisBirthday = birthdate.copyWith(year: currentTime.year);
+ memoryResults.add(
+ spotlightMem.copyWith(
+ isBirthday: false,
+ newAge: newAge,
+ firstDateToShow: thisBirthday
+ .subtract(const Duration(days: 5))
+ .microsecondsSinceEpoch,
+ lastDateToShow: thisBirthday.microsecondsSinceEpoch,
+ ),
+ );
+ memoryResults.add(
+ spotlightMem.copyWith(
+ isBirthday: true,
+ newAge: newAge,
+ firstDateToShow: thisBirthday.microsecondsSinceEpoch,
+ lastDateToShow:
+ thisBirthday.add(kDayItself).microsecondsSinceEpoch,
+ ),
+ );
+ }
+ }
+ final youAndThemCandidate =
+ personCandidates[PeopleMemoryType.youAndThem]?.first;
+ if (youAndThemCandidate != null) {
+ final youAndThemMem = await youAndThemCandidate.realize();
+ if (youAndThemMem != null) {
+ memoryResults.add(
+ youAndThemMem.copyWith(
+ isBirthday: false,
+ newAge: newAge,
+ firstDateToShow: thisBirthday
+ .subtract(const Duration(days: 5))
+ .microsecondsSinceEpoch,
+ lastDateToShow: thisBirthday.microsecondsSinceEpoch,
+ ),
+ );
+ memoryResults.add(
+ youAndThemMem.copyWith(
+ isBirthday: true,
+ newAge: newAge,
+ firstDateToShow: thisBirthday.microsecondsSinceEpoch,
+ lastDateToShow:
+ thisBirthday.add(kDayItself).microsecondsSinceEpoch,
+ ),
+ );
+ }
+ }
+ }
+ }
+ }
+ w?.log('relevancy setup');
+
+ final shownPersonAndTypeTimeout =
+ Duration(days: shownPersonTimeout.inDays * 2);
+ bool addedFromRotation = false;
+ peopleRotationLoop:
+ for (final personID in orderedImportantPersonsID) {
+ for (final memory in memoryResults) {
+ if (memory.personID == personID) {
+ continue peopleRotationLoop;
+ }
+ }
+ for (final shownLog in shownPeople) {
+ if (shownLog.personID != personID) continue;
+ final shownDate =
+ DateTime.fromMicrosecondsSinceEpoch(shownLog.lastTimeShown);
+ final bool seenPersonRecently =
+ currentTime.difference(shownDate) < shownPersonTimeout;
+ if (seenPersonRecently) continue peopleRotationLoop;
+ }
+ final personCandidates = personToCandidates[personID];
+ if (personCandidates == null) continue peopleRotationLoop;
+ int added = 0;
+ final amountOfMemoryTypesForPerson = personCandidates.length;
+ final bool manyMemoryTypes = amountOfMemoryTypesForPerson > 2;
+ potentialMemoryLoop:
+ for (final candidatesForCategory in personCandidates.values) {
+ if (candidatesForCategory.isEmpty) continue;
+ PeopleMemoryCandidate potentialCandidate = candidatesForCategory.first;
+ if (candidatesForCategory.length > 1) {
+ if (potentialCandidate.type !=
+ PeopleMemoryType.doingSomethingTogether) {
+ dev.log(
+ 'Something is going wrong, ${potentialCandidate.type} has multiple memories for same person',
+ );
+ } else {
+ final randIdx = Random().nextInt(candidatesForCategory.length);
+ potentialCandidate = candidatesForCategory[randIdx];
+ }
+ }
+ for (final shownLog in shownPeople) {
+ if (shownLog.personID != personID) continue;
+ if (shownLog.peopleMemoryType != potentialCandidate.type) {
+ continue;
+ }
+ final shownTypeDate =
+ DateTime.fromMicrosecondsSinceEpoch(shownLog.lastTimeShown);
+ final bool seenPersonTypeRecently =
+ currentTime.difference(shownTypeDate) < shownPersonAndTypeTimeout;
+ if (manyMemoryTypes && seenPersonTypeRecently) {
+ continue potentialMemoryLoop;
+ }
+ }
+ final potentialMemory = await potentialCandidate.realize();
+ if (potentialMemory == null) continue;
+ memoryResults.add(potentialMemory);
+ addedFromRotation = true;
+ added++;
+ if (added >= 2) break peopleRotationLoop;
+ }
+ if (added > 0) break peopleRotationLoop;
+ }
+ if (!addedFromRotation && canUseUnnamedFallback) {
+ final eligibleUnnamedCandidates = <PeopleMemoryCandidate>[];
+ for (final candidate in randomizedUnnamedClusterCandidates) {
+ final candidatePersonID = candidate.personID;
+ bool alreadyInResults = false;
+ for (final memory in memoryResults) {
+ if (memory.personID == candidatePersonID) {
+ alreadyInResults = true;
+ break;
+ }
+ }
+ if (alreadyInResults) {
+ continue;
+ }
+ if (SmartMemoriesService._wasPersonShownRecently(
+ personID: candidatePersonID,
+ shownPeople: shownPeople,
+ currentTime: currentTime,
+ shownPersonTimeout: shownPersonTimeout,
+ )) {
+ continue;
+ }
+ eligibleUnnamedCandidates.add(candidate);
+ }
+ final orderedEligibleUnnamedCandidates =
+ SmartMemoriesService._orderUnnamedCandidatesByRecencyAndRandom(
+ candidates: eligibleUnnamedCandidates,
+ shownPeople: shownPeople,
+ currentTime: currentTime,
+ shownPersonTimeout: shownPersonTimeout,
+ );
+ for (final candidate in orderedEligibleUnnamedCandidates) {
+ final potentialMemory = await candidate.realize();
+ if (potentialMemory == null) {
+ continue;
+ }
+ memoryResults.add(potentialMemory);
+ break;
+ }
+ }
+ w?.log('rotation setup');
+
+ return memoryResults;
+ }
+}
diff --git a/mobile/apps/photos/lib/services/smart_memories_service.dart b/mobile/apps/photos/lib/services/smart_memories_service.dart
index 881d7f12d2..30772d408e 100644
--- a/mobile/apps/photos/lib/services/smart_memories_service.dart
+++ b/mobile/apps/photos/lib/services/smart_memories_service.dart
@@ -42,6 +42,11 @@ import "package:photos/services/machine_learning/ml_result.dart";
import "package:photos/services/memories/memories_computation_context.dart";
import "package:photos/services/search_service.dart";
+part "smart_memories_clip_calculator.dart";
+part "smart_memories_people_calculator.dart";
+part "smart_memories_time_calculator.dart";
+part "smart_memories_trip_calculator.dart";
+
class MemoriesResult {
final List<SmartMemory> memories;
final List<BaseLocation> baseLocations;
@@ -997,516 +1002,25 @@ class SmartMemoriesService {
required Vector clipPositiveTextVector,
required Map<PeopleActivity, Vector> clipPeopleActivityVectors,
}) async {
- final w = (kDebugMode ? EnteWatch('getPeopleResults') : null)?..start();
- final List<PeopleMemory> memoryResults = [];
- if (allFiles.isEmpty) return [];
- final nowInMicroseconds = currentTime.microsecondsSinceEpoch;
- final windowEnd =
- currentTime.add(kMemoriesUpdateFrequency).microsecondsSinceEpoch;
- w?.log('allFiles setup');
-
- // Get ordered (random) list of important people
- final personIdToPerson = <String, PersonEntity>{};
- final personIdToFaceIDs = <String, Set<String>>{};
- final personIdToFileIDs = <String, Set<int>>{};
- // final personIdToFaceIdToFace = <String, Map<String, Face>>{}; TODO: lau: try using relative face size as metric of importance
- for (final person in persons) {
- final personID = person.remoteID;
- personIdToPerson[personID] = person;
- personIdToFaceIDs[personID] = {};
- personIdToFileIDs[personID] = {};
- for (final cluster in person.data.assigned) {
- if (cluster.faces.isEmpty) continue;
- personIdToFaceIDs[personID]!.addAll(cluster.faces);
- personIdToFileIDs[personID]!
- .addAll(cluster.faces.map((faceID) => getFileIdFromFaceId(faceID)));
- }
- }
- final List<String> orderedImportantPersonsID = persons
- .where((person) => !isOfflineMode && !person.data.isIgnored)
- .map((p) => p.remoteID)
- .toList();
- orderedImportantPersonsID.shuffle(Random());
- final amountOfPersons = orderedImportantPersonsID.length;
- final shownPersonTimeout = Duration(
- days: min(
- kPersonShowTimeout.inDays,
- max(1, amountOfPersons) * kMemoriesUpdateFrequencyDays,
- ),
- );
- w?.log('orderedImportantPersonsID setup');
-
- // Check if the user has assignmed "me"
- String? meID;
- for (final personEntity in persons) {
- if (personEntity.data.email == currentUserEmail) {
- meID = personEntity.remoteID;
- break;
- }
- }
- final bool isMeAssigned = meID != null;
- Set<int>? meFileIDs;
- if (isMeAssigned) meFileIDs = personIdToFileIDs[meID]!;
-
- // Loop through the people and find all memories
- Future<List<Memory>> selectPeopleMemories(List<Memory> memories) {
- return _bestSelectionPeople(
- memories,
- isOfflineMode: isOfflineMode,
- fileIDToImageEmbedding: fileIDToImageEmbedding,
- clipPositiveTextVector: clipPositiveTextVector,
- );
- }
-
- final unnamedClusterCandidates = _buildUnnamedClusterCandidates(
+ return PeopleMemoriesCalculator.compute(
+ allFiles,
+ allFileIdsToFile,
+ currentTime,
+ shownPeople,
+ surfaceAll: surfaceAll,
+ seenTimes: seenTimes,
+ persons: persons,
+ isOfflineMode: isOfflineMode,
+ canUseUnnamedFallback: canUseUnnamedFallback,
+ currentUserEmail: currentUserEmail,
+ fileIdToFaces: fileIdToFaces,
clusterIdToFaceCount: clusterIdToFaceCount,
clusterIdToFaceIDs: clusterIdToFaceIDs,
assignedClusterIDs: assignedClusterIDs,
- allFileIdsToFile: allFileIdsToFile,
- fileIdToFaces: fileIdToFaces,
- meFileIDs: meFileIDs,
- isMeAssigned: isMeAssigned,
- seenTimes: seenTimes,
- nowInMicroseconds: nowInMicroseconds,
- windowEnd: windowEnd,
- isOfflineMode: isOfflineMode,
- selectionBuilder: selectPeopleMemories,
- );
- final randomizedUnnamedClusterCandidates =
- _orderUnnamedCandidatesByRecencyAndRandom(
- candidates: unnamedClusterCandidates,
- shownPeople: shownPeople,
- currentTime: currentTime,
- shownPersonTimeout: shownPersonTimeout,
+ fileIDToImageEmbedding: fileIDToImageEmbedding,
+ clipPositiveTextVector: clipPositiveTextVector,
+ clipPeopleActivityVectors: clipPeopleActivityVectors,
);
- w?.log('unnamed cluster candidates setup');
-
- if (kDebugMode && _debugForceUnnamedClustersOnly) {
- for (final candidate in randomizedUnnamedClusterCandidates) {
- final memory = await candidate.realize();
- if (memory == null) continue;
- memoryResults.add(memory);
- if (!surfaceAll) break;
- }
- return memoryResults;
- }
-
- final Map<String, Map<PeopleMemoryType, List<PeopleMemoryCandidate>>>
- personToCandidates = {};
- for (final personID in orderedImportantPersonsID) {
- final personFileIDs = personIdToFileIDs[personID]!;
- final personName = personIdToPerson[personID]!.data.name;
- w?.log('start with new person $personName');
- w?.log('personFilesToFaces setup');
-
- // Inside people loop, check for spotlight (Most likely every person will have a spotlight)
- final spotlightFiles = <EnteFile>[];
- for (final fileID in personFileIDs) {
- final int personsPresent = fileIdToFaces[fileID]?.length ?? 10;
- if (personsPresent > 1) continue;
- final file = allFileIdsToFile[fileID];
- if (file != null) {
- spotlightFiles.add(file);
- }
- }
- if (spotlightFiles.length > minimumMemoryLength) {
- final spotlightMemories = spotlightFiles
- .map((f) => Memory.fromFile(f, seenTimes))
- .toList(growable: false);
- final spotlightList =
- personToCandidates.putIfAbsent(personID, () => {}).putIfAbsent(
- PeopleMemoryType.spotlight,
- () => <PeopleMemoryCandidate>[],
- );
- spotlightList.add(
- PeopleMemoryCandidate(
- personID: personID,
- personName: (isMeAssigned && meID == personID) ? null : personName,
- type: PeopleMemoryType.spotlight,
- rawMemories: spotlightMemories,
- firstDateToShow: nowInMicroseconds,
- lastDateToShow: windowEnd,
- selectionBuilder: selectPeopleMemories,
- ),
- );
- }
- w?.log('spotlight setup');
-
- // Inside people loop, check for youAndThem
- if (isMeAssigned && meID != personID) {
- final youAndThemFiles = <EnteFile>[];
- for (final fileID in personFileIDs) {
- final bool mePresent = meFileIDs!.contains(fileID);
- final personFaces = fileIdToFaces[fileID] ?? [];
- if (!mePresent || personFaces.length != 2) continue;
- final file = allFileIdsToFile[fileID];
- if (file != null) {
- youAndThemFiles.add(file);
- }
- }
- if (youAndThemFiles.length > minimumMemoryLength) {
- final youAndThemMemories = youAndThemFiles
- .map((f) => Memory.fromFile(f, seenTimes))
- .toList(growable: false);
- final youAndThemList =
- personToCandidates.putIfAbsent(personID, () => {}).putIfAbsent(
- PeopleMemoryType.youAndThem,
- () => <PeopleMemoryCandidate>[],
- );
- youAndThemList.add(
- PeopleMemoryCandidate(
- personID: personID,
- personName: personName,
- type: PeopleMemoryType.youAndThem,
- rawMemories: youAndThemMemories,
- firstDateToShow: nowInMicroseconds,
- lastDateToShow: windowEnd,
- selectionBuilder: selectPeopleMemories,
- ),
- );
- }
- w?.log('youAndThem setup');
- }
-
- // Inside people loop, check for doingSomethingTogether
- if (isMeAssigned && meID != personID) {
- final vectors = _getEmbeddingsForFileIDs(
- fileIDToImageEmbedding,
- personFileIDs,
- );
- w?.log('getting clip vectors for doingSomethingTogether');
- final activityFiles = <EnteFile>[];
- for (final activity in PeopleActivity.values) {
- activityFiles.clear();
- final Vector? activityVector = clipPeopleActivityVectors[activity];
- if (activityVector == null) {
- dev.log("No vector for activity $activity");
- continue;
- }
- final Map<int, double> similarities = {};
- for (final embedding in vectors) {
- similarities[embedding.fileID] =
- embedding.vector.dot(activityVector);
- }
- w?.log(
- 'comparing embeddings for doingSomethingTogether and $activity',
- );
- for (final fileID in personFileIDs) {
- final similarity = similarities[fileID];
- if (similarity == null) continue;
- if (similarity > _clipActivityQueryThreshold) {
- final file = allFileIdsToFile[fileID];
- if (file != null) {
- activityFiles.add(file);
- }
- }
- }
- if (activityFiles.length > minimumMemoryLength) {
- final activityMemories = activityFiles
- .map((f) => Memory.fromFile(f, seenTimes))
- .toList(growable: false);
- final activityList =
- personToCandidates.putIfAbsent(personID, () => {}).putIfAbsent(
- PeopleMemoryType.doingSomethingTogether,
- () => <PeopleMemoryCandidate>[],
- );
- activityList.add(
- PeopleMemoryCandidate(
- personID: personID,
- personName: personName,
- type: PeopleMemoryType.doingSomethingTogether,
- rawMemories: activityMemories,
- firstDateToShow: nowInMicroseconds,
- lastDateToShow: windowEnd,
- activity: activity,
- selectionBuilder: selectPeopleMemories,
- ),
- );
- }
- }
-
- w?.log('doingSomethingTogether setup');
- }
-
- // Inside people loop, check for lastTimeYouSawThem
- final lastTimeYouSawThemFiles = <EnteFile>[];
- int lastCreationTime = 0;
- bool longAgo = true;
- for (final fileID in personFileIDs) {
- final file = allFileIdsToFile[fileID];
- if (file != null && file.creationTime != null) {
- final creationTime = file.creationTime!;
- final creationDateTime =
- DateTime.fromMicrosecondsSinceEpoch(creationTime);
- if (currentTime.difference(creationDateTime).inDays < 365) {
- longAgo = false;
- break;
- }
- if (creationTime > lastCreationTime - microSecondsInDay) {
- final lastDateTime =
- DateTime.fromMicrosecondsSinceEpoch(lastCreationTime);
- if (creationDateTime.difference(lastDateTime).inHours > 24) {
- lastTimeYouSawThemFiles.clear();
- }
- if (creationTime > lastCreationTime) {
- lastCreationTime = creationTime;
- }
- lastTimeYouSawThemFiles.add(file);
- }
- }
- }
- if (longAgo && lastTimeYouSawThemFiles.length >= 2 && meID != personID) {
- final lastTimeMemories = lastTimeYouSawThemFiles
- .map((f) => Memory.fromFile(f, seenTimes))
- .toList();
- lastTimeMemories.sort(
- (a, b) => a.file.creationTime!.compareTo(b.file.creationTime!),
- );
- final filteredLastTimeMemories = _filterNearDuplicates(
- lastTimeMemories,
- fileIDToImageEmbedding,
- minKeep: 2,
- isOfflineMode: isOfflineMode,
- );
- final spacedLastTimeMemories = _filterByTimeSpacing(
- filteredLastTimeMemories,
- );
- final lastTimeList =
- personToCandidates.putIfAbsent(personID, () => {}).putIfAbsent(
- PeopleMemoryType.lastTimeYouSawThem,
- () => <PeopleMemoryCandidate>[],
- );
- lastTimeList.add(
- PeopleMemoryCandidate(
- personID: personID,
- personName: personName,
- type: PeopleMemoryType.lastTimeYouSawThem,
- rawMemories: spacedLastTimeMemories,
- firstDateToShow: nowInMicroseconds,
- lastDateToShow: windowEnd,
- lastCreationTime: lastCreationTime,
- requiresSelection: false,
- ),
- );
- }
- w?.log('lastTimeYouSawThem setup');
- }
-
- // Surface everything just for debug checking
- if (surfaceAll) {
- for (final personCandidates in personToCandidates.values) {
- for (final candidateList in personCandidates.values) {
- for (final candidate in candidateList) {
- final memory = await candidate.realize();
- if (memory != null) {
- memoryResults.add(memory);
- }
- }
- }
- }
- for (final candidate in unnamedClusterCandidates) {
- final memory = await candidate.realize();
- if (memory != null) {
- memoryResults.add(memory);
- }
- }
- return memoryResults;
- }
-
- // Loop through the people and check if we should surface anything based on relevancy (bday, last met)
- for (final personID in orderedImportantPersonsID) {
- final personCandidates = personToCandidates[personID];
- if (personCandidates == null) continue;
- final person = personIdToPerson[personID]!;
-
- // Check if we should surface memory based on last met
- final lastMetCandidate =
- personCandidates[PeopleMemoryType.lastTimeYouSawThem]?.first;
- if (lastMetCandidate != null &&
- lastMetCandidate.lastCreationTime != null) {
- final lastMetTime = DateTime.fromMicrosecondsSinceEpoch(
- lastMetCandidate.lastCreationTime!,
- ).copyWith(year: currentTime.year);
- final daysSinceLastMet = lastMetTime.difference(currentTime).inDays;
- if (daysSinceLastMet < 7 && daysSinceLastMet >= 0) {
- final lastMetMemory = await lastMetCandidate.realize();
- if (lastMetMemory != null) {
- memoryResults.add(lastMetMemory);
- }
- }
- }
-
- // Check if we should surface memory based on birthday
- final birthdate = DateTime.tryParse(person.data.birthDate ?? "");
- if (birthdate != null) {
- final thisBirthday =
- DateTime(currentTime.year, birthdate.month, birthdate.day);
- final daysTillBirthday = thisBirthday.difference(currentTime).inDays;
- if (daysTillBirthday < 6 && daysTillBirthday >= 0) {
- final int newAge = currentTime.year - birthdate.year;
- final spotlightCandidate =
- personCandidates[PeopleMemoryType.spotlight]?.first;
- if (spotlightCandidate != null &&
- spotlightCandidate.personName != null) {
- final spotlightMem = await spotlightCandidate.realize();
- if (spotlightMem != null) {
- final thisBirthday = birthdate.copyWith(year: currentTime.year);
- memoryResults.add(
- spotlightMem.copyWith(
- isBirthday: false,
- newAge: newAge,
- firstDateToShow: thisBirthday
- .subtract(const Duration(days: 5))
- .microsecondsSinceEpoch,
- lastDateToShow: thisBirthday.microsecondsSinceEpoch,
- ),
- );
- memoryResults.add(
- spotlightMem.copyWith(
- isBirthday: true,
- newAge: newAge,
- firstDateToShow: thisBirthday.microsecondsSinceEpoch,
- lastDateToShow:
- thisBirthday.add(kDayItself).microsecondsSinceEpoch,
- ),
- );
- }
- }
- final youAndThemCandidate =
- personCandidates[PeopleMemoryType.youAndThem]?.first;
- if (youAndThemCandidate != null) {
- final youAndThemMem = await youAndThemCandidate.realize();
- if (youAndThemMem != null) {
- memoryResults.add(
- youAndThemMem.copyWith(
- isBirthday: false,
- newAge: newAge,
- firstDateToShow: thisBirthday
- .subtract(const Duration(days: 5))
- .microsecondsSinceEpoch,
- lastDateToShow: thisBirthday.microsecondsSinceEpoch,
- ),
- );
- memoryResults.add(
- youAndThemMem.copyWith(
- isBirthday: true,
- newAge: newAge,
- firstDateToShow: thisBirthday.microsecondsSinceEpoch,
- lastDateToShow:
- thisBirthday.add(kDayItself).microsecondsSinceEpoch,
- ),
- );
- }
- }
- }
- }
- }
- w?.log('relevancy setup');
-
- // Loop through the people (and memory types) and add based on rotation
- final shownPersonAndTypeTimeout =
- Duration(days: shownPersonTimeout.inDays * 2);
- bool addedFromRotation = false;
- peopleRotationLoop:
- for (final personID in orderedImportantPersonsID) {
- for (final memory in memoryResults) {
- if (memory.personID == personID) {
- continue peopleRotationLoop;
- }
- }
- for (final shownLog in shownPeople) {
- if (shownLog.personID != personID) continue;
- final shownDate =
- DateTime.fromMicrosecondsSinceEpoch(shownLog.lastTimeShown);
- final bool seenPersonRecently =
- currentTime.difference(shownDate) < shownPersonTimeout;
- if (seenPersonRecently) continue peopleRotationLoop;
- }
- final personCandidates = personToCandidates[personID];
- if (personCandidates == null) continue peopleRotationLoop;
- int added = 0;
- final amountOfMemoryTypesForPerson = personCandidates.length;
- final bool manyMemoryTypes = amountOfMemoryTypesForPerson > 2;
- potentialMemoryLoop:
- for (final candidatesForCategory in personCandidates.values) {
- if (candidatesForCategory.isEmpty) continue;
- PeopleMemoryCandidate potentialCandidate = candidatesForCategory.first;
- if (candidatesForCategory.length > 1) {
- if (potentialCandidate.type !=
- PeopleMemoryType.doingSomethingTogether) {
- dev.log(
- 'Something is going wrong, ${potentialCandidate.type} has multiple memories for same person',
- );
- } else {
- final randIdx = Random().nextInt(candidatesForCategory.length);
- potentialCandidate = candidatesForCategory[randIdx];
- }
- }
- for (final shownLog in shownPeople) {
- if (shownLog.personID != personID) continue;
- if (shownLog.peopleMemoryType != potentialCandidate.type) {
- continue;
- }
- final shownTypeDate =
- DateTime.fromMicrosecondsSinceEpoch(shownLog.lastTimeShown);
- final bool seenPersonTypeRecently =
- currentTime.difference(shownTypeDate) < shownPersonAndTypeTimeout;
- if (manyMemoryTypes && seenPersonTypeRecently) {
- continue potentialMemoryLoop;
- }
- }
- final potentialMemory = await potentialCandidate.realize();
- if (potentialMemory == null) continue;
- memoryResults.add(potentialMemory);
- addedFromRotation = true;
- added++;
- if (added >= 2) break peopleRotationLoop;
- }
- if (added > 0) break peopleRotationLoop;
- }
- if (!addedFromRotation && canUseUnnamedFallback) {
- final eligibleUnnamedCandidates = <PeopleMemoryCandidate>[];
- for (final candidate in randomizedUnnamedClusterCandidates) {
- final candidatePersonID = candidate.personID;
- bool alreadyInResults = false;
- for (final memory in memoryResults) {
- if (memory.personID == candidatePersonID) {
- alreadyInResults = true;
- break;
- }
- }
- if (alreadyInResults) {
- continue;
- }
- if (_wasPersonShownRecently(
- personID: candidatePersonID,
- shownPeople: shownPeople,
- currentTime: currentTime,
- shownPersonTimeout: shownPersonTimeout,
- )) {
- continue;
- }
- eligibleUnnamedCandidates.add(candidate);
- }
- final orderedEligibleUnnamedCandidates =
- _orderUnnamedCandidatesByRecencyAndRandom(
- candidates: eligibleUnnamedCandidates,
- shownPeople: shownPeople,
- currentTime: currentTime,
- shownPersonTimeout: shownPersonTimeout,
- );
- for (final candidate in orderedEligibleUnnamedCandidates) {
- final potentialMemory = await candidate.realize();
- if (potentialMemory == null) {
- continue;
- }
- memoryResults.add(potentialMemory);
- break;
- }
- }
- w?.log('rotation setup');
-
- return memoryResults;
}
static Future<List<ClipMemory>> _getClipResults(
@@ -1519,125 +1033,16 @@ class SmartMemoriesService {
required Map<int, EmbeddingVector> fileIDToImageEmbedding,
required Map<ClipMemoryType, Vector> clipMemoryTypeVectors,
}) async {
- final w = (kDebugMode ? EnteWatch('getClipResults') : null)?..start();
- final List<ClipMemory> clipResults = [];
- if (allFiles.isEmpty) return [];
- final nowInMicroseconds = currentTime.microsecondsSinceEpoch;
- final windowEnd =
- currentTime.add(kMemoriesUpdateFrequency).microsecondsSinceEpoch;
- w?.log('allFiles setup');
-
- ClipMemory? buildClipMemory(ClipMemoryType clipMemoryType) {
- final Vector? activityVector = clipMemoryTypeVectors[clipMemoryType];
- if (activityVector == null) {
- dev.log("No vector for clipMemoryType $clipMemoryType");
- return null;
- }
- final Map<int, double> similarities = {};
- for (final entry in fileIDToImageEmbedding.entries) {
- similarities[entry.key] = entry.value.vector.dot(activityVector);
- }
- w?.log(
- 'comparing embeddings for clipMemoryType $clipMemoryType',
- );
- final List<EnteFile> clipFiles = [];
- for (final file in allFiles) {
- final memoryFileID = _memoryFileId(file, isOfflineMode: isOfflineMode);
- if (memoryFileID == null) continue;
- final similarity = similarities[memoryFileID];
- if (similarity == null) continue;
- if (similarity > _clipMemoryTypeQueryThreshold) {
- clipFiles.add(file);
- }
- }
- if (clipFiles.length < 10) return null;
- // sort based on highest similarity first
- clipFiles.sort((a, b) {
- final int bFileID = _memoryFileId(b, isOfflineMode: isOfflineMode)!;
- final int aFileID = _memoryFileId(a, isOfflineMode: isOfflineMode)!;
- return similarities[bFileID]!.compareTo(similarities[aFileID]!);
- });
- final int limit = min(clipFiles.length, 50);
- final List<EnteFile> topCandidates = clipFiles.take(limit).toList();
- topCandidates.shuffle(Random());
- final List<EnteFile> selected = [];
- final selectedFileIDs = <int>[];
- final selectedCreationTimes = <int>[];
- int skipped = 0;
- for (final file in topCandidates) {
- if (selected.length >= 10) break;
- final fileID = _memoryFileId(file, isOfflineMode: isOfflineMode);
- if (fileID == null) continue;
- final creationTime = file.creationTime;
- if (_isTooCloseInTime(
- creationTime,
- selectedCreationTimes,
- )) {
- skipped++;
- continue;
- }
- if (_isNearDuplicate(
- fileID,
- selectedFileIDs,
- fileIDToImageEmbedding,
- ) &&
- (topCandidates.length - skipped) > 10) {
- skipped++;
- continue;
- }
- selected.add(file);
- selectedFileIDs.add(fileID);
- if (creationTime != null) {
- selectedCreationTimes.add(creationTime);
- }
- }
- selected.sort((a, b) {
- final int bFileID = _memoryFileId(b, isOfflineMode: isOfflineMode)!;
- final int aFileID = _memoryFileId(a, isOfflineMode: isOfflineMode)!;
- return similarities[bFileID]!.compareTo(similarities[aFileID]!);
- });
- return ClipMemory(
- selected.map((f) => Memory.fromFile(f, seenTimes)).toList(),
- nowInMicroseconds,
- windowEnd,
- clipMemoryType,
- );
- }
-
- // Surface everything just for debug checking
- if (surfaceAll) {
- for (final clipMemoryType in ClipMemoryType.values) {
- final clipMemory = buildClipMemory(clipMemoryType);
- if (clipMemory != null) clipResults.add(clipMemory);
- }
- return clipResults;
- }
-
- final List<ClipMemoryType> rotationOrder = [...ClipMemoryType.values]
- ..shuffle();
- final List<ClipMemoryType> eligibleClipTypes = [];
-
- clipMemoriesLoop:
- for (final clipMemoryType in rotationOrder) {
- for (final shownLog in shownClip) {
- if (shownLog.clipMemoryType != clipMemoryType) continue;
- final shownDate =
- DateTime.fromMicrosecondsSinceEpoch(shownLog.lastTimeShown);
- final bool seenRecently =
- currentTime.difference(shownDate) < kClipShowTimeout;
- if (seenRecently) continue clipMemoriesLoop;
- }
- eligibleClipTypes.add(clipMemoryType);
- }
-
- for (final clipMemoryType in eligibleClipTypes) {
- final clipMemory = buildClipMemory(clipMemoryType);
- if (clipMemory == null) continue;
- clipResults.add(clipMemory);
- break;
- }
-
- return clipResults;
+ return ClipMemoriesCalculator.compute(
+ allFiles,
+ currentTime,
+ shownClip,
+ surfaceAll: surfaceAll,
+ isOfflineMode: isOfflineMode,
+ seenTimes: seenTimes,
+ fileIDToImageEmbedding: fileIDToImageEmbedding,
+ clipMemoryTypeVectors: clipMemoryTypeVectors,
+ );
}
static Future<(List<TripMemory>, List<BaseLocation>)> _getTripsResults(
@@ -1654,446 +1059,20 @@ class SmartMemoriesService {
required Vector clipPositiveTextVector,
required List<City> cities,
}) async {
- final List<TripMemory> memoryResults = [];
- if (allFiles.isEmpty) return (<TripMemory>[], <BaseLocation>[]);
- final nowInMicroseconds = currentTime.microsecondsSinceEpoch;
- final windowEnd =
- currentTime.add(kMemoriesUpdateFrequency).microsecondsSinceEpoch;
- final currentMonth = currentTime.month;
- final cutOffTime = currentTime.subtract(const Duration(days: 365));
-
- const tripRadius = 100.0;
- const overlapRadius = 10.0;
-
- final List<(List<EnteFile>, Location)> smallRadiusClusters = [];
- final List<(List<EnteFile>, Location)> wideRadiusClusters = [];
- // Go through all files and cluster (incremental clustering)
- for (EnteFile file in allFiles) {
- if (!file.hasLocation) continue;
- // Small radius clustering for base locations
- bool addedToExistingSmallCluster = false;
- for (final cluster in smallRadiusClusters) {
- final clusterLocation = cluster.$2;
- if (isFileInsideLocationTag(
- clusterLocation,
- file.location!,
- baseRadius,
- )) {
- cluster.$1.add(file);
- addedToExistingSmallCluster = true;
- break;
- }
- }
- if (!addedToExistingSmallCluster) {
- smallRadiusClusters.add(([file], file.location!));
- }
- // Wide radius clustering for trip locations
- bool addedToExistingWideCluster = false;
- for (final cluster in wideRadiusClusters) {
- final clusterLocation = cluster.$2;
- if (isFileInsideLocationTag(
- clusterLocation,
- file.location!,
- tripRadius,
- )) {
- cluster.$1.add(file);
- addedToExistingWideCluster = true;
- break;
- }
- }
- if (!addedToExistingWideCluster) {
- wideRadiusClusters.add(([file], file.location!));
- }
- }
-
- // Identify base locations
- final List<BaseLocation> baseLocations = [];
- for (final cluster in smallRadiusClusters) {
- final files = cluster.$1;
- final location = cluster.$2;
- // Check that the photos are distributed over a longer time range (3+ months)
- final creationTimes = <int>[];
- final Set<int> uniqueDays = {};
- for (final file in files) {
- creationTimes.add(file.creationTime!);
- final date = DateTime.fromMicrosecondsSinceEpoch(file.creationTime!);
- final dayStamp =
- DateTime(date.year, date.month, date.day).microsecondsSinceEpoch;
- uniqueDays.add(dayStamp);
- }
- creationTimes.sort();
- if (creationTimes.length < 10) continue;
- final firstCreationTime = DateTime.fromMicrosecondsSinceEpoch(
- creationTimes.first,
- );
- final lastCreationTime = DateTime.fromMicrosecondsSinceEpoch(
- creationTimes.last,
- );
- final daysRange = lastCreationTime.difference(firstCreationTime).inDays;
- if (daysRange < 90) {
- continue;
- }
- // Check for a minimum average number of days photos are clicked in range
- if (uniqueDays.length < daysRange * 0.1) continue;
- // Check that there isn't a huge time gap somewhere in the range
- final int gapThreshold = (daysRange * 0.6).round() * microSecondsInDay;
- int maxGap = 0;
- for (int i = 1; i < creationTimes.length; i++) {
- final gap = creationTimes[i] - creationTimes[i - 1];
- if (gap > maxGap) maxGap = gap;
- }
- if (maxGap > gapThreshold) continue;
- // Check if it's a current or old base location
- final bool isCurrent = lastCreationTime.isAfter(
- DateTime.now().subtract(
- const Duration(days: 90),
- ),
- );
- baseLocations.add(
- BaseLocation(
- files
- .map(
- (file) => _memoryFileId(
- file,
- isOfflineMode: isOfflineMode,
- ),
- )
- .whereType<int>()
- .toList(),
- location,
- isCurrent,
- ),
- );
- }
-
- // Identify trip locations
- final List<TripMemory> tripLocations = [];
- clusteredLocations:
- for (final cluster in wideRadiusClusters) {
- final files = cluster.$1;
- final location = cluster.$2;
- // Check that it's at least 10km away from any base or tag location
- for (final baseLocation in baseLocations) {
- if (isFileInsideLocationTag(
- baseLocation.location,
- location,
- overlapRadius,
- )) {
- continue clusteredLocations;
- }
- }
-
- // Check that the photos are distributed over a short time range (2-30 days) or multiple short time ranges only
- files.sort((a, b) => a.creationTime!.compareTo(b.creationTime!));
- // Find distinct time blocks (potential trips)
- List<EnteFile> currentBlockFiles = [files.first];
- int blockStart = files.first.creationTime!;
- int lastTime = files.first.creationTime!;
- DateTime lastDateTime = DateTime.fromMicrosecondsSinceEpoch(lastTime);
-
- for (int i = 1; i < files.length; i++) {
- final currentFile = files[i];
- final currentTime = currentFile.creationTime!;
- final gap = DateTime.fromMicrosecondsSinceEpoch(currentTime)
- .difference(lastDateTime)
- .inDays;
-
- // If gap is too large, end current block and check if it's a valid trip
- if (gap > 15) {
- // 10 days gap to separate trips. If gap is small, it's likely not a trip
- if (gap < 90) continue clusteredLocations;
-
- final blockDuration = lastDateTime
- .difference(DateTime.fromMicrosecondsSinceEpoch(blockStart))
- .inDays;
-
- // Check if current block is a valid trip (2-30 days)
- if (blockDuration >= 2 && blockDuration <= 30) {
- tripLocations.add(
- TripMemory(
- Memory.fromFiles(
- currentBlockFiles,
- seenTimes,
- ),
- 0,
- 0,
- location,
- firstCreationTime: blockStart,
- lastCreationTime: lastTime,
- ),
- );
- }
-
- // Start new block
- currentBlockFiles = [];
- blockStart = currentTime;
- }
-
- currentBlockFiles.add(currentFile);
- lastTime = currentTime;
- lastDateTime = DateTime.fromMicrosecondsSinceEpoch(lastTime);
- }
- // Check final block
- final lastBlockDuration = lastDateTime
- .difference(DateTime.fromMicrosecondsSinceEpoch(blockStart))
- .inDays;
- if (lastBlockDuration >= 2 && lastBlockDuration <= 30) {
- tripLocations.add(
- TripMemory(
- Memory.fromFiles(currentBlockFiles, seenTimes),
- 0,
- 0,
- location,
- firstCreationTime: blockStart,
- lastCreationTime: lastTime,
- ),
- );
- }
- }
-
- // Check if any trip locations should be merged
- final List<TripMemory> mergedTrips = [];
- for (final trip in tripLocations) {
- final tripFirstTime = DateTime.fromMicrosecondsSinceEpoch(
- trip.firstCreationTime!,
- );
- final tripLastTime = DateTime.fromMicrosecondsSinceEpoch(
- trip.lastCreationTime!,
- );
- bool merged = false;
- for (int idx = 0; idx < mergedTrips.length; idx++) {
- final otherTrip = mergedTrips[idx];
- final otherTripFirstTime =
- DateTime.fromMicrosecondsSinceEpoch(otherTrip.firstCreationTime!);
- final otherTripLastTime =
- DateTime.fromMicrosecondsSinceEpoch(otherTrip.lastCreationTime!);
- if (tripFirstTime
- .isBefore(otherTripLastTime.add(const Duration(days: 3))) &&
- tripLastTime.isAfter(
- otherTripFirstTime.subtract(const Duration(days: 3)),
- )) {
- mergedTrips[idx] = TripMemory(
- otherTrip.memories + trip.memories,
- 0,
- 0,
- otherTrip.location,
- firstCreationTime:
- min(otherTrip.firstCreationTime!, trip.firstCreationTime!),
- lastCreationTime:
- max(otherTrip.lastCreationTime!, trip.lastCreationTime!),
- );
- dev.log('Merged two trip locations');
- merged = true;
- break;
- }
- }
- if (merged) continue;
- mergedTrips.add(
- TripMemory(
- trip.memories,
- 0,
- 0,
- trip.location,
- firstCreationTime: trip.firstCreationTime,
- lastCreationTime: trip.lastCreationTime,
- ),
- );
- }
-
- // Remove too small and too recent trips
- final List<TripMemory> validTrips = [];
- for (final trip in mergedTrips) {
- if (trip.memories.length >= 20 &&
- trip.averageCreationTime() < cutOffTime.microsecondsSinceEpoch) {
- validTrips.add(trip);
- }
- }
-
- // For now for testing let's just surface all base locations
- // For now surface these on the location section TODO: lau: remove internal flag title
- if (surfaceAll) {
- for (final baseLocation in baseLocations) {
- String name =
- "Base (${baseLocation.isCurrentBase ? 'current' : 'old'})";
- final files = baseLocation.fileIDs
- .map((fileID) => allFileIdsToFile[fileID]!)
- .toList();
- final String? locationName = _tryFindLocationName(
- Memory.fromFiles(files, seenTimes),
- cities,
- base: true,
- );
- if (locationName != null) {
- name =
- "$locationName (Base, ${baseLocation.isCurrentBase ? 'current' : 'old'})";
- }
- memoryResults.add(
- TripMemory(
- Memory.fromFiles(files, seenTimes),
- nowInMicroseconds,
- windowEnd,
- baseLocation.location,
- locationName: name,
- ),
- );
- }
- for (final trip in validTrips) {
- final year = DateTime.fromMicrosecondsSinceEpoch(
- trip.averageCreationTime(),
- ).year;
- final String? locationName =
- _tryFindLocationName(trip.memories, cities);
- final photoSelection = await _bestSelection(
- trip.memories,
- isOfflineMode: isOfflineMode,
- fileIdToFaces: fileIdToFaces,
- faceIDsToPersonID: faceIDsToPersonID,
- fileIDToImageEmbedding: fileIDToImageEmbedding,
- clipPositiveTextVector: clipPositiveTextVector,
- );
- memoryResults.add(
- trip.copyWith(
- memories: photoSelection,
- tripYear: year,
- locationName: locationName,
- firstDateToShow: nowInMicroseconds,
- lastDateToShow: windowEnd,
- ),
- );
- }
- return (memoryResults, baseLocations);
- }
-
- // For now we surface the two most recent trips of current month, and if none, the earliest upcoming redundant trip
- // Group the trips per month and then year
- final Map<int, Map<int, List<TripMemory>>> tripsByMonthYear = {};
- for (final trip in validTrips) {
- final tripDate =
- DateTime.fromMicrosecondsSinceEpoch(trip.averageCreationTime());
- tripsByMonthYear
- .putIfAbsent(tripDate.month, () => {})
- .putIfAbsent(tripDate.year, () => [])
- .add(trip);
- }
-
- // Flatten trips for the current month and annotate with their average date.
- final List<TripMemory> currentMonthTrips = [];
- if (tripsByMonthYear.containsKey(currentMonth)) {
- for (final trips in tripsByMonthYear[currentMonth]!.values) {
- for (final trip in trips) {
- currentMonthTrips.add(trip);
- }
- }
- }
-
- // If there are past trips this month, show the one or two most recent ones.
- if (currentMonthTrips.isNotEmpty) {
- currentMonthTrips.sort(
- (a, b) => b.averageCreationTime().compareTo(a.averageCreationTime()),
- );
- final tripsToShow = currentMonthTrips.take(2);
- for (final trip in tripsToShow) {
- final year =
- DateTime.fromMicrosecondsSinceEpoch(trip.averageCreationTime())
- .year;
- final String? locationName =
- _tryFindLocationName(trip.memories, cities);
- final photoSelection = await _bestSelection(
- trip.memories,
- isOfflineMode: isOfflineMode,
- fileIdToFaces: fileIdToFaces,
- faceIDsToPersonID: faceIDsToPersonID,
- fileIDToImageEmbedding: fileIDToImageEmbedding,
- clipPositiveTextVector: clipPositiveTextVector,
- );
- final firstCreationDate = DateTime.fromMicrosecondsSinceEpoch(
- trip.firstCreationTime!,
- );
- final firstDateToShow = DateTime(
- currentTime.year,
- firstCreationDate.month,
- firstCreationDate.day,
- ).subtract(kMemoriesMargin).microsecondsSinceEpoch;
- final lastCreationDate = DateTime.fromMicrosecondsSinceEpoch(
- trip.lastCreationTime!,
- );
- final lastDateToShow = DateTime(
- currentTime.year,
- lastCreationDate.month,
- lastCreationDate.day,
- ).add(kMemoriesMargin).microsecondsSinceEpoch;
- memoryResults.add(
- trip.copyWith(
- memories: photoSelection,
- tripYear: year,
- locationName: locationName,
- firstDateToShow: firstDateToShow,
- lastDateToShow: lastDateToShow,
- ),
- );
- }
- }
- // Otherwise, if no trips happened in the current month,
- // look for the earliest upcoming trip in another month that has 3+ trips.
- else {
- final sortedUpcomingMonths =
- List<int>.generate(6, (i) => ((currentMonth + i) % 12) + 1);
- checkUpcomingMonths:
- for (final month in sortedUpcomingMonths) {
- if (tripsByMonthYear.containsKey(month)) {
- final List<TripMemory> thatMonthTrips = [];
- for (final trips in tripsByMonthYear[month]!.values) {
- thatMonthTrips.addAll(trips);
- }
- if (thatMonthTrips.length >= 3) {
- // take and use the third earliest trip
- thatMonthTrips.sort(
- (a, b) =>
- a.averageCreationTime().compareTo(b.averageCreationTime()),
- );
- checkPotentialTrips:
- for (final trip in thatMonthTrips.sublist(2)) {
- for (final shownTrip in shownTrips) {
- final distance =
- calculateDistance(trip.location, shownTrip.location);
- final shownTripDate = DateTime.fromMicrosecondsSinceEpoch(
- shownTrip.lastTimeShown,
- );
- final shownRecently =
- currentTime.difference(shownTripDate) < kTripShowTimeout;
- if (distance < overlapRadius && shownRecently) {
- continue checkPotentialTrips;
- }
- }
- final year = DateTime.fromMicrosecondsSinceEpoch(
- trip.averageCreationTime(),
- ).year;
- final String? locationName =
- _tryFindLocationName(trip.memories, cities);
- final photoSelection = await _bestSelection(
- trip.memories,
- isOfflineMode: isOfflineMode,
- fileIdToFaces: fileIdToFaces,
- faceIDsToPersonID: faceIDsToPersonID,
- fileIDToImageEmbedding: fileIDToImageEmbedding,
- clipPositiveTextVector: clipPositiveTextVector,
- );
- memoryResults.add(
- trip.copyWith(
- memories: photoSelection,
- tripYear: year,
- locationName: locationName,
- firstDateToShow: nowInMicroseconds,
- lastDateToShow: windowEnd,
- ),
- );
- break checkUpcomingMonths;
- }
- }
- }
- }
- }
- return (memoryResults, baseLocations);
+ return TripMemoriesCalculator.compute(
+ allFiles,
+ allFileIdsToFile,
+ currentTime,
+ shownTrips,
+ surfaceAll: surfaceAll,
+ isOfflineMode: isOfflineMode,
+ seenTimes: seenTimes,
+ fileIdToFaces: fileIdToFaces,
+ faceIDsToPersonID: faceIDsToPersonID,
+ fileIDToImageEmbedding: fileIDToImageEmbedding,
+ clipPositiveTextVector: clipPositiveTextVector,
+ cities: cities,
+ );
}
static Future<List<TimeMemory>> _onThisDayOrWeekResults(
@@ -2106,251 +1085,16 @@ class SmartMemoriesService {
required Map<int, EmbeddingVector> fileIDToImageEmbedding,
required Vector clipPositiveTextVector,
}) async {
- final List<TimeMemory> memoryResult = [];
- if (allFiles.isEmpty) return [];
-
- final currentDayMonth = currentTime.month * 100 + currentTime.day;
- final currentWeek = _getWeekNumber(currentTime);
- final currentMonth = currentTime.month;
- final currentYear = currentTime.year;
- final cutOffTime = currentTime.subtract(const Duration(days: 365));
- final averageDailyPhotos = allFiles.length / 365;
- final significantDayThreshold = averageDailyPhotos * 0.25;
- final significantWeekThreshold = averageDailyPhotos * 0.40;
-
- // Group files by day-month and year
- final dayMonthYearGroups = <int, Map<int, List<Memory>>>{};
-
- for (final file in allFiles) {
- if (file.creationTime! > cutOffTime.microsecondsSinceEpoch) continue;
-
- final creationTime =
- DateTime.fromMicrosecondsSinceEpoch(file.creationTime!);
- final dayMonth = creationTime.month * 100 + creationTime.day;
- final year = creationTime.year;
-
- dayMonthYearGroups
- .putIfAbsent(dayMonth, () => {})
- .putIfAbsent(year, () => [])
- .add(Memory.fromFile(file, seenTimes));
- }
-
- // Process each nearby day-month to find significant days
- for (final dayMonth in dayMonthYearGroups.keys) {
- final dayDiff = dayMonth - currentDayMonth;
- if (dayDiff < 0 || dayDiff > kMemoriesUpdateFrequency.inDays) continue;
- // TODO: lau: this doesn't cover month changes properly
-
- final yearGroups = dayMonthYearGroups[dayMonth]!;
- final significantDays = yearGroups.entries
- .where((e) => e.value.length > significantDayThreshold)
- .map((e) => e.key)
- .toList();
-
- if (significantDays.length >= 3) {
- // Combine all years for this day-month
- final date =
- DateTime(currentTime.year, dayMonth ~/ 100, dayMonth % 100);
- final allPhotos = yearGroups.values.expand((x) => x).toList();
- final photoSelection = await _bestSelection(
- allPhotos,
- isOfflineMode: isOfflineMode,
- fileIdToFaces: fileIdToFaces,
- faceIDsToPersonID: faceIDsToPersonID,
- fileIDToImageEmbedding: fileIDToImageEmbedding,
- clipPositiveTextVector: clipPositiveTextVector,
- );
-
- memoryResult.add(
- TimeMemory(
- photoSelection,
- day: date,
- date.subtract(kMemoriesMargin).microsecondsSinceEpoch,
- date.add(kDayItself).microsecondsSinceEpoch,
- ),
- );
- } else {
- // Individual entries for significant years
- for (final year in significantDays) {
- final date = DateTime(year, dayMonth ~/ 100, dayMonth % 100);
- final showDate =
- DateTime(currentYear, dayMonth ~/ 100, dayMonth % 100);
- final files = yearGroups[year]!;
- final photoSelection = await _bestSelection(
- files,
- isOfflineMode: isOfflineMode,
- fileIdToFaces: fileIdToFaces,
- faceIDsToPersonID: faceIDsToPersonID,
- fileIDToImageEmbedding: fileIDToImageEmbedding,
- clipPositiveTextVector: clipPositiveTextVector,
- );
- memoryResult.add(
- TimeMemory(
- photoSelection,
- day: date,
- yearsAgo: currentTime.year - date.year,
- showDate.subtract(kMemoriesMargin).microsecondsSinceEpoch,
- showDate.add(kDayItself).microsecondsSinceEpoch,
- ),
- );
- }
- }
- }
-
- // process to find significant weeks (only if there are no significant days)
- if (memoryResult.isEmpty) {
- // Group files by week and year
- final currentWeekYearGroups = <int, List<Memory>>{};
- for (final file in allFiles) {
- if (file.creationTime! > cutOffTime.microsecondsSinceEpoch) continue;
-
- final creationTime =
- DateTime.fromMicrosecondsSinceEpoch(file.creationTime!);
- final week = _getWeekNumber(creationTime);
- if (week != currentWeek) continue;
- final year = creationTime.year;
-
- currentWeekYearGroups
- .putIfAbsent(year, () => [])
- .add(Memory.fromFile(file, seenTimes));
- }
-
- // Process the week and see if it's significant
- if (currentWeekYearGroups.isNotEmpty) {
- final significantWeeks = currentWeekYearGroups.entries
- .where((e) => e.value.length > significantWeekThreshold)
- .map((e) => e.key)
- .toList();
- if (significantWeeks.length >= 3) {
- // Combine all years for this week
- final allPhotos =
- currentWeekYearGroups.values.expand((x) => x).toList();
- final photoSelection = await _bestSelection(
- allPhotos,
- isOfflineMode: isOfflineMode,
- fileIdToFaces: fileIdToFaces,
- faceIDsToPersonID: faceIDsToPersonID,
- fileIDToImageEmbedding: fileIDToImageEmbedding,
- clipPositiveTextVector: clipPositiveTextVector,
- );
- // const name = "This week through the years";
- memoryResult.add(
- TimeMemory(
- photoSelection,
- currentTime.subtract(kMemoriesMargin).microsecondsSinceEpoch,
- currentTime.add(kMemoriesUpdateFrequency).microsecondsSinceEpoch,
- ),
- );
- } else {
- // Individual entries for significant years
- for (final year in significantWeeks) {
- final date = DateTime(year, 1, 1).add(
- Duration(days: (currentWeek - 1) * 7),
- );
- final files = currentWeekYearGroups[year]!;
- final photoSelection = await _bestSelection(
- files,
- isOfflineMode: isOfflineMode,
- fileIdToFaces: fileIdToFaces,
- faceIDsToPersonID: faceIDsToPersonID,
- fileIDToImageEmbedding: fileIDToImageEmbedding,
- clipPositiveTextVector: clipPositiveTextVector,
- );
- memoryResult.add(
- TimeMemory(
- photoSelection,
- yearsAgo: currentTime.year - date.year,
- currentTime.subtract(kMemoriesMargin).microsecondsSinceEpoch,
- currentTime
- .add(kMemoriesUpdateFrequency)
- .microsecondsSinceEpoch,
- ),
- );
- }
- }
- }
- }
-
- // process to find months memories
- const monthSelectionSize = 20;
-
- // Group files by month and year
- final currentMonthYearGroups = <int, List<Memory>>{};
- _deductUsedMemories(allFiles, memoryResult);
- for (final file in allFiles) {
- if (file.creationTime! > cutOffTime.microsecondsSinceEpoch) continue;
-
- final creationTime =
- DateTime.fromMicrosecondsSinceEpoch(file.creationTime!);
- final month = creationTime.month;
- if (month != currentMonth) continue;
- final year = creationTime.year;
-
- currentMonthYearGroups
- .putIfAbsent(year, () => [])
- .add(Memory.fromFile(file, seenTimes));
- }
-
- // Add the largest two months plus the month through the years
- final sortedYearsForCurrentMonth = currentMonthYearGroups.keys.toList()
- ..sort(
- (a, b) => currentMonthYearGroups[b]!.length.compareTo(
- currentMonthYearGroups[a]!.length,
- ),
- );
- for (int i = 0; i < 2; i++) {
- if (sortedYearsForCurrentMonth.isEmpty) break;
- final year = sortedYearsForCurrentMonth.removeAt(0);
- final monthYearFiles = currentMonthYearGroups[year]!;
- final photoSelection = await _bestSelection(
- monthYearFiles,
- prefferedSize: monthSelectionSize,
- isOfflineMode: isOfflineMode,
- fileIdToFaces: fileIdToFaces,
- faceIDsToPersonID: faceIDsToPersonID,
- fileIDToImageEmbedding: fileIDToImageEmbedding,
- clipPositiveTextVector: clipPositiveTextVector,
- );
- final daysLeftInMonth =
- DateTime(currentYear, currentMonth + 1, 0).day - currentTime.day + 1;
- memoryResult.add(
- TimeMemory(
- photoSelection,
- month: DateTime(year, currentMonth),
- yearsAgo: currentTime.year - year,
- currentTime.microsecondsSinceEpoch,
- currentTime
- .add(Duration(days: daysLeftInMonth))
- .microsecondsSinceEpoch,
- ),
- );
- }
- // Show the month through the remaining years
- if (sortedYearsForCurrentMonth.length <= 3) return memoryResult;
- final allPhotos = sortedYearsForCurrentMonth
- .expand((year) => currentMonthYearGroups[year]!)
- .toList();
- final photoSelection = await _bestSelection(
- allPhotos,
- prefferedSize: monthSelectionSize,
+ return TimeMemoriesCalculator.computeTimeMemories(
+ allFiles,
+ currentTime,
isOfflineMode: isOfflineMode,
+ seenTimes: seenTimes,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
fileIDToImageEmbedding: fileIDToImageEmbedding,
clipPositiveTextVector: clipPositiveTextVector,
);
- final daysLeftInMonth =
- DateTime(currentYear, currentMonth + 1, 0).day - currentTime.day + 1;
- memoryResult.add(
- TimeMemory(
- photoSelection,
- month: DateTime(currentYear, currentMonth),
- currentTime.microsecondsSinceEpoch,
- currentTime.add(Duration(days: daysLeftInMonth)).microsecondsSinceEpoch,
- ),
- );
-
- return memoryResult;
}
static Future<List<FillerMemory>> _getFillerResults(
@@ -2359,65 +1103,12 @@ class SmartMemoriesService {
required Map<int, int> seenTimes,
Map<String, int>? localIdToIntId,
}) async {
- final List<FillerMemory> memoryResults = [];
- if (allFiles.isEmpty) return [];
- final nowInMicroseconds = currentTime.microsecondsSinceEpoch;
- final windowEnd =
- currentTime.add(kMemoriesUpdateFrequency).microsecondsSinceEpoch;
- final currentYear = currentTime.year;
- final cutOffTime = currentTime
- .subtract(const Duration(days: 364) - kMemoriesUpdateFrequency);
- final timeTillYearEnd = DateTime(currentYear + 1).difference(currentTime);
- final bool almostYearEnd = timeTillYearEnd < kMemoriesUpdateFrequency;
-
- final Map<int, List<Memory>> yearsAgoToMemories = {};
- for (final file in allFiles) {
- if (file.creationTime! > cutOffTime.microsecondsSinceEpoch) {
- continue;
- }
- final fileDate = DateTime.fromMicrosecondsSinceEpoch(file.creationTime!);
- final fileTimeInYear = fileDate.copyWith(year: currentYear);
- final diff = fileTimeInYear.difference(currentTime);
- if (!diff.isNegative && diff < kMemoriesUpdateFrequency) {
- final yearsAgo = currentYear - fileDate.year;
- yearsAgoToMemories.putIfAbsent(yearsAgo, () => []).add(
- Memory.fromFile(
- file,
- seenTimes,
- seenTimeKey: _seenTimeKeyForFile(file, localIdToIntId),
- ),
- );
- } else if (almostYearEnd) {
- final altDiff = fileDate.copyWith(year: currentYear + 1).difference(
- currentTime,
- );
- if (!altDiff.isNegative && altDiff < kMemoriesUpdateFrequency) {
- final yearsAgo = currentYear - fileDate.year + 1;
- yearsAgoToMemories.putIfAbsent(yearsAgo, () => []).add(
- Memory.fromFile(
- file,
- seenTimes,
- seenTimeKey: _seenTimeKeyForFile(file, localIdToIntId),
- ),
- );
- }
- }
- }
- for (var yearAgo = 1; yearAgo <= yearsBefore; yearAgo++) {
- final memories = yearsAgoToMemories[yearAgo];
- if (memories == null) continue;
- memories.sort(
- (a, b) => a.file.creationTime!.compareTo(b.file.creationTime!),
- );
- final fillerMemory = FillerMemory(
- memories,
- yearAgo,
- nowInMicroseconds,
- windowEnd,
- );
- memoryResults.add(fillerMemory);
- }
- return memoryResults;
+ return TimeMemoriesCalculator.computeFillerMemories(
+ allFiles,
+ currentTime,
+ seenTimes: seenTimes,
+ localIdToIntId: localIdToIntId,
+ );
}
Future<Set<int>> getCollectionIDsToExclude() async {
@@ -2472,125 +1163,13 @@ class SmartMemoriesService {
required Set<int> collectionIDsToExclude,
Map<String, int>? localIdToIntId,
}) async {
- final List<OnThisDayMemory> memoryResults = [];
- if (allFiles.isEmpty) return [];
-
- final daysToCompute = kMemoriesUpdateFrequency.inDays;
- final currentYear = currentTime.year;
- final currentMonth = currentTime.month;
- final currentDay = currentTime.day;
- final startPoint = DateTime(currentYear, currentMonth, currentDay);
- final cutOffTime = startPoint
- .subtract(const Duration(days: 363) - kMemoriesUpdateFrequency);
- final diffThreshold = Duration(days: daysToCompute);
-
- final Map<int, List<Memory>> daysToMemories = {};
- final Map<int, List<int>> daysToYears = {};
-
- final timeTillYearEnd = DateTime(currentYear + 1).difference(startPoint);
- final bool almostYearEnd = timeTillYearEnd < diffThreshold;
-
- // Find all the relevant memories
- for (final file in allFiles) {
- if (collectionIDsToExclude.contains(file.collectionID)) continue;
- if (file.creationTime! > cutOffTime.microsecondsSinceEpoch) {
- continue;
- }
- final fileDate = DateTime.fromMicrosecondsSinceEpoch(file.creationTime!);
- final fileTimeInYear = fileDate.copyWith(year: currentYear);
- final diff = fileTimeInYear.difference(startPoint);
- if (!diff.isNegative && diff < diffThreshold) {
- daysToMemories.putIfAbsent(diff.inDays, () => []).add(
- Memory.fromFile(
- file,
- seenTimes,
- seenTimeKey: _seenTimeKeyForFile(file, localIdToIntId),
- ),
- );
- daysToYears.putIfAbsent(diff.inDays, () => []).add(fileDate.year);
- } else if (almostYearEnd) {
- final altDiff = fileDate.copyWith(year: currentYear + 1).difference(
- currentTime,
- );
- if (!altDiff.isNegative && altDiff < diffThreshold) {
- daysToMemories.putIfAbsent(altDiff.inDays, () => []).add(
- Memory.fromFile(
- file,
- seenTimes,
- seenTimeKey: _seenTimeKeyForFile(file, localIdToIntId),
- ),
- );
- daysToYears.putIfAbsent(altDiff.inDays, () => []).add(fileDate.year);
- }
- }
- }
-
- // Per day, filter the memories to find the best ones
- for (var day = 0; day < daysToCompute; day++) {
- final memories = daysToMemories[day];
- if (memories == null) continue;
- if (memories.length < 5) continue;
- final years = daysToYears[day]!;
- if (years.toSet().length < 2) continue;
-
- final filteredMemories = <Memory>[];
- if (memories.length > 20) {
- // Group memories by year
- final Map<int, List<Memory>> memoriesByYear = {};
- for (final memory in memories) {
- final creationTime =
- DateTime.fromMicrosecondsSinceEpoch(memory.file.creationTime!);
- final year = creationTime.year;
- memoriesByYear.putIfAbsent(year, () => []).add(memory);
- }
- for (final year in memoriesByYear.keys) {
- memoriesByYear[year]!.shuffle(Random());
- }
-
- // Get all years, randonly select 20 years if there are more than 20
- List<int> years = memoriesByYear.keys.toList()..sort();
- if (years.length > 20) {
- years.shuffle(Random());
- years = years.take(20).toList()..sort();
- }
-
- // First round to take one memory from each year
- for (final year in years) {
- if (filteredMemories.length >= 20) break;
- final yearMemories = memoriesByYear[year]!;
- if (yearMemories.isNotEmpty) {
- filteredMemories.add(yearMemories.removeAt(0));
- }
- }
-
- // Second round to fill up to 20 memories
- while (filteredMemories.length < 20) {
- bool addedAny = false;
- for (final year in years) {
- if (filteredMemories.length >= 20) break;
- final yearMemories = memoriesByYear[year]!;
- if (yearMemories.isNotEmpty) {
- filteredMemories.add(yearMemories.removeAt(0));
- addedAny = true;
- }
- }
- if (!addedAny) break;
- }
- } else {
- filteredMemories.addAll(memories);
- }
-
- filteredMemories.sort(
- (a, b) => a.file.creationTime!.compareTo(b.file.creationTime!),
- );
- final onThisDayMemory = OnThisDayMemory(
- filteredMemories,
- startPoint.add(Duration(days: day)).microsecondsSinceEpoch,
- startPoint.add(Duration(days: day + 1)).microsecondsSinceEpoch,
- );
- memoryResults.add(onThisDayMemory);
- }
- return memoryResults;
+ return TimeMemoriesCalculator.computeOnThisDayMemories(
+ allFiles,
+ currentTime,
+ seenTimes: seenTimes,
+ collectionIDsToExclude: collectionIDsToExclude,
+ localIdToIntId: localIdToIntId,
+ );
}
static Future<String> getDateFormattedLocale({
@@ -2618,14 +1197,6 @@ class SmartMemoriesService {
);
}
- /// TODO: lau: replace this by just taking next 7 days
- static int _getWeekNumber(DateTime date) {
- // Get day of year (1-366)
- final int dayOfYear = int.parse(DateFormat('D').format(date));
- // Integer division by 7 and add 1 to start from week 1
- return ((dayOfYear - 1) ~/ 7) + 1;
- }
-
static int? _seenTimeKeyForFile(
EnteFile file,
Map<String, int>? localIdToIntId,
diff --git a/mobile/apps/photos/lib/services/smart_memories_time_calculator.dart b/mobile/apps/photos/lib/services/smart_memories_time_calculator.dart
new file mode 100644
index 0000000000..782aec8f8b
--- /dev/null
+++ b/mobile/apps/photos/lib/services/smart_memories_time_calculator.dart
@@ -0,0 +1,452 @@
+part of "smart_memories_service.dart";
+
+class TimeMemoriesCalculator {
+ static Future<List<TimeMemory>> computeTimeMemories(
+ Set<EnteFile> allFiles,
+ DateTime currentTime, {
+ required bool isOfflineMode,
+ required Map<int, int> seenTimes,
+ required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
+ required Map<String, String> faceIDsToPersonID,
+ required Map<int, EmbeddingVector> fileIDToImageEmbedding,
+ required Vector clipPositiveTextVector,
+ }) async {
+ final List<TimeMemory> memoryResult = [];
+ if (allFiles.isEmpty) return [];
+
+ final currentDayMonth = currentTime.month * 100 + currentTime.day;
+ final currentWeek = getWeekNumber(currentTime);
+ final currentMonth = currentTime.month;
+ final currentYear = currentTime.year;
+ final cutOffTime = currentTime.subtract(const Duration(days: 365));
+ final averageDailyPhotos = allFiles.length / 365;
+ final significantDayThreshold = averageDailyPhotos * 0.25;
+ final significantWeekThreshold = averageDailyPhotos * 0.40;
+
+ final dayMonthYearGroups = <int, Map<int, List<Memory>>>{};
+
+ for (final file in allFiles) {
+ if (file.creationTime! > cutOffTime.microsecondsSinceEpoch) continue;
+
+ final creationTime =
+ DateTime.fromMicrosecondsSinceEpoch(file.creationTime!);
+ final dayMonth = creationTime.month * 100 + creationTime.day;
+ final year = creationTime.year;
+
+ dayMonthYearGroups
+ .putIfAbsent(dayMonth, () => {})
+ .putIfAbsent(year, () => [])
+ .add(Memory.fromFile(file, seenTimes));
+ }
+
+ for (final dayMonth in dayMonthYearGroups.keys) {
+ final dayDiff = dayMonth - currentDayMonth;
+ if (dayDiff < 0 || dayDiff > kMemoriesUpdateFrequency.inDays) continue;
+
+ final yearGroups = dayMonthYearGroups[dayMonth]!;
+ final significantDays = yearGroups.entries
+ .where((e) => e.value.length > significantDayThreshold)
+ .map((e) => e.key)
+ .toList();
+
+ if (significantDays.length >= 3) {
+ final date =
+ DateTime(currentTime.year, dayMonth ~/ 100, dayMonth % 100);
+ final allPhotos = yearGroups.values.expand((x) => x).toList();
+ final photoSelection = await SmartMemoriesService._bestSelection(
+ allPhotos,
+ isOfflineMode: isOfflineMode,
+ fileIdToFaces: fileIdToFaces,
+ faceIDsToPersonID: faceIDsToPersonID,
+ fileIDToImageEmbedding: fileIDToImageEmbedding,
+ clipPositiveTextVector: clipPositiveTextVector,
+ );
+
+ memoryResult.add(
+ TimeMemory(
+ photoSelection,
+ day: date,
+ date.subtract(kMemoriesMargin).microsecondsSinceEpoch,
+ date.add(kDayItself).microsecondsSinceEpoch,
+ ),
+ );
+ } else {
+ for (final year in significantDays) {
+ final date = DateTime(year, dayMonth ~/ 100, dayMonth % 100);
+ final showDate =
+ DateTime(currentYear, dayMonth ~/ 100, dayMonth % 100);
+ final files = yearGroups[year]!;
+ final photoSelection = await SmartMemoriesService._bestSelection(
+ files,
+ isOfflineMode: isOfflineMode,
+ fileIdToFaces: fileIdToFaces,
+ faceIDsToPersonID: faceIDsToPersonID,
+ fileIDToImageEmbedding: fileIDToImageEmbedding,
+ clipPositiveTextVector: clipPositiveTextVector,
+ );
+ memoryResult.add(
+ TimeMemory(
+ photoSelection,
+ day: date,
+ yearsAgo: currentTime.year - date.year,
+ showDate.subtract(kMemoriesMargin).microsecondsSinceEpoch,
+ showDate.add(kDayItself).microsecondsSinceEpoch,
+ ),
+ );
+ }
+ }
+ }
+
+ if (memoryResult.isEmpty) {
+ final currentWeekYearGroups = <int, List<Memory>>{};
+ for (final file in allFiles) {
+ if (file.creationTime! > cutOffTime.microsecondsSinceEpoch) continue;
+
+ final creationTime =
+ DateTime.fromMicrosecondsSinceEpoch(file.creationTime!);
+ final week = getWeekNumber(creationTime);
+ if (week != currentWeek) continue;
+ final year = creationTime.year;
+
+ currentWeekYearGroups
+ .putIfAbsent(year, () => [])
+ .add(Memory.fromFile(file, seenTimes));
+ }
+
+ if (currentWeekYearGroups.isNotEmpty) {
+ final significantWeeks = currentWeekYearGroups.entries
+ .where((e) => e.value.length > significantWeekThreshold)
+ .map((e) => e.key)
+ .toList();
+ if (significantWeeks.length >= 3) {
+ final allPhotos =
+ currentWeekYearGroups.values.expand((x) => x).toList();
+ final photoSelection = await SmartMemoriesService._bestSelection(
+ allPhotos,
+ isOfflineMode: isOfflineMode,
+ fileIdToFaces: fileIdToFaces,
+ faceIDsToPersonID: faceIDsToPersonID,
+ fileIDToImageEmbedding: fileIDToImageEmbedding,
+ clipPositiveTextVector: clipPositiveTextVector,
+ );
+ memoryResult.add(
+ TimeMemory(
+ photoSelection,
+ currentTime.subtract(kMemoriesMargin).microsecondsSinceEpoch,
+ currentTime.add(kMemoriesUpdateFrequency).microsecondsSinceEpoch,
+ ),
+ );
+ } else {
+ for (final year in significantWeeks) {
+ final date = DateTime(year, 1, 1).add(
+ Duration(days: (currentWeek - 1) * 7),
+ );
+ final files = currentWeekYearGroups[year]!;
+ final photoSelection = await SmartMemoriesService._bestSelection(
+ files,
+ isOfflineMode: isOfflineMode,
+ fileIdToFaces: fileIdToFaces,
+ faceIDsToPersonID: faceIDsToPersonID,
+ fileIDToImageEmbedding: fileIDToImageEmbedding,
+ clipPositiveTextVector: clipPositiveTextVector,
+ );
+ memoryResult.add(
+ TimeMemory(
+ photoSelection,
+ yearsAgo: currentTime.year - date.year,
+ currentTime.subtract(kMemoriesMargin).microsecondsSinceEpoch,
+ currentTime
+ .add(kMemoriesUpdateFrequency)
+ .microsecondsSinceEpoch,
+ ),
+ );
+ }
+ }
+ }
+ }
+
+ const monthSelectionSize = 20;
+ final currentMonthYearGroups = <int, List<Memory>>{};
+ SmartMemoriesService._deductUsedMemories(allFiles, memoryResult);
+ for (final file in allFiles) {
+ if (file.creationTime! > cutOffTime.microsecondsSinceEpoch) continue;
+
+ final creationTime =
+ DateTime.fromMicrosecondsSinceEpoch(file.creationTime!);
+ final month = creationTime.month;
+ if (month != currentMonth) continue;
+ final year = creationTime.year;
+
+ currentMonthYearGroups
+ .putIfAbsent(year, () => [])
+ .add(Memory.fromFile(file, seenTimes));
+ }
+
+ final sortedYearsForCurrentMonth = currentMonthYearGroups.keys.toList()
+ ..sort(
+ (a, b) => currentMonthYearGroups[b]!.length.compareTo(
+ currentMonthYearGroups[a]!.length,
+ ),
+ );
+ for (int i = 0; i < 2; i++) {
+ if (sortedYearsForCurrentMonth.isEmpty) break;
+ final year = sortedYearsForCurrentMonth.removeAt(0);
+ final monthYearFiles = currentMonthYearGroups[year]!;
+ final photoSelection = await SmartMemoriesService._bestSelection(
+ monthYearFiles,
+ prefferedSize: monthSelectionSize,
+ isOfflineMode: isOfflineMode,
+ fileIdToFaces: fileIdToFaces,
+ faceIDsToPersonID: faceIDsToPersonID,
+ fileIDToImageEmbedding: fileIDToImageEmbedding,
+ clipPositiveTextVector: clipPositiveTextVector,
+ );
+ final daysLeftInMonth =
+ DateTime(currentYear, currentMonth + 1, 0).day - currentTime.day + 1;
+ memoryResult.add(
+ TimeMemory(
+ photoSelection,
+ month: DateTime(year, currentMonth),
+ yearsAgo: currentTime.year - year,
+ currentTime.microsecondsSinceEpoch,
+ currentTime
+ .add(Duration(days: daysLeftInMonth))
+ .microsecondsSinceEpoch,
+ ),
+ );
+ }
+ if (sortedYearsForCurrentMonth.length <= 3) return memoryResult;
+ final allPhotos = sortedYearsForCurrentMonth
+ .expand((year) => currentMonthYearGroups[year]!)
+ .toList();
+ final photoSelection = await SmartMemoriesService._bestSelection(
+ allPhotos,
+ prefferedSize: monthSelectionSize,
+ isOfflineMode: isOfflineMode,
+ fileIdToFaces: fileIdToFaces,
+ faceIDsToPersonID: faceIDsToPersonID,
+ fileIDToImageEmbedding: fileIDToImageEmbedding,
+ clipPositiveTextVector: clipPositiveTextVector,
+ );
+ final daysLeftInMonth =
+ DateTime(currentYear, currentMonth + 1, 0).day - currentTime.day + 1;
+ memoryResult.add(
+ TimeMemory(
+ photoSelection,
+ month: DateTime(currentYear, currentMonth),
+ currentTime.microsecondsSinceEpoch,
+ currentTime.add(Duration(days: daysLeftInMonth)).microsecondsSinceEpoch,
+ ),
+ );
+
+ return memoryResult;
+ }
+
+ static Future<List<FillerMemory>> computeFillerMemories(
+ Iterable<EnteFile> allFiles,
+ DateTime currentTime, {
+ required Map<int, int> seenTimes,
+ Map<String, int>? localIdToIntId,
+ }) async {
+ final List<FillerMemory> memoryResults = [];
+ if (allFiles.isEmpty) return [];
+ final nowInMicroseconds = currentTime.microsecondsSinceEpoch;
+ final windowEnd =
+ currentTime.add(kMemoriesUpdateFrequency).microsecondsSinceEpoch;
+ final currentYear = currentTime.year;
+ final cutOffTime = currentTime
+ .subtract(const Duration(days: 364) - kMemoriesUpdateFrequency);
+ final timeTillYearEnd = DateTime(currentYear + 1).difference(currentTime);
+ final bool almostYearEnd = timeTillYearEnd < kMemoriesUpdateFrequency;
+
+ final Map<int, List<Memory>> yearsAgoToMemories = {};
+ for (final file in allFiles) {
+ if (file.creationTime! > cutOffTime.microsecondsSinceEpoch) {
+ continue;
+ }
+ final fileDate = DateTime.fromMicrosecondsSinceEpoch(file.creationTime!);
+ final fileTimeInYear = fileDate.copyWith(year: currentYear);
+ final diff = fileTimeInYear.difference(currentTime);
+ if (!diff.isNegative && diff < kMemoriesUpdateFrequency) {
+ final yearsAgo = currentYear - fileDate.year;
+ yearsAgoToMemories.putIfAbsent(yearsAgo, () => []).add(
+ Memory.fromFile(
+ file,
+ seenTimes,
+ seenTimeKey: SmartMemoriesService._seenTimeKeyForFile(
+ file,
+ localIdToIntId,
+ ),
+ ),
+ );
+ } else if (almostYearEnd) {
+ final altDiff = fileDate.copyWith(year: currentYear + 1).difference(
+ currentTime,
+ );
+ if (!altDiff.isNegative && altDiff < kMemoriesUpdateFrequency) {
+ final yearsAgo = currentYear - fileDate.year + 1;
+ yearsAgoToMemories.putIfAbsent(yearsAgo, () => []).add(
+ Memory.fromFile(
+ file,
+ seenTimes,
+ seenTimeKey: SmartMemoriesService._seenTimeKeyForFile(
+ file,
+ localIdToIntId,
+ ),
+ ),
+ );
+ }
+ }
+ }
+ for (var yearAgo = 1;
+ yearAgo <= SmartMemoriesService.yearsBefore;
+ yearAgo++) {
+ final memories = yearsAgoToMemories[yearAgo];
+ if (memories == null) continue;
+ memories.sort(
+ (a, b) => a.file.creationTime!.compareTo(b.file.creationTime!),
+ );
+ final fillerMemory = FillerMemory(
+ memories,
+ yearAgo,
+ nowInMicroseconds,
+ windowEnd,
+ );
+ memoryResults.add(fillerMemory);
+ }
+ return memoryResults;
+ }
+
+ static Future<List<OnThisDayMemory>> computeOnThisDayMemories(
+ Iterable<EnteFile> allFiles,
+ DateTime currentTime, {
+ required Map<int, int> seenTimes,
+ required Set<int> collectionIDsToExclude,
+ Map<String, int>? localIdToIntId,
+ }) async {
+ final List<OnThisDayMemory> memoryResults = [];
+ if (allFiles.isEmpty) return [];
+
+ final daysToCompute = kMemoriesUpdateFrequency.inDays;
+ final currentYear = currentTime.year;
+ final currentMonth = currentTime.month;
+ final currentDay = currentTime.day;
+ final startPoint = DateTime(currentYear, currentMonth, currentDay);
+ final cutOffTime = startPoint
+ .subtract(const Duration(days: 363) - kMemoriesUpdateFrequency);
+ final diffThreshold = Duration(days: daysToCompute);
+
+ final Map<int, List<Memory>> daysToMemories = {};
+ final Map<int, List<int>> daysToYears = {};
+
+ final timeTillYearEnd = DateTime(currentYear + 1).difference(startPoint);
+ final bool almostYearEnd = timeTillYearEnd < diffThreshold;
+
+ for (final file in allFiles) {
+ if (collectionIDsToExclude.contains(file.collectionID)) continue;
+ if (file.creationTime! > cutOffTime.microsecondsSinceEpoch) {
+ continue;
+ }
+ final fileDate = DateTime.fromMicrosecondsSinceEpoch(file.creationTime!);
+ final fileTimeInYear = fileDate.copyWith(year: currentYear);
+ final diff = fileTimeInYear.difference(startPoint);
+ if (!diff.isNegative && diff < diffThreshold) {
+ daysToMemories.putIfAbsent(diff.inDays, () => []).add(
+ Memory.fromFile(
+ file,
+ seenTimes,
+ seenTimeKey: SmartMemoriesService._seenTimeKeyForFile(
+ file,
+ localIdToIntId,
+ ),
+ ),
+ );
+ daysToYears.putIfAbsent(diff.inDays, () => []).add(fileDate.year);
+ } else if (almostYearEnd) {
+ final altDiff = fileDate.copyWith(year: currentYear + 1).difference(
+ currentTime,
+ );
+ if (!altDiff.isNegative && altDiff < diffThreshold) {
+ daysToMemories.putIfAbsent(altDiff.inDays, () => []).add(
+ Memory.fromFile(
+ file,
+ seenTimes,
+ seenTimeKey: SmartMemoriesService._seenTimeKeyForFile(
+ file,
+ localIdToIntId,
+ ),
+ ),
+ );
+ daysToYears.putIfAbsent(altDiff.inDays, () => []).add(fileDate.year);
+ }
+ }
+ }
+
+ for (var day = 0; day < daysToCompute; day++) {
+ final memories = daysToMemories[day];
+ if (memories == null) continue;
+ if (memories.length < 5) continue;
+ final years = daysToYears[day]!;
+ if (years.toSet().length < 2) continue;
+
+ final filteredMemories = <Memory>[];
+ if (memories.length > 20) {
+ final Map<int, List<Memory>> memoriesByYear = {};
+ for (final memory in memories) {
+ final creationTime =
+ DateTime.fromMicrosecondsSinceEpoch(memory.file.creationTime!);
+ final year = creationTime.year;
+ memoriesByYear.putIfAbsent(year, () => []).add(memory);
+ }
+ for (final year in memoriesByYear.keys) {
+ memoriesByYear[year]!.shuffle(Random());
+ }
+
+ List<int> years = memoriesByYear.keys.toList()..sort();
+ if (years.length > 20) {
+ years.shuffle(Random());
+ years = years.take(20).toList()..sort();
+ }
+
+ for (final year in years) {
+ if (filteredMemories.length >= 20) break;
+ final yearMemories = memoriesByYear[year]!;
+ if (yearMemories.isNotEmpty) {
+ filteredMemories.add(yearMemories.removeAt(0));
+ }
+ }
+
+ while (filteredMemories.length < 20) {
+ bool addedAny = false;
+ for (final year in years) {
+ if (filteredMemories.length >= 20) break;
+ final yearMemories = memoriesByYear[year]!;
+ if (yearMemories.isNotEmpty) {
+ filteredMemories.add(yearMemories.removeAt(0));
+ addedAny = true;
+ }
+ }
+ if (!addedAny) break;
+ }
+ } else {
+ filteredMemories.addAll(memories);
+ }
+
+ filteredMemories.sort(
+ (a, b) => a.file.creationTime!.compareTo(b.file.creationTime!),
+ );
+ final onThisDayMemory = OnThisDayMemory(
+ filteredMemories,
+ startPoint.add(Duration(days: day)).microsecondsSinceEpoch,
+ startPoint.add(Duration(days: day + 1)).microsecondsSinceEpoch,
+ );
+ memoryResults.add(onThisDayMemory);
+ }
+ return memoryResults;
+ }
+
+ static int getWeekNumber(DateTime date) {
+ final int dayOfYear = int.parse(DateFormat('D').format(date));
+ return ((dayOfYear - 1) ~/ 7) + 1;
+ }
+}
diff --git a/mobile/apps/photos/lib/services/smart_memories_trip_calculator.dart b/mobile/apps/photos/lib/services/smart_memories_trip_calculator.dart
new file mode 100644
index 0000000000..45d2a27f96
--- /dev/null
+++ b/mobile/apps/photos/lib/services/smart_memories_trip_calculator.dart
@@ -0,0 +1,437 @@
+part of "smart_memories_service.dart";
+
+class TripMemoriesCalculator {
+ static Future<(List<TripMemory>, List<BaseLocation>)> compute(
+ Iterable<EnteFile> allFiles,
+ Map<int, EnteFile> allFileIdsToFile,
+ DateTime currentTime,
+ List<TripsShownLog> shownTrips, {
+ bool surfaceAll = false,
+ required bool isOfflineMode,
+ required Map<int, int> seenTimes,
+ required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
+ required Map<String, String> faceIDsToPersonID,
+ required Map<int, EmbeddingVector> fileIDToImageEmbedding,
+ required Vector clipPositiveTextVector,
+ required List<City> cities,
+ }) async {
+ final List<TripMemory> memoryResults = [];
+ if (allFiles.isEmpty) return (<TripMemory>[], <BaseLocation>[]);
+ final nowInMicroseconds = currentTime.microsecondsSinceEpoch;
+ final windowEnd =
+ currentTime.add(kMemoriesUpdateFrequency).microsecondsSinceEpoch;
+ final currentMonth = currentTime.month;
+ final cutOffTime = currentTime.subtract(const Duration(days: 365));
+
+ const tripRadius = 100.0;
+ const overlapRadius = 10.0;
+
+ final List<(List<EnteFile>, Location)> smallRadiusClusters = [];
+ final List<(List<EnteFile>, Location)> wideRadiusClusters = [];
+ for (EnteFile file in allFiles) {
+ if (!file.hasLocation) continue;
+ bool addedToExistingSmallCluster = false;
+ for (final cluster in smallRadiusClusters) {
+ final clusterLocation = cluster.$2;
+ if (isFileInsideLocationTag(
+ clusterLocation,
+ file.location!,
+ baseRadius,
+ )) {
+ cluster.$1.add(file);
+ addedToExistingSmallCluster = true;
+ break;
+ }
+ }
+ if (!addedToExistingSmallCluster) {
+ smallRadiusClusters.add(([file], file.location!));
+ }
+ bool addedToExistingWideCluster = false;
+ for (final cluster in wideRadiusClusters) {
+ final clusterLocation = cluster.$2;
+ if (isFileInsideLocationTag(
+ clusterLocation,
+ file.location!,
+ tripRadius,
+ )) {
+ cluster.$1.add(file);
+ addedToExistingWideCluster = true;
+ break;
+ }
+ }
+ if (!addedToExistingWideCluster) {
+ wideRadiusClusters.add(([file], file.location!));
+ }
+ }
+
+ final List<BaseLocation> baseLocations = [];
+ for (final cluster in smallRadiusClusters) {
+ final files = cluster.$1;
+ final location = cluster.$2;
+ final creationTimes = <int>[];
+ final Set<int> uniqueDays = {};
+ for (final file in files) {
+ creationTimes.add(file.creationTime!);
+ final date = DateTime.fromMicrosecondsSinceEpoch(file.creationTime!);
+ final dayStamp =
+ DateTime(date.year, date.month, date.day).microsecondsSinceEpoch;
+ uniqueDays.add(dayStamp);
+ }
+ creationTimes.sort();
+ if (creationTimes.length < 10) continue;
+ final firstCreationTime = DateTime.fromMicrosecondsSinceEpoch(
+ creationTimes.first,
+ );
+ final lastCreationTime = DateTime.fromMicrosecondsSinceEpoch(
+ creationTimes.last,
+ );
+ final daysRange = lastCreationTime.difference(firstCreationTime).inDays;
+ if (daysRange < 90) {
+ continue;
+ }
+ if (uniqueDays.length < daysRange * 0.1) continue;
+ final int gapThreshold = (daysRange * 0.6).round() * microSecondsInDay;
+ int maxGap = 0;
+ for (int i = 1; i < creationTimes.length; i++) {
+ final gap = creationTimes[i] - creationTimes[i - 1];
+ if (gap > maxGap) maxGap = gap;
+ }
+ if (maxGap > gapThreshold) continue;
+ final bool isCurrent = lastCreationTime.isAfter(
+ DateTime.now().subtract(
+ const Duration(days: 90),
+ ),
+ );
+ baseLocations.add(
+ BaseLocation(
+ files
+ .map(
+ (file) => SmartMemoriesService._memoryFileId(
+ file,
+ isOfflineMode: isOfflineMode,
+ ),
+ )
+ .whereType<int>()
+ .toList(),
+ location,
+ isCurrent,
+ ),
+ );
+ }
+
+ final List<TripMemory> tripLocations = [];
+ clusteredLocations:
+ for (final cluster in wideRadiusClusters) {
+ final files = cluster.$1;
+ final location = cluster.$2;
+ for (final baseLocation in baseLocations) {
+ if (isFileInsideLocationTag(
+ baseLocation.location,
+ location,
+ overlapRadius,
+ )) {
+ continue clusteredLocations;
+ }
+ }
+
+ files.sort((a, b) => a.creationTime!.compareTo(b.creationTime!));
+ List<EnteFile> currentBlockFiles = [files.first];
+ int blockStart = files.first.creationTime!;
+ int lastTime = files.first.creationTime!;
+ DateTime lastDateTime = DateTime.fromMicrosecondsSinceEpoch(lastTime);
+
+ for (int i = 1; i < files.length; i++) {
+ final currentFile = files[i];
+ final currentTime = currentFile.creationTime!;
+ final gap = DateTime.fromMicrosecondsSinceEpoch(currentTime)
+ .difference(lastDateTime)
+ .inDays;
+
+ if (gap > 15) {
+ if (gap < 90) continue clusteredLocations;
+
+ final blockDuration = lastDateTime
+ .difference(DateTime.fromMicrosecondsSinceEpoch(blockStart))
+ .inDays;
+
+ if (blockDuration >= 2 && blockDuration <= 30) {
+ tripLocations.add(
+ TripMemory(
+ Memory.fromFiles(
+ currentBlockFiles,
+ seenTimes,
+ ),
+ 0,
+ 0,
+ location,
+ firstCreationTime: blockStart,
+ lastCreationTime: lastTime,
+ ),
+ );
+ }
+
+ currentBlockFiles = [];
+ blockStart = currentTime;
+ }
+
+ currentBlockFiles.add(currentFile);
+ lastTime = currentTime;
+ lastDateTime = DateTime.fromMicrosecondsSinceEpoch(lastTime);
+ }
+ final lastBlockDuration = lastDateTime
+ .difference(DateTime.fromMicrosecondsSinceEpoch(blockStart))
+ .inDays;
+ if (lastBlockDuration >= 2 && lastBlockDuration <= 30) {
+ tripLocations.add(
+ TripMemory(
+ Memory.fromFiles(currentBlockFiles, seenTimes),
+ 0,
+ 0,
+ location,
+ firstCreationTime: blockStart,
+ lastCreationTime: lastTime,
+ ),
+ );
+ }
+ }
+
+ final List<TripMemory> mergedTrips = [];
+ for (final trip in tripLocations) {
+ final tripFirstTime = DateTime.fromMicrosecondsSinceEpoch(
+ trip.firstCreationTime!,
+ );
+ final tripLastTime = DateTime.fromMicrosecondsSinceEpoch(
+ trip.lastCreationTime!,
+ );
+ bool merged = false;
+ for (int idx = 0; idx < mergedTrips.length; idx++) {
+ final otherTrip = mergedTrips[idx];
+ final otherTripFirstTime =
+ DateTime.fromMicrosecondsSinceEpoch(otherTrip.firstCreationTime!);
+ final otherTripLastTime =
+ DateTime.fromMicrosecondsSinceEpoch(otherTrip.lastCreationTime!);
+ if (tripFirstTime
+ .isBefore(otherTripLastTime.add(const Duration(days: 3))) &&
+ tripLastTime.isAfter(
+ otherTripFirstTime.subtract(const Duration(days: 3)),
+ )) {
+ mergedTrips[idx] = TripMemory(
+ otherTrip.memories + trip.memories,
+ 0,
+ 0,
+ otherTrip.location,
+ firstCreationTime:
+ min(otherTrip.firstCreationTime!, trip.firstCreationTime!),
+ lastCreationTime:
+ max(otherTrip.lastCreationTime!, trip.lastCreationTime!),
+ );
+ dev.log('Merged two trip locations');
+ merged = true;
+ break;
+ }
+ }
+ if (merged) continue;
+ mergedTrips.add(
+ TripMemory(
+ trip.memories,
+ 0,
+ 0,
+ trip.location,
+ firstCreationTime: trip.firstCreationTime,
+ lastCreationTime: trip.lastCreationTime,
+ ),
+ );
+ }
+
+ final List<TripMemory> validTrips = [];
+ for (final trip in mergedTrips) {
+ if (trip.memories.length >= 20 &&
+ trip.averageCreationTime() < cutOffTime.microsecondsSinceEpoch) {
+ validTrips.add(trip);
+ }
+ }
+
+ if (surfaceAll) {
+ for (final baseLocation in baseLocations) {
+ String name =
+ "Base (${baseLocation.isCurrentBase ? 'current' : 'old'})";
+ final files = baseLocation.fileIDs
+ .map((fileID) => allFileIdsToFile[fileID]!)
+ .toList();
+ final String? locationName = SmartMemoriesService._tryFindLocationName(
+ Memory.fromFiles(files, seenTimes),
+ cities,
+ base: true,
+ );
+ if (locationName != null) {
+ name =
+ "$locationName (Base, ${baseLocation.isCurrentBase ? 'current' : 'old'})";
+ }
+ memoryResults.add(
+ TripMemory(
+ Memory.fromFiles(files, seenTimes),
+ nowInMicroseconds,
+ windowEnd,
+ baseLocation.location,
+ locationName: name,
+ ),
+ );
+ }
+ for (final trip in validTrips) {
+ final year = DateTime.fromMicrosecondsSinceEpoch(
+ trip.averageCreationTime(),
+ ).year;
+ final String? locationName = SmartMemoriesService._tryFindLocationName(
+ trip.memories,
+ cities,
+ );
+ final photoSelection = await SmartMemoriesService._bestSelection(
+ trip.memories,
+ isOfflineMode: isOfflineMode,
+ fileIdToFaces: fileIdToFaces,
+ faceIDsToPersonID: faceIDsToPersonID,
+ fileIDToImageEmbedding: fileIDToImageEmbedding,
+ clipPositiveTextVector: clipPositiveTextVector,
+ );
+ memoryResults.add(
+ trip.copyWith(
+ memories: photoSelection,
+ tripYear: year,
+ locationName: locationName,
+ firstDateToShow: nowInMicroseconds,
+ lastDateToShow: windowEnd,
+ ),
+ );
+ }
+ return (memoryResults, baseLocations);
+ }
+
+ final Map<int, Map<int, List<TripMemory>>> tripsByMonthYear = {};
+ for (final trip in validTrips) {
+ final tripDate =
+ DateTime.fromMicrosecondsSinceEpoch(trip.averageCreationTime());
+ tripsByMonthYear
+ .putIfAbsent(tripDate.month, () => {})
+ .putIfAbsent(tripDate.year, () => [])
+ .add(trip);
+ }
+
+ final List<TripMemory> currentMonthTrips = [];
+ if (tripsByMonthYear.containsKey(currentMonth)) {
+ for (final trips in tripsByMonthYear[currentMonth]!.values) {
+ for (final trip in trips) {
+ currentMonthTrips.add(trip);
+ }
+ }
+ }
+
+ if (currentMonthTrips.isNotEmpty) {
+ currentMonthTrips.sort(
+ (a, b) => b.averageCreationTime().compareTo(a.averageCreationTime()),
+ );
+ final tripsToShow = currentMonthTrips.take(2);
+ for (final trip in tripsToShow) {
+ final year =
+ DateTime.fromMicrosecondsSinceEpoch(trip.averageCreationTime())
+ .year;
+ final String? locationName = SmartMemoriesService._tryFindLocationName(
+ trip.memories,
+ cities,
+ );
+ final photoSelection = await SmartMemoriesService._bestSelection(
+ trip.memories,
+ isOfflineMode: isOfflineMode,
+ fileIdToFaces: fileIdToFaces,
+ faceIDsToPersonID: faceIDsToPersonID,
+ fileIDToImageEmbedding: fileIDToImageEmbedding,
+ clipPositiveTextVector: clipPositiveTextVector,
+ );
+ final firstCreationDate = DateTime.fromMicrosecondsSinceEpoch(
+ trip.firstCreationTime!,
+ );
+ final firstDateToShow = DateTime(
+ currentTime.year,
+ firstCreationDate.month,
+ firstCreationDate.day,
+ ).subtract(kMemoriesMargin).microsecondsSinceEpoch;
+ final lastCreationDate = DateTime.fromMicrosecondsSinceEpoch(
+ trip.lastCreationTime!,
+ );
+ final lastDateToShow = DateTime(
+ currentTime.year,
+ lastCreationDate.month,
+ lastCreationDate.day,
+ ).add(kMemoriesMargin).microsecondsSinceEpoch;
+ memoryResults.add(
+ trip.copyWith(
+ memories: photoSelection,
+ tripYear: year,
+ locationName: locationName,
+ firstDateToShow: firstDateToShow,
+ lastDateToShow: lastDateToShow,
+ ),
+ );
+ }
+ } else {
+ final sortedUpcomingMonths =
+ List<int>.generate(6, (i) => ((currentMonth + i) % 12) + 1);
+ checkUpcomingMonths:
+ for (final month in sortedUpcomingMonths) {
+ if (tripsByMonthYear.containsKey(month)) {
+ final List<TripMemory> thatMonthTrips = [];
+ for (final trips in tripsByMonthYear[month]!.values) {
+ thatMonthTrips.addAll(trips);
+ }
+ if (thatMonthTrips.length >= 3) {
+ thatMonthTrips.sort(
+ (a, b) =>
+ a.averageCreationTime().compareTo(b.averageCreationTime()),
+ );
+ checkPotentialTrips:
+ for (final trip in thatMonthTrips.sublist(2)) {
+ for (final shownTrip in shownTrips) {
+ final distance =
+ calculateDistance(trip.location, shownTrip.location);
+ final shownTripDate = DateTime.fromMicrosecondsSinceEpoch(
+ shownTrip.lastTimeShown,
+ );
+ final shownRecently =
+ currentTime.difference(shownTripDate) < kTripShowTimeout;
+ if (distance < overlapRadius && shownRecently) {
+ continue checkPotentialTrips;
+ }
+ }
+ final year = DateTime.fromMicrosecondsSinceEpoch(
+ trip.averageCreationTime(),
+ ).year;
+ final String? locationName =
+ SmartMemoriesService._tryFindLocationName(
+ trip.memories,
+ cities,
+ );
+ final photoSelection = await SmartMemoriesService._bestSelection(
+ trip.memories,
+ isOfflineMode: isOfflineMode,
+ fileIdToFaces: fileIdToFaces,
+ faceIDsToPersonID: faceIDsToPersonID,
+ fileIDToImageEmbedding: fileIDToImageEmbedding,
+ clipPositiveTextVector: clipPositiveTextVector,
+ );
+ memoryResults.add(
+ trip.copyWith(
+ memories: photoSelection,
+ tripYear: year,
+ locationName: locationName,
+ firstDateToShow: nowInMicroseconds,
+ lastDateToShow: windowEnd,
+ ),
+ );
+ break checkUpcomingMonths;
+ }
+ }
+ }
+ }
+ }
+ return (memoryResults, baseLocations);
+ }
+}