//! Albums stage 1 on synthetic libraries (no photos, no owner data). use std::collections::HashMap; use super::bin::{self, Mark}; use super::look::{self, analyse, Grey, Level, Look, PlatformLook}; use super::pass::{self, Progress, State}; use super::picks::picks; use super::sets::{self, Shot}; use super::synthetic::{library, Options, Synth}; use super::tidy::{self, Entry, List}; use super::{size, words, Item, Kind, Platform}; fn looks(lib: &[Synth]) -> Vec { lib.iter().map(|s| analyse(s.grey.as_ref(), s.platform.clone())).collect() } /// Sets over a library: (sets as indices, pair precision, pair recall, exact share). fn measure_sets(lib: &[Synth], looks: &[Look]) -> (Vec>, f64, f64, f64) { let mut shots: Vec> = lib.iter().enumerate().filter(|(i, s)| sets::groupable(&s.item, Some(&looks[*i]))).map(|(i, s)| Shot { index: i, taken_at_ms: s.item.taken_at_ms, look: &looks[i] }).collect(); let found = sets::group(&mut shots); let pairs = |n: u64| n * n.saturating_sub(1) / 2; let mut truth: HashMap = HashMap::new(); for s in lib.iter().filter(|s| s.truth.moment != u32::MAX && s.grey.is_some()) { *truth.entry(s.truth.moment).or_default() += 1; } let mut inter: HashMap<(usize, u32), u64> = HashMap::new(); for (k, set) in found.iter().enumerate() { for &i in set { *inter.entry((k, lib[i].truth.moment)).or_default() += 1; } } let tp: u64 = inter.iter().filter(|((_, m), _)| *m != u32::MAX).map(|(_, &c)| pairs(c)).sum(); let pred: u64 = found.iter().map(|s| pairs(s.len() as u64)).sum(); let real: u64 = truth.values().map(|&c| pairs(c)).sum(); let multi = truth.values().filter(|&&c| c >= 2).count(); let exact = found.iter().filter(|s| { let m = lib[s[0]].truth.moment; m != u32::MAX && s.iter().all(|&i| lib[i].truth.moment == m) && truth[&m] == s.len() as u64 }); (found.clone(), tp as f64 / pred.max(1) as f64, tp as f64 / real.max(1) as f64, exact.count() as f64 / multi.max(1) as f64) } #[test] fn sets_find_the_moments_of_a_64000_item_library() { let lib = library(&Options::default()); assert_eq!(lib.len(), 64_000); let looks = looks(&lib); assert!(looks.iter().all(|l| l.level == Level::Small), "48x36 pictures are graded Small"); let (found, precision, recall, exact) = measure_sets(&lib, &looks); assert!(precision >= 0.99, "pair precision {precision}"); assert!(recall >= 0.98, "pair recall {recall}"); assert!(exact >= 0.93, "moments found exactly {exact}"); assert!(found.len() > 7_000, "sets {}", found.len()); } #[test] fn two_moments_a_minute_apart_stay_apart_and_a_scene_revisited_hours_later_too() { // the library has 20% of moments within 2 minutes of the one before and 5% // revisiting a scene: precision above already counts both; here, directly let lib = library(&Options { items: 6_000, ..Options::default() }); let looks = looks(&lib); let (found, _, _, _) = measure_sets(&lib, &looks); let mixed = found.iter().filter(|s| s.iter().any(|&i| lib[i].truth.moment != lib[s[0]].truth.moment)).count(); assert!((mixed as f64) < 0.01 * found.len() as f64, "{mixed} of {} sets mix moments", found.len()); } #[test] fn picks_keep_a_sharp_shot_and_few_of_a_burst_when_seen_full() { // Full pictures (longest side 256) so sharpness is measured let lib = library(&Options { items: 1_000, width: 256, height: 192, ..Options::default() }); let looks = looks(&lib); assert!(looks.iter().all(|l| l.level == Level::Full && l.sharp.is_some())); let (found, precision, recall, _) = measure_sets(&lib, &looks); assert!(precision >= 0.98 && recall >= 0.97, "full pictures: precision {precision}, recall {recall}"); let (mut bad_first, mut with_good, mut big, mut big_kept) = (0, 0, 0, 0); for set in &found { let members: Vec<&Look> = set.iter().map(|&i| &looks[i]).collect(); let p = picks(&members); assert!(p.sure); assert!(!p.keep.is_empty() && p.keep.len() <= super::picks::CAP); if set.iter().any(|&i| !lib[i].truth.blurred && !lib[i].truth.dark) { with_good += 1; let first = &lib[set[p.keep[0]]].truth; if first.blurred || first.dark { bad_first += 1; } } if set.len() >= 10 { big += 1; big_kept += p.keep.len(); } } assert!(bad_first as f64 <= 0.005 * with_good as f64, "first pick bad in {bad_first} of {with_good}"); assert!(big > 0 && (big_kept as f64 / big as f64) <= 3.0, "sets of 10+ keep {}", big_kept as f64 / big.max(1) as f64); } #[test] fn small_pictures_group_but_make_no_claim_about_blur() { let lib = library(&Options { items: 3_000, ..Options::default() }); let looks = looks(&lib); assert!(looks.iter().all(|l| l.sharp.is_none()), "a small picture hides blur, so no sharpness"); let (found, _, _, _) = measure_sets(&lib, &looks); let members: Vec<&Look> = found[0].iter().map(|&i| &looks[i]).collect(); assert!(!picks(&members).sure, "picks on small pictures are a first guess"); assert_eq!(words::keeps_line(2, false), "A first guess: Albums will look closer on Wi-Fi. Tap a photo to change."); // and Blurry and dark offers nothing it cannot see let entries: Vec> = lib.iter().zip(&looks).map(|(s, l)| Entry { item: &s.item, look: Some(l), mark: Mark::None, set_offer: false, set_pick: false, exact_copy: false }).collect(); assert!(entries.iter().all(|e| tidy::list_of(e) != Some(List::BlurryDark))); } #[test] fn a_photo_with_no_picture_on_the_phone_is_counted_never_grouped_and_asked_again_on_wifi() { let lib = library(&Options { items: 4_000, cloud_only: 0.2, ..Options::default() }); let looks = looks(&lib); let none = looks.iter().filter(|l| l.level == Level::None).count(); assert!(none > 500); for (s, l) in lib.iter().zip(&looks) { if l.level == Level::None { assert!(!sets::groupable(&s.item, Some(l))); assert_eq!(look::match_key(s.item.taken_at_ms, s.item.width, s.item.height, l), None); } } assert_eq!(pass::next_ask(None, false, false), Some(pass::Ask { px: 360, network: false })); assert_eq!(pass::next_ask(Some(Level::None), false, false), None, "off Wi-Fi it waits"); assert_eq!(pass::next_ask(Some(Level::None), false, true), Some(pass::Ask { px: 360, network: true })); assert_eq!(pass::next_ask(Some(Level::None), true, true), None, "asked once with the network: never again, never the original"); assert_eq!(pass::next_ask(Some(Level::Small), false, true), None); // a picture under 32 px is no picture let tiny = Grey::new(24, 18, vec![128; 24 * 18]).unwrap(); assert_eq!(analyse(Some(&tiny), PlatformLook::default()).level, Level::None); } #[test] fn the_grey_and_its_measures_are_the_same_from_either_phone() { // the same photo handed as RGBA by two phones gives one match key let rgba: Vec = (0..64 * 48).flat_map(|i| [(i % 251) as u8, (i % 113) as u8, (i % 61) as u8, 255]).collect(); let a = Grey::from_rgba(64, 48, &rgba).unwrap(); let b = Grey::from_rgba(64, 48, &rgba).unwrap(); let (la, lb) = (analyse(Some(&a), PlatformLook::default()), analyse(Some(&b), PlatformLook::default())); assert_eq!(la, lb); assert_eq!(look::match_key(1_700_000_000_123, 4032, 3024, &la).unwrap(), format!("1700000000:4032x3024:{:016x}", la.dhash)); assert!(Grey::from_rgba(64, 48, &rgba[..100]).is_none()); } #[test] fn a_platform_print_is_used_only_against_one_of_its_own_revision() { let g = Grey::new(64, 48, (0..64 * 48).map(|i| (i % 256) as u8).collect()).unwrap(); let print = |rev: &str, v: f32| PlatformLook { print: Some(look::Print { revision: rev.into(), values: vec![v; 8] }), ..PlatformLook::default() }; let a = analyse(Some(&g), print("2", 0.0)); let far = analyse(Some(&g), print("2", 1.0)); let other_rev = analyse(Some(&g), print("1", 1.0)); assert!(!sets::alike(&a, &far), "same revision, far apart"); assert!(sets::alike(&a, &other_rev), "different revisions fall back to the core's own print"); } fn entries<'a>(lib: &'a [Synth], looks: &'a [Look], marks: &HashMap) -> Vec> { let mut shots: Vec> = lib.iter().enumerate().filter(|(i, s)| sets::groupable(&s.item, Some(&looks[*i])) && marks.get(i).is_none_or(Mark::offered)).map(|(i, s)| Shot { index: i, taken_at_ms: s.item.taken_at_ms, look: &looks[i] }).collect(); let found = sets::group(&mut shots); let (mut offer, mut pick) = (vec![false; lib.len()], vec![false; lib.len()]); for set in &found { let members: Vec<&Look> = set.iter().map(|&i| &looks[i]).collect(); let p = picks(&members); for (k, &i) in set.iter().enumerate() { if p.keep.contains(&k) { pick[i] = true; } else { offer[i] = true; } } } let pairs: Vec<(&Item, Option<&Look>)> = lib.iter().zip(looks).map(|(s, l)| (&s.item, Some(l))).collect(); let mut copy = vec![false; lib.len()]; for g in tidy::exact_copies(&pairs) { for &i in &g[1..] { copy[i] = true; } } lib.iter().enumerate().map(|(i, s)| Entry { item: &s.item, look: Some(&looks[i]), mark: marks.get(&i).copied().unwrap_or(Mark::None), set_offer: offer[i], set_pick: pick[i], exact_copy: copy[i] }).collect() } #[test] fn tidy_lists_put_each_photo_in_one_list_biggest_first() { let lib = library(&Options { items: 20_000, others: true, ..Options::default() }); let looks = looks(&lib); let es = entries(&lib, &looks, &HashMap::new()); let summary = tidy::summarise(&es); let lists: Vec = summary.iter().map(|s| s.list).collect(); for l in [List::Sets, List::LargeVideos, List::WhatsappCopies, List::Screenshots, List::Documents] { assert!(lists.contains(&l), "{l:?} missing from {lists:?}"); } assert!(summary.windows(2).all(|w| w[0].bytes >= w[1].bytes), "biggest first"); // one list each: the counts add up to the entries offered let offered = es.iter().filter(|e| tidy::list_of(e).is_some()).count(); assert_eq!(summary.iter().map(|s| s.count).sum::(), offered); // a set's picks are never offered, its other shots only under Sets for e in &es { if e.set_pick { assert_eq!(tidy::list_of(e), None); } if e.set_offer { assert_eq!(tidy::list_of(e), Some(List::Sets)); } } assert!(summary.iter().all(|s| s.exact)); } #[test] fn kept_favourite_hidden_and_binned_photos_are_never_offered() { let lib = library(&Options { items: 3_000, others: true, ..Options::default() }); let looks = looks(&lib); let mut marks = HashMap::new(); let all = entries(&lib, &looks, &marks); let offered: Vec = all.iter().enumerate().filter(|(_, e)| tidy::list_of(e).is_some()).map(|(i, _)| i).collect(); marks.insert(offered[0], Mark::Keep { at_ms: 1 }); marks.insert(offered[1], Mark::Bin { at_ms: 1 }); let after = entries(&lib, &looks, &marks); assert_eq!(tidy::list_of(&after[offered[0]]), None); assert_eq!(tidy::list_of(&after[offered[1]]), None); let mut fav = lib[offered[2]].item.clone(); fav.flags.push("favourite".into()); let e = Entry { item: &fav, look: Some(&looks[offered[2]]), mark: Mark::None, set_offer: true, set_pick: false, exact_copy: false }; assert_eq!(tidy::list_of(&e), None); } #[test] fn whatsapp_copies_are_told_and_matched_to_their_camera_original() { let item = |path: &str| Item { id: "x".into(), kind: Kind::Photo, taken_at_ms: 0, width: 1600, height: 1200, duration_ms: 0, bytes: None, flags: vec![], path: Some(path.into()), camera: None, cloud_id: None, offset_s: None, added_ms: None, generation_added: None, modified: None }; assert!(tidy::whatsapp(&item("Android/media/com.whatsapp/WhatsApp/Media/WhatsApp Images/"))); assert!(tidy::whatsapp(&item("IMG-20231201-WA0003.jpg"))); assert!(tidy::whatsapp(&item("DCIM/x/VID-20240101-WA0042.mp4"))); assert!(!tidy::whatsapp(&item("IMG_4021.HEIC"))); assert!(!tidy::whatsapp(&item("IMG-2023120-WA0003.jpg"))); let lib = library(&Options { items: 8_000, others: true, ..Options::default() }); let looks = looks(&lib); let camera_idx: Vec = lib.iter().enumerate().filter(|(_, s)| s.item.camera.is_some()).map(|(i, _)| i).collect(); let camera: Vec<(&Item, &Look)> = camera_idx.iter().map(|&i| (&lib[i].item, &looks[i])).collect(); let copies: Vec = lib.iter().enumerate().filter(|(_, s)| tidy::whatsapp(&s.item)).map(|(i, _)| i).collect(); assert!(copies.len() > 50); let (mut right, mut wrong, mut missed, mut real) = (0, 0, 0, 0); for &i in &copies { let found = tidy::copy_of((&lib[i].item, &looks[i]), &camera).map(|k| camera_idx[k]); let truth = lib[i].truth.copy_of; real += usize::from(truth.is_some()); // any shot of the original's moment is a photo he already has let same_moment = |f: usize, t: usize| f == t || (lib[t].truth.moment != u32::MAX && lib[f].truth.moment == lib[t].truth.moment); match (found, truth) { (Some(f), Some(t)) if same_moment(f, t) => right += 1, (Some(_), _) => wrong += 1, (None, Some(_)) => missed += 1, (None, None) => {} } } assert!(wrong as f64 <= 0.02 * copies.len() as f64, "{wrong} wrong matches of {} copies", copies.len()); assert!(right as f64 >= 0.95 * real as f64, "found {right} of {real} originals, missed {missed}"); } #[test] fn exact_copies_keep_the_earliest() { let lib = library(&Options { items: 200, ..Options::default() }); let looks = looks(&lib); let mut items: Vec = lib.iter().map(|s| s.item.clone()).collect(); let mut dup = items[10].clone(); dup.id = "dup".into(); dup.taken_at_ms += 5_000; items.push(dup); let mut ls = looks.clone(); ls.push(looks[10].clone()); let pairs: Vec<(&Item, Option<&Look>)> = items.iter().zip(&ls).map(|(i, l)| (i, Some(l))).collect(); let groups = tidy::exact_copies(&pairs); assert_eq!(groups, vec![vec![10, 200]]); } #[test] fn sizes_are_exact_where_the_phone_says_and_about_where_it_does_not() { let mut photo = Item { id: "p".into(), kind: Kind::Photo, taken_at_ms: 0, width: 4032, height: 3024, duration_ms: 0, bytes: Some(3_100_000), flags: vec![], path: None, camera: None, cloud_id: None, offset_s: None, added_ms: None, generation_added: None, modified: None }; assert_eq!(size::of(&photo), size::Size { bytes: 3_100_000, exact: true }); photo.bytes = None; let est = size::of(&photo); assert!(!est.exact && (2_000_000..4_000_000).contains(&est.bytes), "{est:?}"); photo.flags.push("live".into()); assert!(size::of(&photo).bytes > est.bytes); let video = Item { id: "v".into(), kind: Kind::Video, taken_at_ms: 0, width: 3840, height: 2160, duration_ms: 60_000, bytes: None, flags: vec![], path: None, camera: None, cloud_id: None, offset_s: None, added_ms: None, generation_added: None, modified: None }; assert_eq!(size::of(&video).bytes, 174_000_000); assert_eq!(words::size(31_400_000_000, true), "31.4 GB"); assert_eq!(words::size(400_000_000, false), "about 0.4 GB"); assert_eq!(words::size(82_000_000, true), "82 MB"); assert_eq!(words::delete_all(2_340), "Delete 2,340"); assert_eq!(words::delete_question(2_340, Platform::Ios), "Delete 2,340 from this iPhone?"); assert_eq!(words::delete_question(2_340, Platform::Android), "Delete 2,340 from this phone?"); assert_eq!(words::deleted_after(2_340, 31_400_000_000, true, Platform::Ios), "Deleted 2,340 (31.4 GB). They stay in Photos' Recently Deleted for 30 days."); assert_eq!(words::deleted_after(1, 3_000_000, true, Platform::Android), "Deleted 1 (3 MB). It stays in the phone's trash for 30 days."); // a list holding one estimate says about let lib = library(&Options { items: 3_000, others: true, exact_sizes: false, ..Options::default() }); let looks = looks(&lib); let es = entries(&lib, &looks, &HashMap::new()); assert!(tidy::summarise(&es).iter().any(|s| !s.exact)); } #[test] fn free_asks_the_iphone_once_and_android_in_parts_of_2000() { let ids: Vec = (0..4_500).map(|i| format!("a{i}")).collect(); assert_eq!(bin::free_batches(Platform::Ios, &ids).len(), 1); let parts = bin::free_batches(Platform::Android, &ids); assert_eq!(parts.iter().map(Vec::len).collect::>(), vec![2000, 2000, 500]); let many: Vec = (0..25_000).map(|i| format!("a{i}")).collect(); assert_eq!(bin::free_batches(Platform::Ios, &many).len(), 3); assert_eq!(words::delete_note_many(3, Platform::Ios), "The iPhone asks 3 times, once for each part. They then stay in Photos' Recently Deleted for 30 days."); assert_eq!(words::delete_note_many(3, Platform::Android), "The phone asks 3 times, once for each part. They then stay in the phone's trash for 30 days."); } #[test] fn only_the_library_settles_a_handed_photo() { use bin::LibraryState::*; assert_eq!(bin::settled(Present, 5), Mark::Bin { at_ms: 5 }, "still there: back in the Bin"); assert_eq!(bin::settled(Trashed, 5), Mark::Freed { at_ms: 5 }, "in the phone's trash: freed, never shown as in the Bin"); assert_eq!(bin::settled(Absent, 5), Mark::Freed { at_ms: 5 }); for s in [Present, Trashed, Absent] { assert_eq!(bin::LibraryState::from_key(s.key()), Some(s)); } // a Handed mark cannot be made here (decision M-b): decode a stored one let handed: Mark = serde_json::from_str(r#"{"mark":"handed","at_ms":0}"#).unwrap(); assert!(handed.handed()); assert!(!bin::can_bring_back(&handed), "nothing acts on a handed photo"); assert!(!handed.offered() && !handed.in_bin()); assert_eq!(words::not_freed(2), "2 weren't deleted and are still in the Bin."); assert_eq!(words::held_reason("original_gone"), "Kept: its original is gone."); } #[test] fn one_bin_on_both_phones_keeps_until_delete_with_no_clock() { // decision G: Albums' Bin is marks only on both phones; nothing erases it assert!(bin::can_bring_back(&Mark::Bin { at_ms: 0 }), "a year later it is still there"); assert!(!bin::can_bring_back(&Mark::Freed { at_ms: 0 }), "after Delete only Photos or the phone's trash can"); assert!(!bin::can_bring_back(&Mark::Keep { at_ms: 0 })); } #[test] fn the_progress_line_measures_time_left_and_never_guesses_early() { let mut p = Progress { total: 64_212, ..Progress::default() }; assert_eq!(pass::lines(&p, State::NotStarted, true, Platform::Ios), None); p.looked_at(10, 0, 0); let l = pass::lines(&p, State::Running, true, Platform::Ios).unwrap(); assert_eq!(l.head, "Looking through 64,212 photos and videos"); assert_eq!(l.detail.as_deref(), Some("10 done"), "too few to measure"); // then 25 photos a second (40 ms each) for 500 photos for k in 0..20 { p.looked_at(25, 0, 1_000 * (k + 1)); } p.looked = 18_400; let m = p.minutes_left().unwrap(); assert!((28..=33).contains(&m), "{m} minutes"); let l = pass::lines(&p, State::Running, true, Platform::Ios).unwrap(); assert_eq!(l.detail.unwrap(), format!("18,400 done · about {m} min left while charging")); assert_eq!(l.note.as_deref(), Some("Sets and lists fill in as it goes.")); let paused = pass::lines(&p, State::PausedBattery, false, Platform::Ios).unwrap(); assert_eq!(paused.note.as_deref(), Some("Paused to save battery. Carries on when charging.")); p.cloud_only = 1_204; assert_eq!(pass::lines(&p, State::Running, true, Platform::Ios).unwrap().cloud.unwrap(), "1,204 are only in iCloud. Albums will look at them on Wi-Fi."); let done = pass::lines(&p, State::Done, true, Platform::Ios).unwrap(); assert_eq!((done.head.as_str(), done.fraction), ("Looked through 64,212 photos and videos.", 1.0)); } #[test] fn words_read_as_the_design_says() { assert_eq!(words::count(64_212), "64,212"); assert_eq!(words::count(7), "7"); assert_eq!(words::count(1_000_000), "1,000,000"); assert_eq!(words::in_bin(2_340, 31_400_000_000, true), "In the Bin: 2,340 · 31.4 GB"); assert_eq!(words::could_free(52_000_000_000), "You could free about 52.0 GB more"); assert_eq!(words::keep_button(6, 19), "Keep 6, Bin 19"); assert_eq!(words::kept_after(6, 19), "Kept 6. Moved 19 to the Bin."); assert_eq!(words::keeps_line(6, true), "Keeps the 6 sharpest that look different. Tap a photo to change."); assert_eq!(words::list_name(List::Documents), "Receipts and documents"); // Sat 14 Mar 2026, 6:12 pm in India (+5:30) let at = 1_773_492_120_000; // 2026-03-14T12:42:00Z assert_eq!(words::when(at, 19_800, 2026), "Sat 14 Mar, 6:12 pm"); assert_eq!(words::when(at, 19_800, 2027), "Sat 14 Mar 2026, 6:12 pm"); assert_eq!(words::set_row(25, "Sat 14 Mar, 6:12 pm", 6), "25 photos · Sat 14 Mar, 6:12 pm · Keep 6?"); assert_eq!(words::year_of(at, 19_800), 2026); for banned in ["Trash", "AI", "smart", "memories", "back up"] { for line in [words::PERMISSION_WHY, words::DELETE_NOTE_IOS, words::DELETE_NOTE_ANDROID, words::BIN_NOTE] { assert!(!line.contains(banned), "{line}"); } } } #[test] fn a_raw_and_its_jpeg_or_an_edit_and_its_original_are_one_item() { use super::parts::is_part_of; let it = |id: &str, path: &str, ms: i64| Item { id: id.into(), kind: Kind::Photo, taken_at_ms: ms, width: 4000, height: 3000, duration_ms: 0, bytes: None, flags: vec![], path: Some(path.into()), camera: None, cloud_id: None, offset_s: None, added_ms: None, generation_added: None, modified: None }; let jpg = it("1", "DCIM/Camera/IMG_20260314_181200.jpg", 1_000_400); let raw = it("2", "DCIM/Camera/IMG_20260314_181200.dng", 1_000_900); assert!(is_part_of(&raw, &jpg) && !is_part_of(&jpg, &raw)); let edited = it("3", "DCIM/Camera/IMG_20260314_181200-edited.jpg", 1_000_100); assert!(is_part_of(&jpg, &edited), "the original is a part of its edit"); let later = it("4", "DCIM/Camera/IMG_20260314_181200.dng", 1_002_000); assert!(!is_part_of(&later, &jpg), "another second is another photo"); let other = it("5", "DCIM/Camera/IMG_20260314_181201.dng", 1_000_400); assert!(!is_part_of(&other, &jpg)); } #[test] fn a_trashed_photo_is_never_grouped_or_offered() { let lib = library(&Options { items: 300, ..Options::default() }); let looks = looks(&lib); let mut item = lib[0].item.clone(); item.flags.push("trashed".into()); assert!(!sets::groupable(&item, Some(&looks[0]))); let e = Entry { item: &item, look: Some(&looks[0]), mark: Mark::None, set_offer: true, set_pick: false, exact_copy: false }; assert_eq!(tidy::list_of(&e), None); } #[test] fn each_photo_reads_in_its_own_time_zone() { // the same instant, taken in London and read on a phone in India let at = 1_773_492_120_000; // 12:42 UTC assert_eq!(words::when(at, 0, 2026), "Sat 14 Mar, 12:42 pm"); assert_eq!(words::when(at, 19_800, 2026), "Sat 14 Mar, 6:12 pm"); }