Skip to main content

smriti/services/
same_person.rs

1//! "Same person?" suggestions: pairs of people who are probably one person
2//! split in two (lighting, age, glasses, angle).
3//!
4//! Clustering already merges pairs it is sure about. This finds the pairs
5//! just below that bar and asks, rather than guessing: a wrong automatic
6//! merge is far more costly than a question. Nothing here merges anything.
7//!
8//! Pairs are scored the way the clustering merge pass scores them: the mean
9//! of the three closest face pairs across the two people's galleries. A pair
10//! is never suggested when the people appear together in a photo, when they
11//! were marked as different ("Never"), or while snoozed ("Not now").
12
13use std::collections::{HashMap, HashSet};
14
15use rusqlite::{params, Connection, OptionalExtension, Result as SqliteResult};
16
17use crate::db::face_repo::FaceRepo;
18
19/// Lowest score worth asking about. The merge pass merges on its own from
20/// 0.55, so asking starts a little below where it stops being sure.
21pub const ASK_FROM: f32 = 0.40;
22
23/// Cheap first cut on the average faces, before scoring a pair properly.
24const CENTROID_FLOOR: f32 = 0.25;
25
26/// Same top-k as the clustering merge pass.
27const TOP_K: usize = 3;
28
29/// Unnamed people considered, largest first. Named people always are.
30const MAX_UNNAMED: usize = 500;
31
32/// How long "Not now" keeps a pair from being asked again.
33pub const SNOOZE_DAYS: i64 = 30;
34
35const SNOOZE_KEY: &str = "people.same_person_snoozed";
36
37/// Two people who may be the same, `a < b`.
38#[derive(Debug, Clone, PartialEq)]
39pub struct SamePersonPair {
40    pub a: i64,
41    pub b: i64,
42    pub score: f32,
43}
44
45struct Person {
46    named: bool,
47    faces: i64,
48    gallery: Vec<Vec<f32>>,
49    centroid: Vec<f32>,
50}
51
52/// Up to `limit` pairs worth asking about, those involving a named person
53/// first, then closest first.
54pub fn suggestions(conn: &Connection, limit: usize, now: i64) -> SqliteResult<Vec<SamePersonPair>> {
55    let repo = FaceRepo::new(conn);
56    let mut people = load_people(conn, &repo)?;
57    if people.len() < 2 {
58        return Ok(Vec::new());
59    }
60
61    let cannot = repo.get_cannot_merge_map()?;
62    let snoozed = snoozed_pairs(conn, now)?;
63    let mut photos: HashMap<i64, HashSet<i64>> = HashMap::new();
64    for (cluster, photo) in repo.get_cluster_photo_ids()? {
65        photos.entry(cluster).or_default().insert(photo);
66    }
67
68    // Unnamed people beyond the cap would make the pass quadratic in the
69    // number of strangers; the largest are the ones worth asking about.
70    let mut unnamed: Vec<(i64, i64)> = people
71        .iter()
72        .filter(|(_, p)| !p.named)
73        .map(|(&id, p)| (id, p.faces))
74        .collect();
75    if unnamed.len() > MAX_UNNAMED {
76        unnamed.sort_by(|x, y| y.1.cmp(&x.1).then(x.0.cmp(&y.0)));
77        for (id, _) in unnamed.drain(MAX_UNNAMED..) {
78            people.remove(&id);
79        }
80    }
81
82    let mut ids: Vec<i64> = people.keys().copied().collect();
83    ids.sort_unstable();
84    let mut found = Vec::new();
85    for (i, &a) in ids.iter().enumerate() {
86        for &b in &ids[i + 1..] {
87            let (pa, pb) = (&people[&a], &people[&b]);
88            if dot(&pa.centroid, &pb.centroid) < CENTROID_FLOOR
89                || cannot.get(&a).is_some_and(|s| s.contains(&b))
90                || snoozed.contains(&(a, b))
91                || photos
92                    .get(&a)
93                    .zip(photos.get(&b))
94                    .is_some_and(|(x, y)| x.iter().any(|p| y.contains(p)))
95            {
96                continue;
97            }
98            let score = top_k_mean(&pa.gallery, &pb.gallery);
99            if score >= ASK_FROM {
100                found.push((pa.named || pb.named, SamePersonPair { a, b, score }));
101            }
102        }
103    }
104    found.sort_by(|x, y| y.0.cmp(&x.0).then(y.1.score.total_cmp(&x.1.score)));
105    Ok(found.into_iter().take(limit).map(|(_, p)| p).collect())
106}
107
108/// "Not now": don't ask about this pair for [`SNOOZE_DAYS`].
109pub fn snooze(conn: &Connection, a: i64, b: i64, now: i64) -> SqliteResult<()> {
110    let mut map = read_snoozes(conn)?;
111    map.retain(|_, until| *until > now);
112    map.insert(pair_key(a, b), now + SNOOZE_DAYS * 86_400);
113    let value = serde_json::to_string(&map).unwrap_or_else(|_| "{}".into());
114    conn.execute(
115        "INSERT INTO library_meta (key, value) VALUES (?1, ?2)
116         ON CONFLICT(key) DO UPDATE SET value = excluded.value",
117        params![SNOOZE_KEY, value],
118    )?;
119    Ok(())
120}
121
122/// "Never": these two are different people, for clustering and merging too.
123pub fn never(conn: &Connection, a: i64, b: i64) -> SqliteResult<()> {
124    conn.execute(
125        "INSERT OR IGNORE INTO cluster_cannot_merge (cluster_a_id, cluster_b_id) VALUES (?1, ?2)",
126        params![a.min(b), a.max(b)],
127    )?;
128    Ok(())
129}
130
131/// A person's clearest faces, best first, for showing them side by side.
132pub fn sample_faces(conn: &Connection, cluster_id: i64, limit: usize) -> SqliteResult<Vec<i64>> {
133    let mut stmt = conn.prepare(
134        "SELECT f.id FROM faces f JOIN photos p ON p.id = f.photo_id
135         WHERE f.cluster_id = ?1 AND f.user_confirmed >= 0 AND p.is_trashed = FALSE
136         ORDER BY f.user_confirmed DESC, f.confidence DESC, f.id
137         LIMIT ?2",
138    )?;
139    let rows = stmt.query_map(params![cluster_id, limit as i64], |row| row.get(0))?;
140    rows.collect()
141}
142
143fn load_people(conn: &Connection, repo: &FaceRepo) -> SqliteResult<HashMap<i64, Person>> {
144    let mut people: HashMap<i64, Person> = HashMap::new();
145    {
146        let mut stmt = conn.prepare(
147            "SELECT id, name IS NOT NULL AND TRIM(name) != '', face_count FROM face_clusters",
148        )?;
149        let rows = stmt.query_map([], |row| {
150            Ok((
151                row.get::<_, i64>(0)?,
152                row.get::<_, bool>(1)?,
153                row.get::<_, i64>(2)?,
154            ))
155        })?;
156        for row in rows {
157            let (id, named, faces) = row?;
158            people.insert(
159                id,
160                Person {
161                    named,
162                    faces,
163                    gallery: Vec::new(),
164                    centroid: Vec::new(),
165                },
166            );
167        }
168    }
169    for g in repo.get_gallery_embeddings()? {
170        if let Some(person) = people.get_mut(&g.cluster_id) {
171            person
172                .gallery
173                .push(unit(g.embedding.vector.iter().copied().collect()));
174        }
175    }
176    people.retain(|_, p| !p.gallery.is_empty());
177    for person in people.values_mut() {
178        let mut sum = vec![0.0f32; person.gallery[0].len()];
179        for v in &person.gallery {
180            for (s, x) in sum.iter_mut().zip(v) {
181                *s += x;
182            }
183        }
184        person.centroid = unit(sum);
185    }
186    Ok(people)
187}
188
189fn snoozed_pairs(conn: &Connection, now: i64) -> SqliteResult<HashSet<(i64, i64)>> {
190    Ok(read_snoozes(conn)?
191        .into_iter()
192        .filter(|(_, until)| *until > now)
193        .filter_map(|(key, _)| {
194            let (a, b) = key.split_once('-')?;
195            Some((a.parse().ok()?, b.parse().ok()?))
196        })
197        .collect())
198}
199
200fn read_snoozes(conn: &Connection) -> SqliteResult<HashMap<String, i64>> {
201    let raw: Option<String> = conn
202        .query_row(
203            "SELECT value FROM library_meta WHERE key = ?1",
204            params![SNOOZE_KEY],
205            |row| row.get(0),
206        )
207        .optional()?;
208    Ok(raw
209        .and_then(|s| serde_json::from_str(&s).ok())
210        .unwrap_or_default())
211}
212
213fn pair_key(a: i64, b: i64) -> String {
214    format!("{}-{}", a.min(b), a.max(b))
215}
216
217fn unit(mut v: Vec<f32>) -> Vec<f32> {
218    let norm = v.iter().map(|x| x * x).sum::<f32>().sqrt();
219    if norm > 0.0 {
220        v.iter_mut().for_each(|x| *x /= norm);
221    }
222    v
223}
224
225fn dot(a: &[f32], b: &[f32]) -> f32 {
226    a.iter().zip(b).map(|(x, y)| x * y).sum()
227}
228
229fn top_k_mean(a: &[Vec<f32>], b: &[Vec<f32>]) -> f32 {
230    let mut best = [f32::NEG_INFINITY; TOP_K];
231    for x in a {
232        for y in b {
233            let s = dot(x, y);
234            if s > best[TOP_K - 1] {
235                best[TOP_K - 1] = s;
236                best.sort_by(|p, q| q.total_cmp(p));
237            }
238        }
239    }
240    let kept: Vec<f32> = best.into_iter().filter(|s| s.is_finite()).collect();
241    if kept.is_empty() {
242        0.0
243    } else {
244        kept.iter().sum::<f32>() / kept.len() as f32
245    }
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251
252    #[test]
253    fn top_k_mean_averages_the_three_closest_pairs() {
254        let a = vec![vec![1.0, 0.0], vec![0.0, 1.0]];
255        let b = vec![vec![1.0, 0.0], vec![0.6, 0.8]];
256        // Pair scores: 1.0, 0.6, 0.0, 0.8 -> best three 1.0, 0.8, 0.6.
257        assert!((top_k_mean(&a, &b) - 0.8).abs() < 1e-6);
258        // Fewer than three pairs: the mean of what there is.
259        assert!((top_k_mean(&[vec![1.0, 0.0]], &[vec![0.6, 0.8]]) - 0.6).abs() < 1e-6);
260    }
261
262    #[test]
263    fn pair_keys_ignore_order() {
264        assert_eq!(pair_key(9, 4), "4-9");
265        assert_eq!(pair_key(4, 9), "4-9");
266    }
267}