1use std::collections::HashMap;
7use std::path::{Path, PathBuf};
8use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
9use std::sync::{mpsc, Arc, Mutex};
10
11use rayon::prelude::*;
12
13use crate::db::face_repo::FaceRepo;
14use crate::db::Database;
15use crate::db::InferredIdentityRepo;
16use crate::ml::{
17 ClusterInput, FaceClusterer, FaceDetector, FaceEmbedder, FaceEmbedding, OnnxRuntime,
18};
19use crate::services::image_utils::apply_exif_orientation;
20use crate::services::path_util::safe_join_relative;
21
22const MAX_FACE_ATTEMPTS: i64 = 3;
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum FaceProcessingStage {
30 Detecting,
32 Finishing,
36 Done,
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum EmbedderRoute {
48 Local,
50 Bridge,
52}
53
54impl EmbedderRoute {
55 pub fn as_str(self) -> &'static str {
56 match self {
57 EmbedderRoute::Local => "local",
58 EmbedderRoute::Bridge => "bridge",
59 }
60 }
61}
62
63#[derive(Debug, Clone)]
65pub struct FaceProcessingProgress {
66 pub processed: usize,
67 pub total: usize,
68 pub faces_found: usize,
69 pub elapsed_secs: f64,
71 pub stage: FaceProcessingStage,
72 pub chunks_flushed: u32,
77 pub embedder_route: EmbedderRoute,
84}
85
86impl Default for FaceProcessingProgress {
87 fn default() -> Self {
88 Self {
89 processed: 0,
90 total: 0,
91 faces_found: 0,
92 elapsed_secs: 0.0,
93 stage: FaceProcessingStage::Detecting,
94 chunks_flushed: 0,
95 embedder_route: EmbedderRoute::Local,
96 }
97 }
98}
99
100#[derive(Debug, Clone)]
102pub struct FaceProcessingResult {
103 pub photos_processed: usize,
104 pub faces_detected: usize,
105 pub clusters_created: usize,
106 pub rejected_small: usize,
107 pub rejected_lowconf: usize,
108 pub rejected_blurry: usize,
109 pub rejected_yaw: usize,
110}
111
112struct PhotoFaceResult {
114 photo_id: i64,
115 file_path: String,
116 faces: Vec<FaceInsert>,
117 taken_ts: Option<i64>,
118 brightness: f32,
119 had_error: bool,
120}
121
122struct ProcessedPhotoSummary {
127 photo_id: i64,
128 file_path: String,
129 taken_ts: Option<i64>,
130 brightness: f32,
131 had_error: bool,
132 has_faces: bool,
133}
134
135struct FaceInsert {
137 bbox_normalized: (f32, f32, f32, f32),
138 confidence: f32,
139 embedding: FaceEmbedding,
140 aligned_face: image::RgbImage,
141}
142
143struct ContextPropagationInput<'a> {
144 drive_path: &'a Path,
145 photo_id: i64,
146 file_path: &'a str,
147 target_ts: i64,
148 target_brightness: f32,
149 brightness_map: &'a HashMap<i64, f32>,
150}
151
152pub struct FaceProcessor;
156
157impl FaceProcessor {
158 const CONTEXT_WINDOW_SECS: i64 = 60;
159 const CONTEXT_MIN_CONFIDENCE: f32 = 0.5;
160
161 pub fn process_photos(
166 drive_path: &Path,
167 model_dir: &Path,
168 detector_confidence: f32,
169 clustering_threshold: f32,
170 resolver_weights: crate::ml::ResolverWeights,
171 progress_tx: Option<async_channel::Sender<FaceProcessingProgress>>,
172 cancel_flag: Option<Arc<AtomicBool>>,
173 ) -> Result<FaceProcessingResult, String> {
174 let db = Database::open_for_drive(drive_path)
176 .map_err(|e| format!("Failed to open database: {}", e))?;
177 let face_repo = FaceRepo::new(&db.conn);
178
179 let unprocessed = face_repo
183 .get_unprocessed_photos_with_context()
184 .map_err(|e| format!("Failed to get unprocessed photos: {}", e))?;
185
186 let inferred_repo = InferredIdentityRepo::new(&db.conn);
187
188 let total = unprocessed.len();
189 if total == 0 {
190 let clusters_created =
191 Self::run_clustering(&face_repo, clustering_threshold, resolver_weights)?;
192 return Ok(FaceProcessingResult {
193 photos_processed: 0,
194 faces_detected: 0,
195 clusters_created,
196 rejected_small: 0,
197 rejected_lowconf: 0,
198 rejected_blurry: 0,
199 rejected_yaw: 0,
200 });
201 }
202
203 let pipeline_start = std::time::Instant::now();
204
205 let runtime = OnnxRuntime::init().map_err(|e| {
212 format!(
213 "Face detection unavailable — {}. Enable face recognition in People or Settings.",
214 e
215 )
216 })?;
217
218 let detector_path = model_dir.join("scrfd_10g_bnkps.onnx");
219 let cfg = crate::config::AppConfig::load();
220 let embedder_path = model_dir.join(&cfg.face_embedder_model);
221 let gpu_bridge_url: Option<String> = if cfg.face_gpu_bridge_enabled {
224 cfg.face_gpu_bridge_url.clone()
225 } else {
226 None
227 };
228 let embedder_model_name: String = cfg.face_embedder_model.clone();
229 let embedder_route = if gpu_bridge_url.is_some() {
236 EmbedderRoute::Bridge
237 } else {
238 EmbedderRoute::Local
239 };
240
241 if !detector_path.exists() {
242 return Err(
243 "Face detection model is missing. Enable face recognition in People or Settings."
244 .to_string(),
245 );
246 }
247 if !embedder_path.exists() && gpu_bridge_url.is_none() {
248 return Err(
249 "Face embedding model is missing. Enable face recognition in People or Settings, or configure a healthy remote GPU bridge."
250 .to_string(),
251 );
252 }
253
254 let faces_dir = Self::faces_dir(drive_path);
256 if let Err(e) = std::fs::create_dir_all(&faces_dir) {
257 tracing::warn!("Failed to create faces directory: {}", e);
258 }
259
260 tracing::info!("Face processing: {} photos to process", total);
261
262 let available_cpus = std::thread::available_parallelism()
264 .map(|n| n.get())
265 .unwrap_or(4);
266 let (num_workers, intra_threads, cpu_budget) = background_face_budget(available_cpus);
271
272 tracing::info!(
273 "Face pipeline: {} workers, {} intra-threads per session ({} CPUs, budget {})",
274 num_workers,
275 intra_threads,
276 available_cpus,
277 cpu_budget
278 );
279
280 let pool = rayon::ThreadPoolBuilder::new()
282 .num_threads(num_workers)
283 .build()
284 .map_err(|e| format!("Failed to create thread pool: {}", e))?;
285
286 let processed_count = Arc::new(AtomicUsize::new(0));
287 let faces_count = Arc::new(AtomicUsize::new(0));
288 let rejected_small = Arc::new(AtomicUsize::new(0));
289 let rejected_lowconf = Arc::new(AtomicUsize::new(0));
290 let rejected_blurry = Arc::new(AtomicUsize::new(0));
291 let rejected_yaw = Arc::new(AtomicUsize::new(0));
292 let cancel = cancel_flag
293 .clone()
294 .unwrap_or_else(|| Arc::new(AtomicBool::new(false)));
295 let chunks_flushed = Arc::new(AtomicUsize::new(0));
299
300 let detector_path = Arc::new(detector_path);
302 let embedder_path = Arc::new(embedder_path);
303 let drive_path_arc = Arc::new(drive_path.to_path_buf());
304
305 const FLUSH_CHUNK: usize = 5;
317 let (chunk_tx, chunk_rx) = mpsc::sync_channel::<Vec<PhotoFaceResult>>(4);
318 let writer_handle: std::thread::JoinHandle<Result<(usize, usize), String>> = {
319 let drive_path_buf = drive_path.to_path_buf();
320 let faces_dir_buf = faces_dir.clone();
321 let chunks_flushed = chunks_flushed.clone();
322 let cancel = cancel.clone();
323 let writer_resolver_weights = resolver_weights;
324 std::thread::spawn(move || -> Result<(usize, usize), String> {
325 let writer_db = Database::open_for_drive(&drive_path_buf)
326 .map_err(|e| format!("Failed to open writer DB: {}", e))?;
327 let mut total_faces = 0usize;
328 let mut photos_processed = 0usize;
329 while let Ok(chunk) = chunk_rx.recv() {
330 let was_cancelled = cancel.load(Ordering::Relaxed);
331 let (faces_added, photos_added) = flush_result_chunk(
332 &writer_db,
333 &faces_dir_buf,
334 &chunk,
335 was_cancelled,
336 &chunks_flushed,
337 clustering_threshold,
338 writer_resolver_weights,
339 )?;
340 total_faces += faces_added;
341 photos_processed += photos_added;
342 }
343 Ok((total_faces, photos_processed))
344 })
345 };
346
347 let summaries: Arc<Mutex<Vec<ProcessedPhotoSummary>>> = Arc::new(Mutex::new(Vec::new()));
349 let buffer: Arc<Mutex<Vec<PhotoFaceResult>>> =
350 Arc::new(Mutex::new(Vec::with_capacity(FLUSH_CHUNK)));
351 let chunk_tx = Arc::new(chunk_tx);
352 pool.install(|| {
353 unprocessed
354 .par_iter()
355 .for_each(|(photo_id, file_path, orientation, taken_ts, file_hash)| {
356 if cancel.load(Ordering::Relaxed) {
359 return;
360 }
361 let guarded = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> PhotoFaceResult {
364
365 thread_local! {
367 static DETECTOR: std::cell::RefCell<Option<FaceDetector>> = const { std::cell::RefCell::new(None) };
368 static EMBEDDER: std::cell::RefCell<Option<FaceEmbedder>> = const { std::cell::RefCell::new(None) };
369 }
370
371 let det_path = detector_path.clone();
373 let emb_path = embedder_path.clone();
374 DETECTOR.with(|d| {
375 if d.borrow().is_none() {
376 match FaceDetector::new_with_threads(&runtime, det_path.as_ref(), intra_threads) {
377 Ok(det) => {
378 *d.borrow_mut() = Some(det.with_confidence_threshold(detector_confidence));
379 }
380 Err(e) => {
381 tracing::error!("Failed to init detector in worker: {}", e);
382 }
383 }
384 }
385 });
386 EMBEDDER.with(|e| {
387 if e.borrow().is_none() {
388 let embedder_cfg = crate::ml::EmbedderConfig {
389 model_path: emb_path.as_ref().clone(),
390 gpu_bridge_url: gpu_bridge_url.clone(),
391 expected_model: embedder_model_name.clone(),
392 intra_threads,
393 };
394 match FaceEmbedder::from_config(&runtime, &embedder_cfg) {
395 Ok(emb) => {
396 *e.borrow_mut() = Some(emb);
397 }
398 Err(e_err) => {
399 tracing::error!("Failed to init embedder in worker: {}", e_err);
400 }
401 }
402 }
403 });
404
405 let full_path = match safe_join_relative(&drive_path_arc, file_path) {
415 Ok(path) => path,
416 Err(e) => {
417 tracing::debug!("Invalid stored photo path {}: {}", file_path, e);
418 processed_count.fetch_add(1, Ordering::Relaxed);
419 return PhotoFaceResult {
420 photo_id: *photo_id,
421 file_path: file_path.clone(),
422 faces: Vec::new(),
423 taken_ts: *taken_ts,
424 brightness: 0.0,
425 had_error: true,
426 };
427 }
428 };
429 let large_thumb = crate::services::cache_location::thumbnails_dir(&drive_path_arc)
430 .join("large")
431 .join("v2")
432 .join(&file_hash[..2.min(file_hash.len())])
433 .join(format!("{}.jpg", file_hash));
434
435 let detect_image: image::DynamicImage = if large_thumb.exists() {
437 match image::ImageReader::open(&large_thumb)
438 .ok()
439 .and_then(|r| r.with_guessed_format().ok())
440 .and_then(|r| r.decode().ok())
441 {
442 Some(img) => img,
443 None => match crate::services::image_io::open_image(&full_path) {
444 Ok(img) => {
445 let img = apply_exif_orientation(img, *orientation);
446 let max_dim = img.width().max(img.height());
447 if max_dim > 2048 {
448 img.resize(2048, 2048, image::imageops::FilterType::Triangle)
449 } else {
450 img
451 }
452 }
453 Err(e) => {
454 tracing::debug!("Failed to open image {}: {}", file_path, e);
455 processed_count.fetch_add(1, Ordering::Relaxed);
456 return PhotoFaceResult {
457 photo_id: *photo_id,
458 file_path: file_path.clone(),
459 faces: Vec::new(),
460 taken_ts: *taken_ts,
461 brightness: 0.0,
462 had_error: true,
463 };
464 }
465 },
466 }
467 } else {
468 match crate::services::image_io::open_image(&full_path) {
471 Ok(img) => {
472 let img = apply_exif_orientation(img, *orientation);
473 let max_dim = img.width().max(img.height());
474 if max_dim > 2048 {
475 img.resize(2048, 2048, image::imageops::FilterType::Triangle)
476 } else {
477 img
478 }
479 }
480 Err(e) => {
481 tracing::debug!("Failed to open image {}: {}", file_path, e);
482 processed_count.fetch_add(1, Ordering::Relaxed);
483 return PhotoFaceResult {
484 photo_id: *photo_id,
485 file_path: file_path.clone(),
486 faces: Vec::new(),
487 taken_ts: *taken_ts,
488 brightness: 0.0,
489 had_error: true,
490 };
491 }
492 }
493 };
494
495 let brightness = Self::average_brightness(&detect_image);
497
498 if cancel.load(Ordering::Relaxed) {
499 return PhotoFaceResult {
500 photo_id: *photo_id,
501 file_path: file_path.clone(),
502 faces: Vec::new(),
503 taken_ts: *taken_ts,
504 brightness,
505 had_error: true,
506 };
507 }
508
509 let mut detected = DETECTOR.with(|d| {
511 let mut borrow = d.borrow_mut();
512 match borrow.as_mut() {
513 Some(det) => det.detect_adaptive(&detect_image),
514 None => Vec::new(),
515 }
516 });
517
518 if !detected.is_empty() && large_thumb.exists() {
522 if let Ok(full_img) =
523 crate::services::image_io::open_image(&full_path)
524 {
525 let full_img = apply_exif_orientation(full_img, *orientation);
526 let scale_x =
527 full_img.width() as f32 / detect_image.width() as f32;
528 let scale_y =
529 full_img.height() as f32 / detect_image.height() as f32;
530 for face in detected.iter_mut() {
531 let mut scaled = face.landmarks;
532 for lm in &mut scaled {
533 lm.0 *= scale_x;
534 lm.1 *= scale_y;
535 }
536 if let Some(aligned) =
537 crate::ml::alignment::align_face_112(&full_img, &scaled)
538 {
539 face.aligned_face = Some(aligned);
540 }
541 }
542 }
543 }
544
545 if !detected.is_empty() {
546 tracing::info!(
547 "Photo: {} faces detected in {}",
548 detected.len(),
549 file_path
550 );
551 }
552
553 if cancel.load(Ordering::Relaxed) {
555 return PhotoFaceResult {
556 photo_id: *photo_id,
557 file_path: file_path.clone(),
558 faces: Vec::new(),
559 taken_ts: *taken_ts,
560 brightness,
561 had_error: true,
562 };
563 }
564
565 let mut qualifying: Vec<(usize, &image::RgbImage)> = Vec::new();
569 for (fi, face) in detected.iter().enumerate() {
570 if cancel.load(Ordering::Relaxed) {
571 break;
572 }
573 let (_bx, _by, bw, bh) = face.bbox;
574 if bw * bh < Self::MIN_FACE_AREA_PX2 {
575 rejected_small.fetch_add(1, Ordering::Relaxed);
576 continue;
577 }
578 if face.confidence < Self::MIN_FACE_CONFIDENCE {
579 rejected_lowconf.fetch_add(1, Ordering::Relaxed);
580 continue;
581 }
582 let aligned = match face.aligned_face.as_ref() {
583 Some(a) => a,
584 None => continue,
585 };
586 let sharpness = Self::laplacian_variance(aligned);
587 if sharpness < Self::MIN_LAPLACIAN_VAR {
588 rejected_blurry.fetch_add(1, Ordering::Relaxed);
589 continue;
590 }
591 let yaw = crate::ml::face_detector::estimate_yaw_from_landmarks(
592 &face.landmarks,
593 );
594 if yaw > Self::MAX_FACE_YAW_DEG {
595 rejected_yaw.fetch_add(1, Ordering::Relaxed);
596 continue;
597 }
598 qualifying.push((fi, aligned));
599 }
600
601 let crops: Vec<image::RgbImage> = qualifying
602 .iter()
603 .map(|(_, a)| (*a).clone())
604 .collect();
605 let batch_embs = if crops.is_empty() {
606 Vec::new()
607 } else {
608 EMBEDDER.with(|e| {
609 let mut borrow = e.borrow_mut();
610 borrow
611 .as_mut()
612 .map_or(Vec::new(), |emb| emb.embed_batch(&crops))
613 })
614 };
615
616 let mut face_inserts = Vec::new();
617 for (bi, &(fi, _aligned)) in qualifying.iter().enumerate() {
618 if let Some(embedding) = batch_embs.get(bi).and_then(|e: &Option<FaceEmbedding>| e.clone()) {
619 face_inserts.push(FaceInsert {
620 bbox_normalized: detected[fi].bbox_normalized,
621 confidence: detected[fi].confidence,
622 embedding,
623 aligned_face: detected[fi].aligned_face.clone().unwrap_or_default(),
624 });
625 }
626 }
627
628 faces_count.fetch_add(face_inserts.len(), Ordering::Relaxed);
629 processed_count.fetch_add(1, Ordering::Relaxed);
630
631 PhotoFaceResult {
632 photo_id: *photo_id,
633 file_path: file_path.clone(),
634 faces: face_inserts,
635 taken_ts: *taken_ts,
636 brightness,
637 had_error: false,
638 }
639 }));
640 let result = guarded.unwrap_or_else(|_| {
641 tracing::warn!("face processing crashed on {file_path}; skipping it");
642 processed_count.fetch_add(1, Ordering::Relaxed);
643 PhotoFaceResult {
644 photo_id: *photo_id,
645 file_path: file_path.clone(),
646 faces: Vec::new(),
647 taken_ts: *taken_ts,
648 brightness: 0.0,
649 had_error: true,
650 }
651 });
652
653 if let Some(ref tx) = progress_tx {
654 let _ = tx.try_send(FaceProcessingProgress {
655 processed: processed_count.load(Ordering::Relaxed),
656 total,
657 faces_found: faces_count.load(Ordering::Relaxed),
658 elapsed_secs: pipeline_start.elapsed().as_secs_f64(),
659 stage: FaceProcessingStage::Detecting,
660 chunks_flushed: chunks_flushed.load(Ordering::Relaxed) as u32,
661 embedder_route,
662 });
663 }
664
665 summaries
669 .lock()
670 .unwrap_or_else(|e| e.into_inner())
671 .push(ProcessedPhotoSummary {
672 photo_id: result.photo_id,
673 file_path: result.file_path.clone(),
674 taken_ts: result.taken_ts,
675 brightness: result.brightness,
676 had_error: result.had_error,
677 has_faces: !result.faces.is_empty(),
678 });
679
680 let mut buf = buffer.lock().unwrap_or_else(|e| e.into_inner());
685 buf.push(result);
686 if buf.len() >= FLUSH_CHUNK {
687 let chunk = std::mem::replace(&mut *buf, Vec::with_capacity(FLUSH_CHUNK));
688 drop(buf);
689 let _ = chunk_tx.send(chunk);
693 }
694 });
695 });
696
697 {
699 let leftover = std::mem::take(&mut *buffer.lock().unwrap_or_else(|e| e.into_inner()));
700 if !leftover.is_empty() {
701 let _ = chunk_tx.send(leftover);
702 }
703 }
704 drop(chunk_tx);
707
708 let (mut total_faces, mut photos_processed) = match writer_handle.join() {
710 Ok(Ok(pair)) => pair,
711 Ok(Err(e)) => return Err(e),
712 Err(_) => return Err("Face writer thread panicked".to_string()),
713 };
714 let _ = (&mut total_faces, &mut photos_processed);
719
720 let was_cancelled = cancel.load(Ordering::Relaxed);
724
725 let rej_small = rejected_small.load(Ordering::Relaxed);
726 let rej_lowconf = rejected_lowconf.load(Ordering::Relaxed);
727 let rej_blurry = rejected_blurry.load(Ordering::Relaxed);
728 let rej_yaw = rejected_yaw.load(Ordering::Relaxed);
729 if rej_small + rej_lowconf + rej_blurry + rej_yaw > 0 {
730 tracing::info!(
731 "Quality filter: rejected {} small, {} low-confidence, {} blurry, {} high-yaw faces",
732 rej_small,
733 rej_lowconf,
734 rej_blurry,
735 rej_yaw
736 );
737 }
738
739 if was_cancelled {
740 if let Some(ref tx) = progress_tx {
741 let _ = tx.try_send(FaceProcessingProgress {
742 processed: photos_processed,
743 total,
744 faces_found: total_faces,
745 elapsed_secs: pipeline_start.elapsed().as_secs_f64(),
746 stage: FaceProcessingStage::Done,
747 chunks_flushed: chunks_flushed.load(Ordering::Relaxed) as u32,
748 embedder_route,
749 });
750 }
751 return Ok(FaceProcessingResult {
752 photos_processed,
753 faces_detected: total_faces,
754 clusters_created: 0,
755 rejected_small: rej_small,
756 rejected_lowconf: rej_lowconf,
757 rejected_blurry: rej_blurry,
758 rejected_yaw: rej_yaw,
759 });
760 }
761
762 let summaries_vec =
768 std::mem::take(&mut *summaries.lock().unwrap_or_else(|e| e.into_inner()));
769 let brightness_map: HashMap<i64, f32> = summaries_vec
770 .iter()
771 .filter(|s| !s.had_error)
772 .map(|s| (s.photo_id, s.brightness))
773 .collect();
774
775 for summary in &summaries_vec {
776 if summary.had_error || summary.has_faces {
777 continue; }
779 if let Some(target_ts) = summary.taken_ts {
780 let params = ContextPropagationInput {
781 drive_path,
782 photo_id: summary.photo_id,
783 file_path: &summary.file_path,
784 target_ts,
785 target_brightness: summary.brightness,
786 brightness_map: &brightness_map,
787 };
788 let _ = Self::propagate_identity_from_context(&face_repo, &inferred_repo, ¶ms);
789 }
790 }
791 if let Some(ref tx) = progress_tx {
793 let _ = tx.try_send(FaceProcessingProgress {
794 processed: photos_processed,
795 total,
796 faces_found: total_faces,
797 elapsed_secs: pipeline_start.elapsed().as_secs_f64(),
798 stage: FaceProcessingStage::Finishing,
799 chunks_flushed: chunks_flushed.load(Ordering::Relaxed) as u32,
800 embedder_route,
801 });
802 }
803
804 let clusters_created =
806 Self::run_clustering(&face_repo, clustering_threshold, resolver_weights)?;
807
808 if let Some(ref tx) = progress_tx {
810 let _ = tx.try_send(FaceProcessingProgress {
811 processed: photos_processed,
812 total,
813 faces_found: total_faces,
814 elapsed_secs: pipeline_start.elapsed().as_secs_f64(),
815 stage: FaceProcessingStage::Done,
816 chunks_flushed: chunks_flushed.load(Ordering::Relaxed) as u32,
817 embedder_route,
818 });
819 }
820
821 tracing::info!(
822 "Face processing complete: {} photos, {} faces, {} clusters",
823 photos_processed,
824 total_faces,
825 clusters_created
826 );
827
828 Ok(FaceProcessingResult {
829 photos_processed,
830 faces_detected: total_faces,
831 clusters_created,
832 rejected_small: rej_small,
833 rejected_lowconf: rej_lowconf,
834 rejected_blurry: rej_blurry,
835 rejected_yaw: rej_yaw,
836 })
837 }
838
839 fn propagate_identity_from_context(
840 face_repo: &FaceRepo,
841 inferred_repo: &InferredIdentityRepo,
842 params: &ContextPropagationInput<'_>,
843 ) -> Result<usize, String> {
844 let folder_like = std::path::Path::new(params.file_path).parent().map(|p| {
845 let s = p.to_string_lossy();
846 if s.is_empty() {
847 "%".to_string()
848 } else {
849 format!("{}%", s)
850 }
851 });
852
853 let candidates = face_repo
854 .get_contextual_cluster_candidates(
855 params.photo_id,
856 folder_like.as_deref(),
857 params.target_ts,
858 Self::CONTEXT_WINDOW_SECS,
859 )
860 .map_err(|e| format!("Failed to query contextual candidates: {}", e))?;
861
862 if candidates.is_empty() {
863 return Ok(0);
864 }
865
866 let mut best_by_cluster: HashMap<i64, (i64, f32)> = HashMap::new();
867
868 for (source_photo_id, cluster_id, source_ts, source_file_path) in candidates {
869 let delta = (source_ts - params.target_ts).abs() as f32;
870 let temporal_score = 1.0 - (delta / Self::CONTEXT_WINDOW_SECS as f32).clamp(0.0, 1.0);
871 let mut confidence = 0.5 + (temporal_score * 0.4);
872
873 let source_brightness = params
878 .brightness_map
879 .get(&source_photo_id)
880 .copied()
881 .or_else(|| {
882 face_repo
883 .get_photo_brightness(source_photo_id)
884 .ok()
885 .flatten()
886 })
887 .or_else(|| {
888 Self::load_average_brightness_from_relative(
889 params.drive_path,
890 &source_file_path,
891 )
892 });
893
894 if let Some(source_brightness) = source_brightness {
895 let diff = (params.target_brightness - source_brightness).abs();
897 let brightness_bonus = 0.1 * (1.0 - (diff / 0.3).clamp(0.0, 1.0));
898 confidence += brightness_bonus;
899 }
900
901 confidence = confidence.clamp(0.0, 1.0);
902
903 if confidence < Self::CONTEXT_MIN_CONFIDENCE {
904 continue;
905 }
906
907 match best_by_cluster.get(&cluster_id) {
908 Some((_, existing)) if *existing >= confidence => {}
909 _ => {
910 best_by_cluster.insert(cluster_id, (source_photo_id, confidence));
911 }
912 }
913 }
914
915 let mut inserted = 0usize;
916 for (cluster_id, (source_photo_id, confidence)) in best_by_cluster {
917 if inferred_repo
918 .insert_inferred_identity(params.photo_id, cluster_id, source_photo_id, confidence)
919 .is_ok()
920 {
921 inserted += 1;
922 }
923 }
924
925 Ok(inserted)
926 }
927
928 const MIN_FACE_AREA_PX2: f32 = 900.0;
931
932 const MIN_FACE_CONFIDENCE: f32 = 0.55;
935
936 const MIN_LAPLACIAN_VAR: f32 = 40.0;
939
940 const MAX_FACE_YAW_DEG: f32 = 35.0;
943
944 fn laplacian_variance(img: &image::RgbImage) -> f32 {
947 let w = img.width() as i32;
948 let h = img.height() as i32;
949 if w < 3 || h < 3 {
950 return 0.0;
951 }
952
953 let mut gray = vec![0.0f32; (w * h) as usize];
954 for y in 0..h {
955 for x in 0..w {
956 let p = img.get_pixel(x as u32, y as u32).0;
957 gray[(y * w + x) as usize] =
958 0.299 * p[0] as f32 + 0.587 * p[1] as f32 + 0.114 * p[2] as f32;
959 }
960 }
961
962 let mut sum = 0.0f32;
963 let mut sum_sq = 0.0f32;
964 let mut count = 0usize;
965 for y in 1..(h - 1) {
966 for x in 1..(w - 1) {
967 let idx = (y * w + x) as usize;
968 let center = gray[idx];
969 let l = 4.0 * center
970 - gray[(y * w + (x - 1)) as usize]
971 - gray[(y * w + (x + 1)) as usize]
972 - gray[((y - 1) * w + x) as usize]
973 - gray[((y + 1) * w + x) as usize];
974 sum += l;
975 sum_sq += l * l;
976 count += 1;
977 }
978 }
979
980 let n = count as f32;
981 let mean = sum / n;
982 (sum_sq / n) - mean * mean
983 }
984
985 fn build_resolver_context(
989 face_repo: &FaceRepo,
990 photo_id: i64,
991 face_id: i64,
992 hits: &[crate::ml::RetrievalHit],
993 ) -> crate::ml::ResolverContext {
994 const TEMPORAL_WINDOW_SECS: i64 = 60;
995
996 let photo_other_clusters = face_repo
997 .get_photo_other_clusters(photo_id, face_id)
998 .unwrap_or_default();
999
1000 let mut cooccurrence_scores: std::collections::HashMap<i64, i64> =
1001 std::collections::HashMap::new();
1002 if !photo_other_clusters.is_empty() {
1003 for hit in hits {
1004 let mut total: i64 = 0;
1005 for other in &photo_other_clusters {
1006 total += face_repo
1007 .cooccurrence_count(hit.cluster_id, *other)
1008 .unwrap_or(0);
1009 }
1010 if total > 0 {
1011 cooccurrence_scores.insert(hit.cluster_id, total);
1012 }
1013 }
1014 }
1015
1016 let temporal_neighbor_clusters: std::collections::HashSet<i64> = face_repo
1017 .temporal_neighbor_clusters(photo_id, TEMPORAL_WINDOW_SECS)
1018 .unwrap_or_default()
1019 .into_iter()
1020 .map(|(cid, _)| cid)
1021 .collect();
1022
1023 crate::ml::ResolverContext {
1024 photo_other_clusters,
1025 cooccurrence_scores,
1026 temporal_neighbor_clusters,
1027 }
1028 }
1029
1030 fn average_brightness(image: &image::DynamicImage) -> f32 {
1031 let small = image
1032 .resize(64, 64, image::imageops::FilterType::Triangle)
1033 .to_rgb8();
1034 let mut total = 0.0f32;
1035 let mut count = 0.0f32;
1036
1037 for p in small.pixels() {
1038 let [r, g, b] = p.0;
1039 total += (0.2126 * (r as f32) + 0.7152 * (g as f32) + 0.0722 * (b as f32)) / 255.0;
1040 count += 1.0;
1041 }
1042
1043 if count == 0.0 {
1044 0.0
1045 } else {
1046 total / count
1047 }
1048 }
1049
1050 fn load_average_brightness_from_relative(
1051 drive_path: &Path,
1052 relative_path: &str,
1053 ) -> Option<f32> {
1054 let path = match safe_join_relative(drive_path, relative_path) {
1055 Ok(path) => path,
1056 Err(e) => {
1057 tracing::trace!(
1058 "context-brightness lookup skipped invalid path {}: {}",
1059 relative_path,
1060 e
1061 );
1062 return None;
1063 }
1064 };
1065 match crate::services::image_io::open_image(&path) {
1066 Ok(image) => Some(Self::average_brightness(&image)),
1067 Err(e) => {
1068 tracing::trace!(
1069 "context-brightness lookup failed for {}: {}",
1070 path.display(),
1071 e
1072 );
1073 None
1074 }
1075 }
1076 }
1077}
1078
1079fn flush_result_chunk(
1094 db: &Database,
1095 faces_dir: &Path,
1096 chunk: &[PhotoFaceResult],
1097 was_cancelled: bool,
1098 chunks_flushed: &AtomicUsize,
1099 clustering_threshold: f32,
1100 resolver_weights: crate::ml::ResolverWeights,
1101) -> Result<(usize, usize), String> {
1102 let mut faces_added = 0usize;
1103 let mut photos_added = 0usize;
1104 let after_id: i64 = db
1105 .conn
1106 .query_row("SELECT COALESCE(MAX(id), 0) FROM faces", [], |row| {
1107 row.get(0)
1108 })
1109 .map_err(|e| format!("Read face cursor: {e}"))?;
1110 let mut crops = Vec::new();
1112
1113 let tx = db
1114 .conn
1115 .unchecked_transaction()
1116 .map_err(|e| format!("Failed to begin chunk transaction: {}", e))?;
1117
1118 for result in chunk {
1119 if result.had_error && result.faces.is_empty() {
1120 if !was_cancelled {
1125 let _ = tx.execute(
1126 "UPDATE photos
1127 SET face_attempts = face_attempts + 1,
1128 faces_processed = (face_attempts + 1 >= ?2)
1129 WHERE id = ?1",
1130 rusqlite::params![result.photo_id, MAX_FACE_ATTEMPTS],
1131 );
1132 photos_added += 1;
1133 }
1134 continue;
1135 }
1136
1137 let _ = tx.execute(
1138 "DELETE FROM photo_inferred_identities WHERE photo_id = ?1",
1139 rusqlite::params![result.photo_id],
1140 );
1141
1142 for face in &result.faces {
1143 match tx.execute(
1144 r#"
1145 INSERT INTO faces (
1146 photo_id,
1147 bbox_x, bbox_y, bbox_width, bbox_height,
1148 confidence, embedding
1149 ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
1150 "#,
1151 rusqlite::params![
1152 result.photo_id,
1153 face.bbox_normalized.0,
1154 face.bbox_normalized.1,
1155 face.bbox_normalized.2,
1156 face.bbox_normalized.3,
1157 face.confidence,
1158 face.embedding.to_bytes(),
1159 ],
1160 ) {
1161 Ok(_) => {
1162 let face_id = tx.last_insert_rowid();
1163 crops.push((face_id, &face.aligned_face));
1164 faces_added += 1;
1165 }
1166 Err(e) => {
1167 tracing::warn!("Failed to insert face: {}", e);
1168 }
1169 }
1170 }
1171
1172 let _ = tx.execute(
1176 "UPDATE photos SET faces_processed = TRUE, brightness = ?2 WHERE id = ?1",
1177 rusqlite::params![result.photo_id, result.brightness],
1178 );
1179 photos_added += 1;
1180 }
1181
1182 tx.commit()
1183 .map_err(|e| format!("Failed to commit chunk: {}", e))?;
1184
1185 for (face_id, crop) in crops {
1186 let crop_path = faces_dir.join(format!("{face_id}.jpg"));
1187 if let Err(e) = FaceProcessor::save_face_crop(crop, &crop_path) {
1188 tracing::warn!("Failed to save face crop {}: {}", face_id, e);
1189 }
1190 }
1191 chunks_flushed.fetch_add(1, Ordering::Relaxed);
1193
1194 let face_repo = FaceRepo::new(&db.conn);
1199 if let Err(e) = FaceProcessor::stream_assign_existing_clusters(
1200 &face_repo,
1201 after_id,
1202 clustering_threshold,
1203 resolver_weights,
1204 ) {
1205 tracing::debug!("Per-chunk Stage A skipped: {}", e);
1206 }
1207
1208 Ok((faces_added, photos_added))
1209}
1210
1211mod clustering;
1212mod manual;
1213
1214pub use manual::{iou, ManualFace, ManualFaceError, SoftCrop};
1215
1216fn background_face_budget(logical_cpus: usize) -> (usize, usize, usize) {
1233 let logical = logical_cpus.max(1);
1234 let budget = if logical <= 1 {
1238 1
1239 } else {
1240 (((logical - 1) as f64) * 0.75).floor().max(1.0) as usize
1241 };
1242 let workers = budget.clamp(1, 8);
1243 let intra = (budget / workers).max(1);
1244 (workers, intra, budget)
1245}
1246
1247#[cfg(test)]
1248mod background_budget_tests {
1249 use super::background_face_budget;
1250 #[test]
1251 fn reserves_capacity_on_low_end_and_large_machines() {
1252 for cores in [1, 2, 4, 7, 8, 12, 16, 64] {
1253 let (w, t, b) = background_face_budget(cores);
1254 assert!(w * t <= b, "workers*intra must fit the budget");
1255 assert!(w >= 1);
1256 assert!(t >= 1);
1257 }
1258 }
1259
1260 #[test]
1268 fn budget_always_leaves_headroom_and_never_collapses_to_one_thread() {
1269 for cores in 1..=64usize {
1270 let (workers, intra, budget) = background_face_budget(cores);
1271 assert!(workers >= 1 && intra >= 1, "{cores}: {workers}x{intra}");
1272 assert!(
1273 workers * intra <= budget,
1274 "{cores}: {workers}x{intra} exceeds budget {budget}"
1275 );
1276 assert!(
1277 budget <= cores,
1278 "{cores}: budget {budget} exceeds the CPU count"
1279 );
1280 if cores > 1 {
1281 assert!(
1282 budget < cores,
1283 "{cores}: budget {budget} consumes every CPU; the UI needs one"
1284 );
1285 }
1286 }
1287
1288 assert_eq!(background_face_budget(4), (2, 1, 2));
1291 assert_eq!(background_face_budget(1), (1, 1, 1));
1293 assert_eq!(background_face_budget(8), (5, 1, 5));
1295 assert_eq!(background_face_budget(16), (8, 1, 11));
1296 let (w24, t24, b24) = background_face_budget(24);
1298 assert_eq!(b24, 17);
1299 assert_eq!(
1300 (w24, t24),
1301 (8, 2),
1302 "24-core sessions must not be single-threaded"
1303 );
1304 assert_eq!(background_face_budget(64), (8, 5, 47));
1305 }
1306}