Skip to main content

smriti/services/face_processor/
manual.rs

1//! A face the user marks by hand, for one the detector missed.
2//!
3//! Most missed faces are not invisible to the detector: they are small,
4//! turned or dim, and either scored under the threshold or were dropped by
5//! the quality gates. So instead of trusting the drawn box as is, the
6//! detector runs again on just that part of the photo, at a low threshold
7//! and without the gates, and the face it finds there supplies the eye,
8//! nose and mouth points that alignment needs. The embedding then matches
9//! every other face's, so the face counts for its person like a detected
10//! one. When the detector sees no face at all in the box, nothing is added:
11//! an embedding from a guessed alignment would teach the person's gallery
12//! the wrong face.
13
14use std::path::Path;
15
16use image::DynamicImage;
17use rusqlite::{params, Connection};
18
19use super::FaceProcessor;
20use crate::ml::{EmbedderConfig, FaceDetector, FaceEmbedder, FaceEmbedding, OnnxRuntime};
21
22/// Detection score accepted inside a box the user drew. Far below the
23/// library-wide threshold: the user has already said a face is there.
24const MANUAL_MIN_SCORE: f32 = 0.15;
25
26/// How far the region searched reaches past the drawn box, as a share of
27/// its size on each side. Detectors need some context around a face.
28const CONTEXT: f32 = 0.5;
29
30/// Why a drawn face could not be added.
31#[derive(Debug)]
32pub enum ManualFaceError {
33    /// The detector found no face inside the box.
34    NoFace,
35    /// Face models or the runtime are not installed.
36    Unavailable(String),
37    /// The photo could not be read.
38    Image(String),
39}
40
41impl std::fmt::Display for ManualFaceError {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        match self {
44            Self::NoFace => write!(f, "no face found in that area"),
45            Self::Unavailable(why) | Self::Image(why) => write!(f, "{why}"),
46        }
47    }
48}
49
50/// A face found where the user pointed, ready to store.
51pub struct ManualFace {
52    /// Normalised (x, y, width, height) in display orientation.
53    pub bbox: (f32, f32, f32, f32),
54    pub confidence: f32,
55    pub embedding: FaceEmbedding,
56    pub aligned: image::RgbImage,
57}
58
59impl FaceProcessor {
60    /// Find the face inside `drawn` (normalised, display orientation) in the
61    /// photo at `photo_path`, and embed it. Touches no database, so callers
62    /// can run it without holding the library lock.
63    pub fn find_manual_face(
64        photo_path: &Path,
65        orientation: i32,
66        drawn: (f32, f32, f32, f32),
67        model_dir: &Path,
68    ) -> Result<ManualFace, ManualFaceError> {
69        let image =
70            crate::services::image_io::open_image(photo_path).map_err(ManualFaceError::Image)?;
71        let image = crate::services::image_utils::apply_exif_orientation(image, orientation);
72        let (detector, embedder) = load_models(model_dir)?;
73        find_in(&image, drawn, detector, embedder)
74    }
75
76    /// Store a face found by [`FaceProcessor::find_manual_face`], unassigned,
77    /// and save its crop. Returns the new face's id.
78    pub fn insert_manual_face(
79        conn: &Connection,
80        drive_path: &Path,
81        photo_id: i64,
82        face: &ManualFace,
83    ) -> rusqlite::Result<i64> {
84        conn.execute(
85            "INSERT INTO faces (photo_id, bbox_x, bbox_y, bbox_width, bbox_height, confidence, embedding)
86             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
87            params![
88                photo_id,
89                face.bbox.0,
90                face.bbox.1,
91                face.bbox.2,
92                face.bbox.3,
93                face.confidence,
94                face.embedding.to_bytes(),
95            ],
96        )?;
97        let face_id = conn.last_insert_rowid();
98        let dir = Self::faces_dir(drive_path);
99        let saved = std::fs::create_dir_all(&dir)
100            .map_err(|e| e.to_string())
101            .and_then(|_| {
102                Self::save_face_crop(&face.aligned, &dir.join(format!("{face_id}.jpg")))
103                    .map_err(|e| e.to_string())
104            });
105        if let Err(e) = saved {
106            tracing::warn!("Failed to save face crop {face_id}: {e}");
107        }
108        Ok(face_id)
109    }
110}
111
112fn unavailable(what: &str) -> ManualFaceError {
113    ManualFaceError::Unavailable(format!(
114        "{what}. Enable face recognition in People or Settings."
115    ))
116}
117
118fn load_detector(model_dir: &Path) -> Result<(OnnxRuntime, FaceDetector), ManualFaceError> {
119    let runtime = OnnxRuntime::init().map_err(|_| unavailable("Face recognition isn't set up"))?;
120    let detector_path = model_dir.join("scrfd_10g_bnkps.onnx");
121    if !detector_path.exists() {
122        return Err(unavailable("The face detection model is missing"));
123    }
124    let detector = FaceDetector::new_with_threads(&runtime, &detector_path, 2)
125        .map_err(|_| unavailable("The face detection model could not load"))?
126        .with_confidence_threshold(MANUAL_MIN_SCORE);
127    Ok((runtime, detector))
128}
129
130fn load_models(model_dir: &Path) -> Result<(FaceDetector, FaceEmbedder), ManualFaceError> {
131    let (runtime, detector) = load_detector(model_dir)?;
132    let cfg = crate::config::AppConfig::load();
133    let embedder = FaceEmbedder::from_config(
134        &runtime,
135        &EmbedderConfig {
136            model_path: model_dir.join(&cfg.face_embedder_model),
137            gpu_bridge_url: cfg
138                .face_gpu_bridge_enabled
139                .then(|| cfg.face_gpu_bridge_url.clone())
140                .flatten(),
141            expected_model: cfg.face_embedder_model.clone(),
142            intra_threads: 2,
143        },
144    )
145    .map_err(|_| unavailable("The face recognition model could not load"))?;
146    Ok((detector, embedder))
147}
148
149/// A face found again in a photo.
150struct Located {
151    /// Lined up at 112 px.
152    aligned: image::RgbImage,
153    /// Normalised (x, y, width, height).
154    bbox: (f32, f32, f32, f32),
155    confidence: f32,
156}
157
158/// The face whose centre lies in `area` (normalised), lined up at 112 px,
159/// with its normalised box and detection score.
160fn locate(
161    image: &DynamicImage,
162    area: (f32, f32, f32, f32),
163    detector: &mut FaceDetector,
164) -> Option<Located> {
165    let (w, h) = (image.width() as f32, image.height() as f32);
166    let area_px = (area.0 * w, area.1 * h, area.2 * w, area.3 * h);
167    let (x0, y0, x1, y1) = search_region(area_px, w, h);
168    if x1 <= x0 + 8 || y1 <= y0 + 8 {
169        return None;
170    }
171    let crop = image.crop_imm(x0, y0, x1 - x0, y1 - y0);
172    let (ox, oy) = (x0 as f32, y0 as f32);
173    let local = (area_px.0 - ox, area_px.1 - oy, area_px.2, area_px.3);
174
175    let found = detector
176        .detect(&crop)
177        .into_iter()
178        .filter(|f| center_inside(f.bbox, local))
179        .max_by(|a, b| iou(a.bbox, local).total_cmp(&iou(b.bbox, local)))?;
180
181    let mut landmarks = found.landmarks;
182    for point in &mut landmarks {
183        point.0 += ox;
184        point.1 += oy;
185    }
186    let aligned = crate::ml::alignment::align_face_112(image, &landmarks)?;
187    let (bx, by, bw, bh) = found.bbox;
188    let bbox = (
189        ((bx + ox) / w).clamp(0.0, 1.0),
190        ((by + oy) / h).clamp(0.0, 1.0),
191        (bw / w).clamp(0.0, 1.0),
192        (bh / h).clamp(0.0, 1.0),
193    );
194    Some(Located {
195        aligned,
196        bbox,
197        confidence: found.confidence,
198    })
199}
200
201fn find_in(
202    image: &DynamicImage,
203    drawn: (f32, f32, f32, f32),
204    mut detector: FaceDetector,
205    mut embedder: FaceEmbedder,
206) -> Result<ManualFace, ManualFaceError> {
207    let Located {
208        aligned,
209        bbox,
210        confidence,
211    } = locate(image, drawn, &mut detector).ok_or(ManualFaceError::NoFace)?;
212    let embedding = embedder.embed(&aligned).ok_or_else(|| {
213        ManualFaceError::Unavailable("The face could not be read. Try again.".into())
214    })?;
215    Ok(ManualFace {
216        bbox,
217        confidence,
218        embedding,
219        aligned,
220    })
221}
222
223/// A face whose saved crop predates full-size crops.
224pub struct SoftCrop {
225    pub face_id: i64,
226    /// Normalised box, display orientation.
227    pub bbox: (f32, f32, f32, f32),
228}
229
230impl FaceProcessor {
231    /// Crops saved before 0.6 are 80 px, too soft to judge a face when
232    /// shown large. Re-save them at the full 112 px, lined up the same way
233    /// new crops are, from the original photo. Only the picture changes:
234    /// the face's embedding and everything decided about it stay. Faces the
235    /// detector can't find again keep their old crop. Returns how many were
236    /// re-saved.
237    pub fn sharpen_crops(
238        drive_path: &Path,
239        model_dir: &Path,
240        photo_path: &Path,
241        orientation: i32,
242        faces: &[SoftCrop],
243    ) -> Result<usize, ManualFaceError> {
244        let image =
245            crate::services::image_io::open_image(photo_path).map_err(ManualFaceError::Image)?;
246        let image = crate::services::image_utils::apply_exif_orientation(image, orientation);
247        let (_runtime, mut detector) = load_detector(model_dir)?;
248        let dir = Self::faces_dir(drive_path);
249        let mut saved = 0;
250        for face in faces {
251            let Some(Located { aligned, .. }) = locate(&image, face.bbox, &mut detector) else {
252                continue;
253            };
254            if Self::save_face_crop(&aligned, &dir.join(format!("{}.jpg", face.face_id))).is_ok() {
255                saved += 1;
256            }
257        }
258        Ok(saved)
259    }
260
261    /// Whether a saved face crop is smaller than today's 112 px.
262    pub fn crop_is_soft(drive_path: &Path, face_id: i64) -> bool {
263        image::image_dimensions(Self::faces_dir(drive_path).join(format!("{face_id}.jpg")))
264            .is_ok_and(|(w, _)| w < 112)
265    }
266}
267
268/// The drawn box grown by [`CONTEXT`] on every side, clamped to the photo,
269/// as pixel edges (x0, y0, x1, y1).
270fn search_region(drawn: (f32, f32, f32, f32), w: f32, h: f32) -> (u32, u32, u32, u32) {
271    let (x, y, bw, bh) = drawn;
272    let (mx, my) = (bw * CONTEXT, bh * CONTEXT);
273    let x0 = (x - mx).clamp(0.0, w);
274    let y0 = (y - my).clamp(0.0, h);
275    let x1 = (x + bw + mx).clamp(0.0, w);
276    let y1 = (y + bh + my).clamp(0.0, h);
277    (x0 as u32, y0 as u32, x1 as u32, y1 as u32)
278}
279
280fn center_inside(face: (f32, f32, f32, f32), area: (f32, f32, f32, f32)) -> bool {
281    let (cx, cy) = (face.0 + face.2 / 2.0, face.1 + face.3 / 2.0);
282    cx >= area.0 && cx <= area.0 + area.2 && cy >= area.1 && cy <= area.1 + area.3
283}
284
285/// Intersection over union of two (x, y, width, height) boxes.
286pub fn iou(a: (f32, f32, f32, f32), b: (f32, f32, f32, f32)) -> f32 {
287    let ix = ((a.0 + a.2).min(b.0 + b.2) - a.0.max(b.0)).max(0.0);
288    let iy = ((a.1 + a.3).min(b.1 + b.3) - a.1.max(b.1)).max(0.0);
289    let inter = ix * iy;
290    let union = a.2 * a.3 + b.2 * b.3 - inter;
291    if union <= 0.0 {
292        0.0
293    } else {
294        inter / union
295    }
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301
302    #[test]
303    fn iou_of_same_box_is_one_and_disjoint_is_zero() {
304        let a = (0.1, 0.1, 0.2, 0.2);
305        assert!((iou(a, a) - 1.0).abs() < 1e-6);
306        assert_eq!(iou(a, (0.5, 0.5, 0.1, 0.1)), 0.0);
307    }
308
309    #[test]
310    fn search_region_grows_the_box_but_stays_in_the_photo() {
311        assert_eq!(
312            search_region((100.0, 100.0, 100.0, 100.0), 1000.0, 1000.0),
313            (50, 50, 250, 250)
314        );
315        assert_eq!(
316            search_region((0.0, 950.0, 100.0, 50.0), 1000.0, 1000.0),
317            (0, 925, 150, 1000)
318        );
319    }
320
321    #[test]
322    fn a_face_counts_only_when_its_centre_is_in_the_drawn_box() {
323        let drawn = (10.0, 10.0, 50.0, 50.0);
324        assert!(center_inside((20.0, 20.0, 20.0, 20.0), drawn));
325        assert!(!center_inside((70.0, 20.0, 20.0, 20.0), drawn));
326    }
327}