Skip to main content

smriti/db/face_repo/
write.rs

1//! Write/mutation methods for FaceRepo.
2
3use rusqlite::{params, OptionalExtension, Result as SqliteResult};
4
5use super::{FaceRepo, MergeReceipt};
6
7impl<'a> FaceRepo<'a> {
8    /// Name a cluster (set the person's name)
9    pub fn name_cluster(&self, cluster_id: i64, name: &str) -> SqliteResult<()> {
10        self.conn.execute(
11            "UPDATE face_clusters SET name = ?1, updated_at = CURRENT_TIMESTAMP WHERE id = ?2",
12            params![name, cluster_id],
13        )?;
14        Ok(())
15    }
16
17    /// Delete a face cluster — "this isn't a real person" gesture.
18    ///
19    /// Its faces are set aside (`user_confirmed = -1`), so the next
20    /// clustering pass doesn't quietly rebuild the same person.
21    /// Inferred-identity links and gallery embeddings rooted at the
22    /// cluster cascade away (FK ON DELETE CASCADE in the schema).
23    pub fn delete_cluster(&self, cluster_id: i64) -> SqliteResult<()> {
24        let tx = self.conn.unchecked_transaction()?;
25        tx.execute(
26            "UPDATE faces SET cluster_id = NULL, user_confirmed = -1 WHERE cluster_id = ?1",
27            params![cluster_id],
28        )?;
29        tx.execute(
30            "DELETE FROM photo_inferred_identities WHERE cluster_id = ?1",
31            params![cluster_id],
32        )?;
33        tx.execute(
34            "DELETE FROM person_gallery_embeddings WHERE cluster_id = ?1",
35            params![cluster_id],
36        )?;
37        tx.execute(
38            "DELETE FROM face_clusters WHERE id = ?1",
39            params![cluster_id],
40        )?;
41        tx.commit()
42    }
43
44    /// "Not a face": set a detection aside for good. It leaves its person
45    /// and clustering never picks it up again (`user_confirmed = -1`).
46    pub fn ignore_face(&self, face_id: i64) -> SqliteResult<()> {
47        let tx = self.conn.unchecked_transaction()?;
48        let cluster_id: Option<i64> = tx
49            .query_row(
50                "SELECT cluster_id FROM faces WHERE id = ?1",
51                params![face_id],
52                |row| row.get(0),
53            )
54            .optional()?
55            .flatten();
56        tx.execute(
57            "UPDATE faces SET cluster_id = NULL, user_confirmed = -1 WHERE id = ?1",
58            params![face_id],
59        )?;
60        tx.execute(
61            "DELETE FROM face_review_queue WHERE face_id = ?1",
62            params![face_id],
63        )?;
64        if let Some(cluster_id) = cluster_id {
65            Self::refresh_cluster_stats_tx(&tx, cluster_id)?;
66            Self::refresh_gallery_tx(&tx, cluster_id)?;
67        }
68        tx.commit()
69    }
70
71    /// Delete a face and everything recorded about it (a hand-added face
72    /// being taken back). Its person's count and gallery follow.
73    pub fn delete_face(&self, face_id: i64) -> SqliteResult<()> {
74        let tx = self.conn.unchecked_transaction()?;
75        let cluster_id: Option<i64> = tx
76            .query_row(
77                "SELECT cluster_id FROM faces WHERE id = ?1",
78                params![face_id],
79                |row| row.get(0),
80            )
81            .optional()?
82            .flatten();
83        for sql in [
84            "DELETE FROM person_gallery_embeddings WHERE face_id = ?1",
85            "DELETE FROM face_negatives WHERE face_id = ?1",
86            "DELETE FROM face_review_queue WHERE face_id = ?1",
87            "DELETE FROM faces WHERE id = ?1",
88        ] {
89            tx.execute(sql, params![face_id])?;
90        }
91        if let Some(cluster_id) = cluster_id {
92            Self::refresh_cluster_stats_tx(&tx, cluster_id)?;
93            Self::refresh_gallery_tx(&tx, cluster_id)?;
94        }
95        tx.commit()
96    }
97
98    /// Take a face out of review without deciding about it ("not sure").
99    /// It keeps its person; review just stops asking.
100    pub fn skip_review_face(&self, face_id: i64) -> SqliteResult<()> {
101        self.conn.execute(
102            r#"INSERT INTO library_meta (key, value) VALUES ('people.review_skipped', json_array(?1))
103               ON CONFLICT(key) DO UPDATE SET value = json_insert(value, '$[#]', ?1)"#,
104            params![face_id],
105        )?;
106        Ok(())
107    }
108
109    /// Assign an existing face to an existing cluster and update cluster metadata.
110    pub fn assign_face_to_cluster(&self, face_id: i64, cluster_id: i64) -> SqliteResult<()> {
111        let tx = self.conn.unchecked_transaction()?;
112
113        tx.execute(
114            "UPDATE faces SET cluster_id = ?1 WHERE id = ?2",
115            params![cluster_id, face_id],
116        )?;
117
118        Self::refresh_cluster_stats_tx(&tx, cluster_id)?;
119        Self::refresh_gallery_tx(&tx, cluster_id)?;
120
121        tx.commit()
122    }
123
124    /// Create a new face cluster from a set of face IDs
125    pub fn create_cluster(&self, face_ids: &[i64]) -> SqliteResult<i64> {
126        let tx = self.conn.unchecked_transaction()?;
127
128        tx.execute(
129            r#"
130            INSERT INTO face_clusters (face_count, photo_count)
131            VALUES (0, 0)
132            "#,
133            [],
134        )?;
135
136        let cluster_id = tx.last_insert_rowid();
137
138        // Assign faces to this cluster
139        for face_id in face_ids {
140            tx.execute(
141                "UPDATE faces SET cluster_id = ?1 WHERE id = ?2",
142                params![cluster_id, face_id],
143            )?;
144        }
145
146        Self::refresh_cluster_stats_tx(&tx, cluster_id)?;
147        Self::refresh_gallery_tx(&tx, cluster_id)?;
148
149        tx.commit()?;
150
151        Ok(cluster_id)
152    }
153
154    /// Merge source cluster into target cluster
155    ///
156    /// Moves all faces from source to target, updates counts, deletes source.
157    /// Refuses if a cannot-merge constraint exists between the two clusters.
158    pub fn merge_clusters(
159        &self,
160        source_id: i64,
161        target_id: i64,
162    ) -> SqliteResult<Option<MergeReceipt>> {
163        let blocked: i64 = self.conn.query_row(
164            r#"
165            SELECT COUNT(*) FROM cluster_cannot_merge
166            WHERE (cluster_a_id = ?1 AND cluster_b_id = ?2)
167               OR (cluster_a_id = ?2 AND cluster_b_id = ?1)
168            "#,
169            params![source_id, target_id],
170            |row| row.get(0),
171        )?;
172        if blocked > 0 {
173            tracing::warn!(
174                "Refusing to merge clusters {} and {}: user marked them different",
175                source_id,
176                target_id
177            );
178            return Ok(None);
179        }
180
181        let tx = self.conn.unchecked_transaction()?;
182        let (source_name, source_user_named): (Option<String>, bool) = tx.query_row(
183            "SELECT name, COALESCE(is_user_named, 0) FROM face_clusters WHERE id = ?1",
184            params![source_id],
185            |row| Ok((row.get(0)?, row.get(1)?)),
186        )?;
187        let face_ids: Vec<i64> = {
188            let mut stmt = tx.prepare("SELECT id FROM faces WHERE cluster_id = ?1")?;
189            let rows = stmt.query_map(params![source_id], |row| row.get(0))?;
190            rows.collect::<SqliteResult<_>>()?
191        };
192        let mut target_took_name = false;
193
194        // Preserve names: if the target is unnamed but the source has a name,
195        // carry the name over so we never lose a user-assigned label.
196        let target_name: Option<String> = tx
197            .query_row(
198                "SELECT name FROM face_clusters WHERE id = ?1",
199                params![target_id],
200                |row| row.get(0),
201            )
202            .ok()
203            .flatten();
204        if target_name.is_none() {
205            let source_name: Option<String> = tx
206                .query_row(
207                    "SELECT name FROM face_clusters WHERE id = ?1",
208                    params![source_id],
209                    |row| row.get(0),
210                )
211                .ok()
212                .flatten();
213            if let Some(name) = source_name {
214                tx.execute(
215                    "UPDATE face_clusters SET name = ?1, updated_at = CURRENT_TIMESTAMP WHERE id = ?2",
216                    params![name, target_id],
217                )?;
218                target_took_name = true;
219            }
220        }
221
222        // Move all faces from source to target
223        tx.execute(
224            "UPDATE faces SET cluster_id = ?1 WHERE cluster_id = ?2",
225            params![target_id, source_id],
226        )?;
227
228        // Move inferred identities from source to target (dedupe on unique constraint).
229        tx.execute(
230            r#"
231            INSERT OR IGNORE INTO photo_inferred_identities (photo_id, cluster_id, source_photo_id, confidence)
232            SELECT photo_id, ?1, source_photo_id, confidence
233            FROM photo_inferred_identities
234            WHERE cluster_id = ?2
235            "#,
236            params![target_id, source_id],
237        )?;
238
239        Self::refresh_cluster_stats_tx(&tx, target_id)?;
240        Self::refresh_gallery_tx(&tx, target_id)?;
241
242        // Delete source cluster
243        tx.execute(
244            "DELETE FROM face_clusters WHERE id = ?1",
245            params![source_id],
246        )?;
247
248        tx.commit()?;
249        Ok(Some(MergeReceipt {
250            source_id,
251            target_id,
252            source_name,
253            source_user_named,
254            face_ids,
255            target_took_name,
256        }))
257    }
258
259    /// Undo a merge: bring the source person back with their faces and
260    /// remember the two are different people, so clustering never merges
261    /// them again. Inferred photo links are rebuilt by the next face pass.
262    pub fn unmerge_clusters(&self, receipt: &MergeReceipt) -> SqliteResult<()> {
263        let tx = self.conn.unchecked_transaction()?;
264        tx.execute(
265            "INSERT INTO face_clusters (id, name, is_user_named) VALUES (?1, ?2, ?3)",
266            params![
267                receipt.source_id,
268                receipt.source_name,
269                receipt.source_user_named
270            ],
271        )?;
272        {
273            let mut stmt =
274                tx.prepare("UPDATE faces SET cluster_id = ?1 WHERE id = ?2 AND cluster_id = ?3")?;
275            for face_id in &receipt.face_ids {
276                stmt.execute(params![receipt.source_id, face_id, receipt.target_id])?;
277            }
278        }
279        if receipt.target_took_name {
280            tx.execute(
281                "UPDATE face_clusters SET name = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?1",
282                params![receipt.target_id],
283            )?;
284        }
285        let (a, b) = (
286            receipt.source_id.min(receipt.target_id),
287            receipt.source_id.max(receipt.target_id),
288        );
289        tx.execute(
290            "INSERT OR IGNORE INTO cluster_cannot_merge (cluster_a_id, cluster_b_id) VALUES (?1, ?2)",
291            params![a, b],
292        )?;
293        for cluster_id in [receipt.source_id, receipt.target_id] {
294            Self::refresh_cluster_stats_tx(&tx, cluster_id)?;
295            Self::refresh_gallery_tx(&tx, cluster_id)?;
296        }
297        tx.commit()
298    }
299
300    /// Load all cannot-merge pairs (returns them in both directions for easy lookup).
301    pub fn get_cannot_merge_map(
302        &self,
303    ) -> SqliteResult<std::collections::HashMap<i64, std::collections::HashSet<i64>>> {
304        let mut stmt = self
305            .conn
306            .prepare("SELECT cluster_a_id, cluster_b_id FROM cluster_cannot_merge")?;
307        let rows = stmt.query_map([], |row| Ok((row.get::<_, i64>(0)?, row.get::<_, i64>(1)?)))?;
308
309        let mut map: std::collections::HashMap<i64, std::collections::HashSet<i64>> =
310            std::collections::HashMap::new();
311        for row in rows {
312            let (a, b) = row?;
313            map.entry(a).or_default().insert(b);
314            map.entry(b).or_default().insert(a);
315        }
316        Ok(map)
317    }
318
319    /// The user just put this face with this person, so an earlier "not
320    /// this person" about the pair is out of date: the latest choice wins.
321    /// Left in place, clustering and "Find more like this" would keep
322    /// working against the correction.
323    fn clear_negative_tx(
324        tx: &rusqlite::Transaction<'_>,
325        face_id: i64,
326        cluster_id: i64,
327    ) -> SqliteResult<()> {
328        tx.execute(
329            "DELETE FROM face_negatives WHERE face_id = ?1 AND not_cluster_id = ?2",
330            params![face_id, cluster_id],
331        )?;
332        Ok(())
333    }
334
335    /// Confirm a face: set user_confirmed=1. Add to gallery if not already.
336    pub fn confirm_face(&self, face_id: i64) -> SqliteResult<()> {
337        let tx = self.conn.unchecked_transaction()?;
338
339        tx.execute(
340            "UPDATE faces SET user_confirmed = 1 WHERE id = ?1",
341            params![face_id],
342        )?;
343
344        let (cluster_id, embedding_bytes, confidence): (i64, Vec<u8>, Option<f32>) = tx.query_row(
345            "SELECT cluster_id, embedding, confidence FROM faces WHERE id = ?1",
346            params![face_id],
347            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
348        )?;
349        Self::clear_negative_tx(&tx, face_id, cluster_id)?;
350
351        tx.execute(
352            r#"
353            INSERT INTO person_gallery_embeddings
354                (cluster_id, face_id, embedding, quality_score, source)
355            VALUES (?1, ?2, ?3, ?4, 'user_confirmed')
356            ON CONFLICT(cluster_id, face_id) DO UPDATE SET
357                source = 'user_confirmed',
358                quality_score = excluded.quality_score
359            "#,
360            params![
361                cluster_id,
362                face_id,
363                embedding_bytes,
364                confidence.unwrap_or(0.0)
365            ],
366        )?;
367
368        Self::refresh_cluster_stats_tx(&tx, cluster_id)?;
369        Self::refresh_gallery_tx(&tx, cluster_id)?;
370
371        tx.commit()
372    }
373
374    /// Reject face to unknown: set cluster_id=NULL, user_confirmed=0. Write negative.
375    pub fn reject_face_to_unknown(&self, face_id: i64, prev_cluster_id: i64) -> SqliteResult<()> {
376        let tx = self.conn.unchecked_transaction()?;
377
378        tx.execute(
379            "INSERT OR IGNORE INTO face_negatives (face_id, not_cluster_id) VALUES (?1, ?2)",
380            params![face_id, prev_cluster_id],
381        )?;
382
383        tx.execute(
384            "UPDATE faces SET cluster_id = NULL, user_confirmed = 0 WHERE id = ?1",
385            params![face_id],
386        )?;
387
388        Self::refresh_cluster_stats_tx(&tx, prev_cluster_id)?;
389        Self::refresh_gallery_tx(&tx, prev_cluster_id)?;
390
391        tx.commit()
392    }
393
394    /// Reassign a face to a different cluster. Marks user_confirmed=1, writes negative
395    /// against the old cluster_id so it won't come back.
396    pub fn reassign_face(
397        &self,
398        face_id: i64,
399        new_cluster_id: i64,
400        old_cluster_id: i64,
401    ) -> SqliteResult<()> {
402        let tx = self.conn.unchecked_transaction()?;
403
404        tx.execute(
405            "INSERT OR IGNORE INTO face_negatives (face_id, not_cluster_id) VALUES (?1, ?2)",
406            params![face_id, old_cluster_id],
407        )?;
408
409        tx.execute(
410            "UPDATE faces SET cluster_id = ?1, user_confirmed = 1 WHERE id = ?2",
411            params![new_cluster_id, face_id],
412        )?;
413        Self::clear_negative_tx(&tx, face_id, new_cluster_id)?;
414
415        let embedding_bytes: Vec<u8> = tx.query_row(
416            "SELECT embedding FROM faces WHERE id = ?1",
417            params![face_id],
418            |row| row.get(0),
419        )?;
420        let confidence: Option<f32> = tx
421            .query_row(
422                "SELECT confidence FROM faces WHERE id = ?1",
423                params![face_id],
424                |row| row.get(0),
425            )
426            .ok();
427
428        tx.execute(
429            r#"
430            INSERT INTO person_gallery_embeddings
431                (cluster_id, face_id, embedding, quality_score, source)
432            VALUES (?1, ?2, ?3, ?4, 'user_confirmed')
433            ON CONFLICT(cluster_id, face_id) DO UPDATE SET
434                source = 'user_confirmed',
435                quality_score = excluded.quality_score
436            "#,
437            params![
438                new_cluster_id,
439                face_id,
440                embedding_bytes,
441                confidence.unwrap_or(0.0)
442            ],
443        )?;
444
445        // A confirmed face stays in a gallery through refreshes; it has left.
446        tx.execute(
447            "DELETE FROM person_gallery_embeddings WHERE cluster_id = ?1 AND face_id = ?2",
448            params![old_cluster_id, face_id],
449        )?;
450        Self::refresh_cluster_stats_tx(&tx, old_cluster_id)?;
451        Self::refresh_gallery_tx(&tx, old_cluster_id)?;
452        Self::refresh_cluster_stats_tx(&tx, new_cluster_id)?;
453        Self::refresh_gallery_tx(&tx, new_cluster_id)?;
454
455        tx.commit()
456    }
457
458    /// Confirm a currently-unassigned face into a cluster (used by K-similar flow).
459    pub fn confirm_face_to_cluster(&self, face_id: i64, cluster_id: i64) -> SqliteResult<()> {
460        let tx = self.conn.unchecked_transaction()?;
461        // The person the face is leaving, if any: its count and gallery must
462        // stop including the face too.
463        let previous: Option<i64> = tx
464            .query_row(
465                "SELECT cluster_id FROM faces WHERE id = ?1",
466                params![face_id],
467                |row| row.get(0),
468            )
469            .optional()?
470            .flatten()
471            .filter(|&c| c != cluster_id);
472
473        tx.execute(
474            "UPDATE faces SET cluster_id = ?1, user_confirmed = 1 WHERE id = ?2",
475            params![cluster_id, face_id],
476        )?;
477        Self::clear_negative_tx(&tx, face_id, cluster_id)?;
478
479        let embedding_bytes: Vec<u8> = tx.query_row(
480            "SELECT embedding FROM faces WHERE id = ?1",
481            params![face_id],
482            |row| row.get(0),
483        )?;
484        let confidence: Option<f32> = tx
485            .query_row(
486                "SELECT confidence FROM faces WHERE id = ?1",
487                params![face_id],
488                |row| row.get(0),
489            )
490            .ok();
491
492        tx.execute(
493            r#"
494            INSERT INTO person_gallery_embeddings
495                (cluster_id, face_id, embedding, quality_score, source)
496            VALUES (?1, ?2, ?3, ?4, 'user_confirmed')
497            ON CONFLICT(cluster_id, face_id) DO UPDATE SET
498                source = 'user_confirmed',
499                quality_score = excluded.quality_score
500            "#,
501            params![
502                cluster_id,
503                face_id,
504                embedding_bytes,
505                confidence.unwrap_or(0.0)
506            ],
507        )?;
508
509        Self::refresh_cluster_stats_tx(&tx, cluster_id)?;
510        Self::refresh_gallery_tx(&tx, cluster_id)?;
511        if let Some(previous) = previous {
512            tx.execute(
513                "DELETE FROM person_gallery_embeddings WHERE cluster_id = ?1 AND face_id = ?2",
514                params![previous, face_id],
515            )?;
516            Self::refresh_cluster_stats_tx(&tx, previous)?;
517            Self::refresh_gallery_tx(&tx, previous)?;
518        }
519
520        tx.commit()
521    }
522}