Skip to content

armgit / ente

Public Imported from GitHub
0

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

Make most memories work even when ML is off

laurenspriemb370c3e849f7
diff --git a/mobile/apps/photos/lib/services/memories/memories_computation_context.dart b/mobile/apps/photos/lib/services/memories/memories_computation_context.dart
index 7c65b5a663..138f767236 100644
--- a/mobile/apps/photos/lib/services/memories/memories_computation_context.dart
+++ b/mobile/apps/photos/lib/services/memories/memories_computation_context.dart
@@ -12,6 +12,7 @@ class MemoriesComputationContext {
final Map<int, EnteFile> allFileIdsToFile;
final Set<int> collectionIDsToExclude;
final bool isOfflineMode;
+ final bool mlEnabled;
final DateTime now;
final MemoriesCache oldCache;
final bool debugSurfaceAll;
@@ -33,6 +34,7 @@ class MemoriesComputationContext {
required this.allFileIdsToFile,
required this.collectionIDsToExclude,
required this.isOfflineMode,
+ required this.mlEnabled,
required this.now,
required this.oldCache,
required this.debugSurfaceAll,
@@ -61,6 +63,7 @@ class MemoriesComputationContext {
collectionIDsToExclude:
(args["collectionIDsToExclude"] as Set).cast<int>(),
isOfflineMode: args["isOfflineMode"] ?? false,
+ mlEnabled: args["mlEnabled"] ?? false,
now: args["now"] as DateTime,
oldCache: args["oldCache"] as MemoriesCache,
debugSurfaceAll: args["debugSurfaceAll"] ?? false,
@@ -96,6 +99,7 @@ class MemoriesComputationContext {
"allFileIdsToFile": allFileIdsToFile,
"collectionIDsToExclude": collectionIDsToExclude,
"isOfflineMode": isOfflineMode,
+ "mlEnabled": mlEnabled,
"now": now,
"oldCache": oldCache,
"debugSurfaceAll": debugSurfaceAll,
diff --git a/mobile/apps/photos/lib/services/memories/photo_selector.dart b/mobile/apps/photos/lib/services/memories/photo_selector.dart
index 5053091406..aff462c7d7 100644
--- a/mobile/apps/photos/lib/services/memories/photo_selector.dart
+++ b/mobile/apps/photos/lib/services/memories/photo_selector.dart
@@ -1,5 +1,5 @@
import "dart:developer" as dev show log;
-import "dart:math" show max;
+import "dart:math" show Random, max;
import "package:ente_pure_utils/ente_pure_utils.dart";
import "package:flutter/foundation.dart" show kDebugMode;
@@ -554,11 +554,17 @@ class PhotoSelector {
}
/// Returns the best selection for time and trip memories.
+ ///
+ /// When [mlEnabled] is false, scoring and CLIP near-duplicate filtering are
+ /// skipped; candidates are shuffled randomly and distributed across years or
+ /// chronologically based solely on creation time, keeping only the
+ /// time-spacing filter.
static Future<List<Memory>> bestSelection(
List<Memory> memories, {
int? prefferedSize,
SelectionDistribution? distributionOverride,
required bool isOfflineMode,
+ required bool mlEnabled,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
required Map<String, String> faceIDsToPersonID,
required Map<int, EmbeddingVector> fileIDToImageEmbedding,
@@ -568,6 +574,15 @@ class PhotoSelector {
int targetSize = prefferedSize ?? 10;
if (fileCount <= targetSize) return memories;
+ if (!mlEnabled) {
+ return _bestSelectionNoMl(
+ memories,
+ targetSize: targetSize,
+ isOfflineMode: isOfflineMode,
+ distributionOverride: distributionOverride,
+ );
+ }
+
// Pre-compute combined score: face count * 1000 + CLIP nostalgia.
// This replicates the original two-level stable sort (faces primary,
// CLIP secondary) as a single numeric score.
@@ -653,6 +668,163 @@ class PhotoSelector {
}
}
+ // -----------------------------------------------------------------------
+ // ML-free selection path
+ // -----------------------------------------------------------------------
+
+ /// Produces a time-distributed selection without using any ML signals:
+ /// - No scoring (face counts / CLIP nostalgia).
+ /// - No CLIP near-duplicate filtering.
+ /// - Within each year / bucket, candidates are shuffled with fresh
+ /// randomness and then filtered by the time-spacing rule.
+ static List<Memory> _bestSelectionNoMl(
+ List<Memory> memories, {
+ required int targetSize,
+ required bool isOfflineMode,
+ SelectionDistribution? distributionOverride,
+ }) {
+ final withCreationTime =
+ memories.where((m) => m.file.creationTime != null).toList();
+ if (withCreationTime.length <= targetSize) return withCreationTime;
+
+ final random = Random();
+ final allYears = withCreationTime
+ .map(
+ (e) => DateTime.fromMicrosecondsSinceEpoch(e.file.creationTime!).year,
+ )
+ .toSet();
+
+ int effectiveTargetSize = targetSize;
+ final List<Memory> sortedChronologically;
+
+ if (distributionOverride == SelectionDistribution.timeBuckets ||
+ (distributionOverride == null && allYears.length <= 1)) {
+ sortedChronologically = List<Memory>.from(withCreationTime)
+ ..sort((a, b) => a.file.creationTime!.compareTo(b.file.creationTime!));
+ // Single year / time-buckets override: distribute evenly across the
+ // chronological range and shuffle within each bucket.
+ return _pickAcrossTimeBuckets(
+ sortedChronologically,
+ targetSize: effectiveTargetSize,
+ random: random,
+ );
+ }
+
+ if (distributionOverride == null && (allYears.length * 2) > 10) {
+ effectiveTargetSize = allYears.length * 3;
+ if (withCreationTime.length < effectiveTargetSize) {
+ return withCreationTime;
+ }
+ }
+
+ // Multiple years: round-robin through recent-years-first, shuffling each
+ // year's list with fresh randomness.
+ final yearToFiles = <int, List<Memory>>{};
+ for (final mem in withCreationTime) {
+ final year =
+ DateTime.fromMicrosecondsSinceEpoch(mem.file.creationTime!).year;
+ yearToFiles.putIfAbsent(year, () => []).add(mem);
+ }
+ for (final yearFiles in yearToFiles.values) {
+ yearFiles.shuffle(random);
+ }
+ final years = yearToFiles.keys.toList()..sort((a, b) => b.compareTo(a));
+
+ final selected = <Memory>[];
+ final selectedCreationTimes = <int>[];
+ final fileCount = withCreationTime.length;
+ int skipped = 0;
+
+ outerLoop:
+ while (selected.length + skipped < fileCount) {
+ for (final year in years) {
+ final yearFiles = yearToFiles[year]!;
+ if (yearFiles.isEmpty) continue;
+ final candidate = yearFiles.removeAt(0);
+ final creationTime = candidate.file.creationTime;
+ if (isTooCloseInTime(creationTime, selectedCreationTimes)) {
+ skipped++;
+ continue;
+ }
+ selected.add(candidate);
+ if (creationTime != null) selectedCreationTimes.add(creationTime);
+ if (selected.length >= effectiveTargetSize ||
+ selected.length + skipped >= fileCount) {
+ break outerLoop;
+ }
+ }
+ }
+
+ selected
+ .sort((a, b) => a.file.creationTime!.compareTo(b.file.creationTime!));
+ return selected;
+ }
+
+ static List<Memory> _pickAcrossTimeBuckets(
+ List<Memory> sorted, {
+ required int targetSize,
+ required Random random,
+ }) {
+ if (sorted.length <= targetSize) return sorted;
+ final minCreationTime = sorted.first.file.creationTime!;
+ final maxCreationTime = sorted.last.file.creationTime!;
+ if (minCreationTime == maxCreationTime) {
+ final shuffled = List<Memory>.from(sorted)..shuffle(random);
+ return shuffled.take(targetSize).toList()
+ ..sort((a, b) => a.file.creationTime!.compareTo(b.file.creationTime!));
+ }
+ final int numBuckets = targetSize;
+ final int totalRange = maxCreationTime - minCreationTime + 1;
+ final List<List<Memory>> buckets =
+ List.generate(numBuckets, (_) => <Memory>[]);
+ for (final mem in sorted) {
+ final creationTime = mem.file.creationTime!;
+ final bucketIndex =
+ ((creationTime - minCreationTime) * numBuckets ~/ totalRange)
+ .clamp(0, numBuckets - 1);
+ buckets[bucketIndex].add(mem);
+ }
+
+ final selected = <Memory>[];
+ final selectedCreationTimes = <int>[];
+ for (final bucket in buckets) {
+ if (bucket.isEmpty) continue;
+ bucket.shuffle(random);
+ Memory? chosen;
+ for (final candidate in bucket) {
+ if (!isTooCloseInTime(
+ candidate.file.creationTime,
+ selectedCreationTimes,
+ )) {
+ chosen = candidate;
+ break;
+ }
+ }
+ chosen ??= bucket.first;
+ selected.add(chosen);
+ final ct = chosen.file.creationTime;
+ if (ct != null) selectedCreationTimes.add(ct);
+ }
+
+ if (selected.length < targetSize) {
+ final selectedSet = selected.toSet();
+ for (final mem in sorted) {
+ if (selected.length >= targetSize) break;
+ if (selectedSet.contains(mem)) continue;
+ if (isTooCloseInTime(mem.file.creationTime, selectedCreationTimes)) {
+ continue;
+ }
+ selected.add(mem);
+ final ct = mem.file.creationTime;
+ if (ct != null) selectedCreationTimes.add(ct);
+ }
+ }
+
+ selected
+ .sort((a, b) => a.file.creationTime!.compareTo(b.file.creationTime!));
+ return selected;
+ }
+
// -----------------------------------------------------------------------
// Utility functions (shared building blocks)
// -----------------------------------------------------------------------
diff --git a/mobile/apps/photos/lib/services/memories_cache_service.dart b/mobile/apps/photos/lib/services/memories_cache_service.dart
index 3f49c48294..3f6a05f055 100644
--- a/mobile/apps/photos/lib/services/memories_cache_service.dart
+++ b/mobile/apps/photos/lib/services/memories_cache_service.dart
@@ -9,6 +9,7 @@ import "package:path_provider/path_provider.dart";
import "package:photos/core/event_bus.dart";
import "package:photos/db/files_db.dart";
import "package:photos/db/memories_db.dart";
+import "package:photos/db/ml/db.dart";
import "package:photos/db/offline_files_db.dart";
import "package:photos/events/files_updated_event.dart";
import "package:photos/events/memories_changed_event.dart";
@@ -28,6 +29,7 @@ import "package:photos/services/language_service.dart";
import "package:photos/services/machine_learning/face_ml/person/person_service.dart";
import "package:photos/services/notification_service.dart";
import "package:photos/services/search_service.dart";
+import "package:photos/services/smart_memories_service.dart";
import "package:photos/theme/colors.dart";
import "package:photos/ui/home/memories/all_memories_page.dart";
import "package:photos/ui/home/memories/full_screen_memory.dart";
@@ -44,7 +46,7 @@ class MemoriesCacheService {
/// Delay is for cache update to be done not during app init, during which a
/// lot of other things are happening.
- static const _kCacheUpdateDelay = Duration(seconds: 5);
+ static const _kCacheUpdateDelay = Duration(seconds: 20);
final SharedPreferences _prefs;
static final Logger _logger = Logger("MemoriesCacheService");
@@ -66,6 +68,12 @@ class MemoriesCacheService {
Future.delayed(_kCacheUpdateDelay, () {
_checkIfTimeToUpdateCache();
+ // Self-schedule cache updates independently of runAllML, so that users
+ // with ML disabled still get their memories cache refreshed on the
+ // configured cadence. Safe to call unconditionally: updateCache() is a
+ // no-op when neither _shouldUpdate nor forced is true, and the lock
+ // serialises against concurrent invocations from runAllML.
+ unawaited(updateCache());
_memoriesDB.clearMemoriesSeenBeforeTime(
DateTime.now()
.subtract(kMemoriesUpdateFrequency)
@@ -137,15 +145,25 @@ class MemoriesCacheService {
}
}
- bool get enableSmartMemories =>
- hasGrantedMLConsent &&
- localSettings.isMLLocalIndexingEnabled &&
- localSettings.isSmartMemoriesEnabled;
+ bool get enableSmartMemories => localSettings.isSmartMemoriesEnabled;
- bool get curatedMemoriesOption =>
- showAnyMemories &&
- hasGrantedMLConsent &&
- localSettings.isMLLocalIndexingEnabled;
+ bool get curatedMemoriesOption => showAnyMemories;
+
+ bool get _mlEnabled =>
+ hasGrantedMLConsent && localSettings.isMLLocalIndexingEnabled;
+
+ Future<bool> _isMlReady() async {
+ if (!_mlEnabled) return false;
+ try {
+ final mlDataDB =
+ isOfflineMode ? MLDataDB.offlineInstance : MLDataDB.instance;
+ final clipIndexed = await mlDataDB.getClipIndexedFileCount();
+ return clipIndexed >= SmartMemoriesService.minimumMemoryLength;
+ } catch (e, s) {
+ _logger.warning("Failed to read CLIP indexed count", e, s);
+ return false;
+ }
+ }
void _checkIfTimeToUpdateCache() {
if (!enableSmartMemories) {
@@ -522,8 +540,12 @@ class MemoriesCacheService {
// calculate memories for this period and for the next period
final now = DateTime.now();
final next = now.add(kMemoriesUpdateFrequency);
- final nowResult =
- await smartMemoriesService.calcSmartMemories(now, newCache);
+ final mlReady = await _isMlReady();
+ final nowResult = await smartMemoriesService.calcSmartMemories(
+ now,
+ newCache,
+ mlEnabled: mlReady,
+ );
final carriedForwardTripEntries = List<ToShowMemory>.from(
newCache.toShowMemories,
);
@@ -532,8 +554,11 @@ class MemoriesCacheService {
.whereType<TripMemory>()
.map((memory) => ToShowMemory.fromSmartMemory(memory, now)),
);
- final nextResult =
- await smartMemoriesService.calcSmartMemories(next, newCache);
+ final nextResult = await smartMemoriesService.calcSmartMemories(
+ next,
+ newCache,
+ mlEnabled: mlReady,
+ );
w?.log("calculated new memories");
newCache.toShowMemories
..clear()
@@ -773,6 +798,7 @@ class MemoriesCacheService {
DateTime? calcTime,
}) async {
return _memoriesUpdateLock.synchronized(() async {
+ final mlReady = await _isMlReady();
final result = await smartMemoriesService.calcSmartMemories(
calcTime ?? DateTime.now(),
MemoriesCache(
@@ -783,6 +809,7 @@ class MemoriesCacheService {
baseLocations: [],
),
debugSurfaceAll: true,
+ mlEnabled: mlReady,
);
locationService.baseLocations = result.baseLocations;
return result.memories;
diff --git a/mobile/apps/photos/lib/services/search_service.dart b/mobile/apps/photos/lib/services/search_service.dart
index 4c73e23ce4..59c3283f44 100644
--- a/mobile/apps/photos/lib/services/search_service.dart
+++ b/mobile/apps/photos/lib/services/search_service.dart
@@ -1576,8 +1576,13 @@ class SearchService {
if (pickedTime != null) calcTime = pickedTime;
final cache = await memoriesCacheService.debugCacheForTesting();
- final memoriesResult = await smartMemoriesService
- .calcSmartMemories(calcTime, cache, debugSurfaceAll: true);
+ final memoriesResult = await smartMemoriesService.calcSmartMemories(
+ calcTime,
+ cache,
+ debugSurfaceAll: true,
+ mlEnabled:
+ hasGrantedMLConsent && localSettings.isMLLocalIndexingEnabled,
+ );
locationService.baseLocations = memoriesResult.baseLocations;
for (final nowMemory in memoriesResult.memories) {
cache.toShowMemories
diff --git a/mobile/apps/photos/lib/services/smart_memories_service.dart b/mobile/apps/photos/lib/services/smart_memories_service.dart
index 5aa61957cb..593a6bd13f 100644
--- a/mobile/apps/photos/lib/services/smart_memories_service.dart
+++ b/mobile/apps/photos/lib/services/smart_memories_service.dart
@@ -130,11 +130,13 @@ class SmartMemoriesService {
DateTime now,
MemoriesCache oldCache, {
bool debugSurfaceAll = false,
+ required bool mlEnabled,
}) async {
try {
final TimeLogger t = TimeLogger(context: "calcMemories");
_logger.info(
- 'calcMemories called with time: $now at ${DateTime.now()} $t',
+ 'calcMemories called with time: $now at ${DateTime.now()} '
+ '(mlEnabled: $mlEnabled) $t',
);
final allFileIdsToFile = await _getFilesAndMapForMemories(
@@ -153,7 +155,7 @@ class SmartMemoriesService {
final mlDataDB =
isOfflineMode ? MLDataDB.offlineInstance : MLDataDB.instance;
- final allPersons = isOfflineMode
+ final allPersons = (!mlEnabled || isOfflineMode)
? const <PersonEntity>[]
: await PersonService.instance.getPersons();
final persons =
@@ -162,7 +164,7 @@ class SmartMemoriesService {
'gotten all ${persons.length} persons after filtering $t',
);
final bool unnamedPeopleFallbackEnabled =
- localSettings.showOfflineModeOption;
+ mlEnabled && localSettings.showOfflineModeOption;
final amountOfNonIgnoredPersons =
persons.where((person) => !person.data.isIgnored).length;
final canUseUnnamedFallback = unnamedPeopleFallbackEnabled &&
@@ -190,38 +192,51 @@ class SmartMemoriesService {
final cities = await locationService.getCities();
_logger.info('cities has ${cities.length} entries $t');
- final Map<int, List<FaceWithoutEmbedding>> fileIdToFaces =
- await mlDataDB.getFileIDsToFacesWithoutEmbedding();
+ final Map<int, List<FaceWithoutEmbedding>> fileIdToFaces = mlEnabled
+ ? await mlDataDB.getFileIDsToFacesWithoutEmbedding()
+ : <int, List<FaceWithoutEmbedding>>{};
_logger.info('fileIdToFaces has ${fileIdToFaces.length} entries $t');
- final allImageEmbeddings = await mlDataDB.getAllClipVectors();
+ final allImageEmbeddings = mlEnabled
+ ? await mlDataDB.getAllClipVectors()
+ : const <EmbeddingVector>[];
_logger.info(
'allImageEmbeddings has ${allImageEmbeddings.length} entries $t',
);
- _logger.info('Loading text embeddings via cache service');
- final clipPositiveTextVector = Vector.fromList(
- await textEmbeddingsCacheService.getEmbedding(
- "Photo of a precious and nostalgic memory radiating warmth, vibrant energy, or quiet beauty β€” alive with color, light, or emotion",
- ),
- );
-
- final clipPeopleActivityVectors = <PeopleActivity, Vector>{};
- for (final activity in PeopleActivity.values) {
- final query = activityQuery(activity);
- clipPeopleActivityVectors[activity] = Vector.fromList(
- await textEmbeddingsCacheService.getEmbedding(query),
+ final Vector clipPositiveTextVector;
+ final Map<PeopleActivity, Vector> clipPeopleActivityVectors;
+ final Map<ClipMemoryType, Vector> clipMemoryTypeVectors;
+ if (mlEnabled) {
+ _logger.info('Loading text embeddings via cache service');
+ clipPositiveTextVector = Vector.fromList(
+ await textEmbeddingsCacheService.getEmbedding(
+ "Photo of a precious and nostalgic memory radiating warmth, vibrant energy, or quiet beauty β€” alive with color, light, or emotion",
+ ),
);
- }
- final clipMemoryTypeVectors = <ClipMemoryType, Vector>{};
- for (final memoryType in ClipMemoryType.values) {
- final query = clipQuery(memoryType);
- clipMemoryTypeVectors[memoryType] = Vector.fromList(
- await textEmbeddingsCacheService.getEmbedding(query),
- );
+ clipPeopleActivityVectors = <PeopleActivity, Vector>{};
+ for (final activity in PeopleActivity.values) {
+ final query = activityQuery(activity);
+ clipPeopleActivityVectors[activity] = Vector.fromList(
+ await textEmbeddingsCacheService.getEmbedding(query),
+ );
+ }
+
+ clipMemoryTypeVectors = <ClipMemoryType, Vector>{};
+ for (final memoryType in ClipMemoryType.values) {
+ final query = clipQuery(memoryType);
+ clipMemoryTypeVectors[memoryType] = Vector.fromList(
+ await textEmbeddingsCacheService.getEmbedding(query),
+ );
+ }
+ _logger.info('Text embeddings loaded via cache service');
+ } else {
+ _logger.info('ML disabled, skipping text embedding loads');
+ clipPositiveTextVector = Vector.fromList(const [0.0]);
+ clipPeopleActivityVectors = const <PeopleActivity, Vector>{};
+ clipMemoryTypeVectors = const <ClipMemoryType, Vector>{};
}
- _logger.info('Text embeddings loaded via cache service');
final local = await getLocale();
final languageCode = local?.languageCode ?? "en";
@@ -234,6 +249,7 @@ class SmartMemoriesService {
allFileIdsToFile: allFileIdsToFile,
collectionIDsToExclude: collectionIDsToExclude,
isOfflineMode: isOfflineMode,
+ mlEnabled: mlEnabled,
now: now,
oldCache: oldCache,
debugSurfaceAll: debugSurfaceAll,
@@ -655,6 +671,7 @@ class SmartMemoriesService {
final Set<int> collectionIDsToExclude =
computationContext.collectionIDsToExclude;
final bool isOfflineMode = computationContext.isOfflineMode;
+ final bool mlEnabled = computationContext.mlEnabled;
final DateTime now = computationContext.now;
final MemoriesCache oldCache = computationContext.oldCache;
final bool debugSurfaceAll = computationContext.debugSurfaceAll;
@@ -728,35 +745,39 @@ class SmartMemoriesService {
"${_remainingFilesCount(allFileIdsToFile, usedMemoryFileIds)} $t",
);
- // People memories
- final peopleMemories = await _getPeopleResults(
- allFileIdsToFile,
- now,
- oldCache.peopleShownLogs,
- surfaceAll: debugSurfaceAll,
- seenTimes: seenTimes,
- persons: persons,
- isOfflineMode: isOfflineMode,
- canUseUnnamedFallback: canUseUnnamedFallback,
- currentUserEmail: currentUserEmail,
- fileIdToFaces: fileIdToFaces,
- clusterIdToFaceCount: clusterIdToFaceCount,
- clusterIdToFaceIDs: clusterIdToFaceIDs,
- assignedClusterIDs: assignedClusterIDs,
- fileIDToImageEmbedding: fileIDToImageEmbedding,
- clipPositiveTextVector: clipPositiveTextVector,
- clipPeopleActivityVectors: clipPeopleActivityVectors,
- );
- _markUsedMemories(
- usedMemoryFileIds,
- peopleMemories,
- isOfflineMode: isOfflineMode,
- );
- memories.addAll(peopleMemories);
- dev.log(
- "All files length after people: "
- "${_remainingFilesCount(allFileIdsToFile, usedMemoryFileIds)} $t",
- );
+ // People memories (ML only)
+ if (mlEnabled) {
+ final peopleMemories = await _getPeopleResults(
+ allFileIdsToFile,
+ now,
+ oldCache.peopleShownLogs,
+ surfaceAll: debugSurfaceAll,
+ seenTimes: seenTimes,
+ persons: persons,
+ isOfflineMode: isOfflineMode,
+ canUseUnnamedFallback: canUseUnnamedFallback,
+ currentUserEmail: currentUserEmail,
+ fileIdToFaces: fileIdToFaces,
+ clusterIdToFaceCount: clusterIdToFaceCount,
+ clusterIdToFaceIDs: clusterIdToFaceIDs,
+ assignedClusterIDs: assignedClusterIDs,
+ fileIDToImageEmbedding: fileIDToImageEmbedding,
+ clipPositiveTextVector: clipPositiveTextVector,
+ clipPeopleActivityVectors: clipPeopleActivityVectors,
+ );
+ _markUsedMemories(
+ usedMemoryFileIds,
+ peopleMemories,
+ isOfflineMode: isOfflineMode,
+ );
+ memories.addAll(peopleMemories);
+ dev.log(
+ "All files length after people: "
+ "${_remainingFilesCount(allFileIdsToFile, usedMemoryFileIds)} $t",
+ );
+ } else {
+ dev.log('ML disabled, skipping people memories $t');
+ }
// Trip memories
final (tripMemories, bases) = await _getTripsResults(
@@ -767,6 +788,7 @@ class SmartMemoriesService {
surfaceAll: debugSurfaceAll,
cachedTripMemories: oldCache.toShowMemories,
isOfflineMode: isOfflineMode,
+ mlEnabled: mlEnabled,
seenTimes: seenTimes,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
@@ -785,27 +807,31 @@ class SmartMemoriesService {
"${_remainingFilesCount(allFileIdsToFile, usedMemoryFileIds)} $t",
);
- // Clip memories
- final clipMemories = await _getClipResults(
- fullSourceFiles,
- now,
- oldCache.clipShownLogs,
- surfaceAll: debugSurfaceAll,
- isOfflineMode: isOfflineMode,
- seenTimes: seenTimes,
- fileIDToImageEmbedding: fileIDToImageEmbedding,
- clipMemoryTypeVectors: clipMemoryTypeVectors,
- );
- _markUsedMemories(
- usedMemoryFileIds,
- clipMemories,
- isOfflineMode: isOfflineMode,
- );
- memories.addAll(clipMemories);
- dev.log(
- "All files length after clip memories: "
- "${_remainingFilesCount(allFileIdsToFile, usedMemoryFileIds)} $t",
- );
+ // Clip memories (ML only)
+ if (mlEnabled) {
+ final clipMemories = await _getClipResults(
+ fullSourceFiles,
+ now,
+ oldCache.clipShownLogs,
+ surfaceAll: debugSurfaceAll,
+ isOfflineMode: isOfflineMode,
+ seenTimes: seenTimes,
+ fileIDToImageEmbedding: fileIDToImageEmbedding,
+ clipMemoryTypeVectors: clipMemoryTypeVectors,
+ );
+ _markUsedMemories(
+ usedMemoryFileIds,
+ clipMemories,
+ isOfflineMode: isOfflineMode,
+ );
+ memories.addAll(clipMemories);
+ dev.log(
+ "All files length after clip memories: "
+ "${_remainingFilesCount(allFileIdsToFile, usedMemoryFileIds)} $t",
+ );
+ } else {
+ dev.log('ML disabled, skipping clip memories $t');
+ }
// Time memories
final timeFiles = _collectAvailableFiles(
@@ -817,6 +843,7 @@ class SmartMemoriesService {
now,
recentSourceFiles: fullSourceFiles,
isOfflineMode: isOfflineMode,
+ mlEnabled: mlEnabled,
seenTimes: seenTimes,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
@@ -1032,6 +1059,7 @@ class SmartMemoriesService {
bool surfaceAll = false,
required Iterable<ToShowMemory> cachedTripMemories,
required bool isOfflineMode,
+ required bool mlEnabled,
required Map<int, int> seenTimes,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
required Map<String, String> faceIDsToPersonID,
@@ -1047,6 +1075,7 @@ class SmartMemoriesService {
surfaceAll: surfaceAll,
cachedTripMemories: cachedTripMemories,
isOfflineMode: isOfflineMode,
+ mlEnabled: mlEnabled,
seenTimes: seenTimes,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
@@ -1061,6 +1090,7 @@ class SmartMemoriesService {
DateTime currentTime, {
required Iterable<EnteFile> recentSourceFiles,
required bool isOfflineMode,
+ required bool mlEnabled,
required Map<int, int> seenTimes,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
required Map<String, String> faceIDsToPersonID,
@@ -1072,6 +1102,7 @@ class SmartMemoriesService {
currentTime,
recentSourceFiles: recentSourceFiles,
isOfflineMode: isOfflineMode,
+ mlEnabled: mlEnabled,
seenTimes: seenTimes,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
@@ -1236,6 +1267,7 @@ class SmartMemoriesService {
int? prefferedSize,
SelectionDistribution? distributionOverride,
required bool isOfflineMode,
+ required bool mlEnabled,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
required Map<String, String> faceIDsToPersonID,
required Map<int, EmbeddingVector> fileIDToImageEmbedding,
@@ -1246,6 +1278,7 @@ class SmartMemoriesService {
prefferedSize: prefferedSize,
distributionOverride: distributionOverride,
isOfflineMode: isOfflineMode,
+ mlEnabled: mlEnabled,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
fileIDToImageEmbedding: fileIDToImageEmbedding,
diff --git a/mobile/apps/photos/lib/services/smart_memories_time_calculator.dart b/mobile/apps/photos/lib/services/smart_memories_time_calculator.dart
index 53fb299fa5..63bc188fbf 100644
--- a/mobile/apps/photos/lib/services/smart_memories_time_calculator.dart
+++ b/mobile/apps/photos/lib/services/smart_memories_time_calculator.dart
@@ -8,6 +8,7 @@ class TimeMemoriesCalculator {
DateTime currentTime, {
Iterable<EnteFile>? recentSourceFiles,
required bool isOfflineMode,
+ required bool mlEnabled,
required Map<int, int> seenTimes,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
required Map<String, String> faceIDsToPersonID,
@@ -33,6 +34,7 @@ class TimeMemoriesCalculator {
showEnd: startOfCurrentWeek.add(const Duration(days: 7)),
kind: TimeMemoryKind.lastWeek,
isOfflineMode: isOfflineMode,
+ mlEnabled: mlEnabled,
seenTimes: seenTimes,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
@@ -57,6 +59,7 @@ class TimeMemoriesCalculator {
),
kind: TimeMemoryKind.lastMonth,
isOfflineMode: isOfflineMode,
+ mlEnabled: mlEnabled,
seenTimes: seenTimes,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
@@ -106,6 +109,7 @@ class TimeMemoriesCalculator {
final photoSelection = await SmartMemoriesService._bestSelection(
allPhotos,
isOfflineMode: isOfflineMode,
+ mlEnabled: mlEnabled,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
fileIDToImageEmbedding: fileIDToImageEmbedding,
@@ -129,6 +133,7 @@ class TimeMemoriesCalculator {
final photoSelection = await SmartMemoriesService._bestSelection(
files,
isOfflineMode: isOfflineMode,
+ mlEnabled: mlEnabled,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
fileIDToImageEmbedding: fileIDToImageEmbedding,
@@ -174,6 +179,7 @@ class TimeMemoriesCalculator {
final photoSelection = await SmartMemoriesService._bestSelection(
allPhotos,
isOfflineMode: isOfflineMode,
+ mlEnabled: mlEnabled,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
fileIDToImageEmbedding: fileIDToImageEmbedding,
@@ -195,6 +201,7 @@ class TimeMemoriesCalculator {
final photoSelection = await SmartMemoriesService._bestSelection(
files,
isOfflineMode: isOfflineMode,
+ mlEnabled: mlEnabled,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
fileIDToImageEmbedding: fileIDToImageEmbedding,
@@ -258,6 +265,7 @@ class TimeMemoriesCalculator {
monthYearFiles,
prefferedSize: monthSelectionSize,
isOfflineMode: isOfflineMode,
+ mlEnabled: mlEnabled,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
fileIDToImageEmbedding: fileIDToImageEmbedding,
@@ -287,6 +295,7 @@ class TimeMemoriesCalculator {
allPhotos,
prefferedSize: monthSelectionSize,
isOfflineMode: isOfflineMode,
+ mlEnabled: mlEnabled,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
fileIDToImageEmbedding: fileIDToImageEmbedding,
@@ -315,6 +324,7 @@ class TimeMemoriesCalculator {
required DateTime showEnd,
required TimeMemoryKind kind,
required bool isOfflineMode,
+ required bool mlEnabled,
required Map<int, int> seenTimes,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
required Map<String, String> faceIDsToPersonID,
@@ -343,6 +353,7 @@ class TimeMemoriesCalculator {
prefferedSize: _recentTimeMemorySelectionSize,
distributionOverride: SelectionDistribution.timeBuckets,
isOfflineMode: isOfflineMode,
+ mlEnabled: mlEnabled,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
fileIDToImageEmbedding: fileIDToImageEmbedding,
diff --git a/mobile/apps/photos/lib/services/smart_memories_trip_calculator_v2.dart b/mobile/apps/photos/lib/services/smart_memories_trip_calculator_v2.dart
index ff84530761..cb34f42b2d 100644
--- a/mobile/apps/photos/lib/services/smart_memories_trip_calculator_v2.dart
+++ b/mobile/apps/photos/lib/services/smart_memories_trip_calculator_v2.dart
@@ -139,6 +139,7 @@ class TripMemoriesCalculatorV2 {
bool surfaceAll = false,
required Iterable<ToShowMemory> cachedTripMemories,
required bool isOfflineMode,
+ required bool mlEnabled,
required Map<int, int> seenTimes,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
required Map<String, String> faceIDsToPersonID,
@@ -238,6 +239,7 @@ class TripMemoriesCalculatorV2 {
windowEnd,
seenTimes: seenTimes,
isOfflineMode: isOfflineMode,
+ mlEnabled: mlEnabled,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
fileIDToImageEmbedding: fileIDToImageEmbedding,
@@ -255,6 +257,7 @@ class TripMemoriesCalculatorV2 {
shownTrips,
cachedTripMemories: cachedTripMemories,
isOfflineMode: isOfflineMode,
+ mlEnabled: mlEnabled,
seenTimes: seenTimes,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
@@ -860,6 +863,7 @@ class TripMemoriesCalculatorV2 {
int windowEnd, {
required Map<int, int> seenTimes,
required bool isOfflineMode,
+ required bool mlEnabled,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
required Map<String, String> faceIDsToPersonID,
required Map<int, EmbeddingVector> fileIDToImageEmbedding,
@@ -901,6 +905,7 @@ class TripMemoriesCalculatorV2 {
final photoSelection = await SmartMemoriesService._bestSelection(
trip.memories,
isOfflineMode: isOfflineMode,
+ mlEnabled: mlEnabled,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
fileIDToImageEmbedding: fileIDToImageEmbedding,
@@ -930,6 +935,7 @@ class TripMemoriesCalculatorV2 {
List<TripsShownLog> shownTrips, {
required Iterable<ToShowMemory> cachedTripMemories,
required bool isOfflineMode,
+ required bool mlEnabled,
required Map<int, int> seenTimes,
required Map<int, List<FaceWithoutEmbedding>> fileIdToFaces,
required Map<String, String> faceIDsToPersonID,
@@ -1039,6 +1045,7 @@ class TripMemoriesCalculatorV2 {
final photoSelection = await SmartMemoriesService._bestSelection(
trip.memories,
isOfflineMode: isOfflineMode,
+ mlEnabled: mlEnabled,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
fileIDToImageEmbedding: fileIDToImageEmbedding,
diff --git a/mobile/apps/photos/lib/ui/settings/ml/machine_learning_settings_page.dart b/mobile/apps/photos/lib/ui/settings/ml/machine_learning_settings_page.dart
index e143d0fa63..fe2bcfd41a 100644
--- a/mobile/apps/photos/lib/ui/settings/ml/machine_learning_settings_page.dart
+++ b/mobile/apps/photos/lib/ui/settings/ml/machine_learning_settings_page.dart
@@ -230,6 +230,11 @@ class _MachineLearningSettingsPageState
final oldMlConsent = hasGrantedMLConsent;
final mlConsent = !oldMlConsent;
await setMLConsent(mlConsent);
+ // Queue a memories cache refresh so People/Clip memories appear or
+ // disappear on the next scheduled recompute. We intentionally only queue
+ // here β€” the actual recompute will be picked up by the next updateCache
+ // invocation (runAllML after indexing, or the startup self-schedule).
+ memoriesCacheService.queueUpdateCache();
Bus.instance.fire(NotificationEvent());
if (!mlConsent) {
MLService.instance.pauseIndexingAndClustering();
@@ -358,6 +363,7 @@ class _MachineLearningSettingsPageState
value: () => localSettings.isMLLocalIndexingEnabled,
onChanged: () async {
final localIndexing = await localSettings.toggleLocalMLIndexing();
+ memoriesCacheService.queueUpdateCache();
Bus.instance.fire(NotificationEvent());
if (localIndexing) {
unawaited(MLService.instance.runAllML(force: true));
diff --git a/mobile/apps/photos/test/services/memories/photo_selector_test.dart b/mobile/apps/photos/test/services/memories/photo_selector_test.dart
index c9b77f51e3..9a71157ce2 100644
--- a/mobile/apps/photos/test/services/memories/photo_selector_test.dart
+++ b/mobile/apps/photos/test/services/memories/photo_selector_test.dart
@@ -227,6 +227,7 @@ void main() {
final result = await PhotoSelector.bestSelection(
memories,
isOfflineMode: false,
+ mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
fileIDToImageEmbedding: _embMap(embeddings),
@@ -248,6 +249,7 @@ void main() {
final result = await PhotoSelector.bestSelection(
memories,
isOfflineMode: false,
+ mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
fileIDToImageEmbedding: _embMap(embeddings),
@@ -267,6 +269,7 @@ void main() {
final result = await PhotoSelector.bestSelection(
memories,
isOfflineMode: false,
+ mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
fileIDToImageEmbedding: _embMap(embeddings),
@@ -294,6 +297,7 @@ void main() {
final result = await PhotoSelector.bestSelection(
memories,
isOfflineMode: false,
+ mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
fileIDToImageEmbedding: _embMap(embeddings),
@@ -338,6 +342,7 @@ void main() {
final result = await PhotoSelector.bestSelection(
memories,
isOfflineMode: false,
+ mlEnabled: true,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
fileIDToImageEmbedding: _embMap(embeddings),
@@ -367,6 +372,7 @@ void main() {
final result = await PhotoSelector.bestSelection(
memories,
isOfflineMode: false,
+ mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
fileIDToImageEmbedding: _embMap(embeddings),
@@ -410,6 +416,7 @@ void main() {
final result = await PhotoSelector.bestSelection(
memories,
isOfflineMode: false,
+ mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
fileIDToImageEmbedding: _embMap(embeddings),
@@ -446,6 +453,7 @@ void main() {
final result = await PhotoSelector.bestSelection(
memories,
isOfflineMode: false,
+ mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
fileIDToImageEmbedding: _embMap(embeddings),
@@ -495,6 +503,7 @@ void main() {
final result = await PhotoSelector.bestSelection(
memories,
isOfflineMode: false,
+ mlEnabled: true,
fileIdToFaces: fileIdToFaces,
faceIDsToPersonID: faceIDsToPersonID,
fileIDToImageEmbedding: _embMap(embeddings),
@@ -536,6 +545,7 @@ void main() {
final result = await PhotoSelector.bestSelection(
memories,
isOfflineMode: false,
+ mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
fileIDToImageEmbedding: _embMap(embeddings),
@@ -573,6 +583,7 @@ void main() {
final result = await PhotoSelector.bestSelection(
memories,
isOfflineMode: false,
+ mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
fileIDToImageEmbedding: _embMap(embeddings),
@@ -610,6 +621,7 @@ void main() {
final result = await PhotoSelector.bestSelection(
memories,
isOfflineMode: false,
+ mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
fileIDToImageEmbedding: _embMap(embeddings),
@@ -898,6 +910,7 @@ void main() {
final result = await PhotoSelector.bestSelection(
copy,
isOfflineMode: false,
+ mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
fileIDToImageEmbedding: embMap,
@@ -945,6 +958,7 @@ void main() {
final result = await PhotoSelector.bestSelection(
copy,
isOfflineMode: false,
+ mlEnabled: true,
fileIdToFaces: {},
faceIDsToPersonID: {},
fileIDToImageEmbedding: embMap,
diff --git a/mobile/apps/photos/test/services/memories/smart_memories_source_selection_test.dart b/mobile/apps/photos/test/services/memories/smart_memories_source_selection_test.dart
index 0a3274a311..03a41dce74 100644
--- a/mobile/apps/photos/test/services/memories/smart_memories_source_selection_test.dart
+++ b/mobile/apps/photos/test/services/memories/smart_memories_source_selection_test.dart
@@ -68,6 +68,7 @@ void main() {
surfaceAll: true,
cachedTripMemories: const <ToShowMemory>[],
isOfflineMode: false,
+ mlEnabled: true,
seenTimes: const <int, int>{},
fileIdToFaces: const <int, List<FaceWithoutEmbedding>>{},
faceIDsToPersonID: const <String, String>{},
@@ -84,6 +85,7 @@ void main() {
surfaceAll: true,
cachedTripMemories: const <ToShowMemory>[],
isOfflineMode: false,
+ mlEnabled: true,
seenTimes: const <int, int>{},
fileIdToFaces: const <int, List<FaceWithoutEmbedding>>{},
faceIDsToPersonID: const <String, String>{},
@@ -122,6 +124,7 @@ void main() {
currentTime,
recentSourceFiles: fullRecentSource,
isOfflineMode: false,
+ mlEnabled: true,
seenTimes: const <int, int>{},
fileIdToFaces: const <int, List<FaceWithoutEmbedding>>{},
faceIDsToPersonID: const <String, String>{},