//! The Tidy lists, biggest win first, each with its size (DECISIONS.md //! "Tidy"). **Each photo is in one list only**, so the totals add up and //! "You could free about 52 GB more" is true: //! //! 1. **Sets:** the shots a set does not pick. //! 2. **Large videos:** a video of [`LARGE_VIDEO_BYTES`] or more. //! 3. **WhatsApp copies:** saved from WhatsApp; those whose camera original is //! in the library come first ([`copy_of`]). //! 4. **Screenshots:** screenshots and screen recordings. //! 5. **Receipts and documents:** a document found, or Vision's "utility" //! with text. //! 6. **Blurry and dark:** only when seen at `Full` (a small picture hides blur). //! 7. **Exact copies:** the same picture twice (same hash, size and bytes), //! the earliest kept; listed only when there are any. //! //! Never offered: favourites, hidden photos, shared-album photos, the phone's //! trash, a part of another item (RAW+JPEG, an edit), anything he chose to //! keep, anything in the Bin. //! //! **A copy is a copy only while its original is here** (coordinator's rule E): //! present in the library, not in the Bin and not part of the same act. The //! caller passes only such originals to [`copy_of`] and [`exact_copies`], and //! checks again at the moment of an act. use std::collections::HashMap; use serde::Serialize; use super::bin::Mark; use super::look::{hamming, print_distance, Level, Look}; use super::size::{self, Size}; use super::{Item, Kind}; pub const LARGE_VIDEO_BYTES: u64 = 100_000_000; /// Blurred: sharpness under this (variance of the Laplacian, 128 px reduction). pub const BLUR_MAX: f32 = 0.0008; pub const DARK_BRIGHTNESS: f32 = 0.10; pub const DARK_SHARE: f32 = 0.75; /// A WhatsApp copy's original: taken up to 30 days before the copy was saved. pub const COPY_WINDOW_MS: i64 = 30 * 86_400_000; /// A copy is the same picture re-encoded (WhatsApp shrinks to 1600 px and /// recompresses), which barely moves an 8x8 reduction: so it must match far /// more closely than two shots of one moment do (a set allows 0.55 and 20). pub const COPY_PRINT_MAX: f32 = 0.25; pub const COPY_HAMMING_MAX: u32 = 10; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)] #[serde(rename_all = "snake_case")] pub enum List { Sets, LargeVideos, WhatsappCopies, Screenshots, Documents, BlurryDark, ExactCopies, } impl List { pub const ALL: [List; 7] = [List::Sets, List::LargeVideos, List::WhatsappCopies, List::Screenshots, List::Documents, List::BlurryDark, List::ExactCopies]; pub fn key(self) -> &'static str { match self { List::Sets => "sets", List::LargeVideos => "large_videos", List::WhatsappCopies => "whatsapp_copies", List::Screenshots => "screenshots", List::Documents => "documents", List::BlurryDark => "blurry_dark", List::ExactCopies => "exact_copies", } } pub fn from_key(key: &str) -> Option { List::ALL.into_iter().find(|l| l.key() == key) } } /// One library item as Tidy sees it. pub struct Entry<'a> { pub item: &'a Item, pub look: Option<&'a Look>, pub mark: Mark, /// In a set and not picked. pub set_offer: bool, /// In a set and picked (never offered by another list). pub set_pick: bool, /// The first of a group of exact copies is kept; the rest are offered. pub exact_copy: bool, } pub fn offerable(item: &Item, mark: &Mark) -> bool { mark.offered() && !item.has("favourite") && !item.has("hidden") && !item.has("cloud_shared") && !item.has("trashed") } /// Saved from WhatsApp. Android: WhatsApp's folders. iPhone: WhatsApp's file /// names, when iOS 27 gives `originalFilename` (unconfirmed until measured on /// a phone, RESEARCH.md ยง5). pub fn whatsapp(item: &Item) -> bool { let Some(p) = item.path.as_deref() else { return false }; let lower = p.to_ascii_lowercase(); if lower.contains("whatsapp") { return true; } // IMG-20231201-WA0003.jpg / VID-20231201-WA0003.mp4 let name = lower.rsplit('/').next().unwrap_or(&lower); let b = name.as_bytes(); b.len() >= 19 && (name.starts_with("img-") || name.starts_with("vid-")) && b[4..12].iter().all(u8::is_ascii_digit) && &name[12..15] == "-wa" && b[15..19].iter().all(u8::is_ascii_digit) } fn document(look: Option<&Look>) -> bool { look.is_some_and(|l| l.platform.document == Some(true) || (l.platform.utility == Some(true) && l.platform.text_chars.unwrap_or(0) >= 40)) } fn blurry_or_dark(look: Option<&Look>) -> bool { look.is_some_and(|l| l.level == Level::Full && (l.sharp.is_some_and(|s| s < BLUR_MAX) || (l.brightness < DARK_BRIGHTNESS && l.dark_share > DARK_SHARE))) } /// Which list offers this entry, if any. pub fn list_of(e: &Entry<'_>) -> Option { if !offerable(e.item, &e.mark) || e.set_pick { return None; } if e.set_offer { return Some(List::Sets); } if e.item.kind == Kind::Video && size::of(e.item).bytes >= LARGE_VIDEO_BYTES { return Some(List::LargeVideos); } if whatsapp(e.item) { return Some(List::WhatsappCopies); } if e.item.has("screenshot") || e.item.has("screen_recording") { return Some(List::Screenshots); } if e.item.kind == Kind::Photo && document(e.look) { return Some(List::Documents); } if e.item.kind == Kind::Photo && blurry_or_dark(e.look) { return Some(List::BlurryDark); } if e.exact_copy { return Some(List::ExactCopies); } None } #[derive(Debug, Clone, PartialEq, Serialize)] pub struct Summary { pub list: List, pub count: usize, pub bytes: u64, pub exact: bool, } /// The lists with something in them, biggest first (ties in the fixed order). pub fn summarise(entries: &[Entry<'_>]) -> Vec { let mut by: HashMap = HashMap::new(); for e in entries { if let Some(l) = list_of(e) { let s = by.entry(l).or_insert((0, Size::ZERO)); s.0 += 1; s.1 = s.1.add(size::of(e.item)); } } let mut out: Vec = by.into_iter().map(|(list, (count, s))| Summary { list, count, bytes: s.bytes, exact: s.exact }).collect(); out.sort_by(|a, b| b.bytes.cmp(&a.bytes).then(a.list.cmp(&b.list))); out } /// Groups of exact copies (same difference hash, pixel size and exact bytes), /// each earliest first; the first is the one kept. pub fn exact_copies(items: &[(&Item, Option<&Look>)]) -> Vec> { let mut by: HashMap<(u64, u32, u32, u64), Vec> = HashMap::new(); for (i, (item, look)) in items.iter().enumerate() { let (Some(l), Some(b)) = (look, item.bytes) else { continue }; if l.level == Level::None { continue; } by.entry((l.dhash, item.width, item.height, b)).or_default().push(i); } let mut out: Vec> = by.into_values().filter(|g| g.len() >= 2).collect(); for g in out.iter_mut() { g.sort_by_key(|&i| (items[i].0.taken_at_ms, i)); } out.sort(); out } /// The camera original of a WhatsApp copy among `candidates` (not WhatsApp /// items themselves), taken before the copy was saved and within 30 days; the /// closest by print. Answers the candidate's index. pub fn copy_of(copy: (&Item, &Look), candidates: &[(&Item, &Look)]) -> Option { let (ci, cl) = copy; if cl.level == Level::None { return None; } candidates .iter() .enumerate() .filter(|(_, (i, l))| !whatsapp(i) && l.level != Level::None && i.taken_at_ms <= ci.taken_at_ms && ci.taken_at_ms - i.taken_at_ms <= COPY_WINDOW_MS) .filter(|(_, (_, l))| hamming(l.dhash, cl.dhash) <= COPY_HAMMING_MAX) .map(|(k, (_, l))| (k, print_distance(&l.print, &cl.print))) .filter(|(_, d)| *d <= COPY_PRINT_MAX) .min_by(|a, b| a.1.total_cmp(&b.1)) .map(|(k, _)| k) }