Skip to main content

smriti/db/face_repo/
undo.rs

1//! Undo for a decision about one face: "yes, that's them", "no", "move to
2//! someone else", "not a face", "not sure".
3//!
4//! Before the decision, everything it can change about the face is copied:
5//! its person and decision, its "not this person" marks, its places in
6//! people's galleries, its review-queue rows and whether it was skipped.
7//! Undo puts exactly that back, so it needs no per-action inverse and
8//! never erases an older decision it didn't make.
9
10use std::collections::BTreeSet;
11
12use rusqlite::{params, OptionalExtension, Result as SqliteResult};
13
14use super::FaceRepo;
15
16const SKIPPED_KEY: &str = "people.review_skipped";
17
18/// One face's state before a decision.
19#[derive(Debug, Clone, PartialEq)]
20pub struct FaceSnapshot {
21    pub face_id: i64,
22    cluster_id: Option<i64>,
23    user_confirmed: i32,
24    negatives: Vec<i64>,
25    gallery: Vec<GalleryRow>,
26    review: Vec<ReviewRow>,
27    skipped: bool,
28}
29
30#[derive(Debug, Clone, PartialEq)]
31struct GalleryRow {
32    cluster_id: i64,
33    embedding: Vec<u8>,
34    pose_label: Option<String>,
35    quality_score: Option<f64>,
36    source: Option<String>,
37}
38
39#[derive(Debug, Clone, PartialEq)]
40struct ReviewRow {
41    candidate_cluster_id: i64,
42    score: f64,
43    ambiguity: Option<f64>,
44    resolved_at: Option<String>,
45    resolved_as: Option<String>,
46}
47
48/// A face's person and decision: what an undo checks has not changed since.
49pub type FaceState = (Option<i64>, i32);
50
51impl<'a> FaceRepo<'a> {
52    pub fn face_state(&self, face_id: i64) -> SqliteResult<Option<FaceState>> {
53        self.conn
54            .query_row(
55                "SELECT cluster_id, user_confirmed FROM faces WHERE id = ?1",
56                params![face_id],
57                |row| Ok((row.get(0)?, row.get::<_, Option<i32>>(1)?.unwrap_or(0))),
58            )
59            .optional()
60    }
61
62    pub fn snapshot_face(&self, face_id: i64) -> SqliteResult<FaceSnapshot> {
63        let (cluster_id, user_confirmed) = self
64            .face_state(face_id)?
65            .ok_or(rusqlite::Error::QueryReturnedNoRows)?;
66        let negatives = {
67            let mut stmt = self
68                .conn
69                .prepare("SELECT not_cluster_id FROM face_negatives WHERE face_id = ?1")?;
70            let rows = stmt.query_map(params![face_id], |row| row.get(0))?;
71            rows.collect::<SqliteResult<_>>()?
72        };
73        let gallery = {
74            let mut stmt = self.conn.prepare(
75                "SELECT cluster_id, embedding, pose_label, quality_score, source
76                 FROM person_gallery_embeddings WHERE face_id = ?1",
77            )?;
78            let rows = stmt.query_map(params![face_id], |row| {
79                Ok(GalleryRow {
80                    cluster_id: row.get(0)?,
81                    embedding: row.get(1)?,
82                    pose_label: row.get(2)?,
83                    quality_score: row.get(3)?,
84                    source: row.get(4)?,
85                })
86            })?;
87            rows.collect::<SqliteResult<_>>()?
88        };
89        let review = {
90            let mut stmt = self.conn.prepare(
91                "SELECT candidate_cluster_id, score, ambiguity, resolved_at, resolved_as
92                 FROM face_review_queue WHERE face_id = ?1",
93            )?;
94            let rows = stmt.query_map(params![face_id], |row| {
95                Ok(ReviewRow {
96                    candidate_cluster_id: row.get(0)?,
97                    score: row.get(1)?,
98                    ambiguity: row.get(2)?,
99                    resolved_at: row.get(3)?,
100                    resolved_as: row.get(4)?,
101                })
102            })?;
103            rows.collect::<SqliteResult<_>>()?
104        };
105        let skipped = self.conn.query_row(
106            "SELECT EXISTS (SELECT 1 FROM json_each(COALESCE(
107                 (SELECT value FROM library_meta WHERE key = ?1), '[]')) WHERE value = ?2)",
108            params![SKIPPED_KEY, face_id],
109            |row| row.get(0),
110        )?;
111        Ok(FaceSnapshot {
112            face_id,
113            cluster_id,
114            user_confirmed,
115            negatives,
116            gallery,
117            review,
118            skipped,
119        })
120    }
121
122    /// Put a face back as it was in `snapshot`. The caller checks first that
123    /// nothing else has changed the face since the decision.
124    pub fn restore_face(&self, snapshot: &FaceSnapshot) -> SqliteResult<()> {
125        let tx = self.conn.unchecked_transaction()?;
126        let face = snapshot.face_id;
127        let exists = |cluster: i64| -> SqliteResult<bool> {
128            tx.query_row(
129                "SELECT EXISTS (SELECT 1 FROM face_clusters WHERE id = ?1)",
130                params![cluster],
131                |row| row.get(0),
132            )
133        };
134
135        // Every person the face belongs to, or is in the gallery of, now or
136        // before: their counts and galleries are rebuilt at the end.
137        let mut touched: BTreeSet<i64> = snapshot.gallery.iter().map(|g| g.cluster_id).collect();
138        touched.extend(snapshot.cluster_id);
139        let now: Option<i64> = tx.query_row(
140            "SELECT cluster_id FROM faces WHERE id = ?1",
141            params![face],
142            |row| row.get(0),
143        )?;
144        touched.extend(now);
145        {
146            let mut stmt =
147                tx.prepare("SELECT cluster_id FROM person_gallery_embeddings WHERE face_id = ?1")?;
148            let rows = stmt.query_map(params![face], |row| row.get::<_, i64>(0))?;
149            for row in rows {
150                touched.insert(row?);
151            }
152        }
153
154        let cluster = match snapshot.cluster_id {
155            Some(c) if exists(c)? => Some(c),
156            _ => None,
157        };
158        tx.execute(
159            "UPDATE faces SET cluster_id = ?1, user_confirmed = ?2 WHERE id = ?3",
160            params![cluster, snapshot.user_confirmed, face],
161        )?;
162
163        tx.execute(
164            "DELETE FROM face_negatives WHERE face_id = ?1",
165            params![face],
166        )?;
167        for &not_cluster in &snapshot.negatives {
168            if exists(not_cluster)? {
169                tx.execute(
170                    "INSERT OR IGNORE INTO face_negatives (face_id, not_cluster_id) VALUES (?1, ?2)",
171                    params![face, not_cluster],
172                )?;
173            }
174        }
175
176        tx.execute(
177            "DELETE FROM person_gallery_embeddings WHERE face_id = ?1",
178            params![face],
179        )?;
180        for g in &snapshot.gallery {
181            if exists(g.cluster_id)? {
182                tx.execute(
183                    "INSERT INTO person_gallery_embeddings
184                        (cluster_id, face_id, embedding, pose_label, quality_score, source)
185                     VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
186                    params![
187                        g.cluster_id,
188                        face,
189                        g.embedding,
190                        g.pose_label,
191                        g.quality_score,
192                        g.source
193                    ],
194                )?;
195            }
196        }
197
198        tx.execute(
199            "DELETE FROM face_review_queue WHERE face_id = ?1",
200            params![face],
201        )?;
202        for r in &snapshot.review {
203            if exists(r.candidate_cluster_id)? {
204                tx.execute(
205                    "INSERT INTO face_review_queue
206                        (face_id, candidate_cluster_id, score, ambiguity, resolved_at, resolved_as)
207                     VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
208                    params![
209                        face,
210                        r.candidate_cluster_id,
211                        r.score,
212                        r.ambiguity,
213                        r.resolved_at,
214                        r.resolved_as
215                    ],
216                )?;
217            }
218        }
219
220        if !snapshot.skipped {
221            tx.execute(
222                "UPDATE library_meta
223                 SET value = (SELECT json_group_array(value) FROM json_each(library_meta.value)
224                              WHERE value != ?2)
225                 WHERE key = ?1",
226                params![SKIPPED_KEY, face],
227            )?;
228        }
229
230        for cluster in touched {
231            if exists(cluster)? {
232                Self::refresh_cluster_stats_tx(&tx, cluster)?;
233                Self::refresh_gallery_tx(&tx, cluster)?;
234            }
235        }
236        tx.commit()
237    }
238}