Skip to content

armgit / ente

Public Imported from GitHub
0

💚 End-to-end encrypted cloud for everything.

FacesTimeline first version

laurenspriemc18cd5c24b13
diff --git a/mobile/apps/photos/.docs/face_timeline_spec.md b/mobile/apps/photos/.docs/face_timeline_spec.md
new file mode 100644
index 0000000000..2f45525f99
--- /dev/null
+++ b/mobile/apps/photos/.docs/face_timeline_spec.md
@@ -0,0 +1,56 @@
+## Faces Timeline Feature Spec
+
+### Objective
+Deliver an on-device, auto-playing “faces timeline” for eligible named people that highlights their visual journey over the years and enables sharing a rendered video.
+
+### Eligibility & Precomputation
+- Run background precomputation per person after ML syncs or people data changes.
+- Skip people marked ignored/hidden or lacking ≥7 distinct calendar years that each contribute ≥4 faces (based on file `creationTime`); a year only counts toward eligibility if it independently meets that four-face threshold.
+- Group faces by year, sort chronologically, and select four samples spread across the year (prefer quarterly spacing; gracefully accept uneven distributions).
+- Store the resulting ordered face list with metadata (faceID, fileID, creationTime, optional crop bytes) in a local cache keyed by personID.
+- Persist the ordered timeline metadata for all people in a single JSON cache (e.g., `faces_timeline/cache.json`) that maps each eligible `personID` to the face ordering, timestamps, and auxiliary playback data; continue to rely on the existing face thumbnail cache for the actual crop bytes.
+- Precompute and cache full face crops via existing `MLDataDB.getCoverFaceForPerson` + `getCachedFaceCrops`; avoid runtime generation.
+- Persist readiness state so UI banners only surface when a valid timeline exists; invalidate cache when clusters update or new faces arrive.
+
+### People Page Surfacing
+- Add a new “Faces timeline” banner in the `PeoplePage` header area alongside other suggestions.
+- Banner appears only after precomputation succeeds; tap navigates to a dedicated timeline route.
+- Suppress banner if the timeline export is in progress (tracked with the same lightweight pattern used in `lib/ui/tools/similar_images_page.dart`) or the person becomes ineligible.
+
+### Timeline Playback Experience
+- `FacesTimelinePage` presents cached crops in chronological order with cross-fade or quick dissolve transitions (≈0.8–1.0 s per frame) and optional manual controls (pause/play, next/back).
+- Preload the next frame into memory to avoid jank; fall back gracefully if a crop is missing.
+- Full-bleed presentation with neutral background and subtle parallax is acceptable; no additional chrome beyond playback & share controls.
+
+### Captioning & Time Context
+- Compute per-frame captions displayed at the bottom:
+ - If `person.data.birthDate` available (yyyy-MM-dd), show “\<Name> was X years old”.
+ - Otherwise show “X years ago”.
+- Animate the numeric value smoothly as frames advance using the difference between the face creation time and birthdate or the current time.
+
+### Sharing Flow (Iteration 2)
+- Defer full export/render work to the second iteration; the first iteration ships playback-only UI with the share affordance hidden or disabled.
+- When implemented, provide a share action on the playback page.
+- MVP export: render the sequence to MP4 using `VideoMemoryService` (FFmpeg) at ~1080×1080, 1 s per frame, ≈0.2 s cross-fade, including caption overlays.
+- Save the video to a temporary location and invoke the system share sheet; clean up temp outputs after sharing.
+- If export fails, notify the user and leave the share action disabled until a retry succeeds.
+
+### Performance & Reliability
+- Execute precomputation in a background isolate with throttling (e.g., max once per person per day) to limit resource spikes.
+- Ensure the timeline plays offline by relying on cached crops and locally stored payloads.
+- Add logging (non-PII) for eligibility results, banner impressions, playback starts, and share attempts.
+
+### Testing & QA
+- Unit-test the yearly selection algorithm and eligibility gating.
+- Widget-test banner visibility logic on `PeoplePage`.
+- Manual QA checklist: timeline playback smoothness, caption correctness with/without birthdate, share flow success, failure fallback, offline playback.
+
+### Privacy & Compliance
+- All processing remains on-device, leveraging existing encrypted ML datasets; no new remote calls.
+- Respect cache eviction rules to avoid leaking face crops beyond required usage.
+
+### Implementation Findings & Follow-Up
+- **Background recompute drops people.** The current implementation caps the per-person precompute queue at 200 entries (`lib/services/faces_timeline/faces_timeline_service.dart`) and the queue helper (`lib/utils/standalone/task_queue.dart`) evicts the oldest task when that cap is exceeded. On accounts with >200 named people this means timelines silently never compute for most users. We need a follow-up that guarantees every person is processed (larger cap, disk-backed backlog, or a smarter scheduling policy) and adds logging/metrics so we can detect backlogs.
+- **Share affordance still active.** Iteration 1 calls for the share UI to be hidden or disabled. Right now the share icon in `FacesTimelinePage` still invokes `onPressed` and only shows a “coming soon” snackbar. Please disable the control until export ships so QA can verify the correct state.
+- **Playback cadence slower than spec.** `_frameInterval` in `FacesTimelinePage` is currently 1.2 s, outside the 0.8–1.0 s window defined above. Tighten the interval (e.g. 900–1000 ms) and confirm transitions still feel smooth.
+- **Frame loading is fully serial.** `_loadFrames` fetches crops in sequence, so the user waits for the entire list before the first frame shows. Update the loader to display the first frame immediately and prefetch subsequent frames in the background (ensuring the “preload next frame” requirement stays satisfied).
diff --git a/mobile/apps/photos/ios/Podfile.lock b/mobile/apps/photos/ios/Podfile.lock
index 0ce2f6ed6f..fb061753d8 100644
--- a/mobile/apps/photos/ios/Podfile.lock
+++ b/mobile/apps/photos/ios/Podfile.lock
@@ -467,87 +467,87 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/workmanager_apple/ios"
SPEC CHECKSUMS:
- app_links: f3e17e4ee5e357b39d8b95290a9b2c299fca71c6
- battery_info: b6c551049266af31556b93c9d9b9452cfec0219f
- connectivity_plus: 2a701ffec2c0ae28a48cf7540e279787e77c447d
- cupertino_http: 947a233f40cfea55167a49f2facc18434ea117ba
- dart_ui_isolate: d5bcda83ca4b04f129d70eb90110b7a567aece14
- device_info_plus: bf2e3232933866d73fe290f2942f2156cdd10342
- emoji_picker_flutter: fe2e6151c5b548e975d546e6eeb567daf0962a58
+ app_links: 76b66b60cc809390ca1ad69bfd66b998d2387ac7
+ battery_info: 83f3aae7be2fccefab1d2bf06b8aa96f11c8bcdd
+ connectivity_plus: cb623214f4e1f6ef8fe7403d580fdad517d2f7dd
+ cupertino_http: 94ac07f5ff090b8effa6c5e2c47871d48ab7c86c
+ dart_ui_isolate: 46f6714abe6891313267153ef6f9748d8ecfcab1
+ device_info_plus: 21fcca2080fbcd348be798aa36c3e5ed849eefbe
+ emoji_picker_flutter: ed468d9746c21711e66b2788880519a9de5de211
ffmpeg_kit_custom: 682b4f2f1ff1f8abae5a92f6c3540f2441d5be99
- ffmpeg_kit_flutter: 9dce4803991478c78c6fb9f972703301101095fe
- file_saver: 503e386464dbe118f630e17b4c2e1190fa0cf808
+ ffmpeg_kit_flutter: 915b345acc97d4142e8a9a8549d177ff10f043f5
+ file_saver: 6cdbcddd690cb02b0c1a0c225b37cd805c2bf8b6
Firebase: d99ac19b909cd2c548339c2241ecd0d1599ab02e
- firebase_core: cf4d42a8ac915e51c0c2dc103442f3036d941a2d
- firebase_messaging: fee490327c1aae28a0da1e65fca856547deca493
+ firebase_core: ece862f94b2bc72ee0edbeec7ab5c7cb09fe1ab5
+ firebase_messaging: e1a5fae495603115be1d0183bc849da748734e2b
FirebaseCore: efb3893e5b94f32b86e331e3bd6dadf18b66568e
FirebaseCoreInternal: 9afa45b1159304c963da48addb78275ef701c6b4
FirebaseInstallations: 317270fec08a5d418fdbc8429282238cab3ac843
FirebaseMessaging: 3b26e2cee503815e01c3701236b020aa9b576f09
Flutter: e0871f40cf51350855a761d2e70bf5af5b9b5de7
- flutter_email_sender: e03bdda7637bcd3539bfe718fddd980e9508efaa
- flutter_image_compress_common: ec1d45c362c9d30a3f6a0426c297f47c52007e3e
- flutter_inappwebview_ios: 6f63631e2c62a7c350263b13fa5427aedefe81d4
- flutter_local_notifications: ff50f8405aaa0ccdc7dcfb9022ca192e8ad9688f
- flutter_native_splash: df59bb2e1421aa0282cb2e95618af4dcb0c56c29
- flutter_secure_storage: 23fc622d89d073675f2eaa109381aefbcf5a49be
- flutter_sodium: a00383520fc689c688b66fd3092984174712493e
- flutter_timezone: ac3da59ac941ff1c98a2e1f0293420e020120282
- fluttertoast: 21eecd6935e7064cc1fcb733a4c5a428f3f24f0f
+ flutter_email_sender: aa1e9772696691d02cd91fea829856c11efb8e58
+ flutter_image_compress_common: 1697a328fd72bfb335507c6bca1a65fa5ad87df1
+ flutter_inappwebview_ios: b89ba3482b96fb25e00c967aae065701b66e9b99
+ flutter_local_notifications: a5a732f069baa862e728d839dd2ebb904737effb
+ flutter_native_splash: c32d145d68aeda5502d5f543ee38c192065986cf
+ flutter_secure_storage: 2c2ff13db9e0a5647389bff88b0ecac56e3f3418
+ flutter_sodium: 7e4621538491834eba53bd524547854bcbbd6987
+ flutter_timezone: 7c838e17ffd4645d261e87037e5bebf6d38fe544
+ fluttertoast: 2c67e14dce98bbdb200df9e1acf610d7a6264ea1
GoogleDataTransport: aae35b7ea0c09004c3797d53c8c41f66f219d6a7
GoogleUtilities: 00c88b9a86066ef77f0da2fab05f65d7768ed8e1
- home_widget: 0434835a4c9a75704264feff6be17ea40e0f0d57
- in_app_purchase_storekit: a1ce04056e23eecc666b086040239da7619cd783
- integration_test: 252f60fa39af5e17c3aa9899d35d908a0721b573
- launcher_icon_switcher: 8e0ad2131a20c51c1dd939896ee32e70cd845b37
+ home_widget: f169fc41fd807b4d46ab6615dc44d62adbf9f64f
+ in_app_purchase_storekit: d1a48cb0f8b29dbf5f85f782f5dd79b21b90a5e6
+ integration_test: 4a889634ef21a45d28d50d622cf412dc6d9f586e
+ launcher_icon_switcher: 84c218d233505aa7d8655d8fa61a3ba802c022da
libwebp: 02b23773aedb6ff1fd38cec7a77b81414c6842a8
- local_auth_ios: 5046a18c018dd973247a0564496c8898dbb5adf9
+ local_auth_ios: f7a1841beef3151d140a967c2e46f30637cdf451
Mantle: c5aa8794a29a022dfbbfc9799af95f477a69b62d
- maps_launcher: 2e5b6a2d664ec6c27f82ffa81b74228d770ab203
- media_extension: 6618f07abd762cdbfaadf1b0c56a287e820f0c84
- media_kit_libs_ios_video: a5fe24bc7875ccd6378a0978c13185e1344651c1
- media_kit_video: 5da63f157170e5bf303bf85453b7ef6971218a2e
- mobile_ocr: 2bba4e291977aa2d48a2464295df9cbba5693cfc
- motion_sensors: 03f55b7c637a7e365a0b5f9697a449f9059d5d91
- motionphoto: 8b65ce50c7d7ff3c767534fc3768b2eed9ac24e4
- move_to_background: cd3091014529ec7829e342ad2d75c0a11f4378a5
+ maps_launcher: edf829809ba9e894d70e569bab11c16352dedb45
+ media_extension: 671e2567880d96c95c65c9a82ccceed8f2e309fd
+ media_kit_libs_ios_video: 5a18affdb97d1f5d466dc79988b13eff6c5e2854
+ media_kit_video: 1746e198cb697d1ffb734b1d05ec429d1fcd1474
+ mobile_ocr: bb5125a6810b4eead3c69778e6b7f3c61fb3c24d
+ motion_sensors: 741e702c17467b9569a92165dda8d4d88c6167f1
+ motionphoto: 23e2aeb5c6380112f69468d71f970fa7438e5ed1
+ move_to_background: 7e3467dd2a1d1013e98c9c1cb93fd53cd7ef9d84
nanopb: fad817b59e0457d11a5dfbde799381cd727c1275
- native_video_editor: edcc94eaa32977d1c5e8cbb881fdd9390572a8a6
- native_video_player: 29ab24a926804ac8c4a57eb6d744c7d927c2bc3e
- objective_c: 77e887b5ba1827970907e10e832eec1683f3431d
- onnxruntime: e7c2ae44385191eaad5ae64c935a72debaddc997
+ native_video_editor: bb979c7b6feb7013006099c8abaf0055c116aaa0
+ native_video_player: 6809dec117e8997161dbfb42a6f90d6df71a504d
+ objective_c: 89e720c30d716b036faf9c9684022048eee1eee2
+ onnxruntime: f9b296392c96c42882be020a59dbeac6310d81b2
onnxruntime-c: a909204639a1f035f575127ac406f781ac797c9c
onnxruntime-objc: b6fab0f1787aa6f7190c2013f03037df4718bd8b
- open_mail_app: 70273c53f768beefdafbe310c3d9086e4da3cb02
+ open_mail_app: 7314a609e88eed22d53671279e189af7a0ab0f11
OrderedSet: e539b66b644ff081c73a262d24ad552a69be3a94
- package_info_plus: c0502532a26c7662a62a356cebe2692ec5fe4ec4
- path_provider_foundation: 2b6b4c569c0fb62ec74538f866245ac84301af46
- permission_handler_apple: 9878588469a2b0d0fc1e048d9f43605f92e6cec2
- photo_manager: 81954a1bf804b6e882d0453b3b6bc7fad7b47d3d
- privacy_screen: 1a131c052ceb3c3659934b003b0d397c2381a24e
+ package_info_plus: af8e2ca6888548050f16fa2f1938db7b5a5df499
+ path_provider_foundation: 080d55be775b7414fd5a5ef3ac137b97b097e564
+ permission_handler_apple: 4ed2196e43d0651e8ff7ca3483a069d469701f2d
+ photo_manager: 1d80ae07a89a67dfbcae95953a1e5a24af7c3e62
+ privacy_screen: 3159a541f5d3a31bea916cfd4e58f9dc722b3fd4
PromisesObjC: f5707f49cb48b9636751c5b2e7d227e43fba9f47
- receive_sharing_intent: 79c848f5b045674ad60b9fea3bafea59962ad2c1
- rive_common: 4743dbfd2911c99066547a3c6454681e0fa907df
- rust_lib_photos: 8813b31af48ff02ca75520cbc81a363a13d51a84
+ receive_sharing_intent: 222384f00ffe7e952bbfabaa9e3967cb87e5fe00
+ rive_common: dd421daaf9ae69f0125aa761dd96abd278399952
+ rust_lib_photos: 04d3901908d2972192944083310b65abf410774c
SDWebImage: 9f177d83116802728e122410fb25ad88f5c7608a
SDWebImageWebPCoder: e38c0a70396191361d60c092933e22c20d5b1380
Sentry: da60d980b197a46db0b35ea12cb8f39af48d8854
- sentry_flutter: 2df8b0aab7e4aba81261c230cbea31c82a62dd1b
- share_plus: 8b6f8b3447e494cca5317c8c3073de39b3600d1f
- shared_preferences_foundation: fcdcbc04712aee1108ac7fda236f363274528f78
- sqflite_darwin: 5a7236e3b501866c1c9befc6771dfd73ffb8702d
+ sentry_flutter: 27892878729f42701297c628eb90e7c6529f3684
+ share_plus: 50da8cb520a8f0f65671c6c6a99b3617ed10a58a
+ shared_preferences_foundation: 9e1978ff2562383bd5676f64ec4e9aa8fa06a6f7
+ sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
sqlite3: 73513155ec6979715d3904ef53a8d68892d4032b
- sqlite3_flutter_libs: 2c48c4ee7217fd653251975e43412250d5bcbbe2
- system_info_plus: 5393c8da281d899950d751713575fbf91c7709aa
- thermal: a9261044101ae8f532fa29cab4e8270b51b3f55c
- ua_client_hints: aeabd123262c087f0ce151ef96fa3ab77bfc8b38
- url_launcher_ios: 5334b05cef931de560670eeae103fd3e431ac3fe
- vibration: 7d883d141656a1c1a6d8d238616b2042a51a1241
- video_player_avfoundation: 7c6c11d8470e1675df7397027218274b6d2360b3
- video_thumbnail: c4e2a3c539e247d4de13cd545344fd2d26ffafd1
- volume_controller: 2e3de73d6e7e81a0067310d17fb70f2f86d71ac7
- wakelock_plus: 76957ab028e12bfa4e66813c99e46637f367fc7e
- workmanager_apple: 7bac258335c310689a641e2d66e88d4845d372e9
+ sqlite3_flutter_libs: e7fc8c9ea2200ff3271f08f127842131746b70e2
+ system_info_plus: 555ce7047fbbf29154726db942ae785c29211740
+ thermal: d4c48be750d1ddbab36b0e2dcb2471531bc8df41
+ ua_client_hints: 92fe0d139619b73ec9fcb46cc7e079a26178f586
+ url_launcher_ios: 694010445543906933d732453a59da0a173ae33d
+ vibration: 8e2f50fc35bb736f9eecb7dd9f7047fbb6a6e888
+ video_player_avfoundation: 2cef49524dd1f16c5300b9cd6efd9611ce03639b
+ video_thumbnail: b637e0ad5f588ca9945f6e2c927f73a69a661140
+ volume_controller: 3657a1f65bedb98fa41ff7dc5793537919f31b12
+ wakelock_plus: e29112ab3ef0b318e58cfa5c32326458be66b556
+ workmanager_apple: 904529ae31e97fc5be632cf628507652294a0778
PODFILE CHECKSUM: cce2cd3351d3488dca65b151118552b680e23635
diff --git a/mobile/apps/photos/lib/events/faces_timeline_changed_event.dart b/mobile/apps/photos/lib/events/faces_timeline_changed_event.dart
new file mode 100644
index 0000000000..de28ad32a1
--- /dev/null
+++ b/mobile/apps/photos/lib/events/faces_timeline_changed_event.dart
@@ -0,0 +1,18 @@
+import "package:photos/events/event.dart";
+import "package:photos/models/faces_timeline/faces_timeline_models.dart";
+
+class FacesTimelineChangedEvent extends Event {
+ final String personId;
+ final FacesTimelineStatus status;
+
+ FacesTimelineChangedEvent({
+ required this.personId,
+ required this.status,
+ });
+
+ bool get isReady => status == FacesTimelineStatus.ready;
+
+ @override
+ String get reason =>
+ '$runtimeType{personId: $personId, status: ${status.name}}';
+}
diff --git a/mobile/apps/photos/lib/l10n/intl_en.arb b/mobile/apps/photos/lib/l10n/intl_en.arb
index 6c94cfef3f..357369944c 100644
--- a/mobile/apps/photos/lib/l10n/intl_en.arb
+++ b/mobile/apps/photos/lib/l10n/intl_en.arb
@@ -1991,6 +1991,78 @@
"artisticPortraits": "Artful portraits",
"streetFood": "Street food bites",
"riverCruises": "River cruise views",
+ "facesTimelineBannerTitle": "Faces timeline",
+ "@facesTimelineBannerTitle": {
+ "description": "Title for the faces timeline suggestion banner shown on a person's page"
+ },
+ "facesTimelineBannerSubtitle": "See {name}'s photos across the years",
+ "@facesTimelineBannerSubtitle": {
+ "description": "Subtitle for faces timeline banner describing the timeline for a person",
+ "placeholders": {
+ "name": {
+ "type": "String",
+ "description": "The display name of the person"
+ }
+ }
+ },
+ "facesTimelineAppBarTitle": "{name}'s faces timeline",
+ "@facesTimelineAppBarTitle": {
+ "description": "Faces timeline page title shown in the app bar",
+ "placeholders": {
+ "name": {
+ "type": "String",
+ "description": "The person's display name"
+ }
+ }
+ },
+ "facesTimelineCaptionYearsOld": "{name} was {count, plural, one {# year old} other {# years old}}",
+ "@facesTimelineCaptionYearsOld": {
+ "description": "Caption for frames when birthdate is known, describing the person's age",
+ "placeholders": {
+ "name": {
+ "type": "String",
+ "description": "Person's name"
+ },
+ "count": {
+ "type": "int",
+ "description": "Number of years old"
+ }
+ }
+ },
+ "facesTimelineCaptionYearsAgo": "{count, plural, one {# year ago} other {# years ago}}",
+ "@facesTimelineCaptionYearsAgo": {
+ "description": "Caption for frames when birthdate is unknown, expressing time difference",
+ "placeholders": {
+ "count": {
+ "type": "int",
+ "description": "Years ago"
+ }
+ }
+ },
+ "facesTimelineShareComingSoon": "Video sharing coming soon",
+ "@facesTimelineShareComingSoon": {
+ "description": "Message shown when the share action is not yet available"
+ },
+ "facesTimelinePlaybackPrevious": "Previous",
+ "@facesTimelinePlaybackPrevious": {
+ "description": "Tooltip or semantics label for the previous frame control"
+ },
+ "facesTimelinePlaybackNext": "Next",
+ "@facesTimelinePlaybackNext": {
+ "description": "Tooltip or semantics label for the next frame control"
+ },
+ "facesTimelinePlaybackPlay": "Play",
+ "@facesTimelinePlaybackPlay": {
+ "description": "Tooltip or semantics label for the play button"
+ },
+ "facesTimelinePlaybackPause": "Pause",
+ "@facesTimelinePlaybackPause": {
+ "description": "Tooltip or semantics label for the pause button"
+ },
+ "facesTimelineUnavailable": "Faces timeline is preparing...",
+ "@facesTimelineUnavailable": {
+ "description": "Fallback message when the faces timeline cannot be displayed yet"
+ },
"playfulKids": "Playful kids",
"coastalCliffs": "Cliffs by the sea"
}
diff --git a/mobile/apps/photos/lib/main.dart b/mobile/apps/photos/lib/main.dart
index b7fb25b3e7..fb96bbbeda 100644
--- a/mobile/apps/photos/lib/main.dart
+++ b/mobile/apps/photos/lib/main.dart
@@ -29,6 +29,7 @@ import "package:photos/service_locator.dart";
import "package:photos/services/account/user_service.dart";
import 'package:photos/services/app_lifecycle_service.dart';
import 'package:photos/services/collections_service.dart';
+import 'package:photos/services/faces_timeline/faces_timeline_service.dart';
import 'package:photos/services/favorites_service.dart';
import 'package:photos/services/home_widget_service.dart';
import 'package:photos/services/local_file_update_service.dart';
@@ -312,6 +313,10 @@ Future<void> _init(bool isBackground, {String via = ''}) async {
unawaited(SemanticSearchService.instance.init());
unawaited(MLService.instance.init());
await PersonService.init(entityService, MLDataDB.instance, preferences);
+ await FacesTimelineService.instance.init();
+ FacesTimelineService.instance
+ .queueFullRecompute(force: true, trigger: "startup")
+ .ignore();
EnteWakeLockService.instance.init(preferences);
logLocalSettings();
initComplete = true;
diff --git a/mobile/apps/photos/lib/models/faces_timeline/faces_timeline_models.dart b/mobile/apps/photos/lib/models/faces_timeline/faces_timeline_models.dart
new file mode 100644
index 0000000000..5b9f5efd35
--- /dev/null
+++ b/mobile/apps/photos/lib/models/faces_timeline/faces_timeline_models.dart
@@ -0,0 +1,159 @@
+import "dart:convert";
+
+enum FacesTimelineStatus { ready, ineligible }
+
+FacesTimelineStatus facesTimelineStatusFromString(String value) {
+ switch (value) {
+ case "ready":
+ return FacesTimelineStatus.ready;
+ case "ineligible":
+ return FacesTimelineStatus.ineligible;
+ default:
+ throw ArgumentError.value(value, "value", "Unsupported timeline status");
+ }
+}
+
+String facesTimelineStatusToString(FacesTimelineStatus status) {
+ switch (status) {
+ case FacesTimelineStatus.ready:
+ return "ready";
+ case FacesTimelineStatus.ineligible:
+ return "ineligible";
+ }
+}
+
+class FacesTimelineEntry {
+ final String faceId;
+ final int fileId;
+ final int creationTimeMicros;
+ final int year;
+
+ const FacesTimelineEntry({
+ required this.faceId,
+ required this.fileId,
+ required this.creationTimeMicros,
+ required this.year,
+ });
+
+ Map<String, dynamic> toJson() => {
+ "faceId": faceId,
+ "fileId": fileId,
+ "creationTime": creationTimeMicros,
+ "year": year,
+ };
+
+ factory FacesTimelineEntry.fromJson(Map<String, dynamic> json) {
+ return FacesTimelineEntry(
+ faceId: json["faceId"] as String,
+ fileId: json["fileId"] as int,
+ creationTimeMicros: json["creationTime"] as int,
+ year: json["year"] as int,
+ );
+ }
+}
+
+class FacesTimelinePersonTimeline {
+ final String personId;
+ final FacesTimelineStatus status;
+ final int updatedAtMicros;
+ final List<FacesTimelineEntry> entries;
+
+ const FacesTimelinePersonTimeline({
+ required this.personId,
+ required this.status,
+ required this.updatedAtMicros,
+ required this.entries,
+ });
+
+ bool get isReady => status == FacesTimelineStatus.ready;
+
+ Map<String, dynamic> toJson() => {
+ "personId": personId,
+ "status": facesTimelineStatusToString(status),
+ "updatedAt": updatedAtMicros,
+ "entries": entries.map((entry) => entry.toJson()).toList(),
+ };
+
+ factory FacesTimelinePersonTimeline.fromJson(Map<String, dynamic> json) {
+ final Iterable entriesJson = json["entries"] as Iterable? ?? [];
+ return FacesTimelinePersonTimeline(
+ personId: json["personId"] as String,
+ status: facesTimelineStatusFromString(json["status"] as String),
+ updatedAtMicros: json["updatedAt"] as int,
+ entries: entriesJson
+ .map(
+ (entry) =>
+ FacesTimelineEntry.fromJson(entry as Map<String, dynamic>),
+ )
+ .toList(growable: false),
+ );
+ }
+
+ FacesTimelinePersonTimeline copyWith({
+ FacesTimelineStatus? status,
+ int? updatedAtMicros,
+ List<FacesTimelineEntry>? entries,
+ }) {
+ return FacesTimelinePersonTimeline(
+ personId: personId,
+ status: status ?? this.status,
+ updatedAtMicros: updatedAtMicros ?? this.updatedAtMicros,
+ entries: entries ?? this.entries,
+ );
+ }
+}
+
+class FacesTimelineCachePayload {
+ static const currentVersion = 1;
+
+ final int version;
+ final Map<String, FacesTimelinePersonTimeline> timelines;
+
+ const FacesTimelineCachePayload({
+ required this.version,
+ required this.timelines,
+ });
+
+ FacesTimelineCachePayload.empty() : version = currentVersion, timelines = {};
+
+ Map<String, dynamic> toJson() => {
+ "version": version,
+ "people": timelines.map((key, value) => MapEntry(key, value.toJson())),
+ };
+
+ String toEncodedJson() => jsonEncode(toJson());
+
+ FacesTimelinePersonTimeline? operator [](String personId) =>
+ timelines[personId];
+
+ Iterable<FacesTimelinePersonTimeline> get allTimelines => timelines.values;
+
+ FacesTimelineCachePayload copyWithTimeline(
+ FacesTimelinePersonTimeline timeline,
+ ) {
+ final updated = Map<String, FacesTimelinePersonTimeline>.from(timelines);
+ updated[timeline.personId] = timeline;
+ return FacesTimelineCachePayload(version: version, timelines: updated);
+ }
+
+ FacesTimelineCachePayload copyWithoutPerson(String personId) {
+ final updated = Map<String, FacesTimelinePersonTimeline>.from(timelines)
+ ..remove(personId);
+ return FacesTimelineCachePayload(version: version, timelines: updated);
+ }
+
+ factory FacesTimelineCachePayload.fromJson(Map<String, dynamic> json) {
+ final int jsonVersion = json["version"] as int? ?? currentVersion;
+ final peopleJson = json["people"] as Map<String, dynamic>? ?? {};
+ final timelines = <String, FacesTimelinePersonTimeline>{};
+ for (final entry in peopleJson.entries) {
+ timelines[entry.key] = FacesTimelinePersonTimeline.fromJson(
+ Map<String, dynamic>.from(entry.value as Map),
+ );
+ }
+ return FacesTimelineCachePayload(
+ version: jsonVersion,
+ timelines: timelines,
+ );
+ }
+}
diff --git a/mobile/apps/photos/lib/services/faces_timeline/faces_timeline_cache_service.dart b/mobile/apps/photos/lib/services/faces_timeline/faces_timeline_cache_service.dart
new file mode 100644
index 0000000000..6f14e2478b
--- /dev/null
+++ b/mobile/apps/photos/lib/services/faces_timeline/faces_timeline_cache_service.dart
@@ -0,0 +1,149 @@
+import "dart:convert";
+import "dart:io";
+
+import "package:logging/logging.dart";
+import "package:path/path.dart" as p;
+import "package:path_provider/path_provider.dart";
+import "package:photos/models/faces_timeline/faces_timeline_models.dart";
+import "package:synchronized/synchronized.dart";
+
+class FacesTimelineCacheService {
+ FacesTimelineCacheService._internal();
+
+ static final FacesTimelineCacheService instance =
+ FacesTimelineCacheService._internal();
+
+ static const _cacheDirectoryName = "faces_timeline";
+ static const _cacheFileName = "cache.json";
+
+ final Logger _logger = Logger("FacesTimelineCacheService");
+ final Lock _lock = Lock();
+
+ FacesTimelineCachePayload? _cache;
+ File? _cacheFile;
+ bool _initialized = false;
+
+ Future<void> init() async {
+ if (_initialized) return;
+
+ final directory = await getApplicationDocumentsDirectory();
+ final cacheDirectory = Directory(
+ p.join(directory.path, _cacheDirectoryName),
+ );
+ if (!await cacheDirectory.exists()) {
+ await cacheDirectory.create(recursive: true);
+ }
+ final file = File(p.join(cacheDirectory.path, _cacheFileName));
+
+ await _lock.synchronized(() async {
+ _cacheFile = file;
+ if (!await file.exists()) {
+ _cache = FacesTimelineCachePayload.empty();
+ await _writeCacheUnsafe();
+ } else {
+ await _loadCacheUnsafe();
+ }
+ _initialized = true;
+ });
+ }
+
+ Future<FacesTimelineCachePayload> getCache() async {
+ await _ensureInitialized();
+ return _lock.synchronized(() async {
+ _cache ??= await _loadCacheUnsafe();
+ return _cache!;
+ });
+ }
+
+ Future<FacesTimelinePersonTimeline?> getTimeline(String personId) async {
+ final cache = await getCache();
+ return cache[personId];
+ }
+
+ Future<void> upsertTimeline(FacesTimelinePersonTimeline timeline) async {
+ await _ensureInitialized();
+ await _lock.synchronized(() async {
+ final currentCache = await _loadCacheUnsafe();
+ final updatedCache = currentCache.copyWithTimeline(timeline);
+ _cache = updatedCache;
+ await _writeCacheUnsafe();
+ });
+ }
+
+ Future<void> removeTimeline(String personId) async {
+ await _ensureInitialized();
+ await _lock.synchronized(() async {
+ final currentCache = await _loadCacheUnsafe();
+ if (!currentCache.timelines.containsKey(personId)) {
+ return;
+ }
+ final updatedCache = currentCache.copyWithoutPerson(personId);
+ _cache = updatedCache;
+ await _writeCacheUnsafe();
+ });
+ }
+
+ Future<void> replaceAll(FacesTimelineCachePayload payload) async {
+ await _ensureInitialized();
+ await _lock.synchronized(() async {
+ _cache = payload;
+ await _writeCacheUnsafe();
+ });
+ }
+
+ Future<void> clear() async {
+ await _ensureInitialized();
+ await _lock.synchronized(() async {
+ _cache = FacesTimelineCachePayload.empty();
+ await _writeCacheUnsafe();
+ });
+ }
+
+ Future<void> _ensureInitialized() async {
+ if (_initialized) return;
+ await init();
+ }
+
+ Future<FacesTimelineCachePayload> _loadCacheUnsafe() async {
+ if (_cache != null) return _cache!;
+ final file = _cacheFile;
+ if (file == null) {
+ _logger.severe("Faces timeline cache accessed before initialization");
+ _cache = FacesTimelineCachePayload.empty();
+ return _cache!;
+ }
+ try {
+ final contents = await file.readAsString();
+ if (contents.trim().isEmpty) {
+ _cache = FacesTimelineCachePayload.empty();
+ return _cache!;
+ }
+ final decoded = jsonDecode(contents);
+ if (decoded is! Map<String, dynamic>) {
+ throw const FormatException("Timeline cache is not a JSON map");
+ }
+ _cache = FacesTimelineCachePayload.fromJson(decoded);
+ return _cache!;
+ } catch (error, stackTrace) {
+ _logger.severe("Failed to read faces timeline cache", error, stackTrace);
+ _cache = FacesTimelineCachePayload.empty();
+ await _writeCacheUnsafe();
+ return _cache!;
+ }
+ }
+
+ Future<void> _writeCacheUnsafe() async {
+ final file = _cacheFile;
+ if (file == null) {
+ _logger.severe("Faces timeline cache file missing during write");
+ return;
+ }
+ final payload = _cache ?? FacesTimelineCachePayload.empty();
+ try {
+ await file.writeAsString(payload.toEncodedJson(), flush: true);
+ } catch (error, stackTrace) {
+ _logger.severe("Failed to write faces timeline cache", error, stackTrace);
+ rethrow;
+ }
+ }
+}
diff --git a/mobile/apps/photos/lib/services/faces_timeline/faces_timeline_service.dart b/mobile/apps/photos/lib/services/faces_timeline/faces_timeline_service.dart
new file mode 100644
index 0000000000..b9bf80c0c3
--- /dev/null
+++ b/mobile/apps/photos/lib/services/faces_timeline/faces_timeline_service.dart
@@ -0,0 +1,552 @@
+import "dart:async";
+
+import "package:collection/collection.dart";
+import "package:computer/computer.dart";
+import "package:flutter/foundation.dart";
+import "package:logging/logging.dart";
+import "package:photos/core/event_bus.dart";
+import "package:photos/db/files_db.dart";
+import "package:photos/db/ml/db.dart";
+import "package:photos/events/faces_timeline_changed_event.dart";
+import "package:photos/events/people_changed_event.dart";
+import "package:photos/models/faces_timeline/faces_timeline_models.dart";
+import "package:photos/models/file/file.dart";
+import "package:photos/models/ml/face/face.dart";
+import "package:photos/models/ml/face/person.dart";
+import "package:photos/services/faces_timeline/faces_timeline_cache_service.dart";
+import "package:photos/services/machine_learning/face_ml/person/person_service.dart";
+import "package:photos/services/machine_learning/ml_result.dart";
+import "package:photos/utils/face/face_thumbnail_cache.dart";
+import "package:photos/utils/standalone/task_queue.dart";
+
+typedef _TimelineComputationResult = ({
+ FacesTimelinePersonTimeline timeline,
+ Map<int, EnteFile> filesById,
+});
+
+class FacesTimelineService {
+ FacesTimelineService._internal();
+
+ static final FacesTimelineService instance = FacesTimelineService._internal();
+
+ static const _minimumYears = 7;
+ static const _minimumFacesPerYear = 4;
+ static const _recomputeCooldown = Duration(hours: 24);
+
+ final Logger _logger = Logger("FacesTimelineService");
+ final FacesTimelineCacheService _cacheService =
+ FacesTimelineCacheService.instance;
+ final MLDataDB _mlDataDB = MLDataDB.instance;
+ final FilesDB _filesDB = FilesDB.instance;
+ final TaskQueue<String> _precomputeQueue = TaskQueue(
+ maxConcurrentTasks: 1,
+ taskTimeout: const Duration(minutes: 2),
+ maxQueueSize: 200,
+ );
+
+ final ValueNotifier<Set<String>> readyPersonIds = ValueNotifier<Set<String>>(
+ {},
+ );
+
+ final Map<String, int> _lastForcedComputeMicros = {};
+
+ bool _initialized = false;
+
+ StreamSubscription<PeopleChangedEvent>? _peopleChangedSubscription;
+
+ Future<void> init() async {
+ if (_initialized) return;
+ await _cacheService.init();
+ await _refreshReadyPersonIds();
+ _peopleChangedSubscription = Bus.instance.on<PeopleChangedEvent>().listen(
+ _handlePeopleChange,
+ );
+ _initialized = true;
+ }
+
+ Future<void> dispose() async {
+ await _peopleChangedSubscription?.cancel();
+ readyPersonIds.dispose();
+ }
+
+ Future<void> queueFullRecompute({
+ bool force = false,
+ String trigger = "",
+ }) async {
+ if (!PersonService.isInitialized) {
+ _logger.warning(
+ "Faces timeline full recompute skipped: PersonService not initialized",
+ );
+ return;
+ }
+ final persons = await PersonService.instance.getPersons();
+ for (final person in persons) {
+ if (person.data.isIgnored) {
+ await _handleIgnoredPerson(person.remoteID);
+ continue;
+ }
+ schedulePersonRecompute(
+ person.remoteID,
+ force: force,
+ trigger: trigger.isEmpty ? "full_recompute" : trigger,
+ );
+ }
+ }
+
+ void schedulePersonRecompute(
+ String personId, {
+ bool force = false,
+ String trigger = "",
+ }) {
+ if (personId.isEmpty) return;
+ _precomputeQueue.addTask(personId, () async {
+ await _recomputeTimelineForPerson(
+ personId,
+ force: force,
+ trigger: trigger,
+ );
+ }).ignore();
+ }
+
+ Future<FacesTimelinePersonTimeline?> getTimeline(String personId) {
+ return _cacheService.getTimeline(personId);
+ }
+
+ bool hasReadyTimelineSync(String personId) {
+ return readyPersonIds.value.contains(personId);
+ }
+
+ Future<bool> hasReadyTimeline(String personId) async {
+ final timeline = await _cacheService.getTimeline(personId);
+ return timeline?.isReady ?? false;
+ }
+
+ Future<void> _handleIgnoredPerson(String personId) async {
+ await _cacheService.removeTimeline(personId);
+ await _refreshReadyPersonIds();
+ Bus.instance.fire(
+ FacesTimelineChangedEvent(
+ personId: personId,
+ status: FacesTimelineStatus.ineligible,
+ ),
+ );
+ }
+
+ void _handlePeopleChange(PeopleChangedEvent event) {
+ final personId = event.person?.remoteID;
+ switch (event.type) {
+ case PeopleEventType.saveOrEditPerson:
+ case PeopleEventType.addedClusterToPerson:
+ case PeopleEventType.removedFaceFromCluster:
+ case PeopleEventType.removedFilesFromCluster:
+ if (personId != null) {
+ schedulePersonRecompute(
+ personId,
+ force: true,
+ trigger: "people_event_${event.type.name}",
+ );
+ } else {
+ queueFullRecompute(
+ force: true,
+ trigger: "people_event_${event.type.name}",
+ );
+ }
+ break;
+ case PeopleEventType.syncDone:
+ queueFullRecompute(force: true, trigger: "sync_done");
+ break;
+ case PeopleEventType.defaultType:
+ if (personId != null) {
+ schedulePersonRecompute(personId, trigger: "people_default");
+ }
+ break;
+ }
+ }
+
+ Future<void> _recomputeTimelineForPerson(
+ String personId, {
+ required bool force,
+ required String trigger,
+ }) async {
+ if (!PersonService.isInitialized) {
+ _logger.warning(
+ "Faces timeline recompute skipped for $personId: PersonService not initialized",
+ );
+ return;
+ }
+
+ final person = await PersonService.instance.getPerson(personId);
+ if (person == null) {
+ _logger.info("Faces timeline: person $personId missing, clearing cache");
+ await _cacheService.removeTimeline(personId);
+ await _refreshReadyPersonIds();
+ Bus.instance.fire(
+ FacesTimelineChangedEvent(
+ personId: personId,
+ status: FacesTimelineStatus.ineligible,
+ ),
+ );
+ return;
+ }
+ if (person.data.isIgnored) {
+ _logger.info("Faces timeline: person $personId ignored, clearing cache");
+ await _handleIgnoredPerson(personId);
+ return;
+ }
+
+ final nowMicros = DateTime.now().microsecondsSinceEpoch;
+ final existing = await _cacheService.getTimeline(personId);
+ final lastComputedMicros = existing?.updatedAtMicros;
+ final lastForcedMicros = _lastForcedComputeMicros[personId];
+ if (!force && lastComputedMicros != null) {
+ final remaining = nowMicros - lastComputedMicros;
+ if (remaining < _recomputeCooldown.inMicroseconds) {
+ _logger.fine(
+ "Faces timeline compute skipped for $personId due to cooldown "
+ "(elapsed ${remaining / Duration.microsecondsPerHour} hours, trigger: $trigger)",
+ );
+ return;
+ }
+ }
+ if (!force && lastForcedMicros != null) {
+ final remaining = nowMicros - lastForcedMicros;
+ if (remaining < _recomputeCooldown.inMicroseconds) {
+ _logger.fine(
+ "Faces timeline compute skipped for $personId due to forced cooldown "
+ "(elapsed ${remaining / Duration.microsecondsPerHour} hours, trigger: $trigger)",
+ );
+ return;
+ }
+ }
+
+ if (force) {
+ _lastForcedComputeMicros[personId] = nowMicros;
+ }
+
+ try {
+ final result = await _computeTimeline(person, nowMicros);
+ await _cacheService.upsertTimeline(result.timeline);
+ await _refreshReadyPersonIds();
+ Bus.instance.fire(
+ FacesTimelineChangedEvent(
+ personId: person.remoteID,
+ status: result.timeline.status,
+ ),
+ );
+ if (result.timeline.isReady) {
+ await _ensureFaceCrops(
+ person,
+ result.timeline.entries,
+ result.filesById,
+ );
+ }
+ } catch (error, stackTrace) {
+ _logger.severe(
+ "Faces timeline compute failed for $personId (trigger: $trigger)",
+ error,
+ stackTrace,
+ );
+ }
+ }
+
+ Future<_TimelineComputationResult> _computeTimeline(
+ PersonEntity person,
+ int nowMicros,
+ ) async {
+ final personId = person.remoteID;
+ final faceIds = await _mlDataDB.getFaceIDsForPerson(personId);
+ if (faceIds.isEmpty) {
+ _logger.fine(
+ "Faces timeline: person $personId has no faces, marking ineligible",
+ );
+ final timeline = FacesTimelinePersonTimeline(
+ personId: personId,
+ status: FacesTimelineStatus.ineligible,
+ updatedAtMicros: nowMicros,
+ entries: const [],
+ );
+ return (timeline: timeline, filesById: const <int, EnteFile>{});
+ }
+
+ final List<int> uniqueFileIds =
+ faceIds.map(getFileIdFromFaceId<int>).toSet().toList();
+ final fileMap = await _filesDB.getFileIDToFileFromIDs(uniqueFileIds);
+
+ final faces = <_TimelineFaceData>[];
+ for (final faceId in faceIds) {
+ final fileId = getFileIdFromFaceId<int>(faceId);
+ final file = fileMap[fileId];
+ if (file == null) {
+ continue;
+ }
+ final creationTime = file.creationTime;
+ if (creationTime == null || creationTime <= 0) {
+ continue;
+ }
+ final date = DateTime.fromMicrosecondsSinceEpoch(creationTime);
+ faces.add(
+ _TimelineFaceData(
+ faceId: faceId,
+ fileId: fileId,
+ creationTimeMicros: creationTime,
+ year: date.year,
+ ),
+ );
+ }
+
+ if (faces.isEmpty) {
+ _logger.fine(
+ "Faces timeline: person $personId has no usable faces after filtering, marking ineligible",
+ );
+ final timeline = FacesTimelinePersonTimeline(
+ personId: personId,
+ status: FacesTimelineStatus.ineligible,
+ updatedAtMicros: nowMicros,
+ entries: const [],
+ );
+ return (timeline: timeline, filesById: fileMap);
+ }
+
+ final selectionResult = await Computer.shared().compute(
+ selectTimelineEntriesTask,
+ param: {
+ "faces": faces.map((face) => face.toJson()).toList(),
+ "minYears": _minimumYears,
+ "minFaces": _minimumFacesPerYear,
+ },
+ taskName: "faces_timeline_select_${person.remoteID}",
+ );
+
+ if (selectionResult["status"] != "ready") {
+ final eligibleYearCount =
+ selectionResult["eligibleYearCount"] as int? ?? 0;
+ _logger.info(
+ "Faces timeline: person $personId ineligible "
+ "(eligibleYears=$eligibleYearCount, faces=${faces.length})",
+ );
+ final timeline = FacesTimelinePersonTimeline(
+ personId: personId,
+ status: FacesTimelineStatus.ineligible,
+ updatedAtMicros: nowMicros,
+ entries: const [],
+ );
+ return (timeline: timeline, filesById: fileMap);
+ }
+
+ final entriesJson = (selectionResult["entries"] as List<dynamic>)
+ .cast<Map<String, dynamic>>();
+ final entries = entriesJson
+ .map(
+ (entryJson) => FacesTimelineEntry(
+ faceId: entryJson["faceId"] as String,
+ fileId: entryJson["fileId"] as int,
+ creationTimeMicros: entryJson["creationTime"] as int,
+ year: entryJson["year"] as int,
+ ),
+ )
+ .toList();
+
+ final timeline = FacesTimelinePersonTimeline(
+ personId: personId,
+ status: FacesTimelineStatus.ready,
+ updatedAtMicros: nowMicros,
+ entries: entries,
+ );
+
+ final years =
+ (selectionResult["years"] as List<dynamic>?)?.cast<int>().join(", ") ??
+ "unknown";
+ _logger.info(
+ "Faces timeline ready for $personId "
+ "(frames=${entries.length}, years=$years)",
+ );
+
+ return (timeline: timeline, filesById: fileMap);
+ }
+
+ Future<void> _ensureFaceCrops(
+ PersonEntity person,
+ List<FacesTimelineEntry> entries,
+ Map<int, EnteFile> fileMap,
+ ) async {
+ final personId = person.remoteID;
+ final entriesByFile = <int, List<FacesTimelineEntry>>{};
+ for (final entry in entries) {
+ entriesByFile.putIfAbsent(entry.fileId, () => []).add(entry);
+ }
+
+ for (final entry in entriesByFile.entries) {
+ final file = fileMap[entry.key];
+ if (file == null) continue;
+ final faces = await _mlDataDB.getFacesForGivenFileID(entry.key);
+ if (faces == null || faces.isEmpty) continue;
+ final selectedFaces = entry.value
+ .map(
+ (timelineEntry) => faces.firstWhereOrNull(
+ (face) => face.faceID == timelineEntry.faceId,
+ ),
+ )
+ .whereType<Face>()
+ .toList();
+ if (selectedFaces.isEmpty) continue;
+ try {
+ await getCachedFaceCrops(
+ file,
+ selectedFaces,
+ useFullFile: true,
+ personOrClusterID: personId,
+ useTempCache: false,
+ );
+ } catch (error, stackTrace) {
+ _logger.warning(
+ "Faces timeline: failed to cache crops for $personId file ${entry.key}",
+ error,
+ stackTrace,
+ );
+ }
+ }
+ }
+
+ Future<void> _refreshReadyPersonIds() async {
+ final cache = await _cacheService.getCache();
+ final current = cache.allTimelines
+ .where((timeline) => timeline.isReady)
+ .map((timeline) => timeline.personId)
+ .toSet();
+ readyPersonIds.value = current;
+ }
+}
+
+class _TimelineFaceData {
+ final String faceId;
+ final int fileId;
+ final int creationTimeMicros;
+ final int year;
+
+ const _TimelineFaceData({
+ required this.faceId,
+ required this.fileId,
+ required this.creationTimeMicros,
+ required this.year,
+ });
+
+ Map<String, dynamic> toJson() => {
+ "faceId": faceId,
+ "fileId": fileId,
+ "creationTime": creationTimeMicros,
+ "year": year,
+ };
+
+ factory _TimelineFaceData.fromJson(Map<String, dynamic> json) {
+ return _TimelineFaceData(
+ faceId: json["faceId"] as String,
+ fileId: json["fileId"] as int,
+ creationTimeMicros: json["creationTime"] as int,
+ year: json["year"] as int,
+ );
+ }
+}
+
+Map<String, dynamic> selectTimelineEntriesTask(Map<String, dynamic> param) {
+ final facesJson =
+ (param["faces"] as List<dynamic>).cast<Map<String, dynamic>>();
+ final minYears = param["minYears"] as int;
+ final minFacesPerYear = param["minFaces"] as int;
+
+ final faces = facesJson.map(_TimelineFaceData.fromJson).toList();
+
+ if (faces.isEmpty) {
+ return {"status": "ineligible", "eligibleYearCount": 0};
+ }
+
+ final yearGroups = <int, List<_TimelineFaceData>>{};
+ for (final face in faces) {
+ yearGroups.putIfAbsent(face.year, () => []).add(face);
+ }
+
+ final eligibleEntries = yearGroups.entries
+ .where((entry) => entry.value.length >= minFacesPerYear)
+ .toList()
+ ..sort((a, b) => a.key.compareTo(b.key));
+
+ if (eligibleEntries.length < minYears) {
+ return {
+ "status": "ineligible",
+ "eligibleYearCount": eligibleEntries.length,
+ };
+ }
+
+ final selected = <_TimelineFaceData>[];
+ final years = <int>[];
+ for (final entry in eligibleEntries) {
+ entry.value.sort(
+ (a, b) => a.creationTimeMicros.compareTo(b.creationTimeMicros),
+ );
+ years.add(entry.key);
+ final picks = _pickFacesForYear(entry.value);
+ selected.addAll(picks);
+ }
+
+ selected.sort((a, b) => a.creationTimeMicros.compareTo(b.creationTimeMicros));
+
+ return {
+ "status": "ready",
+ "entries": selected.map((face) => face.toJson()).toList(),
+ "years": years,
+ };
+}
+
+List<_TimelineFaceData> _pickFacesForYear(List<_TimelineFaceData> faces) {
+ if (faces.length <= 4) {
+ return List<_TimelineFaceData>.from(faces);
+ }
+
+ final total = faces.length;
+ final targetPositions = <double>[
+ 0,
+ (total - 1) / 3,
+ (total - 1) * 2 / 3,
+ total - 1,
+ ];
+ final selectedIndices = <int>{};
+ final picks = <_TimelineFaceData>[];
+
+ for (final position in targetPositions) {
+ int index = position.round().clamp(0, total - 1);
+ if (selectedIndices.contains(index)) {
+ int offset = 1;
+ bool assigned = false;
+ while (!assigned && (index - offset >= 0 || index + offset < total)) {
+ if (index - offset >= 0 && !selectedIndices.contains(index - offset)) {
+ index = index - offset;
+ assigned = true;
+ break;
+ }
+ if (index + offset < total &&
+ !selectedIndices.contains(index + offset)) {
+ index = index + offset;
+ assigned = true;
+ break;
+ }
+ offset++;
+ }
+ if (!assigned) {
+ continue;
+ }
+ }
+ if (selectedIndices.add(index)) {
+ picks.add(faces[index]);
+ }
+ }
+
+ if (picks.length < 4) {
+ for (var i = 0; i < total && picks.length < 4; i++) {
+ if (selectedIndices.add(i)) {
+ picks.add(faces[i]);
+ }
+ }
+ }
+
+ picks.sort((a, b) => a.creationTimeMicros.compareTo(b.creationTimeMicros));
+ return picks;
+}
diff --git a/mobile/apps/photos/lib/ui/viewer/people/faces_timeline_banner.dart b/mobile/apps/photos/lib/ui/viewer/people/faces_timeline_banner.dart
new file mode 100644
index 0000000000..33c6616ed4
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/viewer/people/faces_timeline_banner.dart
@@ -0,0 +1,91 @@
+import "package:flutter/material.dart";
+import "package:photos/l10n/l10n.dart";
+import "package:photos/models/ml/face/person.dart";
+import "package:photos/theme/ente_theme.dart";
+
+class FacesTimelineBanner extends StatelessWidget {
+ final String title;
+ final String subtitle;
+ final VoidCallback onTap;
+
+ const FacesTimelineBanner({
+ required this.title,
+ required this.subtitle,
+ required this.onTap,
+ super.key,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ final textTheme = getEnteTextTheme(context);
+ return GestureDetector(
+ onTap: onTap,
+ child: Container(
+ margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 18),
+ decoration: BoxDecoration(
+ color: colorScheme.backgroundElevated2,
+ borderRadius: BorderRadius.circular(16),
+ border: Border.all(color: colorScheme.strokeFaint),
+ ),
+ child: Row(
+ children: [
+ Container(
+ width: 48,
+ height: 48,
+ decoration: BoxDecoration(
+ color: colorScheme.fillFaint,
+ borderRadius: BorderRadius.circular(24),
+ ),
+ child: Icon(
+ Icons.play_circle_outline,
+ size: 28,
+ color: colorScheme.primary500,
+ ),
+ ),
+ const SizedBox(width: 16),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(title, style: textTheme.bodyBold),
+ const SizedBox(height: 6),
+ Text(subtitle, style: textTheme.miniMuted),
+ ],
+ ),
+ ),
+ const Icon(Icons.chevron_right),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+class FacesTimelineBannerSection extends StatelessWidget {
+ final bool showBanner;
+ final PersonEntity person;
+ final VoidCallback? onTap;
+
+ const FacesTimelineBannerSection({
+ required this.showBanner,
+ required this.person,
+ this.onTap,
+ super.key,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ if (!showBanner || onTap == null) {
+ return const SizedBox.shrink();
+ }
+ return FacesTimelineBanner(
+ title: context.l10n.facesTimelineBannerTitle,
+ subtitle: context.l10n.facesTimelineBannerSubtitle(
+ name: person.data.name,
+ ),
+ onTap: onTap!,
+ );
+ }
+}
diff --git a/mobile/apps/photos/lib/ui/viewer/people/faces_timeline_debug_panel.dart b/mobile/apps/photos/lib/ui/viewer/people/faces_timeline_debug_panel.dart
new file mode 100644
index 0000000000..ed3f93cfa9
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/viewer/people/faces_timeline_debug_panel.dart
@@ -0,0 +1,225 @@
+import "dart:async";
+
+import "package:flutter/foundation.dart";
+import "package:flutter/material.dart";
+import "package:photos/core/event_bus.dart";
+import "package:photos/events/faces_timeline_changed_event.dart";
+import "package:photos/models/faces_timeline/faces_timeline_models.dart";
+import "package:photos/models/ml/face/person.dart";
+import "package:photos/services/faces_timeline/faces_timeline_cache_service.dart";
+import "package:photos/services/faces_timeline/faces_timeline_service.dart";
+import "package:photos/theme/ente_theme.dart";
+
+class FacesTimelineDebugPanel extends StatefulWidget {
+ final PersonEntity person;
+
+ const FacesTimelineDebugPanel({required this.person, super.key});
+
+ @override
+ State<FacesTimelineDebugPanel> createState() =>
+ _FacesTimelineDebugPanelState();
+}
+
+class _FacesTimelineDebugPanelState extends State<FacesTimelineDebugPanel> {
+ FacesTimelinePersonTimeline? _timeline;
+ bool _loading = false;
+ String? _error;
+ String? _info;
+ StreamSubscription<FacesTimelineChangedEvent>? _timelineSubscription;
+
+ @override
+ void initState() {
+ super.initState();
+ if (kDebugMode) {
+ _reloadTimeline();
+ _timelineSubscription = Bus.instance
+ .on<FacesTimelineChangedEvent>()
+ .listen(_handleTimelineChanged);
+ }
+ }
+
+ @override
+ void dispose() {
+ _timelineSubscription?.cancel();
+ super.dispose();
+ }
+
+ void _handleTimelineChanged(FacesTimelineChangedEvent event) {
+ if (event.personId != widget.person.remoteID) return;
+ _reloadTimeline();
+ }
+
+ Future<void> _reloadTimeline() async {
+ if (!mounted) return;
+ setState(() {
+ _loading = true;
+ _error = null;
+ });
+ try {
+ final timeline = await FacesTimelineService.instance
+ .getTimeline(widget.person.remoteID);
+ if (!mounted) return;
+ setState(() {
+ _timeline = timeline;
+ });
+ } catch (error) {
+ if (!mounted) return;
+ setState(() {
+ _error = "$error";
+ });
+ } finally {
+ if (mounted) {
+ setState(() {
+ _loading = false;
+ });
+ }
+ }
+ }
+
+ Future<void> _forceRecompute() async {
+ FacesTimelineService.instance.schedulePersonRecompute(
+ widget.person.remoteID,
+ force: true,
+ trigger: "debug_panel",
+ );
+ if (!mounted) return;
+ setState(() {
+ _info =
+ "Recompute queued at ${DateTime.now().toLocal().toIso8601String()}";
+ });
+ }
+
+ Future<void> _clearTimeline() async {
+ setState(() {
+ _loading = true;
+ _error = null;
+ });
+ try {
+ await FacesTimelineCacheService.instance
+ .removeTimeline(widget.person.remoteID);
+ await _reloadTimeline();
+ if (!mounted) return;
+ setState(() {
+ _info =
+ "Timeline cache cleared at ${DateTime.now().toLocal().toIso8601String()}";
+ });
+ } catch (error) {
+ if (!mounted) return;
+ setState(() {
+ _error = "$error";
+ });
+ } finally {
+ if (mounted) {
+ setState(() {
+ _loading = false;
+ });
+ }
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ if (!kDebugMode) return const SizedBox.shrink();
+ final colorScheme = getEnteColorScheme(context);
+ final textTheme = getEnteTextTheme(context);
+ final timeline = _timeline;
+ final bool inReadySet = FacesTimelineService.instance
+ .hasReadyTimelineSync(widget.person.remoteID);
+ final DateTime? updatedAt = timeline == null
+ ? null
+ : DateTime.fromMicrosecondsSinceEpoch(timeline.updatedAtMicros)
+ .toLocal();
+ final int uniqueYears = timeline == null
+ ? 0
+ : timeline.entries.map((entry) => entry.year).toSet().length;
+
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
+ child: Container(
+ padding: const EdgeInsets.all(16),
+ decoration: BoxDecoration(
+ color: colorScheme.fillFaint,
+ borderRadius: BorderRadius.circular(12),
+ border: Border.all(color: colorScheme.strokeFaint),
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ children: [
+ Icon(Icons.bug_report_outlined, color: colorScheme.primary500),
+ const SizedBox(width: 8),
+ Text("Faces timeline debug", style: textTheme.bodyBold),
+ const Spacer(),
+ IconButton(
+ onPressed: _loading ? null : _reloadTimeline,
+ tooltip: "Refresh timeline",
+ icon: _loading
+ ? SizedBox(
+ width: 16,
+ height: 16,
+ child: CircularProgressIndicator(
+ strokeWidth: 2,
+ color: colorScheme.primary500,
+ ),
+ )
+ : const Icon(Icons.refresh),
+ ),
+ ],
+ ),
+ const SizedBox(height: 12),
+ if (_error != null)
+ Text(
+ _error!,
+ style: textTheme.miniMuted.copyWith(
+ color: colorScheme.warning500,
+ ),
+ ),
+ if (_info != null)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: Text(
+ _info!,
+ style: textTheme.miniMuted.copyWith(
+ color: colorScheme.primary500,
+ ),
+ ),
+ ),
+ Text(
+ "Status: ${timeline == null ? "missing" : timeline.status.name}",
+ style: textTheme.miniMuted,
+ ),
+ Text(
+ "Ready set contains person: ${inReadySet ? "yes" : "no"}",
+ style: textTheme.miniMuted,
+ ),
+ Text(
+ "Entries: ${timeline?.entries.length ?? 0} • Years: $uniqueYears",
+ style: textTheme.miniMuted,
+ ),
+ Text(
+ "Updated: ${updatedAt?.toIso8601String() ?? "n/a"}",
+ style: textTheme.miniMuted,
+ ),
+ const SizedBox(height: 12),
+ Wrap(
+ spacing: 8,
+ runSpacing: 8,
+ children: [
+ FilledButton(
+ onPressed: _loading ? null : _forceRecompute,
+ child: const Text("Force recompute"),
+ ),
+ FilledButton.tonal(
+ onPressed:
+ _loading || timeline == null ? null : _clearTimeline,
+ child: const Text("Clear cache entry"),
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/apps/photos/lib/ui/viewer/people/faces_timeline_page.dart b/mobile/apps/photos/lib/ui/viewer/people/faces_timeline_page.dart
new file mode 100644
index 0000000000..c0264e538c
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/viewer/people/faces_timeline_page.dart
@@ -0,0 +1,428 @@
+import "dart:async";
+import "dart:typed_data";
+
+import "package:collection/collection.dart";
+import "package:flutter/material.dart";
+import "package:logging/logging.dart";
+import "package:photos/db/files_db.dart";
+import "package:photos/db/ml/db.dart";
+import "package:photos/l10n/l10n.dart";
+import "package:photos/models/faces_timeline/faces_timeline_models.dart";
+import "package:photos/models/ml/face/face.dart";
+import "package:photos/models/ml/face/person.dart";
+import "package:photos/services/faces_timeline/faces_timeline_service.dart";
+import "package:photos/theme/colors.dart";
+import "package:photos/theme/ente_theme.dart";
+import "package:photos/ui/components/buttons/icon_button_widget.dart";
+import "package:photos/utils/face/face_thumbnail_cache.dart";
+
+class FacesTimelinePage extends StatefulWidget {
+ final PersonEntity person;
+
+ const FacesTimelinePage({required this.person, super.key});
+
+ @override
+ State<FacesTimelinePage> createState() => _FacesTimelinePageState();
+}
+
+class _FacesTimelinePageState extends State<FacesTimelinePage>
+ with TickerProviderStateMixin {
+ static const _frameInterval = Duration(milliseconds: 1200);
+
+ final Logger _logger = Logger("FacesTimelinePage");
+
+ late Future<List<_TimelineFrame>> _framesFuture;
+ final List<_TimelineFrame> _frames = [];
+
+ Timer? _playTimer;
+ bool _isPlaying = false;
+ bool _loggedPlaybackStart = false;
+
+ int _currentIndex = 0;
+ double _previousCaptionValue = 0;
+ double _currentCaptionValue = 0;
+ _CaptionType _currentCaptionType = _CaptionType.yearsAgo;
+
+ @override
+ void initState() {
+ super.initState();
+ _framesFuture = _loadFrames();
+ }
+
+ @override
+ void dispose() {
+ _playTimer?.cancel();
+ super.dispose();
+ }
+
+ Future<List<_TimelineFrame>> _loadFrames() async {
+ final timeline = await FacesTimelineService.instance.getTimeline(
+ widget.person.remoteID,
+ );
+ if (timeline == null || !timeline.isReady || timeline.entries.isEmpty) {
+ return <_TimelineFrame>[];
+ }
+ final frames = <_TimelineFrame>[];
+ for (final entry in timeline.entries) {
+ frames.add(await _buildFrame(entry));
+ }
+ if (frames.isNotEmpty && mounted) {
+ _frames
+ ..clear()
+ ..addAll(frames);
+ _currentIndex = 0;
+ _currentCaptionValue = frames.first.captionValue;
+ _previousCaptionValue = _currentCaptionValue;
+ _currentCaptionType = frames.first.captionType;
+ _startPlayback();
+ _logPlaybackStart(frames.length);
+ }
+ return frames;
+ }
+
+ Future<_TimelineFrame> _buildFrame(FacesTimelineEntry entry) async {
+ final file = await FilesDB.instance.getAnyUploadedFile(entry.fileId);
+ MemoryImage? image;
+ if (file != null) {
+ final faces = await MLDataDB.instance.getFacesForGivenFileID(
+ entry.fileId,
+ );
+ final Face? face = faces?.firstWhereOrNull(
+ (element) => element.faceID == entry.faceId,
+ );
+ if (face != null) {
+ try {
+ final cropMap = await getCachedFaceCrops(
+ file,
+ [face],
+ useFullFile: true,
+ personOrClusterID: widget.person.remoteID,
+ useTempCache: false,
+ );
+ final Uint8List? bytes = cropMap?[face.faceID];
+ if (bytes != null && bytes.isNotEmpty) {
+ image = MemoryImage(bytes);
+ }
+ } catch (error, stackTrace) {
+ _logger.warning(
+ "Failed to fetch face crop for ${entry.faceId}",
+ error,
+ stackTrace,
+ );
+ }
+ }
+ }
+ final creationDate = DateTime.fromMicrosecondsSinceEpoch(
+ entry.creationTimeMicros,
+ );
+ final captionType = widget.person.data.birthDate != null
+ ? _CaptionType.age
+ : _CaptionType.yearsAgo;
+ double captionValue;
+ if (captionType == _CaptionType.age) {
+ final birthDateString = widget.person.data.birthDate!;
+ final birthDate = DateTime.tryParse(birthDateString);
+ if (birthDate == null) {
+ captionValue = _yearsBetween(creationDate, DateTime.now());
+ } else {
+ captionValue = _yearsBetween(birthDate, creationDate);
+ }
+ } else {
+ captionValue = _yearsBetween(creationDate, DateTime.now());
+ }
+ captionValue = captionValue.clamp(0, double.infinity);
+ return _TimelineFrame(
+ entry: entry,
+ image: image,
+ creationDate: creationDate,
+ captionType: captionType,
+ captionValue: captionValue,
+ );
+ }
+
+ void _logPlaybackStart(int frameCount) {
+ if (_loggedPlaybackStart) return;
+ _logger.info(
+ "playback_start person=${widget.person.remoteID} frames=$frameCount",
+ );
+ _loggedPlaybackStart = true;
+ }
+
+ void _startPlayback() {
+ _playTimer?.cancel();
+ if (_frames.isEmpty) return;
+ _playTimer = Timer.periodic(_frameInterval, (_) {
+ if (!mounted || !_isPlaying || _frames.isEmpty) return;
+ _showNextFrame();
+ });
+ setState(() {
+ _isPlaying = true;
+ });
+ }
+
+ void _pausePlayback() {
+ _playTimer?.cancel();
+ setState(() {
+ _isPlaying = false;
+ });
+ }
+
+ void _togglePlayback() {
+ if (_isPlaying) {
+ _pausePlayback();
+ } else {
+ _startPlayback();
+ }
+ }
+
+ void _showNextFrame() {
+ if (_frames.isEmpty) return;
+ final nextIndex = (_currentIndex + 1) % _frames.length;
+ _setCurrentFrame(nextIndex);
+ }
+
+ void _showPreviousFrame() {
+ if (_frames.isEmpty) return;
+ final previousIndex = (_currentIndex - 1 + _frames.length) % _frames.length;
+ _setCurrentFrame(previousIndex);
+ }
+
+ void _setCurrentFrame(int index) {
+ if (index < 0 || index >= _frames.length) return;
+ final frame = _frames[index];
+ setState(() {
+ _previousCaptionValue = _currentCaptionValue;
+ _currentCaptionValue = frame.captionValue;
+ _currentCaptionType = frame.captionType;
+ _currentIndex = index;
+ });
+ }
+
+ void _onSharePressed() {
+ _logger.info("share_attempt person=${widget.person.remoteID}");
+ ScaffoldMessenger.of(context).showSnackBar(
+ SnackBar(content: Text(context.l10n.facesTimelineShareComingSoon)),
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final title = context.l10n.facesTimelineAppBarTitle(
+ name: widget.person.data.name,
+ );
+ final colorScheme = getEnteColorScheme(context);
+ return Scaffold(
+ appBar: AppBar(
+ title: Text(title),
+ actions: [
+ IconButton(
+ onPressed: _onSharePressed,
+ icon: const Icon(Icons.ios_share),
+ tooltip: context.l10n.facesTimelineShareComingSoon,
+ ),
+ ],
+ ),
+ body: FutureBuilder<List<_TimelineFrame>>(
+ future: _framesFuture,
+ builder: (context, snapshot) {
+ if (snapshot.connectionState != ConnectionState.done) {
+ return const Center(child: CircularProgressIndicator());
+ }
+ if (snapshot.hasError) {
+ _logger.severe(
+ "Faces timeline failed to load",
+ snapshot.error,
+ snapshot.stackTrace,
+ );
+ return Center(child: Text(context.l10n.facesTimelineUnavailable));
+ }
+ final frames = snapshot.data ?? [];
+ if (frames.isEmpty) {
+ return Center(child: Text(context.l10n.facesTimelineUnavailable));
+ }
+ return Column(
+ children: [
+ Expanded(
+ child: Stack(
+ children: [
+ Positioned.fill(
+ child: AnimatedSwitcher(
+ duration: const Duration(milliseconds: 800),
+ switchInCurve: Curves.easeInOut,
+ switchOutCurve: Curves.easeInOut,
+ child: _buildFrameView(colorScheme),
+ ),
+ ),
+ Positioned(
+ top: 24,
+ left: 0,
+ right: 0,
+ child: Center(
+ child: Container(
+ padding: const EdgeInsets.symmetric(
+ vertical: 6,
+ horizontal: 12,
+ ),
+ decoration: BoxDecoration(
+ color: colorScheme.fillFaint,
+ borderRadius: BorderRadius.circular(24),
+ ),
+ child: Text(
+ _frames[_currentIndex].entry.year.toString(),
+ style: getEnteTextTheme(context).bodyMuted,
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 24,
+ vertical: 20,
+ ),
+ child: Column(
+ children: [
+ _buildCaption(context),
+ const SizedBox(height: 20),
+ _buildControls(context),
+ ],
+ ),
+ ),
+ ],
+ );
+ },
+ ),
+ );
+ }
+
+ Widget _buildFrameView(EnteColorScheme colorScheme) {
+ if (_frames.isEmpty) {
+ return Container(color: colorScheme.backgroundBase);
+ }
+ final frame = _frames[_currentIndex];
+ final key = ValueKey<String>(frame.entry.faceId);
+ if (frame.image != null) {
+ return Container(
+ key: key,
+ color: colorScheme.backgroundBase,
+ child: Image(
+ image: frame.image!,
+ fit: BoxFit.cover,
+ width: double.infinity,
+ height: double.infinity,
+ gaplessPlayback: true,
+ ),
+ );
+ }
+ return Container(
+ key: key,
+ color: colorScheme.backgroundElevated2,
+ alignment: Alignment.center,
+ child: Icon(
+ Icons.person_outline,
+ size: 72,
+ color: colorScheme.strokeMuted,
+ ),
+ );
+ }
+
+ Widget _buildCaption(BuildContext context) {
+ final textTheme = getEnteTextTheme(context);
+ final captionType = _currentCaptionType;
+ return TweenAnimationBuilder<double>(
+ key: ValueKey<int>(_currentIndex),
+ tween: Tween<double>(
+ begin: _previousCaptionValue,
+ end: _currentCaptionValue,
+ ),
+ duration: const Duration(milliseconds: 500),
+ builder: (context, value, child) {
+ final rounded = value.round().clamp(0, 1000);
+ final text = captionType == _CaptionType.age
+ ? context.l10n.facesTimelineCaptionYearsOld(
+ name: widget.person.data.name,
+ count: rounded,
+ )
+ : context.l10n.facesTimelineCaptionYearsAgo(count: rounded);
+ return Text(text, style: textTheme.body, textAlign: TextAlign.center);
+ },
+ );
+ }
+
+ Widget _buildControls(BuildContext context) {
+ final colorScheme = getEnteColorScheme(context);
+ return Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ Tooltip(
+ message: context.l10n.facesTimelinePlaybackPrevious,
+ child: IconButtonWidget(
+ icon: Icons.skip_previous,
+ iconButtonType: IconButtonType.primary,
+ onTap: _frames.isEmpty ? null : _showPreviousFrame,
+ iconColor: colorScheme.strokeBase,
+ defaultColor: colorScheme.fillFaint,
+ pressedColor: colorScheme.fillMuted,
+ size: 24,
+ roundedIcon: true,
+ ),
+ ),
+ const SizedBox(width: 8),
+ Tooltip(
+ message: _isPlaying
+ ? context.l10n.facesTimelinePlaybackPause
+ : context.l10n.facesTimelinePlaybackPlay,
+ child: IconButtonWidget(
+ icon: _isPlaying ? Icons.pause : Icons.play_arrow,
+ iconButtonType: IconButtonType.primary,
+ onTap: _frames.isEmpty ? null : _togglePlayback,
+ iconColor: colorScheme.strokeBase,
+ defaultColor: colorScheme.fillFaint,
+ pressedColor: colorScheme.fillMuted,
+ size: 28,
+ roundedIcon: true,
+ ),
+ ),
+ const SizedBox(width: 8),
+ Tooltip(
+ message: context.l10n.facesTimelinePlaybackNext,
+ child: IconButtonWidget(
+ icon: Icons.skip_next,
+ iconButtonType: IconButtonType.primary,
+ onTap: _frames.isEmpty ? null : _showNextFrame,
+ iconColor: colorScheme.strokeBase,
+ defaultColor: colorScheme.fillFaint,
+ pressedColor: colorScheme.fillMuted,
+ size: 24,
+ roundedIcon: true,
+ ),
+ ),
+ ],
+ );
+ }
+}
+
+class _TimelineFrame {
+ final FacesTimelineEntry entry;
+ final MemoryImage? image;
+ final DateTime creationDate;
+ final _CaptionType captionType;
+ final double captionValue;
+
+ _TimelineFrame({
+ required this.entry,
+ required this.image,
+ required this.creationDate,
+ required this.captionType,
+ required this.captionValue,
+ });
+}
+
+enum _CaptionType { age, yearsAgo }
+
+double _yearsBetween(DateTime start, DateTime end) {
+ final days = end.difference(start).inDays;
+ return days / 365.25;
+}
diff --git a/mobile/apps/photos/lib/ui/viewer/people/people_page.dart b/mobile/apps/photos/lib/ui/viewer/people/people_page.dart
index 2195a04cfe..5a970ce113 100644
--- a/mobile/apps/photos/lib/ui/viewer/people/people_page.dart
+++ b/mobile/apps/photos/lib/ui/viewer/people/people_page.dart
@@ -14,6 +14,7 @@ import 'package:photos/models/gallery_type.dart';
import "package:photos/models/ml/face/person.dart";
import "package:photos/models/search/search_result.dart";
import 'package:photos/models/selected_files.dart';
+import 'package:photos/services/faces_timeline/faces_timeline_service.dart';
import "package:photos/services/machine_learning/face_ml/feedback/cluster_feedback.dart";
import "package:photos/services/search_service.dart";
import "package:photos/ui/components/end_to_end_banner.dart";
@@ -25,8 +26,10 @@ import "package:photos/ui/viewer/gallery/state/gallery_files_inherited_widget.da
import "package:photos/ui/viewer/gallery/state/inherited_search_filter_data.dart";
import "package:photos/ui/viewer/gallery/state/search_filter_data_provider.dart";
import "package:photos/ui/viewer/gallery/state/selection_state.dart";
+import "package:photos/ui/viewer/people/faces_timeline_banner.dart";
+import "package:photos/ui/viewer/people/faces_timeline_debug_panel.dart";
+import "package:photos/ui/viewer/people/faces_timeline_page.dart";
import "package:photos/ui/viewer/people/link_email_screen.dart";
-
import "package:photos/ui/viewer/people/people_app_bar.dart";
import "package:photos/ui/viewer/people/person_gallery_suggestion.dart";
import "package:photos/utils/navigation_util.dart";
@@ -52,6 +55,7 @@ class PeoplePage extends StatefulWidget {
class _PeoplePageState extends State<PeoplePage> {
final Logger _logger = Logger("_PeoplePageState");
+ final Logger _timelineLogger = Logger("FacesTimelineInteractions");
final _selectedFiles = SelectedFiles();
List<EnteFile>? files;
Future<List<EnteFile>> filesFuture = Future.value([]);
@@ -62,6 +66,8 @@ class _PeoplePageState extends State<PeoplePage> {
late final StreamSubscription<LocalPhotosUpdatedEvent> _filesUpdatedEvent;
late final StreamSubscription<PeopleChangedEvent> _peopleChangedEvent;
late SearchFilterDataProvider? _searchFilterDataProvider;
+ ValueNotifier<Set<String>>? _timelineNotifier;
+ VoidCallback? _timelineListener;
@override
void initState() {
@@ -81,8 +87,9 @@ class _PeoplePageState extends State<PeoplePage> {
filesFuture = loadPersonFiles();
- _filesUpdatedEvent =
- Bus.instance.on<LocalPhotosUpdatedEvent>().listen((event) {
+ _filesUpdatedEvent = Bus.instance.on<LocalPhotosUpdatedEvent>().listen((
+ event,
+ ) {
if (event.type == EventType.deletedFromDevice ||
event.type == EventType.deletedFromEverywhere ||
event.type == EventType.deletedFromRemote ||
@@ -99,11 +106,24 @@ class _PeoplePageState extends State<PeoplePage> {
widget.searchResult!.getHierarchicalSearchFilter(),
)
: null;
+ _timelineNotifier = FacesTimelineService.instance.readyPersonIds;
+ _timelineListener = () {
+ if (!mounted) return;
+ setState(() {});
+ };
+ _timelineNotifier!.addListener(_timelineListener!);
+ if (!FacesTimelineService.instance.hasReadyTimelineSync(_person.remoteID)) {
+ FacesTimelineService.instance.schedulePersonRecompute(
+ _person.remoteID,
+ trigger: "people_page_visit",
+ );
+ }
}
Future<List<EnteFile>> loadPersonFiles() async {
- final result = await SearchService.instance
- .getClusterFilesForPersonID(_person.remoteID);
+ final result = await SearchService.instance.getClusterFilesForPersonID(
+ _person.remoteID,
+ );
if (result.isEmpty) {
_logger.severe(
"No files found for person with id ${_person.remoteID}, can't load files",
@@ -124,12 +144,22 @@ class _PeoplePageState extends State<PeoplePage> {
void dispose() {
_filesUpdatedEvent.cancel();
_peopleChangedEvent.cancel();
+ if (_timelineListener != null && _timelineNotifier != null) {
+ _timelineNotifier!.removeListener(_timelineListener!);
+ }
super.dispose();
}
+ void _openFacesTimelinePage() {
+ _timelineLogger.info("banner_tap person=${_person.remoteID}");
+ unawaited(routeToPage(context, FacesTimelinePage(person: _person)));
+ }
+
@override
Widget build(BuildContext context) {
_logger.info("Building for ${_person.data.name}");
+ final bool showFacesTimelineBanner =
+ FacesTimelineService.instance.hasReadyTimelineSync(_person.remoteID);
return GalleryBoundariesProvider(
child: GalleryFilesState(
@@ -137,8 +167,9 @@ class _PeoplePageState extends State<PeoplePage> {
searchFilterDataProvider: _searchFilterDataProvider,
child: Scaffold(
appBar: PreferredSize(
- preferredSize:
- Size.fromHeight(widget.searchResult != null ? 90.0 : 50.0),
+ preferredSize: Size.fromHeight(
+ widget.searchResult != null ? 90.0 : 50.0,
+ ),
child: PeopleAppBar(
GalleryType.peopleTag,
_person.data.isIgnored
@@ -166,11 +197,7 @@ class _PeoplePageState extends State<PeoplePage> {
valueListenable: inheritedSearchFilterData
.searchFilterDataProvider!
.isSearchingNotifier,
- builder: (
- context,
- value,
- _,
- ) {
+ builder: (context, value, _) {
return value
? HierarchicalSearchGallery(
tagPrefix: widget.tagPrefix,
@@ -182,6 +209,9 @@ class _PeoplePageState extends State<PeoplePage> {
personFiles: personFiles,
loadPersonFiles: loadPersonFiles,
personEntity: _person,
+ showTimelineBanner:
+ showFacesTimelineBanner,
+ onTimelineTap: _openFacesTimelinePage,
);
},
)
@@ -191,6 +221,8 @@ class _PeoplePageState extends State<PeoplePage> {
personFiles: personFiles,
loadPersonFiles: loadPersonFiles,
personEntity: _person,
+ showTimelineBanner: showFacesTimelineBanner,
+ onTimelineTap: _openFacesTimelinePage,
),
FileSelectionOverlayBar(
PeoplePage.overlayType,
@@ -207,9 +239,7 @@ class _PeoplePageState extends State<PeoplePage> {
//Need to show an error on the UI here
return const SizedBox.shrink();
} else {
- return const Center(
- child: CircularProgressIndicator(),
- );
+ return const Center(child: CircularProgressIndicator());
}
},
),
@@ -226,6 +256,8 @@ class _Gallery extends StatefulWidget {
final List<EnteFile> personFiles;
final Future<List<EnteFile>> Function() loadPersonFiles;
final PersonEntity personEntity;
+ final bool showTimelineBanner;
+ final VoidCallback? onTimelineTap;
const _Gallery({
required this.tagPrefix,
@@ -233,6 +265,8 @@ class _Gallery extends StatefulWidget {
required this.personFiles,
required this.loadPersonFiles,
required this.personEntity,
+ this.showTimelineBanner = false,
+ this.onTimelineTap,
});
@override
@@ -241,23 +275,29 @@ class _Gallery extends StatefulWidget {
class _GalleryState extends State<_Gallery> {
bool userDismissedPersonGallerySuggestion = false;
+ final Logger _timelineLogger = Logger("FacesTimelineBanner");
+ bool _loggedTimelineImpression = false;
+
+ @override
+ void didUpdateWidget(covariant _Gallery oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (!widget.showTimelineBanner && oldWidget.showTimelineBanner) {
+ _loggedTimelineImpression = false;
+ }
+ }
@override
Widget build(BuildContext context) {
+ if (widget.showTimelineBanner && !_loggedTimelineImpression) {
+ _timelineLogger.info(
+ "banner_impression person=${widget.personEntity.remoteID}",
+ );
+ _loggedTimelineImpression = true;
+ }
return Gallery(
- asyncLoader: (
- creationStartTime,
- creationEndTime, {
- limit,
- asc,
- }) async {
+ asyncLoader: (creationStartTime, creationEndTime, {limit, asc}) async {
final result = await widget.loadPersonFiles();
- return Future.value(
- FileLoadResult(
- result,
- false,
- ),
- );
+ return Future.value(FileLoadResult(result, false));
},
reloadEvent: Bus.instance.on<LocalPhotosUpdatedEvent>(),
forceReloadEvents: [Bus.instance.on<PeopleChangedEvent>()],
@@ -290,6 +330,12 @@ class _GalleryState extends State<_Gallery> {
},
),
),
+ FacesTimelineBannerSection(
+ showBanner: widget.showTimelineBanner,
+ person: widget.personEntity,
+ onTap: widget.onTimelineTap,
+ ),
+ FacesTimelineDebugPanel(person: widget.personEntity),
!userDismissedPersonGallerySuggestion
? Dismissible(
key: const Key("personGallerySuggestion"),
diff --git a/mobile/apps/photos/test/services/faces_timeline/timeline_selector_test.dart b/mobile/apps/photos/test/services/faces_timeline/timeline_selector_test.dart
new file mode 100644
index 0000000000..53da685253
--- /dev/null
+++ b/mobile/apps/photos/test/services/faces_timeline/timeline_selector_test.dart
@@ -0,0 +1,81 @@
+import "package:flutter_test/flutter_test.dart";
+import "package:photos/services/faces_timeline/faces_timeline_service.dart";
+
+Map<String, dynamic> _buildFace(
+ String faceId,
+ int fileId,
+ DateTime creationDate,
+) {
+ return {
+ "faceId": faceId,
+ "fileId": fileId,
+ "creationTime": creationDate.microsecondsSinceEpoch,
+ "year": creationDate.year,
+ };
+}
+
+void main() {
+ group("Faces timeline selection", () {
+ test("returns ready when at least seven eligible years are present", () {
+ final faces = <Map<String, dynamic>>[];
+ for (int year = 2010; year < 2017; year++) {
+ for (int index = 0; index < 5; index++) {
+ faces.add(
+ _buildFace(
+ "face-$year-$index",
+ year * 10 + index,
+ DateTime(year, 1, 1).add(Duration(days: index * 60)),
+ ),
+ );
+ }
+ }
+
+ final result = selectTimelineEntriesTask({
+ "faces": faces,
+ "minYears": 7,
+ "minFaces": 4,
+ });
+
+ expect(result["status"], equals("ready"));
+ final years = (result["years"] as List<dynamic>).cast<int>();
+ expect(years, equals(List<int>.generate(7, (i) => 2010 + i)));
+
+ final entries =
+ (result["entries"] as List<dynamic>).cast<Map<String, dynamic>>();
+ expect(entries.length, equals(28));
+ final faceIds = entries.map((entry) => entry["faceId"]).toSet();
+ expect(faceIds.length, equals(entries.length));
+
+ for (final year in years) {
+ final yearEntries =
+ entries.where((entry) => entry["year"] == year).toList();
+ expect(yearEntries.length, equals(4));
+ }
+ });
+
+ test("returns ineligible when fewer than seven years qualify", () {
+ final faces = <Map<String, dynamic>>[];
+ for (int year = 2011; year < 2017; year++) {
+ for (int index = 0; index < 4; index++) {
+ faces.add(
+ _buildFace(
+ "face-$year-$index",
+ year * 100 + index,
+ DateTime(year, 3, 1).add(Duration(days: index * 40)),
+ ),
+ );
+ }
+ }
+
+ final result = selectTimelineEntriesTask({
+ "faces": faces,
+ "minYears": 7,
+ "minFaces": 4,
+ });
+
+ expect(result["status"], equals("ineligible"));
+ expect(result["eligibleYearCount"], equals(6));
+ expect(result["entries"], isNull);
+ });
+ });
+}
diff --git a/mobile/apps/photos/test/ui/viewer/people/faces_timeline_banner_section_test.dart b/mobile/apps/photos/test/ui/viewer/people/faces_timeline_banner_section_test.dart
new file mode 100644
index 0000000000..d9e87e309e
--- /dev/null
+++ b/mobile/apps/photos/test/ui/viewer/people/faces_timeline_banner_section_test.dart
@@ -0,0 +1,67 @@
+import "package:flutter/material.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:photos/generated/intl/app_localizations.dart";
+import "package:photos/models/ml/face/person.dart";
+import "package:photos/ui/viewer/people/faces_timeline_banner.dart";
+
+void main() {
+ group("FacesTimelineBannerSection", () {
+ late PersonEntity person;
+
+ setUp(() {
+ person = PersonEntity(
+ "person-1",
+ PersonData(name: "Alex"),
+ );
+ });
+
+ testWidgets("renders banner when timeline is ready", (tester) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ localizationsDelegates: AppLocalizations.localizationsDelegates,
+ supportedLocales: AppLocalizations.supportedLocales,
+ home: FacesTimelineBannerSection(
+ showBanner: true,
+ person: person,
+ onTap: () {},
+ ),
+ ),
+ );
+
+ expect(find.byType(FacesTimelineBanner), findsOneWidget);
+ expect(find.textContaining("Faces timeline"), findsOneWidget);
+ });
+
+ testWidgets("hides banner when timeline is unavailable", (tester) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ localizationsDelegates: AppLocalizations.localizationsDelegates,
+ supportedLocales: AppLocalizations.supportedLocales,
+ home: FacesTimelineBannerSection(
+ showBanner: false,
+ person: person,
+ onTap: () {},
+ ),
+ ),
+ );
+
+ expect(find.byType(FacesTimelineBanner), findsNothing);
+ });
+
+ testWidgets("hides banner when tap callback is missing", (tester) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ localizationsDelegates: AppLocalizations.localizationsDelegates,
+ supportedLocales: AppLocalizations.supportedLocales,
+ home: FacesTimelineBannerSection(
+ showBanner: true,
+ person: person,
+ onTap: null,
+ ),
+ ),
+ );
+
+ expect(find.byType(FacesTimelineBanner), findsNothing);
+ });
+ });
+}