π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mob][photos] Clip memories
laurenspriemf05c3c98a7c7
diff --git a/mobile/lib/models/memories/clip_memory.dart b/mobile/lib/models/memories/clip_memory.dartnew file mode 100644index 0000000000..7ec73aa5db--- /dev/null+++ b/mobile/lib/models/memories/clip_memory.dart@@ -0,0 +1,131 @@+import "package:photos/models/memories/memory.dart";+import "package:photos/models/memories/smart_memory.dart";++enum ClipMemoryType {+ sunrise,+ sunset,+ mountains,+ greenery,+ beach,+ city,+ moon,+ onTheRoad,+ food,+ pets+}++ClipMemoryType clipMemoryTypeFromString(String type) {+ switch (type) {+ case "sunrise":+ return ClipMemoryType.sunrise;+ case "sunset":+ return ClipMemoryType.sunset;+ case "mountains":+ return ClipMemoryType.mountains;+ case "greenery":+ return ClipMemoryType.greenery;+ case "beach":+ return ClipMemoryType.beach;+ case "city":+ return ClipMemoryType.city;+ case "moon":+ return ClipMemoryType.moon;+ case "onTheRoad":+ return ClipMemoryType.onTheRoad;+ case "food":+ return ClipMemoryType.food;+ case "pets":+ return ClipMemoryType.pets;+ default:+ throw ArgumentError("Invalid people memory type: $type");+ }+}++String clipQuery(ClipMemoryType clipMemoryType) {+ switch (clipMemoryType) {+ case ClipMemoryType.sunrise:+ return "Photo of an absolutely stunning sunrise";+ case ClipMemoryType.sunset:+ return "Photo of an absolutely stunning sunset";+ case ClipMemoryType.mountains:+ return "Photo of a beautiful mountain range";+ case ClipMemoryType.greenery:+ return "Photo of lush greenery";+ case ClipMemoryType.beach:+ return "Photo of a beautiful beach";+ case ClipMemoryType.city:+ return "Beautiful photo showing a metropolitan city";+ case ClipMemoryType.moon:+ return "Photo of a beautiful moon";+ case ClipMemoryType.onTheRoad:+ return "Photo of a nostalgic road trip";+ case ClipMemoryType.food:+ return "Photo of delicious looking food";+ case ClipMemoryType.pets:+ return "Photo of cute pets";+ }+}++String clipTitle(ClipMemoryType clipMemoryType) {+ switch (clipMemoryType) {+ case ClipMemoryType.sunrise:+ return "Sunrise";+ case ClipMemoryType.sunset:+ return "Sunset";+ case ClipMemoryType.mountains:+ return "Mountains";+ case ClipMemoryType.greenery:+ return "Greenery";+ case ClipMemoryType.beach:+ return "Beach";+ case ClipMemoryType.city:+ return "City";+ case ClipMemoryType.moon:+ return "Moon";+ case ClipMemoryType.onTheRoad:+ return "On the Road";+ case ClipMemoryType.food:+ return "Food";+ case ClipMemoryType.pets:+ return "Pets";+ }+}++class ClipMemory extends SmartMemory {+ final ClipMemoryType clipMemoryType;++ ClipMemory(+ List<Memory> memories,+ String title,+ int firstDateToShow,+ int lastDateToShow,+ this.clipMemoryType, {+ super.firstCreationTime,+ super.lastCreationTime,+ }) : super(+ memories,+ MemoryType.clip,+ title,+ firstDateToShow,+ lastDateToShow,+ );++ ClipMemory copyWith({+ List<Memory>? memories,+ String? title,+ int? firstDateToShow,+ int? lastDateToShow,+ int? firstCreationTime,+ int? lastCreationTime,+ }) {+ return ClipMemory(+ memories ?? this.memories,+ title ?? this.title,+ firstDateToShow ?? this.firstDateToShow,+ lastDateToShow ?? this.lastDateToShow,+ clipMemoryType,+ firstCreationTime: firstCreationTime ?? this.firstCreationTime,+ lastCreationTime: lastCreationTime ?? this.lastCreationTime,+ );+ }+}diff --git a/mobile/lib/models/memories/memories_cache.dart b/mobile/lib/models/memories/memories_cache.dartindex 8d6a85d4a1..7a5ba47507 100644--- a/mobile/lib/models/memories/memories_cache.dart+++ b/mobile/lib/models/memories/memories_cache.dart@@ -3,6 +3,7 @@ import "dart:convert";import "package:photos/models/base_location.dart";import "package:photos/models/file/file.dart";import "package:photos/models/location/location.dart";+import "package:photos/models/memories/clip_memory.dart";import "package:photos/models/memories/people_memory.dart";import "package:photos/models/memories/smart_memory.dart";import "package:photos/models/memories/smart_memory_constants.dart";@@ -10,6 +11,7 @@ import "package:photos/models/memories/trip_memory.dart";const kPersonShowTimeout = Duration(days: 7 * 10);const kPersonAndTypeShowTimeout = Duration(days: 7 * 26);+const kClipShowTimeout = Duration(days: 3 * 10);const kTripShowTimeout = Duration(days: 7 * 25);final maxShowTimeout = [@@ -22,12 +24,14 @@ final maxShowTimeout = [class MemoriesCache {final List<ToShowMemory> toShowMemories;final List<PeopleShownLog> peopleShownLogs;+ final List<ClipShownLog> clipShownLogs;final List<TripsShownLog> tripsShownLogs;final List<BaseLocation> baseLocations;MemoriesCache({required this.toShowMemories,required this.peopleShownLogs,+ required this.clipShownLogs,required this.tripsShownLogs,required this.baseLocations,});@@ -39,6 +43,7 @@ class MemoriesCache {return MemoriesCache(toShowMemories: ToShowMemory.decodeJsonToList(json['toShowMemories']),peopleShownLogs: PeopleShownLog.decodeJsonToList(json['peopleShownLogs']),+ clipShownLogs: ClipShownLog.decodeJsonToList(json['clipShownLogs']),tripsShownLogs: TripsShownLog.decodeJsonToList(json['tripsShownLogs']),baseLocations: json['baseLocations'] != null? BaseLocation.decodeJsonToList(@@ -53,6 +58,7 @@ class MemoriesCache {return {'toShowMemories': ToShowMemory.encodeListToJson(toShowMemories),'peopleShownLogs': PeopleShownLog.encodeListToJson(peopleShownLogs),+ 'clipShownLogs': ClipShownLog.encodeListToJson(clipShownLogs),'tripsShownLogs': TripsShownLog.encodeListToJson(tripsShownLogs),'baseLocations': BaseLocation.encodeListToJson(baseLocations),};@@ -80,6 +86,7 @@ class ToShowMemory {final String? personID;final PeopleMemoryType? peopleMemoryType;+ final ClipMemoryType? clipMemoryType;final Location? location;bool get isOld {@@ -104,25 +111,32 @@ class ToShowMemory {this.calculationTime, {this.personID,this.peopleMemoryType,+ this.clipMemoryType,this.location,}) : assert((type == MemoryType.people &&personID != null &&peopleMemoryType != null) ||(type == MemoryType.trips && location != null) ||- (type != MemoryType.people && type != MemoryType.trips),+ (type == MemoryType.clip && clipMemoryType != null) ||+ (type != MemoryType.people &&+ type != MemoryType.trips &&+ type != MemoryType.clip),"PersonID and peopleMemoryType must be provided for people memory type, and location must be provided for trips memory type",);factory ToShowMemory.fromSmartMemory(SmartMemory memory, DateTime calcTime) {String? personID;PeopleMemoryType? peopleMemoryType;+ ClipMemoryType? clipMemoryType;Location? location;if (memory is PeopleMemory) {personID = memory.personID;peopleMemoryType = memory.peopleMemoryType;} else if (memory is TripMemory) {location = memory.location;+ } else if (memory is ClipMemory) {+ clipMemoryType = memory.clipMemoryType;}return ToShowMemory(memory.title,@@ -136,6 +150,7 @@ class ToShowMemory {calcTime.microsecondsSinceEpoch,personID: personID,peopleMemoryType: peopleMemoryType,+ clipMemoryType: clipMemoryType,location: location,);}@@ -152,6 +167,9 @@ class ToShowMemory {peopleMemoryType: json['peopleMemoryType'] != null? peopleMemoryTypeFromString(json['peopleMemoryType']): null,+ clipMemoryType: json['clipMemoryType'] != null+ ? clipMemoryTypeFromString(json['clipMemoryType'])+ : null,location: json['location'] != null? Location(latitude: json['location']['latitude'],@@ -171,6 +189,7 @@ class ToShowMemory {'calculationTime': calculationTime,'personID': personID,'peopleMemoryType': peopleMemoryType?.toString().split('.').last,+ 'clipMemoryType': clipMemoryType?.toString().split('.').last,'location': location != null? {'latitude': location!.latitude!,@@ -242,6 +261,50 @@ class PeopleShownLog {}}+class ClipShownLog {+ final ClipMemoryType clipMemoryType;+ final int lastTimeShown;++ ClipShownLog(+ this.clipMemoryType,+ this.lastTimeShown,+ );++ factory ClipShownLog.fromOldCacheMemory(ToShowMemory memory) {+ assert(+ memory.type == MemoryType.clip && memory.clipMemoryType != null,+ );+ return ClipShownLog(+ memory.clipMemoryType!,+ memory.lastTimeToShow,+ );+ }++ factory ClipShownLog.fromJson(Map<String, dynamic> json) {+ return ClipShownLog(+ clipMemoryTypeFromString(json['clipMemoryType']),+ json['lastTimeShown'],+ );+ }++ Map<String, dynamic> toJson() {+ return {+ 'clipMemoryType': clipMemoryType.toString().split('.').last,+ 'lastTimeShown': lastTimeShown,+ };+ }++ static String encodeListToJson(List<ClipShownLog> shownLogs) {+ final jsonList = shownLogs.map((log) => log.toJson()).toList();+ return jsonEncode(jsonList);+ }++ static List<ClipShownLog> decodeJsonToList(String jsonString) {+ final jsonList = jsonDecode(jsonString) as List;+ return jsonList.map((json) => ClipShownLog.fromJson(json)).toList();+ }+}+class TripsShownLog {final Location location;final int lastTimeShown;diff --git a/mobile/lib/models/memories/smart_memory.dart b/mobile/lib/models/memories/smart_memory.dartindex b00f83e2bb..cc216d540a 100644--- a/mobile/lib/models/memories/smart_memory.dart+++ b/mobile/lib/models/memories/smart_memory.dart@@ -3,6 +3,7 @@ import "package:photos/models/memories/memory.dart";enum MemoryType {people,trips,+ clip,time,filler,}@@ -17,6 +18,8 @@ MemoryType memoryTypeFromString(String type) {return MemoryType.time;case "filler":return MemoryType.filler;+ case "clip":+ return MemoryType.clip;default:throw ArgumentError("Invalid memory type: $type");}diff --git a/mobile/lib/services/memories_cache_service.dart b/mobile/lib/services/memories_cache_service.dartindex 7d6930fff2..d21834f83c 100644--- a/mobile/lib/services/memories_cache_service.dart+++ b/mobile/lib/services/memories_cache_service.dart@@ -103,7 +103,7 @@ class MemoriesCacheService {Future<String> _getCachePath() async {return (await getApplicationSupportDirectory()).path +- "/cache/test3/memories_cache";+ "/cache/test4/memories_cache";// TODO: lau: remove the test1 directory after testing}@@ -197,6 +197,7 @@ class MemoriesCacheService {MemoriesCache _processOldCache(MemoriesCache? oldCache) {final List<PeopleShownLog> peopleShownLogs = [];+ final List<ClipShownLog> clipShownLogs = [];final List<TripsShownLog> tripsShownLogs = [];if (oldCache != null) {final now = DateTime.now();@@ -216,12 +217,22 @@ class MemoriesCacheService {tripsShownLogs.add(tripsLog);}}+ for (final clipLog in oldCache.clipShownLogs) {+ if (now.difference(+ DateTime.fromMicrosecondsSinceEpoch(clipLog.lastTimeShown),+ ) <+ maxShowTimeout) {+ clipShownLogs.add(clipLog);+ }+ }for (final oldMemory in oldCache.toShowMemories) {if (oldMemory.isOld) {if (oldMemory.type == MemoryType.people) {- peopleShownLogs.add(PeopleShownLog.fromOldCacheMemory(oldMemory));+ peopleShownLogs.add(PeopleShownLog.fromOldCacheMemory(oldMemory));+ } else if (oldMemory.type == MemoryType.clip) {+ clipShownLogs.add(ClipShownLog.fromOldCacheMemory(oldMemory));} else if (oldMemory.type == MemoryType.trips) {- tripsShownLogs.add(TripsShownLog.fromOldCacheMemory(oldMemory));+ tripsShownLogs.add(TripsShownLog.fromOldCacheMemory(oldMemory));}}}@@ -229,6 +240,7 @@ class MemoriesCacheService {return MemoriesCache(toShowMemories: [],peopleShownLogs: peopleShownLogs,+ clipShownLogs: clipShownLogs,tripsShownLogs: tripsShownLogs,baseLocations: [],);diff --git a/mobile/lib/services/smart_memories_service.dart b/mobile/lib/services/smart_memories_service.dartindex 638a16824f..698accf994 100644--- a/mobile/lib/services/smart_memories_service.dart+++ b/mobile/lib/services/smart_memories_service.dart@@ -15,6 +15,7 @@ import "package:photos/extensions/stop_watch.dart";import "package:photos/models/base_location.dart";import "package:photos/models/file/file.dart";import "package:photos/models/location/location.dart";+import "package:photos/models/memories/clip_memory.dart";import "package:photos/models/memories/filler_memory.dart";import "package:photos/models/memories/memories_cache.dart";import "package:photos/models/memories/memory.dart";@@ -47,6 +48,7 @@ class SmartMemoriesService {static const _clipSimilarImageThreshold = 0.75;static const _clipActivityQueryThreshold = 0.25;+ static const _clipMemoryTypeQueryThreshold = 0.25;static const yearsBefore = 30;@@ -100,6 +102,13 @@ class SmartMemoriesService {await MLComputer.instance.runClipText(activityQuery(peopleActivity)),);}+ final Map<ClipMemoryType, Vector> clipMemoryTypeVectors = {};+ for (final clipMemoryType in ClipMemoryType.values) {+ clipMemoryTypeVectors[clipMemoryType] ??= Vector.fromList(+ await MLComputer.instance.runClipText(clipQuery(clipMemoryType)),+ );+ }+ _logger.finest('clipPositiveTextVector and clipPeopleActivityVectors $t');// final locale = await getLocale();// TODO: lau: locale with DateFormat is not working well in computer, fix later@@ -121,6 +130,7 @@ class SmartMemoriesService {"allImageEmbeddings": allImageEmbeddings,"clipPositiveTextVector": clipPositiveTextVector,"clipPeopleActivityVectors": clipPeopleActivityVectors,+ "clipMemoryTypeVectors": clipMemoryTypeVectors,},);} catch (e, s) {@@ -181,6 +191,8 @@ class SmartMemoriesService {final Vector clipPositiveTextVector = args["clipPositiveTextVector"];final Map<PeopleActivity, Vector> clipPeopleActivityVectors =args["clipPeopleActivityVectors"];+ final Map<ClipMemoryType, Vector> clipMemoryTypeVectors =+ args["clipMemoryTypeVectors"];dev.log('All arguments (direct data) unwrapped $t');final Map<String, String> faceIDsToPersonID = {};@@ -236,6 +248,20 @@ class SmartMemoriesService {memories.addAll(tripMemories);dev.log("All files length after trips: ${allFiles.length} $t");+ // Clip memories+ final clipMemories = await _getClipResults(+ allFiles,+ now,+ oldCache.clipShownLogs,+ surfaceAll: debugSurfaceAll,+ seenTimes: seenTimes,+ fileIDToImageEmbedding: fileIDToImageEmbedding,+ clipMemoryTypeVectors: clipMemoryTypeVectors,+ );+ _deductUsedMemories(allFiles, clipMemories);+ memories.addAll(clipMemories);+ dev.log("All files length after clip memories: ${allFiles.length} $t");+// Time memoriesfinal timeMemories = await _onThisDayOrWeekResults(allFiles,@@ -324,8 +350,10 @@ class SmartMemoriesService {.addAll(cluster.faces.map((faceID) => getFileIdFromFaceId(faceID)));}}- final List<String> orderedImportantPersonsID =- persons.where((person) => !person.data.isHidden).map((p) => p.remoteID).toList();+ final List<String> orderedImportantPersonsID = persons+ .where((person) => !person.data.isHidden)+ .map((p) => p.remoteID)+ .toList();orderedImportantPersonsID.sort((a, b) {final aFaces = personIdToFaceIDs[a]!.length;final bFaces = personIdToFaceIDs[b]!.length;@@ -651,6 +679,92 @@ class SmartMemoriesService {return memoryResults;}+ static Future<List<ClipMemory>> _getClipResults(+ Iterable<EnteFile> allFiles,+ DateTime currentTime,+ List<ClipShownLog> shownClip, {+ bool surfaceAll = false,+ 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;+ final Map<ClipMemoryType, ClipMemory> clipTypeToMemory = {};+ w?.log('allFiles setup');++ // Loop through the clip types and find all memories+ final clipFiles = <EnteFile>[];+ for (final clipMemoryType in ClipMemoryType.values) {+ clipFiles.clear();+ final Vector? activityVector = clipMemoryTypeVectors[clipMemoryType];+ if (activityVector == null) {+ dev.log("No vector for clipMemoryType $clipMemoryType");+ continue;+ }+ final Map<int, double> similarities = {};+ for (final fileID in fileIDToImageEmbedding.keys) {+ similarities[fileID] =+ fileIDToImageEmbedding[fileID]!.vector.dot(activityVector);+ }+ w?.log(+ 'comparing embeddings for clipMemoryType $clipMemoryType',+ );+ for (final file in allFiles) {+ final similarity = similarities[file.uploadedFileID!];+ if (similarity == null) continue;+ if (similarity > _clipMemoryTypeQueryThreshold) {+ clipFiles.add(file);+ }+ }+ if (clipFiles.length < 10) continue;+ // sort based on highest similarity first+ clipFiles.sort((a, b) {+ return similarities[b.uploadedFileID!]!+ .compareTo(similarities[a.uploadedFileID!]!);+ });+ clipTypeToMemory[clipMemoryType] = ClipMemory(+ clipFiles.take(10).map((f) => Memory.fromFile(f, seenTimes)).toList(),+ clipTitle(clipMemoryType),+ nowInMicroseconds,+ windowEnd,+ clipMemoryType,+ );+ }++ // Surface everything just for debug checking+ if (surfaceAll) {+ for (final clipMemoryType in ClipMemoryType.values) {+ final clipMemory = clipTypeToMemory[clipMemoryType];+ if (clipMemory != null) clipResults.add(clipMemory);+ }+ return clipResults;+ }++ // Loop through the clip types and add based on rotation+ clipMemoriesLoop:+ for (final clipMemoryType in ClipMemoryType.values) {+ final clipMemory = clipTypeToMemory[clipMemoryType];+ if (clipMemory == null) continue;+ 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;+ }+ clipResults.add(clipMemory);+ break;+ }++ return clipResults;+ }+static Future<(List<TripMemory>, List<BaseLocation>)> _getTripsResults(Iterable<EnteFile> allFiles,DateTime currentTime,