1use std::path::Path;
15
16use image::DynamicImage;
17use rusqlite::{params, Connection};
18
19use super::FaceProcessor;
20use crate::ml::{EmbedderConfig, FaceDetector, FaceEmbedder, FaceEmbedding, OnnxRuntime};
21
22const MANUAL_MIN_SCORE: f32 = 0.15;
25
26const CONTEXT: f32 = 0.5;
29
30#[derive(Debug)]
32pub enum ManualFaceError {
33 NoFace,
35 Unavailable(String),
37 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
50pub struct ManualFace {
52 pub bbox: (f32, f32, f32, f32),
54 pub confidence: f32,
55 pub embedding: FaceEmbedding,
56 pub aligned: image::RgbImage,
57}
58
59impl FaceProcessor {
60 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 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
149struct Located {
151 aligned: image::RgbImage,
153 bbox: (f32, f32, f32, f32),
155 confidence: f32,
156}
157
158fn 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
223pub struct SoftCrop {
225 pub face_id: i64,
226 pub bbox: (f32, f32, f32, f32),
228}
229
230impl FaceProcessor {
231 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 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
268fn 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
285pub 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}