Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Add pet face and body detection, alignment, and embedding pipeline

Amrithesh Kakkoth Ente18a5b8baf968
diff --git a/mobile/apps/photos/rust/src/ml/pet/align.rs b/mobile/apps/photos/rust/src/ml/pet/align.rs
new file mode 100644
index 0000000000..a49e76b5e1
--- /dev/null
+++ b/mobile/apps/photos/rust/src/ml/pet/align.rs
@@ -0,0 +1,184 @@
+use image::{ImageBuffer, Rgb, RgbImage};
+use imageproc::geometric_transformations::{Interpolation, Projection, warp_into};
+
+use crate::ml::{
+ error::{MlError, MlResult},
+ types::{DecodedImage, PetAlignmentResult, PetFaceDetection, PetFaceResult, to_face_id},
+};
+
+
+const PET_FACE_CROP_SIZE: u32 = 224;
+
+/// 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
+/// 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 mut aligned_inputs = Vec::with_capacity(detections.len());
+ let mut face_results = Vec::with_capacity(detections.len());
+
+ for detection in detections {
+ // Convert relative keypoints to absolute
+ let left_eye = [
+ detection.keypoints[0][0] * img_w,
+ detection.keypoints[0][1] * img_h,
+ ];
+ let right_eye = [
+ detection.keypoints[1][0] * img_w,
+ detection.keypoints[1][1] * img_h,
+ ];
+
+ // 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;
+
+ // 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
+ );
+ 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
+ );
+ continue;
+ }
+ };
+
+ 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 pet_face_id = to_face_id(file_id, detection.box_xyxy);
+
+ let alignment = PetAlignmentResult {
+ center: [center_x, center_y],
+ angle,
+ crop_size,
+ };
+
+ aligned_inputs.push(normalized);
+ face_results.push(PetFaceResult {
+ detection: detection.clone(),
+ species: 0, // will be set after species detection
+ face_embedding: Vec::new(),
+ pet_face_id,
+ alignment,
+ });
+ }
+
+ Ok((aligned_inputs, face_results))
+}
+
+fn rgb_image_from_decoded(decoded: &DecodedImage) -> MlResult<RgbImage> {
+ ImageBuffer::<Rgb<u8>, _>::from_raw(
+ decoded.dimensions.width,
+ decoded.dimensions.height,
+ decoded.rgb.clone(),
+ )
+ .ok_or_else(|| MlError::Preprocess("failed to build RGB source image for pet alignment".to_string()))
+}
+
+/// Convert an aligned pet face image to ImageNet-normalized CHW tensor.
+fn aligned_face_to_tensor(face_image: &RgbImage) -> Vec<f32> {
+ let w = face_image.width() as usize;
+ let h = face_image.height() as usize;
+ let pixel_count = w * h;
+ let mut output = vec![0.0f32; 3 * pixel_count];
+
+ const MEAN: [f32; 3] = [0.485, 0.456, 0.406];
+ const STD: [f32; 3] = [0.229, 0.224, 0.225];
+
+ let r_off = 0;
+ let g_off = pixel_count;
+ let b_off = 2 * pixel_count;
+
+ for y in 0..h {
+ for x in 0..w {
+ let px = face_image.get_pixel(x as u32, y as u32).0;
+ let idx = y * w + x;
+ output[r_off + idx] = (px[0] as f32 / 255.0 - MEAN[0]) / STD[0];
+ output[g_off + idx] = (px[1] as f32 / 255.0 - MEAN[1]) / STD[1];
+ output[b_off + idx] = (px[2] as f32 / 255.0 - MEAN[2]) / STD[2];
+ }
+ }
+
+ output
+}
diff --git a/mobile/apps/photos/rust/src/ml/pet/detect.rs b/mobile/apps/photos/rust/src/ml/pet/detect.rs
new file mode 100644
index 0000000000..04f3ac1376
--- /dev/null
+++ b/mobile/apps/photos/rust/src/ml/pet/detect.rs
@@ -0,0 +1,342 @@
+use crate::ml::{
+ error::{MlError, MlResult},
+ onnx, preprocess,
+ runtime::MlRuntime,
+ types::{DecodedImage, PetFaceDetection, PetBodyDetection},
+};
+
+const INPUT_WIDTH: f32 = 640.0;
+const INPUT_HEIGHT: f32 = 640.0;
+
+// Pet face detection thresholds (from Python config)
+const PET_FACE_IOU_THRESHOLD: f32 = 0.5;
+const PET_FACE_MIN_SCORE: f32 = 0.3;
+
+// Body detection thresholds
+const BODY_IOU_THRESHOLD: f32 = 0.5;
+const BODY_MIN_SCORE: f32 = 0.3;
+
+// COCO class IDs
+const COCO_CAT: u8 = 15;
+const COCO_DOG: u8 = 16;
+
+/// Run pet face detection using YOLOv5-face model with 3 keypoints.
+///
+/// Output format per row: [x, y, w, h, obj_conf, lx, ly, rx, ry, nx, ny, ...]
+/// 3 keypoints: left_eye, right_eye, nose (6 values for coords).
+///
+/// This mirrors `pet_pipeline/detection.py` `FaceDetector.detect()`.
+pub fn run_pet_face_detection(
+ runtime: &mut MlRuntime,
+ decoded: &DecodedImage,
+) -> MlResult<Vec<PetFaceDetection>> {
+ let (input, scaled_width, scaled_height, pad_left, pad_top) =
+ preprocess::preprocess_yolo(decoded)?;
+
+ let pet_face_detection = runtime.pet_face_detection_session_mut()?;
+ let (output_shape, output_data) = onnx::run_f32(
+ pet_face_detection,
+ input,
+ vec![1, 3, INPUT_HEIGHT as i64, INPUT_WIDTH as i64],
+ )?;
+
+ // Row format: [x, y, w, h, obj_conf, lx, ly, rx, ry, nx, ny, cls_conf...]
+ // For 2-class model (cat/dog): row_len = 4 + 1 + 6 + 2 = 13
+ // For 1-class model: row_len = 4 + 1 + 6 + 1 = 12
+ // Use the output shape's last dimension to determine row length reliably.
+ let row_len = if output_shape.len() >= 2 {
+ *output_shape.last().unwrap() as usize
+ } else if output_shape.len() == 1 {
+ // Flat output: total_elements, must infer row_len
+ // Try common sizes: 13 (2-class), 12 (1-class), 11 (no class)
+ let total = output_data.len();
+ if total % 13 == 0 { 13 }
+ else if total % 12 == 0 { 12 }
+ else if total % 11 == 0 { 11 }
+ else {
+ return Err(MlError::Postprocess(format!(
+ "unexpected pet face detector output size: {} (shape: {:?})",
+ total, output_shape
+ )));
+ }
+ } else {
+ return Err(MlError::Postprocess(
+ "pet face detector output shape is empty".to_string(),
+ ));
+ };
+ if row_len < 11 || output_data.len() < row_len {
+ return Err(MlError::Postprocess(format!(
+ "pet face detector row_len={} too small or output too short (len={})",
+ row_len, output_data.len()
+ )));
+ }
+
+ let detection_rows = output_data.len() / row_len;
+ let mut detections = Vec::with_capacity(detection_rows);
+
+ for i in 0..detection_rows {
+ let start = i * row_len;
+ let row = &output_data[start..(start + row_len)];
+ let score = row[4];
+ if score < PET_FACE_MIN_SCORE {
+ continue;
+ }
+
+ let x_min_abs = row[0] - row[2] / 2.0;
+ let y_min_abs = row[1] - row[3] / 2.0;
+ let x_max_abs = row[0] + row[2] / 2.0;
+ let y_max_abs = row[1] + row[3] / 2.0;
+
+ let mut box_xyxy = [
+ x_min_abs / INPUT_WIDTH,
+ y_min_abs / INPUT_HEIGHT,
+ x_max_abs / INPUT_WIDTH,
+ y_max_abs / INPUT_HEIGHT,
+ ];
+
+ // 3 keypoints: left_eye, right_eye, nose
+ let mut keypoints = [
+ [row[5] / INPUT_WIDTH, row[6] / INPUT_HEIGHT],
+ [row[7] / INPUT_WIDTH, row[8] / INPUT_HEIGHT],
+ [row[9] / INPUT_WIDTH, row[10] / INPUT_HEIGHT],
+ ];
+
+ correct_for_maintained_aspect_ratio_3kp(
+ &mut box_xyxy,
+ &mut keypoints,
+ scaled_width,
+ scaled_height,
+ pad_left,
+ pad_top,
+ );
+
+ detections.push(PetFaceDetection {
+ score,
+ box_xyxy,
+ keypoints,
+ });
+ }
+
+ Ok(naive_nms_pet_face(detections, PET_FACE_IOU_THRESHOLD))
+}
+
+/// Run pet body detection using YOLOv5n model.
+///
+/// Filters detections by COCO class 15 (cat) or 16 (dog).
+/// Returns the best detection per species class found.
+///
+/// This mirrors `pet_pipeline/detection.py` `BodyDetector.detect()`.
+pub fn run_pet_body_detection(
+ runtime: &mut MlRuntime,
+ decoded: &DecodedImage,
+) -> MlResult<Vec<PetBodyDetection>> {
+ let (input, scaled_width, scaled_height, pad_left, pad_top) =
+ preprocess::preprocess_yolo(decoded)?;
+
+ let body_detection = runtime.pet_body_detection_session_mut()?;
+ let (_output_shape, output_data) = onnx::run_f32(
+ body_detection,
+ input,
+ vec![1, 3, INPUT_HEIGHT as i64, INPUT_WIDTH as i64],
+ )?;
+
+ // YOLOv5 output format: [x, y, w, h, obj_conf, cls0, cls1, ..., cls79]
+ // Total columns: 4 + 1 + 80 = 85
+ let row_len = 85usize;
+ if output_data.len() < row_len {
+ return Ok(Vec::new());
+ }
+
+ let detection_rows = output_data.len() / row_len;
+ let mut detections = Vec::new();
+
+ for i in 0..detection_rows {
+ let start = i * row_len;
+ let row = &output_data[start..(start + row_len)];
+ let obj_conf = row[4];
+
+ // Check cat (class 15) and dog (class 16) scores
+ for &class_id in &[COCO_CAT, COCO_DOG] {
+ let class_score = row[5 + class_id as usize] * obj_conf;
+ if class_score < BODY_MIN_SCORE {
+ continue;
+ }
+
+ let x_min_abs = row[0] - row[2] / 2.0;
+ let y_min_abs = row[1] - row[3] / 2.0;
+ let x_max_abs = row[0] + row[2] / 2.0;
+ let y_max_abs = row[1] + row[3] / 2.0;
+
+ let mut box_xyxy = [
+ x_min_abs / INPUT_WIDTH,
+ y_min_abs / INPUT_HEIGHT,
+ x_max_abs / INPUT_WIDTH,
+ y_max_abs / INPUT_HEIGHT,
+ ];
+
+ correct_box_for_aspect_ratio(
+ &mut box_xyxy,
+ scaled_width,
+ scaled_height,
+ pad_left,
+ pad_top,
+ );
+
+ detections.push(PetBodyDetection {
+ score: class_score,
+ box_xyxy,
+ coco_class: class_id,
+ });
+ }
+ }
+
+ Ok(naive_nms_pet_body(detections, BODY_IOU_THRESHOLD))
+}
+
+/// Auto-detect which species is dominant in the body detections.
+///
+/// Returns 0 for dog, 1 for cat based on which class has more/higher confidence detections.
+pub fn detect_species(body_detections: &[PetBodyDetection]) -> u8 {
+ let mut dog_score: f32 = 0.0;
+ let mut cat_score: f32 = 0.0;
+
+ for det in body_detections {
+ match det.coco_class {
+ COCO_DOG => dog_score += det.score,
+ COCO_CAT => cat_score += det.score,
+ _ => {}
+ }
+ }
+
+ if cat_score > dog_score { 1 } else { 0 }
+}
+
+fn correct_for_maintained_aspect_ratio_3kp(
+ box_xyxy: &mut [f32; 4],
+ keypoints: &mut [[f32; 2]; 3],
+ scaled_width: usize,
+ scaled_height: usize,
+ pad_left: usize,
+ pad_top: usize,
+) {
+ if scaled_width == INPUT_WIDTH as usize
+ && scaled_height == INPUT_HEIGHT as usize
+ && pad_left == 0
+ && pad_top == 0
+ {
+ return;
+ }
+
+ let scaled_width = scaled_width as f32;
+ let scaled_height = scaled_height as f32;
+ let pad_left = pad_left as f32;
+ let pad_top = pad_top as f32;
+
+ let transform_x =
+ |x: f32| -> f32 { ((x * INPUT_WIDTH - pad_left) / scaled_width).clamp(0.0, 1.0) };
+ let transform_y =
+ |y: f32| -> f32 { ((y * INPUT_HEIGHT - pad_top) / scaled_height).clamp(0.0, 1.0) };
+
+ box_xyxy[0] = transform_x(box_xyxy[0]);
+ box_xyxy[1] = transform_y(box_xyxy[1]);
+ box_xyxy[2] = transform_x(box_xyxy[2]);
+ box_xyxy[3] = transform_y(box_xyxy[3]);
+
+ for point in keypoints.iter_mut() {
+ point[0] = transform_x(point[0]);
+ point[1] = transform_y(point[1]);
+ }
+}
+
+fn correct_box_for_aspect_ratio(
+ box_xyxy: &mut [f32; 4],
+ scaled_width: usize,
+ scaled_height: usize,
+ pad_left: usize,
+ pad_top: usize,
+) {
+ if scaled_width == INPUT_WIDTH as usize
+ && scaled_height == INPUT_HEIGHT as usize
+ && pad_left == 0
+ && pad_top == 0
+ {
+ return;
+ }
+
+ let scaled_width = scaled_width as f32;
+ let scaled_height = scaled_height as f32;
+ let pad_left = pad_left as f32;
+ let pad_top = pad_top as f32;
+
+ let transform_x =
+ |x: f32| -> f32 { ((x * INPUT_WIDTH - pad_left) / scaled_width).clamp(0.0, 1.0) };
+ let transform_y =
+ |y: f32| -> f32 { ((y * INPUT_HEIGHT - pad_top) / scaled_height).clamp(0.0, 1.0) };
+
+ box_xyxy[0] = transform_x(box_xyxy[0]);
+ box_xyxy[1] = transform_y(box_xyxy[1]);
+ box_xyxy[2] = transform_x(box_xyxy[2]);
+ box_xyxy[3] = transform_y(box_xyxy[3]);
+}
+
+fn calculate_iou_4(a: &[f32; 4], b: &[f32; 4]) -> f32 {
+ let area_a = (a[2] - a[0]).max(0.0) * (a[3] - a[1]).max(0.0);
+ let area_b = (b[2] - b[0]).max(0.0) * (b[3] - b[1]).max(0.0);
+
+ let ix1 = a[0].max(b[0]);
+ let iy1 = a[1].max(b[1]);
+ let ix2 = a[2].min(b[2]);
+ let iy2 = a[3].min(b[3]);
+
+ let iw = ix2 - ix1;
+ let ih = iy2 - iy1;
+ if iw < 0.0 || ih < 0.0 {
+ return 0.0;
+ }
+
+ let inter = iw * ih;
+ let union = area_a + area_b - inter;
+ if union <= 0.0 { 0.0 } else { inter / union }
+}
+
+fn naive_nms_pet_face(
+ mut detections: Vec<PetFaceDetection>,
+ iou_threshold: f32,
+) -> Vec<PetFaceDetection> {
+ detections.sort_by(|a, b| b.score.total_cmp(&a.score));
+ let mut i = 0usize;
+ while i + 1 < detections.len() {
+ let mut j = i + 1;
+ while j < detections.len() {
+ let iou = calculate_iou_4(&detections[i].box_xyxy, &detections[j].box_xyxy);
+ if iou >= iou_threshold {
+ detections.remove(j);
+ } else {
+ j += 1;
+ }
+ }
+ i += 1;
+ }
+ detections
+}
+
+fn naive_nms_pet_body(
+ mut detections: Vec<PetBodyDetection>,
+ iou_threshold: f32,
+) -> Vec<PetBodyDetection> {
+ detections.sort_by(|a, b| b.score.total_cmp(&a.score));
+ let mut i = 0usize;
+ while i + 1 < detections.len() {
+ let mut j = i + 1;
+ while j < detections.len() {
+ let iou = calculate_iou_4(&detections[i].box_xyxy, &detections[j].box_xyxy);
+ if iou >= iou_threshold {
+ detections.remove(j);
+ } else {
+ j += 1;
+ }
+ }
+ i += 1;
+ }
+ detections
+}
diff --git a/mobile/apps/photos/rust/src/ml/pet/embed.rs b/mobile/apps/photos/rust/src/ml/pet/embed.rs
new file mode 100644
index 0000000000..8c89d49e3e
--- /dev/null
+++ b/mobile/apps/photos/rust/src/ml/pet/embed.rs
@@ -0,0 +1,148 @@
+use crate::ml::{
+ error::{MlError, MlResult},
+ onnx,
+ runtime::MlRuntime,
+ types::{DecodedImage, PetBodyResult, PetFaceResult},
+};
+
+use super::preprocess::{extract_crop, preprocess_pet_embedding};
+
+const FACE_EMBED_INPUT_SIZE: i64 = 224;
+const BODY_EMBED_INPUT_SIZE: i64 = 224;
+const FACE_EMBED_CHANNELS: i64 = 3;
+const BODY_EMBED_CHANNELS: i64 = 3;
+
+/// Run pet face embedding on aligned face inputs.
+///
+/// The species parameter (0=dog, 1=cat) selects the model to use.
+///
+/// Input per face: CHW float32 of shape [1, 3, 224, 224], ImageNet-normalized.
+/// Output: L2-normalized embedding vector (128-d for BYOL).
+///
+/// This mirrors `pet_pipeline/embedding.py` `Embedder.embed_face()`.
+pub fn run_pet_face_embedding(
+ runtime: &mut MlRuntime,
+ aligned_faces: &[Vec<f32>],
+ face_results: &mut [PetFaceResult],
+ species: u8,
+) -> MlResult<()> {
+ if aligned_faces.is_empty() {
+ return Ok(());
+ }
+ if aligned_faces.len() != face_results.len() {
+ return Err(MlError::Postprocess(format!(
+ "aligned pet faces count ({}) does not match face result count ({})",
+ aligned_faces.len(),
+ face_results.len()
+ )));
+ }
+
+ let per_face_len = (FACE_EMBED_INPUT_SIZE * FACE_EMBED_INPUT_SIZE * FACE_EMBED_CHANNELS) as usize;
+ let mut input = Vec::with_capacity(per_face_len * aligned_faces.len());
+ for aligned in aligned_faces {
+ if aligned.len() != per_face_len {
+ return Err(MlError::Preprocess(format!(
+ "aligned pet face tensor length {} does not match expected {}",
+ aligned.len(),
+ per_face_len
+ )));
+ }
+ input.extend_from_slice(aligned);
+ }
+
+ let session = if species == 0 {
+ runtime.pet_face_embedding_dog_session_mut()?
+ } else {
+ runtime.pet_face_embedding_cat_session_mut()?
+ };
+
+ let (shape, output) = onnx::run_f32(
+ session,
+ input,
+ vec![
+ aligned_faces.len() as i64,
+ FACE_EMBED_CHANNELS,
+ FACE_EMBED_INPUT_SIZE,
+ FACE_EMBED_INPUT_SIZE,
+ ],
+ )?;
+
+ if shape.is_empty() {
+ return Err(MlError::Postprocess(
+ "pet face embedding output shape is empty".to_string(),
+ ));
+ }
+ let batch = shape[0] as usize;
+ if batch != face_results.len() {
+ return Err(MlError::Postprocess(format!(
+ "pet face embedding batch mismatch: output={batch}, expected={}",
+ face_results.len()
+ )));
+ }
+ let embedding_size = output.len() / batch;
+
+ for (idx, face_result) in face_results.iter_mut().enumerate() {
+ let start = idx * embedding_size;
+ let mut embedding = output[start..(start + embedding_size)].to_vec();
+ normalize_embedding(&mut embedding);
+ face_result.face_embedding = embedding;
+ face_result.species = species;
+ }
+
+ Ok(())
+}
+
+/// Run pet body embedding on cropped body regions.
+///
+/// For each body detection, extracts a crop, preprocesses with ImageNet
+/// normalization, and runs through the species-specific body embedding model.
+///
+/// This mirrors `pet_pipeline/embedding.py` `Embedder.embed_body()`.
+pub fn run_pet_body_embedding(
+ runtime: &mut MlRuntime,
+ decoded: &DecodedImage,
+ body_results: &mut [PetBodyResult],
+ species: u8,
+) -> MlResult<()> {
+ for body_result in body_results.iter_mut() {
+ let (crop_data, crop_w, crop_h) = extract_crop(decoded, &body_result.detection.box_xyxy)?;
+ let input = preprocess_pet_embedding(&crop_data, crop_w, crop_h)?;
+
+ let session = if species == 0 {
+ runtime.pet_body_embedding_dog_session_mut()?
+ } else {
+ runtime.pet_body_embedding_cat_session_mut()?
+ };
+
+ let (_shape, output) = onnx::run_f32(
+ session,
+ input,
+ vec![
+ 1,
+ BODY_EMBED_CHANNELS,
+ BODY_EMBED_INPUT_SIZE,
+ BODY_EMBED_INPUT_SIZE,
+ ],
+ )?;
+
+ let mut embedding = output;
+ normalize_embedding(&mut embedding);
+ body_result.body_embedding = embedding;
+ }
+
+ Ok(())
+}
+
+fn normalize_embedding(embedding: &mut [f32]) {
+ let mut norm = 0.0f32;
+ for value in embedding.iter() {
+ norm += value * value;
+ }
+ let norm = norm.sqrt();
+ if norm <= f32::EPSILON {
+ return;
+ }
+ for value in embedding.iter_mut() {
+ *value /= norm;
+ }
+}
diff --git a/mobile/apps/photos/rust/src/ml/pet/mod.rs b/mobile/apps/photos/rust/src/ml/pet/mod.rs
new file mode 100644
index 0000000000..de8d91a240
--- /dev/null
+++ b/mobile/apps/photos/rust/src/ml/pet/mod.rs
@@ -0,0 +1,4 @@
+pub mod align;
+pub mod detect;
+pub mod embed;
+pub mod preprocess;
diff --git a/mobile/apps/photos/rust/src/ml/pet/preprocess.rs b/mobile/apps/photos/rust/src/ml/pet/preprocess.rs
new file mode 100644
index 0000000000..5a6f6fb432
--- /dev/null
+++ b/mobile/apps/photos/rust/src/ml/pet/preprocess.rs
@@ -0,0 +1,116 @@
+use fast_image_resize::{
+ FilterType, PixelType, ResizeAlg, ResizeOptions, Resizer, images::Image as FirImage,
+};
+
+use crate::ml::{
+ error::{MlError, MlResult},
+ types::DecodedImage,
+};
+
+const PET_EMBED_INPUT_SIZE: usize = 224;
+
+// ImageNet normalization constants
+const IMAGENET_MEAN: [f32; 3] = [0.485, 0.456, 0.406];
+const IMAGENET_STD: [f32; 3] = [0.229, 0.224, 0.225];
+
+/// Preprocess a cropped pet face/body image for embedding extraction.
+///
+/// Steps:
+/// 1. Resize to 224x224 using bilinear interpolation
+/// 2. Normalize using ImageNet mean/std
+/// 3. Output CHW layout as float32
+///
+/// This mirrors the Python pipeline's preprocessing:
+/// ```python
+/// img = cv2.resize(crop, (224, 224))
+/// img = img / 255.0
+/// img = (img - IMAGENET_MEAN) / IMAGENET_STD
+/// img = img.transpose(2, 0, 1) # HWC -> CHW
+/// ```
+pub fn preprocess_pet_embedding(
+ rgb_crop: &[u8],
+ crop_width: u32,
+ crop_height: u32,
+) -> MlResult<Vec<f32>> {
+ if crop_width == 0 || crop_height == 0 {
+ return Err(MlError::Preprocess(
+ "crop dimensions cannot be zero".to_string(),
+ ));
+ }
+
+ let target_w = PET_EMBED_INPUT_SIZE as u32;
+ let target_h = PET_EMBED_INPUT_SIZE as u32;
+
+ let src_image = FirImage::from_vec_u8(crop_width, crop_height, rgb_crop.to_vec(), PixelType::U8x3)
+ .map_err(|e| MlError::Preprocess(format!("failed to create FIR source image: {e}")))?;
+
+ let mut resized_image = FirImage::new(target_w, target_h, PixelType::U8x3);
+ let mut resizer = Resizer::new();
+ let options = ResizeOptions::new().resize_alg(ResizeAlg::Interpolation(FilterType::Bilinear));
+ resizer
+ .resize(&src_image, &mut resized_image, Some(&options))
+ .map_err(|e| MlError::Preprocess(format!("failed to resize pet embedding input: {e}")))?;
+
+ let resized = resized_image.buffer();
+ let pixel_count = PET_EMBED_INPUT_SIZE * PET_EMBED_INPUT_SIZE;
+ let mut output = vec![0.0f32; 3 * pixel_count];
+
+ // CHW layout with ImageNet normalization
+ let r_offset = 0;
+ let g_offset = pixel_count;
+ let b_offset = 2 * pixel_count;
+
+ for y in 0..PET_EMBED_INPUT_SIZE {
+ for x in 0..PET_EMBED_INPUT_SIZE {
+ let src_idx = (y * PET_EMBED_INPUT_SIZE + x) * 3;
+ let dst_idx = y * PET_EMBED_INPUT_SIZE + x;
+
+ let r = resized[src_idx] as f32 / 255.0;
+ let g = resized[src_idx + 1] as f32 / 255.0;
+ let b = resized[src_idx + 2] as f32 / 255.0;
+
+ output[r_offset + dst_idx] = (r - IMAGENET_MEAN[0]) / IMAGENET_STD[0];
+ output[g_offset + dst_idx] = (g - IMAGENET_MEAN[1]) / IMAGENET_STD[1];
+ output[b_offset + dst_idx] = (b - IMAGENET_MEAN[2]) / IMAGENET_STD[2];
+ }
+ }
+
+ Ok(output)
+}
+
+/// Extract a cropped region from a decoded image given a bounding box.
+///
+/// The bounding box is in relative coordinates [0, 1].
+/// Returns the crop as RGB bytes and its dimensions.
+pub fn extract_crop(
+ decoded: &DecodedImage,
+ box_xyxy: &[f32; 4],
+) -> MlResult<(Vec<u8>, u32, u32)> {
+ let img_w = decoded.dimensions.width;
+ let img_h = decoded.dimensions.height;
+
+ let x1 = (box_xyxy[0] * img_w as f32).round().max(0.0) as u32;
+ let y1 = (box_xyxy[1] * img_h as f32).round().max(0.0) as u32;
+ let x2 = (box_xyxy[2] * img_w as f32).round().min(img_w as f32) as u32;
+ let y2 = (box_xyxy[3] * img_h as f32).round().min(img_h as f32) as u32;
+
+ let crop_w = x2.saturating_sub(x1);
+ let crop_h = y2.saturating_sub(y1);
+
+ if crop_w == 0 || crop_h == 0 {
+ return Err(MlError::Preprocess(
+ "crop region has zero area".to_string(),
+ ));
+ }
+
+ let mut crop = Vec::with_capacity((crop_w * crop_h * 3) as usize);
+ for row in y1..y2 {
+ let row_start = ((row * img_w + x1) * 3) as usize;
+ let row_end = ((row * img_w + x2) * 3) as usize;
+ if row_end <= decoded.rgb.len() {
+ crop.extend_from_slice(&decoded.rgb[row_start..row_end]);
+ }
+ }
+
+ Ok((crop, crop_w, crop_h))
+}