Skip to main content

smriti/services/
collage_picks.rs

1//! Picking photos for collages: the best few from any set, and the
2//! "Made for you" collages offered on the Memories page.
3//!
4//! Nothing here is stored. Suggestions are recomputed from the library each
5//! time and are stable for a day; the only write is a dismissal, kept in
6//! `memory_blocks` under kind `collage` so a dismissed source stays hidden.
7
8use std::collections::HashSet;
9
10use chrono::{Datelike, NaiveDate};
11use rusqlite::{params, params_from_iter, Connection, Result as SqliteResult};
12
13use crate::db::album_suggestion_repo::AlbumSuggestionRepo;
14use crate::services::memories::{MemoryCard, MemoryKind};
15use crate::services::story;
16
17/// The largest collage the auto picker builds. Busier frames stop reading
18/// as one picture at the sizes collages are shared at.
19pub const MAX_AUTO_PHOTOS: usize = 6;
20/// Fewer good photos than this and a set isn't worth a collage.
21pub const MIN_AUTO_PHOTOS: usize = 3;
22/// How many "Made for you" collages to offer at once.
23pub const MAX_SUGGESTIONS: usize = 3;
24/// Larger sets are thinned evenly before scoring; a collage needs six photos,
25/// not an exhaustive ranking of a 50,000-photo album.
26const MAX_CANDIDATES: usize = 4000;
27/// Two photos whose perceptual hashes differ in at most this many bits look
28/// alike at collage size.
29const PHASH_NEAR: u32 = 10;
30/// Photos taken this close together are usually the same moment.
31const SAME_MOMENT_SECS: i64 = 60;
32/// SQLite parameters per statement, kept well under every build's limit.
33const CHUNK: usize = 500;
34
35const BLOCK_KIND: &str = "collage";
36/// Screenshots by their usual file names, for queries over `photos p`.
37pub(crate) const NOT_SCREENSHOT: &str =
38    "lower(p.file_name) NOT LIKE 'screenshot%' AND lower(p.file_name) NOT LIKE 'screen shot%'";
39const GROUP_BURST: u8 = 0;
40const GROUP_DUPLICATE: u8 = 1;
41
42#[derive(Debug, Clone)]
43struct Candidate {
44    id: i64,
45    /// Seconds since the epoch, when the photo is dated.
46    taken: Option<i64>,
47    score: f32,
48    file_hash: String,
49    phash: Option<u64>,
50    /// Burst and duplicate groups: one photo per group at most.
51    groups: Vec<(u8, i64)>,
52    video: bool,
53}
54
55/// Options for [`pick_best`].
56#[derive(Debug, Clone, Copy)]
57pub struct PickOptions {
58    pub max: usize,
59    /// Leave out photos of people hidden from Memories.
60    pub skip_hidden_people: bool,
61}
62
63impl Default for PickOptions {
64    fn default() -> Self {
65        Self {
66            max: MAX_AUTO_PHOTOS,
67            skip_hidden_people: false,
68        }
69    }
70}
71
72/// The best few photos of `photo_ids` for a collage: the strongest photo
73/// first (it gets the feature cell), then the rest in the order they were
74/// taken. Videos, screenshots, near-duplicates and badly exposed shots are
75/// left out, and picks are spread across the set's time span so a trip
76/// isn't summed up by one afternoon.
77pub fn pick_best(
78    conn: &Connection,
79    photo_ids: &[i64],
80    options: PickOptions,
81) -> SqliteResult<Vec<i64>> {
82    let ids = thin_evenly(photo_ids, MAX_CANDIDATES);
83    let mut candidates = Vec::with_capacity(ids.len());
84    for chunk in ids.chunks(CHUNK) {
85        candidates.extend(load_candidates(
86            conn,
87            chunk,
88            options.skip_hidden_people,
89            false,
90        )?);
91    }
92    Ok(choose(candidates, options.max.min(MAX_AUTO_PHOTOS)))
93}
94
95/// Every `len / max`-th id, so a huge set is sampled across its whole span.
96fn thin_evenly(ids: &[i64], max: usize) -> Vec<i64> {
97    if ids.len() <= max {
98        return ids.to_vec();
99    }
100    (0..max).map(|i| ids[i * ids.len() / max]).collect()
101}
102
103/// A photo kept by [`curate`], with how strongly it deserves to be seen.
104#[derive(Debug, Clone, Copy, PartialEq)]
105pub struct Curated {
106    pub id: i64,
107    pub score: f32,
108    pub video: bool,
109}
110
111/// The photos of a set worth looking back at, in the order they were taken.
112/// Screenshots, tiny or badly exposed shots and repeats (copies, look-alikes)
113/// are left out; a set with more than `max` left keeps the best photo of each
114/// of `max` equal stretches of its time span. Videos stay in.
115pub fn curate(
116    conn: &Connection,
117    photo_ids: &[i64],
118    max: usize,
119    skip_hidden_people: bool,
120) -> SqliteResult<Vec<Curated>> {
121    let mut candidates = Vec::with_capacity(photo_ids.len());
122    for chunk in photo_ids.chunks(CHUNK) {
123        candidates.extend(load_candidates(conn, chunk, skip_hidden_people, true)?);
124    }
125    candidates.sort_by_key(|c| (c.taken.is_none(), c.taken.unwrap_or(0), c.id));
126
127    // One of each copy or look-alike: the best one.
128    let mut by_quality: Vec<usize> = (0..candidates.len()).collect();
129    by_quality.sort_by(|&a, &b| by_score(&candidates[b], &candidates[a]).then(a.cmp(&b)));
130    let mut kept: Vec<usize> = Vec::with_capacity(candidates.len());
131    for i in by_quality {
132        if !clashes(&candidates, &kept, i, Repeat::Copy) {
133            kept.push(i);
134        }
135    }
136    kept.sort_unstable();
137
138    if max > 0 && kept.len() > max {
139        kept = (0..max)
140            .filter_map(|b| {
141                kept[b * kept.len() / max..(b + 1) * kept.len() / max]
142                    .iter()
143                    .copied()
144                    .max_by(|&a, &b| by_score(&candidates[a], &candidates[b]).then(b.cmp(&a)))
145            })
146            .collect();
147    }
148    Ok(kept
149        .into_iter()
150        .map(|i| Curated {
151            id: candidates[i].id,
152            score: candidates[i].score,
153            video: candidates[i].video,
154        })
155        .collect())
156}
157
158fn load_candidates(
159    conn: &Connection,
160    ids: &[i64],
161    skip_hidden_people: bool,
162    videos: bool,
163) -> SqliteResult<Vec<Candidate>> {
164    let placeholders = vec!["?"; ids.len()].join(",");
165    let hidden_people = if skip_hidden_people {
166        "AND NOT EXISTS (
167           SELECT 1 FROM faces f JOIN memory_blocks mb
168             ON mb.kind = 'person' AND mb.target_key = CAST(f.cluster_id AS TEXT)
169           WHERE f.photo_id = p.id AND f.user_confirmed >= 0)"
170    } else {
171        ""
172    };
173    let media = if videos {
174        "p.media_type IN ('photo', 'video')"
175    } else {
176        "p.media_type = 'photo'"
177    };
178    let sql = format!(
179        r#"SELECT p.id, CAST(strftime('%s', p.date_taken) AS INTEGER), p.is_favorite,
180                  COALESCE(p.width, 0), COALESCE(p.height, 0), p.brightness,
181                  p.phash, p.file_hash,
182                  (SELECT COUNT(*) FROM faces f WHERE f.photo_id = p.id AND f.user_confirmed >= 0),
183                  (SELECT MAX(f.bbox_width * f.bbox_height) FROM faces f
184                   WHERE f.photo_id = p.id AND f.user_confirmed >= 0),
185                  (SELECT bgm.group_id FROM burst_group_members bgm WHERE bgm.photo_id = p.id LIMIT 1),
186                  COALESCE((SELECT MAX(bgm.is_suggested_best) FROM burst_group_members bgm
187                            WHERE bgm.photo_id = p.id), 0),
188                  (SELECT dgm.group_id FROM duplicate_group_members dgm WHERE dgm.photo_id = p.id LIMIT 1),
189                  COALESCE((SELECT MAX(dgm.is_suggested_keep) FROM duplicate_group_members dgm
190                            WHERE dgm.photo_id = p.id), 0),
191                  p.media_type = 'video'
192           FROM photos p
193           WHERE p.id IN ({placeholders})
194             AND p.is_trashed = FALSE
195             AND {media}
196             AND {NOT_SCREENSHOT}
197             -- Stacked look-alikes: only the stack's cover is a candidate.
198             AND NOT EXISTS (
199               SELECT 1 FROM photo_stack_members psm
200               JOIN photo_stacks ps ON ps.id = psm.stack_id
201               WHERE psm.photo_id = p.id AND ps.dismissed = FALSE AND psm.is_cover = FALSE)
202             {hidden_people}"#
203    );
204    let mut stmt = conn.prepare(&sql)?;
205    let rows = stmt.query_map(params_from_iter(ids.iter()), |row| {
206        let width: i64 = row.get(3)?;
207        let height: i64 = row.get(4)?;
208        let signals = Signals {
209            favorite: row.get::<_, Option<bool>>(2)?.unwrap_or(false),
210            width,
211            height,
212            brightness: row.get(5)?,
213            faces: row.get(8)?,
214            largest_face: row.get::<_, Option<f64>>(9)?.unwrap_or(0.0),
215            burst_runner_up: row.get::<_, Option<i64>>(10)?.is_some() && !row.get::<_, bool>(11)?,
216            duplicate_runner_up: row.get::<_, Option<i64>>(12)?.is_some()
217                && !row.get::<_, bool>(13)?,
218        };
219        let mut groups = Vec::new();
220        if let Some(group) = row.get::<_, Option<i64>>(10)? {
221            groups.push((GROUP_BURST, group));
222        }
223        if let Some(group) = row.get::<_, Option<i64>>(12)? {
224            groups.push((GROUP_DUPLICATE, group));
225        }
226        let Some(score) = signals.score() else {
227            return Ok(None);
228        };
229        Ok(Some(Candidate {
230            id: row.get(0)?,
231            taken: row.get(1)?,
232            score,
233            file_hash: row.get(7)?,
234            phash: row.get::<_, Option<i64>>(6)?.map(|h| h as u64),
235            groups,
236            video: row.get(14)?,
237        }))
238    })?;
239    let mut out = Vec::new();
240    for row in rows {
241        if let Some(candidate) = row? {
242            out.push(candidate);
243        }
244    }
245    Ok(out)
246}
247
248struct Signals {
249    favorite: bool,
250    width: i64,
251    height: i64,
252    /// Average luma in 0..1, when the face pipeline has measured it.
253    brightness: Option<f64>,
254    faces: i64,
255    /// Largest face as a fraction of the photo's area.
256    largest_face: f64,
257    burst_runner_up: bool,
258    duplicate_runner_up: bool,
259}
260
261impl Signals {
262    /// How much this photo deserves a place in a collage, or `None` when it
263    /// shouldn't be used at all.
264    fn score(&self) -> Option<f32> {
265        let (w, h) = (self.width.max(0) as f64, self.height.max(0) as f64);
266        // Too small to fill a cell without looking soft.
267        if w > 0.0 && h > 0.0 && w * h < 300_000.0 {
268            return None;
269        }
270        // Nearly black or blown out.
271        if self.brightness.is_some_and(|b| !(0.1..=0.92).contains(&b)) {
272            return None;
273        }
274        let mut score = 1.0_f32;
275        if self.favorite {
276            score += 3.0;
277        }
278        if self.faces > 0 {
279            score += 1.2;
280            // A face you can actually see at collage size.
281            if self.largest_face >= 0.01 {
282                score += 0.6;
283            }
284            // Group shots are good, crowds are hard to frame.
285            if (2..=5).contains(&self.faces) {
286                score += 0.3;
287            }
288        }
289        if let Some(b) = self.brightness {
290            if !(0.18..=0.85).contains(&b) {
291                score -= 0.6;
292            }
293        }
294        if w > 0.0 && h > 0.0 {
295            let aspect = (w / h).max(h / w);
296            // Panoramas lose most of themselves in a cell.
297            if aspect > 2.4 {
298                score -= 1.5;
299            }
300        }
301        if self.burst_runner_up {
302            score -= 0.8;
303        }
304        if self.duplicate_runner_up {
305            score -= 0.8;
306        }
307        Some(score)
308    }
309}
310
311/// The selection itself, on already scored candidates.
312fn choose(mut candidates: Vec<Candidate>, max: usize) -> Vec<i64> {
313    if candidates.is_empty() || max == 0 {
314        return Vec::new();
315    }
316    let target = target_count(candidates.len()).min(max);
317    // Time order; undated photos go last in id order.
318    candidates.sort_by_key(|c| (c.taken.is_none(), c.taken.unwrap_or(0), c.id));
319
320    let mut picks: Vec<usize> = Vec::with_capacity(target);
321    // First pass: one photo from each equal slice of the timeline, so the
322    // picks span the whole set. Same-moment shots are skipped here.
323    for b in 0..target {
324        let slice = (b * candidates.len() / target)..((b + 1) * candidates.len() / target);
325        let best = slice
326            .filter(|&i| !clashes(&candidates, &picks, i, Repeat::Moment))
327            .max_by(|&a, &b| by_score(&candidates[a], &candidates[b]));
328        if let Some(i) = best {
329            picks.push(i);
330        }
331    }
332    // Then fill any gaps from the best of the rest: first allowing shots
333    // of the same moment, then, for small sets, burst siblings too. Copies
334    // and look-alikes are never used twice.
335    let mut rest: Vec<usize> = (0..candidates.len()).collect();
336    rest.sort_by(|&a, &b| by_score(&candidates[b], &candidates[a]));
337    for level in [Repeat::Burst, Repeat::Copy] {
338        for &i in &rest {
339            if picks.len() >= target {
340                break;
341            }
342            if !clashes(&candidates, &picks, i, level) {
343                picks.push(i);
344            }
345        }
346    }
347
348    // Strongest first (it takes the feature cell), the rest in time order.
349    picks.sort_unstable();
350    if let Some(lead) = (0..picks.len()).max_by(|&a, &b| {
351        by_score(&candidates[picks[a]], &candidates[picks[b]])
352            // Ties go to the earlier photo.
353            .then(picks[b].cmp(&picks[a]))
354    }) {
355        let first = picks.remove(lead);
356        picks.insert(0, first);
357    }
358    picks.into_iter().map(|i| candidates[i].id).collect()
359}
360
361fn by_score(a: &Candidate, b: &Candidate) -> std::cmp::Ordering {
362    a.score
363        .partial_cmp(&b.score)
364        .unwrap_or(std::cmp::Ordering::Equal)
365}
366
367/// How many photos to use for a set of `pool` usable ones.
368fn target_count(pool: usize) -> usize {
369    match pool {
370        0..=3 => pool,
371        4..=7 => 4,
372        8..=15 => 5,
373        _ => MAX_AUTO_PHOTOS,
374    }
375}
376
377/// How close to an earlier pick a photo may be, loosest last.
378#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
379enum Repeat {
380    /// Not even the same moment.
381    Moment,
382    /// Not from the same burst.
383    Burst,
384    /// Only never a copy or a look-alike.
385    Copy,
386}
387
388/// Would adding candidate `i` repeat something already picked?
389fn clashes(candidates: &[Candidate], picks: &[usize], i: usize, level: Repeat) -> bool {
390    let c = &candidates[i];
391    picks.iter().any(|&p| {
392        let other = &candidates[p];
393        let shared = |kind: u8| {
394            other
395                .groups
396                .iter()
397                .any(|g| g.0 == kind && c.groups.contains(g))
398        };
399        p == i
400            || other.file_hash == c.file_hash
401            || shared(GROUP_DUPLICATE)
402            || matches!((other.phash, c.phash), (Some(a), Some(b)) if (a ^ b).count_ones() <= PHASH_NEAR)
403            || (level <= Repeat::Burst && shared(GROUP_BURST))
404            || (level == Repeat::Moment
405                && matches!((other.taken, c.taken), (Some(a), Some(b)) if (a - b).abs() < SAME_MOMENT_SECS))
406    })
407}
408
409// ---------- Suggestions ----------
410
411/// Where a suggested collage's photos come from.
412#[derive(Debug, Clone, PartialEq, Eq)]
413pub enum SuggestionSource {
414    Memory { id: String, kind: MemoryKind },
415    AlbumSuggestion { kind: String, fingerprint: String },
416    Album { id: i64 },
417    Favourites,
418}
419
420impl SuggestionSource {
421    /// Stable key, also used to remember a dismissal.
422    pub fn key(&self) -> String {
423        match self {
424            Self::Memory { id, .. } => format!("memory:{id}"),
425            Self::AlbumSuggestion { fingerprint, .. } => format!("suggestion:{fingerprint}"),
426            Self::Album { id } => format!("album:{id}"),
427            Self::Favourites => "favourites".into(),
428        }
429    }
430
431    /// A short line above the title saying why this collage was made:
432    /// "On this day", "Your trip · Dec 2023", "Your album · 2019 – 2023".
433    fn eyebrow(&self, conn: &Connection, ids: &[i64]) -> String {
434        let when = || story::span_label(conn, ids);
435        let with_when = |lead: &str| match when() {
436            Some(when) => format!("{lead} · {when}"),
437            None => lead.to_string(),
438        };
439        match self {
440            Self::Memory { kind, .. } => match kind {
441                MemoryKind::OnThisDay => "On this day".into(),
442                MemoryKind::FallbackWindow => "This week, years ago".into(),
443                MemoryKind::SeasonalRecap => "This month, years ago".into(),
444                MemoryKind::PersonStory => "Through the years".into(),
445                MemoryKind::PlaceStory => "A place you keep going back to".into(),
446                MemoryKind::YearRecap => "A year to remember".into(),
447            },
448            Self::AlbumSuggestion { kind, .. } => with_when(match kind.as_str() {
449                "trip" => "Your trip",
450                "gathering" => "Together",
451                _ => "A day out",
452            }),
453            Self::Album { .. } => with_when("Your album"),
454            Self::Favourites => "Starred by you".into(),
455        }
456    }
457}
458
459#[derive(Debug, Clone)]
460pub struct CollageSuggestion {
461    pub source: SuggestionSource,
462    pub title: String,
463    /// Why it was suggested, shown above the title.
464    pub eyebrow: String,
465    /// In collage order: the feature photo first.
466    pub photo_ids: Vec<i64>,
467}
468
469/// Collages for today, built from today's memories, pending trip and event
470/// suggestions, the user's albums and favourites. The same library gives the
471/// same suggestions all day; rotating sources change from one day to the
472/// next. A photo is used by one suggestion at most.
473pub fn suggestions_for_today(
474    conn: &Connection,
475    today: NaiveDate,
476    memories: &[MemoryCard],
477) -> SqliteResult<Vec<CollageSuggestion>> {
478    let dismissed = dismissed_keys(conn)?;
479    let day = today.ordinal0() as usize + today.year() as usize * 366;
480
481    // Candidate sources in order of preference. Memories are already
482    // ranked; the other pools rotate by day.
483    let mut sources: Vec<(SuggestionSource, String, Vec<i64>)> = Vec::new();
484    let mut memory_sources = memories.iter().map(|card| {
485        (
486            SuggestionSource::Memory {
487                id: card.id.clone(),
488                kind: card.kind,
489            },
490            card.title.clone(),
491            card.photo_ids.clone(),
492        )
493    });
494    sources.extend(memory_sources.next());
495    for suggestion in rotate(AlbumSuggestionRepo::new(conn).get_pending()?, day) {
496        let ids = suggestion.photo_ids();
497        sources.push((
498            SuggestionSource::AlbumSuggestion {
499                kind: suggestion.kind,
500                fingerprint: suggestion.fingerprint,
501            },
502            // Stored as "title  ·  dates"; the dates move to the eyebrow.
503            story::split(&suggestion.title).0.to_string(),
504            ids,
505        ));
506    }
507    for (id, name) in rotate(albums_with_photos(conn)?, day / 2) {
508        sources.push((
509            SuggestionSource::Album { id },
510            name,
511            album_photo_ids(conn, id)?,
512        ));
513    }
514    sources.extend(memory_sources);
515    sources.push((
516        SuggestionSource::Favourites,
517        "Your favourites".into(),
518        favourite_ids(conn)?,
519    ));
520
521    let mut out = Vec::new();
522    let mut used: HashSet<i64> = HashSet::new();
523    let mut kinds_used: HashSet<std::mem::Discriminant<SuggestionSource>> = HashSet::new();
524    // Two passes: first one suggestion per kind of source for variety, then
525    // fill from whatever is left.
526    for pass in 0..2 {
527        for (source, title, ids) in &sources {
528            if out.len() >= MAX_SUGGESTIONS {
529                return Ok(out);
530            }
531            let kind = std::mem::discriminant(source);
532            if dismissed.contains(&source.key())
533                || out.iter().any(|s: &CollageSuggestion| &s.source == source)
534                || (pass == 0 && kinds_used.contains(&kind))
535            {
536                continue;
537            }
538            let fresh: Vec<i64> = ids
539                .iter()
540                .copied()
541                .filter(|id| !used.contains(id))
542                .collect();
543            let photo_ids = pick_best(
544                conn,
545                &fresh,
546                PickOptions {
547                    skip_hidden_people: true,
548                    ..PickOptions::default()
549                },
550            )?;
551            if photo_ids.len() < MIN_AUTO_PHOTOS {
552                continue;
553            }
554            used.extend(photo_ids.iter().copied());
555            kinds_used.insert(kind);
556            out.push(CollageSuggestion {
557                source: source.clone(),
558                title: title.clone(),
559                eyebrow: source.eyebrow(conn, ids),
560                photo_ids,
561            });
562        }
563    }
564    Ok(out)
565}
566
567/// Hide a suggested collage's source for good.
568pub fn dismiss(conn: &Connection, key: &str) -> SqliteResult<()> {
569    conn.execute(
570        "INSERT OR IGNORE INTO memory_blocks (kind, target_key) VALUES (?1, ?2)",
571        params![BLOCK_KIND, key],
572    )?;
573    Ok(())
574}
575
576fn dismissed_keys(conn: &Connection) -> SqliteResult<HashSet<String>> {
577    let mut stmt = conn.prepare("SELECT target_key FROM memory_blocks WHERE kind = ?1")?;
578    let rows = stmt.query_map([BLOCK_KIND], |row| row.get::<_, String>(0))?;
579    rows.collect()
580}
581
582/// `items` starting at `day % len`, wrapping round.
583fn rotate<T>(mut items: Vec<T>, day: usize) -> Vec<T> {
584    if !items.is_empty() {
585        let len = items.len();
586        items.rotate_left(day % len);
587    }
588    items
589}
590
591/// User albums with enough live photos to pick from, oldest first so the
592/// rotation order doesn't shift every time an album is edited.
593fn albums_with_photos(conn: &Connection) -> SqliteResult<Vec<(i64, String)>> {
594    let mut stmt = conn.prepare(
595        r#"SELECT a.id, a.name FROM albums a
596           JOIN album_photos ap ON ap.album_id = a.id
597           JOIN photos p ON p.id = ap.photo_id
598           WHERE p.is_trashed = FALSE AND p.media_type = 'photo'
599           GROUP BY a.id
600           HAVING COUNT(*) >= ?1
601           ORDER BY a.id"#,
602    )?;
603    let rows = stmt.query_map([MIN_AUTO_PHOTOS as i64], |row| {
604        Ok((row.get(0)?, row.get(1)?))
605    })?;
606    rows.collect()
607}
608
609/// Photos of an album in time order.
610pub fn album_photo_ids(conn: &Connection, album_id: i64) -> SqliteResult<Vec<i64>> {
611    let mut stmt = conn.prepare(
612        r#"SELECT p.id FROM album_photos ap JOIN photos p ON p.id = ap.photo_id
613           WHERE ap.album_id = ?1 AND p.is_trashed = FALSE
614           ORDER BY p.date_taken IS NULL, p.date_taken, p.id"#,
615    )?;
616    let rows = stmt.query_map([album_id], |row| row.get(0))?;
617    rows.collect()
618}
619
620/// Favourite photos in time order.
621pub fn favourite_ids(conn: &Connection) -> SqliteResult<Vec<i64>> {
622    let mut stmt = conn.prepare(
623        r#"SELECT id FROM photos WHERE is_favorite = TRUE AND is_trashed = FALSE
624           ORDER BY date_taken IS NULL, date_taken, id"#,
625    )?;
626    let rows = stmt.query_map([], |row| row.get(0))?;
627    rows.collect()
628}
629
630#[cfg(test)]
631mod tests {
632    use super::*;
633    use crate::services::memories::MemoryKind;
634
635    fn fresh_db() -> Connection {
636        let conn = Connection::open_in_memory().unwrap();
637        crate::db::schema::create_schema(&conn).unwrap();
638        conn
639    }
640
641    /// A 12 MP landscape photo, one hour apart per id, with a distinct hash.
642    fn insert(conn: &Connection, id: i64) {
643        conn.execute(
644            "INSERT INTO photos (id, file_path, file_name, file_hash, file_size, date_taken, width, height)
645             VALUES (?1, ?2, ?2, ?3, 1, datetime('2022-06-01 08:00:00', ?4), 4000, 3000)",
646            params![
647                id,
648                format!("p{id}.jpg"),
649                format!("hash{id}"),
650                format!("+{id} hours")
651            ],
652        )
653        .unwrap();
654    }
655
656    fn pick(conn: &Connection, ids: &[i64]) -> Vec<i64> {
657        pick_best(conn, ids, PickOptions::default()).unwrap()
658    }
659
660    #[test]
661    fn leaves_out_videos_screenshots_trash_and_tiny_or_dark_photos() {
662        let conn = fresh_db();
663        for id in 1..=7 {
664            insert(&conn, id);
665        }
666        conn.execute_batch(
667            "UPDATE photos SET media_type = 'video' WHERE id = 2;
668             UPDATE photos SET file_name = 'Screenshot 1.png' WHERE id = 3;
669             UPDATE photos SET is_trashed = TRUE WHERE id = 4;
670             UPDATE photos SET width = 320, height = 240 WHERE id = 5;
671             UPDATE photos SET brightness = 0.03 WHERE id = 6;",
672        )
673        .unwrap();
674        let mut picked = pick(&conn, &(1..=7).collect::<Vec<_>>());
675        picked.sort();
676        assert_eq!(picked, vec![1, 7]);
677    }
678
679    #[test]
680    fn favourite_leads_and_the_rest_follow_in_time_order() {
681        let conn = fresh_db();
682        for id in 1..=12 {
683            insert(&conn, id);
684        }
685        conn.execute("UPDATE photos SET is_favorite = TRUE WHERE id = 9", [])
686            .unwrap();
687        let picked = pick(&conn, &(1..=12).collect::<Vec<_>>());
688        assert_eq!(picked.len(), 5);
689        assert_eq!(picked[0], 9);
690        assert!(picked[1..].windows(2).all(|w| w[0] < w[1]));
691    }
692
693    #[test]
694    fn picks_span_the_whole_set() {
695        let conn = fresh_db();
696        for id in 1..=40 {
697            insert(&conn, id);
698        }
699        let mut picked = pick(&conn, &(1..=40).collect::<Vec<_>>());
700        picked.sort();
701        assert_eq!(picked.len(), MAX_AUTO_PHOTOS);
702        assert!(picked[0] <= 7, "{picked:?}");
703        assert!(*picked.last().unwrap() >= 34, "{picked:?}");
704    }
705
706    #[test]
707    fn look_alikes_and_stack_members_appear_once() {
708        let conn = fresh_db();
709        for id in 1..=8 {
710            insert(&conn, id);
711        }
712        conn.execute_batch(
713            "UPDATE photos SET phash = 0 WHERE id IN (1, 2, 3, 4);
714             UPDATE photos SET file_hash = 'same' WHERE id IN (5, 6);
715             INSERT INTO photo_stacks (id, kind, source_group_id, cover_photo_id) VALUES (1, 'burst', 1, 7);
716             INSERT INTO photo_stack_members (stack_id, photo_id, is_cover) VALUES (1, 7, TRUE), (1, 8, FALSE);",
717        )
718        .unwrap();
719        let picked = pick(&conn, &(1..=8).collect::<Vec<_>>());
720        assert_eq!(
721            picked.iter().filter(|id| **id <= 4).count(),
722            1,
723            "{picked:?}"
724        );
725        assert_eq!(picked.iter().filter(|id| [5, 6].contains(*id)).count(), 1);
726        assert!(!picked.contains(&8));
727    }
728
729    #[test]
730    fn same_moment_shots_are_avoided_while_others_remain() {
731        let conn = fresh_db();
732        for id in 1..=8 {
733            insert(&conn, id);
734        }
735        // Photos 1 and 2 taken seconds apart; 2 is a favourite.
736        conn.execute_batch(
737            "UPDATE photos SET date_taken = '2022-06-01 09:00:10' WHERE id = 2;
738             UPDATE photos SET is_favorite = TRUE WHERE id IN (1, 2);",
739        )
740        .unwrap();
741        let picked = pick(&conn, &(1..=8).collect::<Vec<_>>());
742        assert_eq!(picked.len(), 5);
743        assert!(!(picked.contains(&1) && picked.contains(&2)), "{picked:?}");
744    }
745
746    #[test]
747    fn a_small_burst_still_makes_a_collage_but_copies_never_repeat() {
748        let conn = fresh_db();
749        for id in 1..=3 {
750            insert(&conn, id);
751        }
752        conn.execute_batch(
753            "UPDATE photos SET date_taken = '2022-06-01 09:00:00';
754             INSERT INTO burst_groups (id, start_time, end_time) VALUES (1, '2022-06-01', '2022-06-01');
755             INSERT INTO burst_group_members (group_id, photo_id) VALUES (1, 1), (1, 2), (1, 3);
756             INSERT INTO duplicate_groups (id, duplicate_type) VALUES (1, 'exact');
757             INSERT INTO duplicate_group_members (group_id, photo_id) VALUES (1, 2), (1, 3);",
758        )
759        .unwrap();
760        let mut picked = pick(&conn, &[1, 2, 3]);
761        picked.sort();
762        assert_eq!(picked.len(), 2, "{picked:?}");
763        assert!(picked.contains(&1));
764    }
765
766    #[test]
767    fn huge_sets_are_sampled_not_ignored() {
768        assert_eq!(
769            thin_evenly(&(0..10).collect::<Vec<_>>(), 5),
770            vec![0, 2, 4, 6, 8]
771        );
772        assert_eq!(thin_evenly(&[1, 2], 5), vec![1, 2]);
773    }
774
775    fn memory(id: &str, ids: Vec<i64>) -> MemoryCard {
776        MemoryCard {
777            id: id.into(),
778            kind: MemoryKind::OnThisDay,
779            title: format!("Memory {id}"),
780            hero_photo_id: ids[0],
781            hero_thumbnail_path: None,
782            photo_count: ids.len(),
783            photo_ids: ids,
784            hide_key: format!("day:{id}"),
785        }
786    }
787
788    #[test]
789    fn suggestions_vary_sources_never_share_photos_and_respect_dismissals() {
790        let conn = fresh_db();
791        for id in 1..=30 {
792            insert(&conn, id);
793        }
794        conn.execute_batch(
795            "INSERT INTO albums (id, name) VALUES (1, 'Goa');
796             INSERT INTO album_photos (album_id, photo_id)
797               SELECT 1, id FROM photos WHERE id BETWEEN 11 AND 20;",
798        )
799        .unwrap();
800        let today = NaiveDate::from_ymd_opt(2026, 10, 17).unwrap();
801        let memories = vec![
802            memory("a", (1..=10).collect()),
803            memory("b", (1..=25).collect()),
804        ];
805
806        let suggestions = suggestions_for_today(&conn, today, &memories).unwrap();
807        let keys: Vec<String> = suggestions.iter().map(|s| s.source.key()).collect();
808        assert_eq!(keys, vec!["memory:a", "album:1", "memory:b"]);
809        let mut all: Vec<i64> = suggestions
810            .iter()
811            .flat_map(|s| s.photo_ids.clone())
812            .collect();
813        let total = all.len();
814        all.sort();
815        all.dedup();
816        assert_eq!(all.len(), total, "a photo was used twice");
817
818        // Same day, same library: same suggestions.
819        let again = suggestions_for_today(&conn, today, &memories).unwrap();
820        assert_eq!(
821            again
822                .iter()
823                .map(|s| s.photo_ids.clone())
824                .collect::<Vec<_>>(),
825            suggestions
826                .iter()
827                .map(|s| s.photo_ids.clone())
828                .collect::<Vec<_>>()
829        );
830
831        dismiss(&conn, "album:1").unwrap();
832        dismiss(&conn, "album:1").unwrap();
833        let after = suggestions_for_today(&conn, today, &memories).unwrap();
834        assert!(after.iter().all(|s| s.source.key() != "album:1"));
835    }
836
837    #[test]
838    fn hidden_people_stay_out_of_suggestions() {
839        let conn = fresh_db();
840        for id in 1..=4 {
841            insert(&conn, id);
842        }
843        conn.execute_batch(
844            "INSERT INTO face_clusters (id, name) VALUES (1, 'Hidden');
845             INSERT INTO faces (photo_id, bbox_x, bbox_y, bbox_width, bbox_height, confidence, embedding, cluster_id)
846               VALUES (2, 0.4, 0.4, 0.2, 0.2, 0.9, zeroblob(16), 1);
847             INSERT INTO memory_blocks (kind, target_key) VALUES ('person', '1');",
848        )
849        .unwrap();
850        let today = NaiveDate::from_ymd_opt(2026, 10, 17).unwrap();
851        let suggestions =
852            suggestions_for_today(&conn, today, &[memory("a", vec![1, 2, 3, 4])]).unwrap();
853        assert_eq!(suggestions.len(), 1);
854        assert!(!suggestions[0].photo_ids.contains(&2));
855        // Asking for a collage directly still uses everyone.
856        assert!(pick(&conn, &[1, 2, 3, 4]).contains(&2));
857    }
858}