π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Fix pet recognition: class mapping, face alignment, and petEnabled refactor
Amrithesh Kakkoth Ente1d8486bdfb11
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart b/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dartindex 928f5d1c72..0b77a06d68 100644--- a/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart+++ b/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart@@ -3,7 +3,7 @@ import "dart:io" show Platform;import "package:flutter/foundation.dart" show debugPrint;import "package:logging/logging.dart";-import "package:photos/service_locator.dart" show flagService, isOfflineMode;+import "package:photos/service_locator.dart" show flagService, isOfflineMode, localSettings;import 'package:photos/services/machine_learning/face_ml/face_detection/face_detection_service.dart';import 'package:photos/services/machine_learning/face_ml/face_embedding/face_embedding_service.dart';import "package:photos/services/machine_learning/ml_models_overview.dart";@@ -183,7 +183,7 @@ class MLIndexingIsolate extends SuperIsolate {ClipImageEncoder.instance.downloadModel(forceRefresh),];- if (flagService.petEnabled) {+ if (flagService.internalUser && localSettings.petRecognitionEnabled) {modelsToDownload.addAll([PetFaceDetectionService.instance.downloadModel(forceRefresh),PetFaceEmbeddingDogService.instance.downloadModel(forceRefresh),@@ -371,7 +371,7 @@ class MLIndexingIsolate extends SuperIsolate {String petBodyEmbeddingDogPath = "";String petBodyEmbeddingCatPath = "";- if (flagService.petEnabled) {+ if (flagService.internalUser && localSettings.petRecognitionEnabled) {petFaceDetectionPath =(await PetFaceDetectionService.instance.getModelNameAndPath()).$2;petFaceEmbeddingDogPath =diff --git a/mobile/apps/photos/lib/ui/viewer/file/file_details_widget.dart b/mobile/apps/photos/lib/ui/viewer/file/file_details_widget.dartindex 1898e96b48..0cb61eded4 100644--- a/mobile/apps/photos/lib/ui/viewer/file/file_details_widget.dart+++ b/mobile/apps/photos/lib/ui/viewer/file/file_details_widget.dart@@ -306,7 +306,7 @@ class _FileDetailsWidgetState extends State<FileDetailsWidget> {FacesItemWidget(file),const FileDetailsDivider(),]);- if (flagService.petEnabled) {+ if (flagService.internalUser && localSettings.petRecognitionEnabled) {fileDetailsTiles.addAll([PetsItemWidget(file),const FileDetailsDivider(),diff --git a/mobile/apps/photos/lib/utils/ml_util.dart b/mobile/apps/photos/lib/utils/ml_util.dartindex 97ea1536be..dbb297411c 100644--- a/mobile/apps/photos/lib/utils/ml_util.dart+++ b/mobile/apps/photos/lib/utils/ml_util.dart@@ -77,7 +77,7 @@ Future<IndexStatus> getIndexStatus() async {final int facesIndexedFiles = await mlDataDB.getFaceIndexedFileCount();final int clipIndexedFiles = await mlDataDB.getClipIndexedFileCount();int indexedFiles = math.min(facesIndexedFiles, clipIndexedFiles);- if (flagService.petEnabled) {+ if (flagService.internalUser && localSettings.petRecognitionEnabled) {final int petIndexedFiles = await mlDataDB.getPetIndexedFileCount();indexedFiles = math.min(indexedFiles, petIndexedFiles);}@@ -109,7 +109,7 @@ Future<List<FileMLInstruction>> getFilesForMlIndexing() async {final Map<int, int> faceIndexedFileIDs = await mlDataDB.faceIndexedFileIds();final Map<int, int> clipIndexedFileIDs =await mlDataDB.clipIndexedFileWithVersion();- final bool petEnabled = flagService.petEnabled;+ final bool petEnabled = flagService.internalUser && localSettings.petRecognitionEnabled;final Map<int, int> petIndexedFileIDs =petEnabled ? await mlDataDB.petIndexedFileIds() : const {};final Set<int> queuedFiledIDs = {};@@ -224,7 +224,7 @@ Future<List<FileMLInstruction>> getOfflineFilesForMlIndexing() async {final Map<int, int> faceIndexedFileIDs = await mlDataDB.faceIndexedFileIds();final Map<int, int> clipIndexedFileIDs =await mlDataDB.clipIndexedFileWithVersion();- final bool petEnabled = flagService.petEnabled;+ final bool petEnabled = flagService.internalUser && localSettings.petRecognitionEnabled;final Map<int, int> petIndexedFileIDs =petEnabled ? await mlDataDB.petIndexedFileIds() : const {};final Set<int> queuedFileIDs = {};diff --git a/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart b/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dartindex 014bc9820a..4f1ab63fcc 100644--- a/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart+++ b/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart@@ -102,9 +102,6 @@ class FlagService {bool get useRustForFaceThumbnails => internalUser;- bool get petEnabled =>- internalUser && (_prefs.getBool("ls.pet_recognition_enabled") ?? false);-bool get qrFeatureEnabled => internalUser;Future<void> tryRefreshFlags() async {diff --git a/mobile/apps/photos/rust/src/ml/pet/align.rs b/mobile/apps/photos/rust/src/ml/pet/align.rsindex a49e76b5e1..b064ef92ea 100644--- a/mobile/apps/photos/rust/src/ml/pet/align.rs+++ b/mobile/apps/photos/rust/src/ml/pet/align.rs@@ -1,5 +1,7 @@+use fast_image_resize::{+ FilterType, PixelType, ResizeAlg, ResizeOptions, Resizer, images::Image as FirImage,+};use image::{ImageBuffer, Rgb, RgbImage};-use imageproc::geometric_transformations::{Interpolation, Projection, warp_into};use crate::ml::{error::{MlError, MlResult},@@ -8,30 +10,31 @@ use crate::ml::{const PET_FACE_CROP_SIZE: u32 = 224;+/// Minimum eye distance in pixels below which alignment is skipped.+const MIN_EYE_DISTANCE: f32 = 5.0;+/// Angle threshold in degrees; below this, skip rotation and just crop.+const ANGLE_SKIP_DEG: f32 = 1.0;+/// Expand factor applied to each side of the bounding box when cropping.+const CROP_EXPAND: f32 = 0.1;/// Run pet face alignment using 3-point landmarks (left_eye, right_eye, nose).///-/// For each detection:-/// 1. Compute rotation angle from the eye line-/// 2. Rotate image around eye midpoint-/// 3. Crop a square region centered on the face bounding box-/// 4. Resize to 224x224+/// Mirrors `pet_pipeline/detection.py` `_align_face()`:+/// 1. Skip if eye distance < 5 px+/// 2. If angle < 1Β°, crop bounding box directly (no rotation)+/// 3. Otherwise rotate around face center, then crop with 10% expand+/// 4. Resize to 224Γ224/// 5. Apply ImageNet normalization (CHW)-///-/// This mirrors `pet_pipeline/detection.py` `_align_face()`:-/// ```python-/// angle = np.degrees(np.arctan2(r_eye[1]-l_eye[1], r_eye[0]-l_eye[0]))-/// center = ((l_eye[0]+r_eye[0])//2, (l_eye[1]+r_eye[1])//2)-/// M = cv2.getRotationMatrix2D(center, angle, 1.0)-/// ```pub fn run_pet_face_alignment(file_id: i64,decoded: &DecodedImage,detections: &[PetFaceDetection],) -> MlResult<(Vec<Vec<f32>>, Vec<PetFaceResult>)> {let source = rgb_image_from_decoded(decoded)?;- let img_w = decoded.dimensions.width as f32;- let img_h = decoded.dimensions.height as f32;+ let img_w = decoded.dimensions.width;+ let img_h = decoded.dimensions.height;+ let img_wf = img_w as f32;+ let img_hf = img_h as f32;let mut aligned_inputs = Vec::with_capacity(detections.len());let mut face_results = Vec::with_capacity(detections.len());@@ -39,105 +42,91 @@ pub fn run_pet_face_alignment(for detection in detections {// Convert relative keypoints to absolutelet left_eye = [- detection.keypoints[0][0] * img_w,- detection.keypoints[0][1] * img_h,+ detection.keypoints[0][0] * img_wf,+ detection.keypoints[0][1] * img_hf,];let right_eye = [- detection.keypoints[1][0] * img_w,- detection.keypoints[1][1] * img_h,+ detection.keypoints[1][0] * img_wf,+ detection.keypoints[1][1] * img_hf,];- // Compute rotation angle from eye line- let dy = right_eye[1] - left_eye[1];let dx = right_eye[0] - left_eye[0];- let angle = dy.atan2(dx); // radians-- // Eye midpoint as rotation center- let center_x = (left_eye[0] + right_eye[0]) / 2.0;- let center_y = (left_eye[1] + right_eye[1]) / 2.0;+ let dy = right_eye[1] - left_eye[1];+ let eye_dist = (dx * dx + dy * dy).sqrt();- // Absolute bounding box- let box_x1 = (detection.box_xyxy[0] * img_w).max(0.0);- let box_y1 = (detection.box_xyxy[1] * img_h).max(0.0);- let box_x2 = (detection.box_xyxy[2] * img_w).min(img_w);- let box_y2 = (detection.box_xyxy[3] * img_h).min(img_h);-- // Square crop size: max of box width/height with some padding- let box_w = box_x2 - box_x1;- let box_h = box_y2 - box_y1;- let crop_size = box_w.max(box_h) * 1.3; // 30% padding like Python pipeline-- // Skip degenerate detections where the bounding box is too small- // to produce a valid affine transform (determinant = scale^2 ~ 0)- if crop_size < 1.0 {- eprintln!(- "Skipping pet face detection with degenerate bounding box (crop_size={:.2})",- crop_size- );+ // Skip if eyes are too close together+ if eye_dist < MIN_EYE_DISTANCE {continue;}- // Build rotation matrix (rotate then translate to center the crop)- let cos_a = angle.cos();- let sin_a = angle.sin();-- // The projection matrix maps OUTPUT coords to INPUT coords.- // We want: rotate by -angle around (center_x, center_y), then- // shift so that the crop center maps to (PET_FACE_CROP_SIZE/2, PET_FACE_CROP_SIZE/2).- let scale = crop_size / PET_FACE_CROP_SIZE as f32;- let half_out = PET_FACE_CROP_SIZE as f32 / 2.0;-- // Inverse transform: output -> input- let a00 = cos_a * scale;- let a01 = -sin_a * scale;- let a10 = sin_a * scale;- let a11 = cos_a * scale;- let tx = center_x - half_out * a00 - half_out * a01;- let ty = center_y - half_out * a10 - half_out * a11;-- let projection = match Projection::from_matrix([- a00, a01, tx,- a10, a11, ty,- 0.0, 0.0, 1.0,- ]) {- Some(p) => p,- None => {- eprintln!(- "Skipping pet face with non-invertible projection matrix (scale={:.4}, crop_size={:.2})",- scale, crop_size- );+ // Absolute bounding box (clamped)+ let box_x1 = (detection.box_xyxy[0] * img_wf).max(0.0) as i32;+ let box_y1 = (detection.box_xyxy[1] * img_hf).max(0.0) as i32;+ let box_x2 = (detection.box_xyxy[2] * img_wf).min(img_wf) as i32;+ let box_y2 = (detection.box_xyxy[3] * img_hf).min(img_hf) as i32;++ let angle_deg = dy.atan2(dx).to_degrees();+ let angle_rad = dy.atan2(dx);++ let aligned_rgb = if angle_deg.abs() < ANGLE_SKIP_DEG {+ // No rotation needed β just crop the bounding box directly+ let cx1 = box_x1.max(0) as u32;+ let cy1 = box_y1.max(0) as u32;+ let cx2 = (box_x2 as u32).min(img_w);+ let cy2 = (box_y2 as u32).min(img_h);+ let crop_w = cx2.saturating_sub(cx1);+ let crop_h = cy2.saturating_sub(cy1);+ if crop_w == 0 || crop_h == 0 {continue;}+ crop_and_resize_rgb(&source, cx1, cy1, crop_w, crop_h)?+ } else {+ // Rotate around face center, then crop with expand+ let face_cx = (box_x1 + box_x2) as f64 / 2.0;+ let face_cy = (box_y1 + box_y2) as f64 / 2.0;++ let rotated = rotate_around_center(+ &source,+ angle_rad as f64,+ face_cx,+ face_cy,+ );++ // Crop with 10% expand on each side+ let bw = (box_x2 - box_x1) as f32;+ let bh = (box_y2 - box_y1) as f32;+ let nx1 = (box_x1 as f32 - bw * CROP_EXPAND).max(0.0) as u32;+ let ny1 = (box_y1 as f32 - bh * CROP_EXPAND).max(0.0) as u32;+ let nx2 = (box_x2 as f32 + bw * CROP_EXPAND).min(img_wf) as u32;+ let ny2 = (box_y2 as f32 + bh * CROP_EXPAND).min(img_hf) as u32;+ let crop_w = nx2.saturating_sub(nx1);+ let crop_h = ny2.saturating_sub(ny1);+ if crop_w == 0 || crop_h == 0 {+ continue;+ }+ crop_and_resize_rgb(&rotated, nx1, ny1, crop_w, crop_h)?};- let mut output = RgbImage::from_pixel(- PET_FACE_CROP_SIZE,- PET_FACE_CROP_SIZE,- Rgb([114, 114, 114]),- );- warp_into(- &source,- &projection,- Interpolation::Bicubic,- Rgb([114, 114, 114]),- &mut output,- );-- // Convert aligned face to ImageNet-normalized CHW tensor- let normalized = aligned_face_to_tensor(&output);+ let normalized = aligned_face_to_tensor(&aligned_rgb);let pet_face_id = to_face_id(file_id, detection.box_xyxy);+ let center_x = (left_eye[0] + right_eye[0]) / 2.0;+ let center_y = (left_eye[1] + right_eye[1]) / 2.0;+ let box_w = (box_x2 - box_x1) as f32;+ let box_h = (box_y2 - box_y1) as f32;+ let crop_size = box_w.max(box_h) * (1.0 + 2.0 * CROP_EXPAND);+let alignment = PetAlignmentResult {center: [center_x, center_y],- angle,+ angle: angle_rad,crop_size,};aligned_inputs.push(normalized);face_results.push(PetFaceResult {detection: detection.clone(),- species: 0, // will be set after species detection+ species: 0, // will be set after embeddingface_embedding: Vec::new(),pet_face_id,alignment,@@ -147,6 +136,99 @@ pub fn run_pet_face_alignment(Ok((aligned_inputs, face_results))}+/// Rotate an image around a center point using bilinear interpolation+/// with BORDER_REPLICATE behaviour (clamp to nearest edge pixel).+fn rotate_around_center(+ source: &RgbImage,+ angle_rad: f64,+ cx: f64,+ cy: f64,+) -> RgbImage {+ let w = source.width();+ let h = source.height();+ let cos_a = angle_rad.cos();+ let sin_a = angle_rad.sin();++ // Build forward rotation matrix (output -> input):+ // x_in = cos_a * (x_out - cx) + sin_a * (y_out - cy) + cx+ // y_in = -sin_a * (x_out - cx) + cos_a * (y_out - cy) + cy++ let mut output = RgbImage::new(w, h);+ let w_f = w as f64;+ let h_f = h as f64;++ for out_y in 0..h {+ for out_x in 0..w {+ let dx = out_x as f64 - cx;+ let dy = out_y as f64 - cy;+ let src_x = cos_a * dx + sin_a * dy + cx;+ let src_y = -sin_a * dx + cos_a * dy + cy;++ // BORDER_REPLICATE: clamp to valid range+ let sx = src_x.max(0.0).min(w_f - 1.0);+ let sy = src_y.max(0.0).min(h_f - 1.0);++ // Bilinear interpolation+ let x0 = sx.floor() as u32;+ let y0 = sy.floor() as u32;+ let x1 = (x0 + 1).min(w - 1);+ let y1 = (y0 + 1).min(h - 1);+ let fx = (sx - sx.floor()) as f32;+ let fy = (sy - sy.floor()) as f32;++ let p00 = source.get_pixel(x0, y0).0;+ let p10 = source.get_pixel(x1, y0).0;+ let p01 = source.get_pixel(x0, y1).0;+ let p11 = source.get_pixel(x1, y1).0;++ let mut px = [0u8; 3];+ for c in 0..3 {+ let v = p00[c] as f32 * (1.0 - fx) * (1.0 - fy)+ + p10[c] as f32 * fx * (1.0 - fy)+ + p01[c] as f32 * (1.0 - fx) * fy+ + p11[c] as f32 * fx * fy;+ px[c] = v.round().max(0.0).min(255.0) as u8;+ }+ output.put_pixel(out_x, out_y, Rgb(px));+ }+ }++ output+}++/// Crop a region from an RGB image and resize to 224Γ224 using bilinear interpolation.+fn crop_and_resize_rgb(+ source: &RgbImage,+ x: u32,+ y: u32,+ w: u32,+ h: u32,+) -> MlResult<RgbImage> {+ // Extract crop bytes+ let src_w = source.width();+ let mut crop_bytes = Vec::with_capacity((w * h * 3) as usize);+ for row in y..(y + h) {+ for col in x..(x + w) {+ let px = source.get_pixel(col.min(src_w - 1), row.min(source.height() - 1)).0;+ crop_bytes.extend_from_slice(&px);+ }+ }++ let src_img = FirImage::from_vec_u8(w, h, crop_bytes, PixelType::U8x3)+ .map_err(|e| MlError::Preprocess(format!("FIR source: {e}")))?;++ let mut dst_img = FirImage::new(PET_FACE_CROP_SIZE, PET_FACE_CROP_SIZE, PixelType::U8x3);+ let mut resizer = Resizer::new();+ let opts = ResizeOptions::new().resize_alg(ResizeAlg::Interpolation(FilterType::Bilinear));+ resizer+ .resize(&src_img, &mut dst_img, Some(&opts))+ .map_err(|e| MlError::Preprocess(format!("FIR resize: {e}")))?;++ let buf = dst_img.into_vec();+ ImageBuffer::<Rgb<u8>, _>::from_raw(PET_FACE_CROP_SIZE, PET_FACE_CROP_SIZE, buf)+ .ok_or_else(|| MlError::Preprocess("failed to build aligned face image".to_string()))+}+fn rgb_image_from_decoded(decoded: &DecodedImage) -> MlResult<RgbImage> {ImageBuffer::<Rgb<u8>, _>::from_raw(decoded.dimensions.width,diff --git a/mobile/apps/photos/rust/src/ml/pet/detect.rs b/mobile/apps/photos/rust/src/ml/pet/detect.rsindex 428650ee7e..dcbe4759f1 100644--- a/mobile/apps/photos/rust/src/ml/pet/detect.rs+++ b/mobile/apps/photos/rust/src/ml/pet/detect.rs@@ -109,12 +109,12 @@ pub fn run_pet_face_detection(pad_top,);- // For a 2-class model (row_len >= 13): row[11] = dog score,- // row[12] = cat score. Pick argmax.+ // For a 2-class model (row_len >= 13): row[11] = cat score,+ // row[12] = dog score. Pick argmax and map to 0=dog, 1=cat.// For a 1-class model (row_len == 12): row[11] is the single class// score; class is always 0 (dog).let class_id: u8 = if row_len >= 13 {- if row[12] > row[11] { 1 } else { 0 }+ if row[12] > row[11] { 0 } else { 1 }} else {0};