π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Refactor
laurenspriem2f778f024b23
diff --git a/rust/crates/photos/src/ml/clip/image.rs b/rust/crates/photos/src/ml/clip/image.rsindex 150cae192d..5750d08d39 100644--- a/rust/crates/photos/src/ml/clip/image.rs+++ b/rust/crates/photos/src/ml/clip/image.rs@@ -1,45 +1,28 @@use crate::ml::{- error::{MlError, MlResult},+ error::MlResult,onnx, preprocess,runtime::MlRuntimeView,types::{ClipResult, DecodedImage},};-pub fn run_clip_image(runtime: &MlRuntimeView<'_>, decoded: &DecodedImage) -> MlResult<ClipResult> {+use super::{CLIP_IMAGE_INPUT_SIZE, finish_embedding};++pub(crate) fn run_clip_image(+ runtime: &MlRuntimeView<'_>,+ decoded: &DecodedImage,+) -> MlResult<ClipResult> {let input = preprocess::preprocess_clip(decoded)?;let mut clip_image = runtime.clip_image_session()?;- let (shape, output) = onnx::run_f32(&mut clip_image, input, [1, 3, 256, 256])?;-- let mut embedding = if shape.len() == 2 {- if shape[0] != 1 {- return Err(MlError::Postprocess(format!(- "unexpected CLIP batch size in shape {:?}",- shape- )));- }- output- } else if shape.len() == 1 {- output- } else {- return Err(MlError::Postprocess(format!(- "unsupported CLIP output shape {:?}",- shape- )));- };- normalize_embedding(&mut embedding);- Ok(ClipResult { embedding })-}+ let (shape, output) = onnx::run_f32(+ &mut clip_image,+ input,+ [+ 1,+ 3,+ CLIP_IMAGE_INPUT_SIZE as i64,+ CLIP_IMAGE_INPUT_SIZE as i64,+ ],+ )?;-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;- }+ finish_embedding("CLIP", shape, output)}diff --git a/rust/crates/photos/src/ml/clip/mod.rs b/rust/crates/photos/src/ml/clip/mod.rsindex c539df6d30..3a6441e31d 100644--- a/rust/crates/photos/src/ml/clip/mod.rs+++ b/rust/crates/photos/src/ml/clip/mod.rs@@ -1,3 +1,42 @@-pub mod image;-pub mod text;-pub mod tokenizer;+mod image;+mod text;+mod tokenizer;++pub(super) use image::run_clip_image;+pub(super) use text::run_clip_text_query;+pub(super) use tokenizer::tokenize_clip_text;++use crate::ml::{+ error::{MlError, MlResult},+ postprocess::l2_normalize,+ types::ClipResult,+};++pub(super) const CLIP_IMAGE_INPUT_SIZE: usize = 256;+pub(super) const CLIP_TEXT_TOKEN_COUNT: usize = 77;++pub(super) fn finish_embedding(+ name: &str,+ shape: Vec<i64>,+ output: Vec<f32>,+) -> MlResult<ClipResult> {+ let mut embedding = if shape.len() == 2 {+ if shape[0] != 1 {+ return Err(MlError::Postprocess(format!(+ "unexpected {name} batch size in shape {:?}",+ shape+ )));+ }+ output+ } else if shape.len() == 1 {+ output+ } else {+ return Err(MlError::Postprocess(format!(+ "unsupported {name} output shape {:?}",+ shape+ )));+ };++ l2_normalize(&mut embedding, f32::EPSILON);+ Ok(ClipResult { embedding })+}diff --git a/rust/crates/photos/src/ml/clip/text.rs b/rust/crates/photos/src/ml/clip/text.rsindex 95b4bf29cf..a42db183d8 100644--- a/rust/crates/photos/src/ml/clip/text.rs+++ b/rust/crates/photos/src/ml/clip/text.rs@@ -6,9 +6,9 @@ use crate::ml::{types::ClipResult,};-const CLIP_TEXT_TOKEN_COUNT: usize = 77;+use super::{CLIP_TEXT_TOKEN_COUNT, finish_embedding};-pub fn run_clip_text(runtime: &MlRuntimeView<'_>, token_ids: &[i32]) -> MlResult<ClipResult> {+fn run_clip_text(runtime: &MlRuntimeView<'_>, token_ids: &[i32]) -> MlResult<ClipResult> {if token_ids.len() != CLIP_TEXT_TOKEN_COUNT {return Err(MlError::InvalidRequest(format!("clip text expects exactly {CLIP_TEXT_TOKEN_COUNT} tokens, got {}",@@ -17,34 +17,13 @@ pub fn run_clip_text(runtime: &MlRuntimeView<'_>, token_ids: &[i32]) -> MlResult}let mut clip_text = runtime.clip_text_session()?;- let (shape, output) = onnx::run_i32_f32(- &mut clip_text,- token_ids.to_vec(),- [1, CLIP_TEXT_TOKEN_COUNT as i64],- )?;+ let (shape, output) =+ onnx::run_i32_f32(&mut clip_text, token_ids, [1, CLIP_TEXT_TOKEN_COUNT as i64])?;- let mut embedding = if shape.len() == 2 {- if shape[0] != 1 {- return Err(MlError::Postprocess(format!(- "unexpected CLIP text batch size in shape {:?}",- shape- )));- }- output- } else if shape.len() == 1 {- output- } else {- return Err(MlError::Postprocess(format!(- "unsupported CLIP text output shape {:?}",- shape- )));- };-- normalize_embedding(&mut embedding);- Ok(ClipResult { embedding })+ finish_embedding("CLIP text", shape, output)}-pub fn run_clip_text_query(+pub(crate) fn run_clip_text_query(runtime: &MlRuntimeView<'_>,query: &str,vocab_path: &str,@@ -52,17 +31,3 @@ pub fn run_clip_text_query(let token_ids = tokenizer::tokenize_clip_text(query, vocab_path)?;run_clip_text(runtime, &token_ids)}--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/rust/crates/photos/src/ml/clip/tokenizer.rs b/rust/crates/photos/src/ml/clip/tokenizer.rsindex 49c3cf65f1..d544b9bf3c 100644--- a/rust/crates/photos/src/ml/clip/tokenizer.rs+++ b/rust/crates/photos/src/ml/clip/tokenizer.rs@@ -11,7 +11,8 @@ use regex::Regex;use crate::ml::error::{MlError, MlResult};-const CLIP_TEXT_TOKEN_COUNT: usize = 77;+use super::CLIP_TEXT_TOKEN_COUNT;+const BPE_MERGES_END_EXCLUSIVE: usize = 49152 - 256 - 2 + 1;static TOKEN_PATTERN: Lazy<Regex> = Lazy::new(|| {@@ -33,7 +34,7 @@ struct TokenizerState {static TOKENIZER_STATE: Lazy<Mutex<Option<TokenizerState>>> = Lazy::new(|| Mutex::new(None));-pub fn tokenize_clip_text(text: &str, vocab_path: &str) -> MlResult<Vec<i32>> {+pub(crate) fn tokenize_clip_text(text: &str, vocab_path: &str) -> MlResult<Vec<i32>> {let mut state = match TOKENIZER_STATE.lock() {Ok(guard) => guard,Err(poisoned) => {diff --git a/rust/crates/photos/src/ml/face/align.rs b/rust/crates/photos/src/ml/face/align.rsindex e9baf1bad6..55d3680eee 100644--- a/rust/crates/photos/src/ml/face/align.rs+++ b/rust/crates/photos/src/ml/face/align.rs@@ -7,7 +7,8 @@ use crate::ml::{types::{AlignmentResult, DecodedImage, FaceDetection, FaceResult, to_face_id},};-const FACE_SIZE: u32 = 112;+use super::FACE_INPUT_SIZE;+const LAPLACIAN_HARD_THRESHOLD: f32 = 10.0;const REMOVE_SIDE_COLUMNS: usize = 56;@@ -31,7 +32,7 @@ struct FaceDetectionAbsolute {keypoints: [[f32; 2]; 5],}-pub fn run_face_alignment(+pub(crate) fn run_face_alignment(file_id: i64,decoded: &mut DecodedImage,detections: Vec<FaceDetection>,@@ -218,7 +219,7 @@ fn warp_face_image(source: &RgbImage, affine_matrix: &[[f32; 3]; 3]) -> MlResulttransform[row][col] = if (value - 1.0).abs() <= f32::EPSILON {1.0} else {- value * FACE_SIZE as f32+ value * FACE_INPUT_SIZE as f32};}}@@ -236,7 +237,7 @@ fn warp_face_image(source: &RgbImage, affine_matrix: &[[f32; 3]; 3]) -> MlResult]).ok_or_else(|| MlError::Postprocess("invalid affine matrix projection".to_string()))?;- let mut output = RgbImage::from_pixel(FACE_SIZE, FACE_SIZE, Rgb([114, 114, 114]));+ let mut output = RgbImage::from_pixel(FACE_INPUT_SIZE, FACE_INPUT_SIZE, Rgb([114, 114, 114]));warp_into(source,&projection,@@ -248,9 +249,9 @@ fn warp_face_image(source: &RgbImage, affine_matrix: &[[f32; 3]; 3]) -> MlResult}fn normalize_face_rgb_for_mobilefacenet(face_image: &RgbImage) -> Vec<f32> {- let mut output = Vec::with_capacity((FACE_SIZE * FACE_SIZE * 3) as usize);- for y in 0..FACE_SIZE {- for x in 0..FACE_SIZE {+ let mut output = Vec::with_capacity((FACE_INPUT_SIZE * FACE_INPUT_SIZE * 3) as usize);+ for y in 0..FACE_INPUT_SIZE {+ for x in 0..FACE_INPUT_SIZE {let px = face_image.get_pixel(x, y).0;output.push(px[0] as f32 / 127.5 - 1.0);output.push(px[1] as f32 / 127.5 - 1.0);diff --git a/rust/crates/photos/src/ml/face/detect.rs b/rust/crates/photos/src/ml/face/detect.rsindex f8b5e53d65..ae9b33a656 100644--- a/rust/crates/photos/src/ml/face/detect.rs+++ b/rust/crates/photos/src/ml/face/detect.rs@@ -1,13 +1,11 @@use crate::ml::{error::{MlError, MlResult},onnx,- preprocess::YoloInput,+ preprocess::{YOLO_INPUT_SIZE, YoloInput},runtime::MlRuntimeView,types::FaceDetection,};-const INPUT_WIDTH: f32 = 640.0;-const INPUT_HEIGHT: f32 = 640.0;const IOU_THRESHOLD: f32 = 0.4;const MIN_SCORE_THRESHOLD: f32 = 0.5;@@ -19,7 +17,7 @@ pub(crate) fn run_face_detection(onnx::with_prepared_f32_output(&mut face_detection,&input.tensor,- [1, 3, INPUT_HEIGHT as i64, INPUT_WIDTH as i64],+ [1, 3, YOLO_INPUT_SIZE as i64, YOLO_INPUT_SIZE as i64],|_output_shape, output_data| postprocess_face_detections(output_data, input),)}@@ -51,27 +49,35 @@ fn postprocess_face_detections(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,+ x_min_abs / YOLO_INPUT_SIZE as f32,+ y_min_abs / YOLO_INPUT_SIZE as f32,+ x_max_abs / YOLO_INPUT_SIZE as f32,+ y_max_abs / YOLO_INPUT_SIZE as f32,];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],- [row[11] / INPUT_WIDTH, row[12] / INPUT_HEIGHT],- [row[13] / INPUT_WIDTH, row[14] / INPUT_HEIGHT],+ [+ row[5] / YOLO_INPUT_SIZE as f32,+ row[6] / YOLO_INPUT_SIZE as f32,+ ],+ [+ row[7] / YOLO_INPUT_SIZE as f32,+ row[8] / YOLO_INPUT_SIZE as f32,+ ],+ [+ row[9] / YOLO_INPUT_SIZE as f32,+ row[10] / YOLO_INPUT_SIZE as f32,+ ],+ [+ row[11] / YOLO_INPUT_SIZE as f32,+ row[12] / YOLO_INPUT_SIZE as f32,+ ],+ [+ row[13] / YOLO_INPUT_SIZE as f32,+ row[14] / YOLO_INPUT_SIZE as f32,+ ],];- correct_for_maintained_aspect_ratio(- &mut box_xyxy,- &mut keypoints,- input.scaled_width,- input.scaled_height,- input.pad_left,- input.pad_top,- );+ input.correct_box_and_keypoints(&mut box_xyxy, &mut keypoints);detections.push(FaceDetection {score,@@ -83,43 +89,6 @@ fn postprocess_face_detections(Ok(naive_non_max_suppression(detections, IOU_THRESHOLD))}-fn correct_for_maintained_aspect_ratio(- box_xyxy: &mut [f32; 4],- keypoints: &mut [[f32; 2]; 5],- 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 naive_non_max_suppression(mut detections: Vec<FaceDetection>,iou_threshold: f32,diff --git a/rust/crates/photos/src/ml/face/embed.rs b/rust/crates/photos/src/ml/face/embed.rsindex 37aa1938e3..dae858dc3c 100644--- a/rust/crates/photos/src/ml/face/embed.rs+++ b/rust/crates/photos/src/ml/face/embed.rs@@ -1,15 +1,16 @@use crate::ml::{error::{MlError, MlResult},onnx,+ postprocess::l2_normalize,runtime::MlRuntimeView,types::FaceResult,};-const FACE_INPUT_WIDTH: i64 = 112;-const FACE_INPUT_HEIGHT: i64 = 112;+use super::FACE_INPUT_SIZE;+const FACE_INPUT_CHANNELS: i64 = 3;-pub fn run_face_embedding(+pub(crate) fn run_face_embedding(runtime: &MlRuntimeView<'_>,aligned_faces: Vec<Vec<f32>>,face_results: &mut [FaceResult],@@ -25,7 +26,8 @@ pub fn run_face_embedding()));}- let expected_input_len = (FACE_INPUT_WIDTH * FACE_INPUT_HEIGHT * FACE_INPUT_CHANNELS) as usize;+ let face_input_size = FACE_INPUT_SIZE as i64;+ let expected_input_len = (face_input_size * face_input_size * FACE_INPUT_CHANNELS) as usize;let mut face_embedding = runtime.face_embedding_session()?;for (aligned, face_result) in aligned_faces.into_iter().zip(face_results.iter_mut()) {if aligned.len() != expected_input_len {@@ -39,7 +41,7 @@ pub fn run_face_embedding(let (shape, mut embedding) = onnx::run_f32(&mut face_embedding,aligned,- [1, FACE_INPUT_HEIGHT, FACE_INPUT_WIDTH, FACE_INPUT_CHANNELS],+ [1, face_input_size, face_input_size, FACE_INPUT_CHANNELS],)?;if shape.first() != Some(&1) || embedding.is_empty() {return Err(MlError::Postprocess(format!(@@ -48,23 +50,9 @@ pub fn run_face_embedding(embedding.len())));}- normalize_embedding(&mut embedding);+ l2_normalize(&mut embedding, f32::EPSILON);face_result.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/rust/crates/photos/src/ml/face/mod.rs b/rust/crates/photos/src/ml/face/mod.rsindex 88903b37eb..cdef015e7a 100644--- a/rust/crates/photos/src/ml/face/mod.rs+++ b/rust/crates/photos/src/ml/face/mod.rs@@ -1,4 +1,10 @@-pub mod align;-pub mod detect;-pub mod embed;+mod align;+mod detect;+mod embed;pub mod thumbnail;++pub(crate) use align::run_face_alignment;+pub(crate) use detect::run_face_detection;+pub(crate) use embed::run_face_embedding;++const FACE_INPUT_SIZE: u32 = 112;diff --git a/rust/crates/photos/src/ml/indexing.rs b/rust/crates/photos/src/ml/indexing.rsindex 8527bd97b6..7108350977 100644--- a/rust/crates/photos/src/ml/indexing.rs+++ b/rust/crates/photos/src/ml/indexing.rs@@ -1,14 +1,10 @@use crate::ml::{- clip::{- image::run_clip_image, text::run_clip_text_query,- tokenizer::tokenize_clip_text as tokenize_clip_text_impl,- },+ clip::{run_clip_image, run_clip_text_query, tokenize_clip_text as tokenize_clip_text_impl},error::{MlError, MlResult},- face::{align::run_face_alignment, detect::run_face_detection, embed::run_face_embedding},+ face::{run_face_alignment, run_face_detection, run_face_embedding},pet::{- align::run_pet_face_alignment,- detect::{run_pet_body_detection, run_pet_face_detection},- embed::{run_pet_body_embedding, run_pet_face_embedding},+ run_pet_body_detection, run_pet_body_embedding, run_pet_face_alignment,+ run_pet_face_detection, run_pet_face_embedding,},preprocess,runtime::{self, ModelPaths},@@ -109,7 +105,7 @@ pub fn analyze_image(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {let pet_face_results = if !pet_face_detections.is_empty() {let (aligned, mut pet_results) =- run_pet_face_alignment(file_id, &decoded, &pet_face_detections)?;+ run_pet_face_alignment(file_id, &decoded, pet_face_detections)?;run_pet_face_embedding(runtime, aligned, &mut pet_results)?;pet_results} else {diff --git a/rust/crates/photos/src/ml/mod.rs b/rust/crates/photos/src/ml/mod.rsindex 2d13e41afc..90dcc7acff 100644--- a/rust/crates/photos/src/ml/mod.rs+++ b/rust/crates/photos/src/ml/mod.rs@@ -1,10 +1,11 @@-pub mod clip;+mod clip;pub mod error;pub mod face;pub mod indexing;-pub mod onnx;-pub mod pet;-pub mod preprocess;+mod onnx;+mod pet;+mod postprocess;+mod preprocess;pub mod runtime;pub mod types;pub mod vector_db;diff --git a/rust/crates/photos/src/ml/onnx.rs b/rust/crates/photos/src/ml/onnx.rsindex 5faa34195b..39eae5aaa9 100644--- a/rust/crates/photos/src/ml/onnx.rs+++ b/rust/crates/photos/src/ml/onnx.rs@@ -176,7 +176,7 @@ fn session_expects_f16(session: &Session) -> bool {/// Run inference accepting f32 data and returning f32 results./// Automatically converts inputs/outputs for FP16 models.-pub fn run_f32<const N: usize>(+pub(crate) fn run_f32<const N: usize>(session: &mut Session,input: Vec<f32>,input_shape: [i64; N],@@ -243,12 +243,12 @@ pub(crate) fn with_prepared_f32_output<const N: usize, T>(}}-pub fn run_i32_f32<const N: usize>(+pub(crate) fn run_i32_f32<const N: usize>(session: &mut Session,- input: Vec<i32>,+ input: &[i32],input_shape: [i64; N],) -> MlResult<(Vec<i64>, Vec<f32>)> {- let input_tensor = Tensor::<i32>::from_array((input_shape, input))?;+ let input_tensor = TensorRef::<i32>::from_array_view((input_shape, input))?;let outputs = session.run(ort::inputs![input_tensor])?;if outputs.len() == 0 {return Err(MlError::Ort("missing first output tensor".to_string()));diff --git a/rust/crates/photos/src/ml/pet/align.rs b/rust/crates/photos/src/ml/pet/align.rsindex 5fff953f58..5d90eb924b 100644--- a/rust/crates/photos/src/ml/pet/align.rs+++ b/rust/crates/photos/src/ml/pet/align.rs@@ -6,11 +6,10 @@ use crate::ml::{};use super::{- embed::PetFaceEmbeddingInputs,- preprocess::{PixelCrop, RgbCropResizer, append_imagenet_tensor},+ PET_EMBEDDING_INPUT_SIZE, PET_SPECIES_CAT,+ preprocess::{PetFaceEmbeddingInputs, PixelCrop, RgbCropResizer, append_imagenet_tensor},};-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.@@ -29,7 +28,7 @@ const CROP_EXPAND: f32 = 0.1;pub(crate) fn run_pet_face_alignment(file_id: i64,decoded: &DecodedImage,- detections: &[PetFaceDetection],+ detections: Vec<PetFaceDetection>,) -> MlResult<(PetFaceEmbeddingInputs, Vec<PetFaceResult>)> {let img_w = decoded.dimensions.width;let img_h = decoded.dimensions.height;@@ -38,12 +37,12 @@ pub(crate) fn run_pet_face_alignment(let cat_capacity = detections.iter()- .filter(|detection| detection.class_id == 1)+ .filter(|detection| detection.class_id == PET_SPECIES_CAT).count();let dog_capacity = detections.len() - cat_capacity;let mut aligned_inputs = PetFaceEmbeddingInputs::new(dog_capacity, cat_capacity);let mut face_results = Vec::with_capacity(detections.len());- let mut crop_resizer = RgbCropResizer::new(PET_FACE_CROP_SIZE);+ let mut crop_resizer = RgbCropResizer::new(PET_EMBEDDING_INPUT_SIZE as u32);for detection in detections {// Convert relative keypoints to absolute@@ -148,8 +147,8 @@ pub(crate) fn run_pet_face_alignment(};face_results.push(PetFaceResult {- detection: detection.clone(),- species: 0, // will be set after embedding+ species: detection.class_id,+ detection,face_embedding: Vec::new(),pet_face_id,alignment,diff --git a/rust/crates/photos/src/ml/pet/detect.rs b/rust/crates/photos/src/ml/pet/detect.rsindex 1b12c88500..bc83442d87 100644--- a/rust/crates/photos/src/ml/pet/detect.rs+++ b/rust/crates/photos/src/ml/pet/detect.rs@@ -1,13 +1,12 @@use crate::ml::{error::{MlError, MlResult},onnx,- preprocess::YoloInput,+ preprocess::{YOLO_INPUT_SIZE, YoloInput},runtime::MlRuntimeView,types::{PetBodyDetection, PetFaceDetection},};-const INPUT_WIDTH: f32 = 640.0;-const INPUT_HEIGHT: f32 = 640.0;+use super::{COCO_CAT, COCO_DOG, PET_SPECIES_CAT, PET_SPECIES_DOG};// Pet face detection thresholds (from Python config)const PET_FACE_IOU_THRESHOLD: f32 = 0.5;@@ -17,10 +16,6 @@ const PET_FACE_MIN_SCORE: f32 = 0.3;const BODY_IOU_THRESHOLD: f32 = 0.5;const BODY_MIN_SCORE: f32 = 0.3;-// COCO class IDs (used by body detection)-const COCO_CAT: u8 = 15;-const COCO_DOG: u8 = 16;-// Species IDs used across both Rust and Dart:// 0 = dog (face detection class_id=0, COCO_DOG=16)// 1 = cat (face detection class_id=1, COCO_CAT=15)@@ -40,7 +35,7 @@ pub(crate) fn run_pet_face_detection(onnx::with_prepared_f32_output(&mut pet_face_detection,&input.tensor,- [1, 3, INPUT_HEIGHT as i64, INPUT_WIDTH as i64],+ [1, 3, YOLO_INPUT_SIZE as i64, YOLO_INPUT_SIZE as i64],|output_shape, output_data| {postprocess_pet_face_detections(output_shape, output_data, input)},@@ -113,36 +108,42 @@ fn postprocess_pet_face_detections(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,+ x_min_abs / YOLO_INPUT_SIZE as f32,+ y_min_abs / YOLO_INPUT_SIZE as f32,+ x_max_abs / YOLO_INPUT_SIZE as f32,+ y_max_abs / YOLO_INPUT_SIZE as f32,];// 3 keypoints: left_eye, right_eye, noselet 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],+ [+ row[5] / YOLO_INPUT_SIZE as f32,+ row[6] / YOLO_INPUT_SIZE as f32,+ ],+ [+ row[7] / YOLO_INPUT_SIZE as f32,+ row[8] / YOLO_INPUT_SIZE as f32,+ ],+ [+ row[9] / YOLO_INPUT_SIZE as f32,+ row[10] / YOLO_INPUT_SIZE as f32,+ ],];- correct_for_maintained_aspect_ratio_3kp(- &mut box_xyxy,- &mut keypoints,- input.scaled_width,- input.scaled_height,- input.pad_left,- input.pad_top,- );+ input.correct_box_and_keypoints(&mut box_xyxy, &mut keypoints);// 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] { 0 } else { 1 }+ if row[12] > row[11] {+ PET_SPECIES_DOG+ } else {+ PET_SPECIES_CAT+ }} else {- 0+ PET_SPECIES_DOG};detections.push(PetFaceDetection {@@ -170,7 +171,7 @@ pub(crate) fn run_pet_body_detection(onnx::with_prepared_f32_output(&mut body_detection,&input.tensor,- [1, 3, INPUT_HEIGHT as i64, INPUT_WIDTH as i64],+ [1, 3, YOLO_INPUT_SIZE as i64, YOLO_INPUT_SIZE as i64],|_output_shape, output_data| postprocess_pet_body_detections(output_data, input),)}@@ -218,19 +219,13 @@ fn postprocess_pet_body_detections(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,+ x_min_abs / YOLO_INPUT_SIZE as f32,+ y_min_abs / YOLO_INPUT_SIZE as f32,+ x_max_abs / YOLO_INPUT_SIZE as f32,+ y_max_abs / YOLO_INPUT_SIZE as f32,];- correct_box_for_aspect_ratio(- &mut box_xyxy,- input.scaled_width,- input.scaled_height,- input.pad_left,- input.pad_top,- );+ input.correct_box(&mut box_xyxy);detections.push(PetBodyDetection {score: class_score,@@ -242,68 +237,6 @@ fn postprocess_pet_body_detections(Ok(naive_nms_pet_body(detections, BODY_IOU_THRESHOLD))}-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 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,-) {- correct_box_for_aspect_ratio(box_xyxy, scaled_width, scaled_height, pad_left, pad_top);-- if scaled_width == INPUT_WIDTH as usize- && scaled_height == INPUT_HEIGHT as usize- && pad_left == 0- && pad_top == 0- {- return;- }-- let transform_x = |x: f32| -> f32 {- ((x * INPUT_WIDTH - pad_left as f32) / scaled_width as f32).clamp(0.0, 1.0)- };- let transform_y = |y: f32| -> f32 {- ((y * INPUT_HEIGHT - pad_top as f32) / scaled_height as f32).clamp(0.0, 1.0)- };-- for point in keypoints.iter_mut() {- point[0] = transform_x(point[0]);- point[1] = transform_y(point[1]);- }-}-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);diff --git a/rust/crates/photos/src/ml/pet/embed.rs b/rust/crates/photos/src/ml/pet/embed.rsindex fd6dadfd18..6f43099f8e 100644--- a/rust/crates/photos/src/ml/pet/embed.rs+++ b/rust/crates/photos/src/ml/pet/embed.rs@@ -1,58 +1,15 @@use crate::ml::{error::{MlError, MlResult},onnx,+ postprocess::l2_normalize,runtime::MlRuntimeView,types::{DecodedImage, PetBodyResult, PetFaceResult},};-use super::preprocess::PetEmbeddingPreprocessor;--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;--pub(super) struct IndexedEmbeddingBatch {- pub(super) indices: Vec<usize>,- pub(super) input: Vec<f32>,-}--impl IndexedEmbeddingBatch {- fn new(item_capacity: usize, floats_per_item: usize) -> Self {- Self {- indices: Vec::with_capacity(item_capacity),- input: Vec::with_capacity(item_capacity * floats_per_item),- }- }-- fn is_empty(&self) -> bool {- self.indices.is_empty()- }-}--pub(crate) struct PetFaceEmbeddingInputs {- pub(super) dog: IndexedEmbeddingBatch,- pub(super) cat: IndexedEmbeddingBatch,-}--impl PetFaceEmbeddingInputs {- pub(super) fn new(dog_capacity: usize, cat_capacity: usize) -> Self {- let floats_per_face =- (FACE_EMBED_INPUT_SIZE * FACE_EMBED_INPUT_SIZE * FACE_EMBED_CHANNELS) as usize;- Self {- dog: IndexedEmbeddingBatch::new(dog_capacity, floats_per_face),- cat: IndexedEmbeddingBatch::new(cat_capacity, floats_per_face),- }- }-- pub(super) fn batch_mut(&mut self, class_id: u8) -> &mut IndexedEmbeddingBatch {- if class_id == 1 {- &mut self.cat- } else {- &mut self.dog- }- }-}+use super::{+ COCO_CAT, PET_EMBEDDING_CHANNELS, PET_EMBEDDING_INPUT_SIZE, PET_SPECIES_CAT, PET_SPECIES_DOG,+ preprocess::{IndexedEmbeddingBatch, PetEmbeddingPreprocessor, PetFaceEmbeddingInputs},+};/// Run pet face embedding on aligned face inputs.///@@ -83,10 +40,12 @@ pub(crate) fn run_pet_face_embedding()));}- let per_face_len =- (FACE_EMBED_INPUT_SIZE * FACE_EMBED_INPUT_SIZE * FACE_EMBED_CHANNELS) as usize;+ let per_face_len = PET_EMBEDDING_INPUT_SIZE * PET_EMBEDDING_INPUT_SIZE * PET_EMBEDDING_CHANNELS;- for (species, batch) in [(0u8, aligned_faces.dog), (1u8, aligned_faces.cat)] {+ for (species, batch) in [+ (PET_SPECIES_DOG, aligned_faces.dog),+ (PET_SPECIES_CAT, aligned_faces.cat),+ ] {if batch.is_empty() {continue;}@@ -98,7 +57,7 @@ pub(crate) fn run_pet_face_embedding()));}- let mut session = if species == 0 {+ let mut session = if species == PET_SPECIES_DOG {runtime.pet_face_embedding_dog_session()?} else {runtime.pet_face_embedding_cat_session()?@@ -109,38 +68,20 @@ pub(crate) fn run_pet_face_embedding(batch.input,[batch.indices.len() as i64,- FACE_EMBED_CHANNELS,- FACE_EMBED_INPUT_SIZE,- FACE_EMBED_INPUT_SIZE,+ PET_EMBEDDING_CHANNELS as i64,+ PET_EMBEDDING_INPUT_SIZE as i64,+ PET_EMBEDDING_INPUT_SIZE as i64,],)?;- if shape.is_empty() {- return Err(MlError::Postprocess(- "pet face embedding output shape is empty".to_string(),- ));- }- let output_batch = shape[0] as usize;- if output_batch != batch.indices.len() {- return Err(MlError::Postprocess(format!(- "pet face embedding batch mismatch: output={output_batch}, expected={}",- batch.indices.len()- )));- }- let embedding_size = output.len() / output_batch;- if embedding_size == 0 || output.len() != output_batch * embedding_size {- return Err(MlError::Postprocess(format!(- "pet face embedding output not evenly divisible: len={}, batch={output_batch}",- output.len()- )));- }+ let embedding_size =+ validate_embedding_batch_output("face", &shape, output.len(), batch.indices.len())?;for (batch_idx, &orig_idx) in batch.indices.iter().enumerate() {let start = batch_idx * embedding_size;let mut embedding = output[start..(start + embedding_size)].to_vec();- normalize_embedding(&mut embedding);+ l2_normalize(&mut embedding, 1e-12);face_results[orig_idx].face_embedding = embedding;- face_results[orig_idx].species = species;}}@@ -163,15 +104,14 @@ pub(crate) fn run_pet_body_embedding(return Ok(());}- let per_body_len =- (BODY_EMBED_INPUT_SIZE * BODY_EMBED_INPUT_SIZE * BODY_EMBED_CHANNELS) as usize;+ let per_body_len = PET_EMBEDDING_INPUT_SIZE * PET_EMBEDDING_INPUT_SIZE * PET_EMBEDDING_CHANNELS;// Preprocess all crops and group by species.// Skip detections whose crop is invalid (e.g. zero-area edge boxes)// rather than aborting the whole image.let cat_count = body_results.iter()- .filter(|result| result.detection.coco_class == 15)+ .filter(|result| result.detection.coco_class == COCO_CAT).count();let dog_count = body_results.len() - cat_count;let mut dog_batch = IndexedEmbeddingBatch::new(dog_count, per_body_len);@@ -179,7 +119,7 @@ pub(crate) fn run_pet_body_embedding(let mut preprocessor = PetEmbeddingPreprocessor::new();for (i, body_result) in body_results.iter().enumerate() {- let batch = if body_result.detection.coco_class == 15 {+ let batch = if body_result.detection.coco_class == COCO_CAT {&mut cat_batch} else {&mut dog_batch@@ -211,36 +151,19 @@ pub(crate) fn run_pet_body_embedding(batch.input,[batch.indices.len() as i64,- BODY_EMBED_CHANNELS,- BODY_EMBED_INPUT_SIZE,- BODY_EMBED_INPUT_SIZE,+ PET_EMBEDDING_CHANNELS as i64,+ PET_EMBEDDING_INPUT_SIZE as i64,+ PET_EMBEDDING_INPUT_SIZE as i64,],)?;- if shape.is_empty() {- return Err(MlError::Postprocess(- "pet body embedding output shape is empty".to_string(),- ));- }- let output_batch = shape[0] as usize;- if output_batch != batch.indices.len() {- return Err(MlError::Postprocess(format!(- "pet body embedding batch mismatch: output={output_batch}, expected={}",- batch.indices.len()- )));- }- let embedding_size = output.len() / output_batch;- if embedding_size == 0 || output.len() != output_batch * embedding_size {- return Err(MlError::Postprocess(format!(- "pet body embedding output not evenly divisible: len={}, batch={output_batch}",- output.len()- )));- }+ let embedding_size =+ validate_embedding_batch_output("body", &shape, output.len(), batch.indices.len())?;for (batch_idx, &orig_idx) in batch.indices.iter().enumerate() {let start = batch_idx * embedding_size;let mut embedding = output[start..(start + embedding_size)].to_vec();- normalize_embedding(&mut embedding);+ l2_normalize(&mut embedding, 1e-12);body_results[orig_idx].body_embedding = embedding;}}@@ -248,16 +171,54 @@ pub(crate) fn run_pet_body_embedding(Ok(())}-fn normalize_embedding(embedding: &mut [f32]) {- let mut norm = 0.0f32;- for value in embedding.iter() {- norm += value * value;+fn validate_embedding_batch_output(+ kind: &str,+ shape: &[i64],+ output_len: usize,+ expected_batch: usize,+) -> MlResult<usize> {+ if shape.is_empty() {+ return Err(MlError::Postprocess(format!(+ "pet {kind} embedding output shape is empty"+ )));}- let norm = norm.sqrt();- if norm <= 1e-12 {- return;++ let output_batch = shape[0] as usize;+ if output_batch != expected_batch {+ return Err(MlError::Postprocess(format!(+ "pet {kind} embedding batch mismatch: output={output_batch}, expected={expected_batch}"+ )));}- for value in embedding.iter_mut() {- *value /= norm;++ let embedding_size = output_len / output_batch;+ if embedding_size == 0 || output_len != output_batch * embedding_size {+ return Err(MlError::Postprocess(format!(+ "pet {kind} embedding output not evenly divisible: len={output_len}, batch={output_batch}"+ )));+ }++ Ok(embedding_size)+}++#[cfg(test)]+mod tests {+ use super::validate_embedding_batch_output;++ #[test]+ fn validates_pet_embedding_batch_shape() {+ assert_eq!(+ validate_embedding_batch_output("face", &[2, 128], 256, 2).unwrap(),+ 128+ );+ }++ #[test]+ fn rejects_uneven_pet_embedding_output() {+ let error = validate_embedding_batch_output("body", &[2, 128], 255, 2).unwrap_err();++ assert_eq!(+ error.to_string(),+ "postprocess error: pet body embedding output not evenly divisible: len=255, batch=2"+ );}}diff --git a/rust/crates/photos/src/ml/pet/mod.rs b/rust/crates/photos/src/ml/pet/mod.rsindex de8d91a240..515f3b00d9 100644--- a/rust/crates/photos/src/ml/pet/mod.rs+++ b/rust/crates/photos/src/ml/pet/mod.rs@@ -1,4 +1,15 @@-pub mod align;-pub mod detect;-pub mod embed;-pub mod preprocess;+mod align;+mod detect;+mod embed;+mod preprocess;++pub(super) use align::run_pet_face_alignment;+pub(super) use detect::{run_pet_body_detection, run_pet_face_detection};+pub(super) use embed::{run_pet_body_embedding, run_pet_face_embedding};++const PET_EMBEDDING_INPUT_SIZE: usize = 224;+const PET_EMBEDDING_CHANNELS: usize = 3;+const PET_SPECIES_DOG: u8 = 0;+const PET_SPECIES_CAT: u8 = 1;+const COCO_CAT: u8 = 15;+const COCO_DOG: u8 = 16;diff --git a/rust/crates/photos/src/ml/pet/preprocess.rs b/rust/crates/photos/src/ml/pet/preprocess.rsindex c00191b275..44e6a2d124 100644--- a/rust/crates/photos/src/ml/pet/preprocess.rs+++ b/rust/crates/photos/src/ml/pet/preprocess.rs@@ -8,12 +8,54 @@ use crate::ml::{types::DecodedImage,};-const PET_EMBED_INPUT_SIZE: usize = 224;+use super::{PET_EMBEDDING_CHANNELS, PET_EMBEDDING_INPUT_SIZE, PET_SPECIES_CAT};// ImageNet normalization constantsconst IMAGENET_MEAN: [f32; 3] = [0.485, 0.456, 0.406];const IMAGENET_STD: [f32; 3] = [0.229, 0.224, 0.225];+pub(super) struct IndexedEmbeddingBatch {+ pub(super) indices: Vec<usize>,+ pub(super) input: Vec<f32>,+}++impl IndexedEmbeddingBatch {+ pub(super) fn new(item_capacity: usize, floats_per_item: usize) -> Self {+ Self {+ indices: Vec::with_capacity(item_capacity),+ input: Vec::with_capacity(item_capacity * floats_per_item),+ }+ }++ pub(super) fn is_empty(&self) -> bool {+ self.indices.is_empty()+ }+}++pub(crate) struct PetFaceEmbeddingInputs {+ pub(super) dog: IndexedEmbeddingBatch,+ pub(super) cat: IndexedEmbeddingBatch,+}++impl PetFaceEmbeddingInputs {+ pub(super) fn new(dog_capacity: usize, cat_capacity: usize) -> Self {+ let floats_per_face =+ PET_EMBEDDING_INPUT_SIZE * PET_EMBEDDING_INPUT_SIZE * PET_EMBEDDING_CHANNELS;+ Self {+ dog: IndexedEmbeddingBatch::new(dog_capacity, floats_per_face),+ cat: IndexedEmbeddingBatch::new(cat_capacity, floats_per_face),+ }+ }++ pub(super) fn batch_mut(&mut self, class_id: u8) -> &mut IndexedEmbeddingBatch {+ if class_id == PET_SPECIES_CAT {+ &mut self.cat+ } else {+ &mut self.dog+ }+ }+}+#[derive(Clone, Copy)]pub(super) struct PixelCrop {pub(super) x: u32,@@ -43,7 +85,7 @@ pub(super) struct PetEmbeddingPreprocessor {impl PetEmbeddingPreprocessor {pub(super) fn new() -> Self {Self {- crop_resizer: RgbCropResizer::new(PET_EMBED_INPUT_SIZE as u32),+ crop_resizer: RgbCropResizer::new(PET_EMBEDDING_INPUT_SIZE as u32),}}@@ -149,7 +191,7 @@ impl RgbCropResizer {}pub(super) fn append_imagenet_tensor(resized: &[u8], output: &mut Vec<f32>) {- let pixel_count = PET_EMBED_INPUT_SIZE * PET_EMBED_INPUT_SIZE;+ let pixel_count = PET_EMBEDDING_INPUT_SIZE * PET_EMBEDDING_INPUT_SIZE;let start = output.len();output.resize(start + 3 * pixel_count, 0.0);let tensor = &mut output[start..];diff --git a/rust/crates/photos/src/ml/postprocess.rs b/rust/crates/photos/src/ml/postprocess.rsnew file mode 100644index 0000000000..3fe9d6009b--- /dev/null+++ b/rust/crates/photos/src/ml/postprocess.rs@@ -0,0 +1,36 @@+pub(crate) fn l2_normalize(embedding: &mut [f32], zero_threshold: f32) {+ let mut norm = 0.0f32;+ for value in embedding.iter() {+ norm += value * value;+ }+ let norm = norm.sqrt();+ if norm <= zero_threshold {+ return;+ }+ for value in embedding.iter_mut() {+ *value /= norm;+ }+}++#[cfg(test)]+mod tests {+ use super::l2_normalize;++ #[test]+ fn l2_normalization_preserves_the_existing_arithmetic() {+ let mut embedding = [3.0, 4.0];++ l2_normalize(&mut embedding, f32::EPSILON);++ assert_eq!(embedding, [0.6, 0.8]);+ }++ #[test]+ fn l2_normalization_honors_the_callers_zero_threshold() {+ let mut embedding = [1e-13];++ l2_normalize(&mut embedding, 1e-12);++ assert_eq!(embedding, [1e-13]);+ }+}diff --git a/rust/crates/photos/src/ml/preprocess.rs b/rust/crates/photos/src/ml/preprocess.rsindex 8050545772..72161b1ff4 100644--- a/rust/crates/photos/src/ml/preprocess.rs+++ b/rust/crates/photos/src/ml/preprocess.rs@@ -4,15 +4,13 @@ use fast_image_resize::{};use crate::ml::{+ clip::CLIP_IMAGE_INPUT_SIZE,error::{MlError, MlResult},onnx::PreparedF32Input,types::DecodedImage,};-const YOLO_INPUT_WIDTH: usize = 640;-const YOLO_INPUT_HEIGHT: usize = 640;-const CLIP_INPUT_WIDTH: usize = 256;-const CLIP_INPUT_HEIGHT: usize = 256;+pub(crate) const YOLO_INPUT_SIZE: usize = 640;const PAD_VALUE: f32 = 114.0;pub(crate) struct YoloInput {@@ -23,6 +21,55 @@ pub(crate) struct YoloInput {pub(crate) pad_top: usize,}+impl YoloInput {+ pub(crate) fn correct_box(&self, box_xyxy: &mut [f32; 4]) {+ if self.has_identity_geometry() {+ return;+ }+ self.correct_box_with_padding(box_xyxy);+ }++ pub(crate) fn correct_box_and_keypoints<const N: usize>(+ &self,+ box_xyxy: &mut [f32; 4],+ keypoints: &mut [[f32; 2]; N],+ ) {+ if self.has_identity_geometry() {+ return;+ }++ self.correct_box_with_padding(box_xyxy);+ for point in keypoints {+ point[0] = self.original_x(point[0]);+ point[1] = self.original_y(point[1]);+ }+ }++ fn has_identity_geometry(&self) -> bool {+ self.scaled_width == YOLO_INPUT_SIZE+ && self.scaled_height == YOLO_INPUT_SIZE+ && self.pad_left == 0+ && self.pad_top == 0+ }++ fn correct_box_with_padding(&self, box_xyxy: &mut [f32; 4]) {+ box_xyxy[0] = self.original_x(box_xyxy[0]);+ box_xyxy[1] = self.original_y(box_xyxy[1]);+ box_xyxy[2] = self.original_x(box_xyxy[2]);+ box_xyxy[3] = self.original_y(box_xyxy[3]);+ }++ fn original_x(&self, x: f32) -> f32 {+ ((x * YOLO_INPUT_SIZE as f32 - self.pad_left as f32) / self.scaled_width as f32)+ .clamp(0.0, 1.0)+ }++ fn original_y(&self, y: f32) -> f32 {+ ((y * YOLO_INPUT_SIZE as f32 - self.pad_top as f32) / self.scaled_height as f32)+ .clamp(0.0, 1.0)+ }+}+pub(crate) fn preprocess_yolo(decoded: &DecodedImage) -> MlResult<YoloInput> {if decoded.dimensions.width == 0 || decoded.dimensions.height == 0 {return Err(MlError::Preprocess(@@ -32,9 +79,9 @@ pub(crate) fn preprocess_yolo(decoded: &DecodedImage) -> MlResult<YoloInput> {let src_w = decoded.dimensions.width as f32;let src_h = decoded.dimensions.height as f32;- let scale = (YOLO_INPUT_WIDTH as f32 / src_w).min(YOLO_INPUT_HEIGHT as f32 / src_h);- let scaled_width = (src_w * scale).round().clamp(1.0, YOLO_INPUT_WIDTH as f32) as u32;- let scaled_height = (src_h * scale).round().clamp(1.0, YOLO_INPUT_HEIGHT as f32) as u32;+ let scale = (YOLO_INPUT_SIZE as f32 / src_w).min(YOLO_INPUT_SIZE as f32 / src_h);+ let scaled_width = (src_w * scale).round().clamp(1.0, YOLO_INPUT_SIZE as f32) as u32;+ let scaled_height = (src_h * scale).round().clamp(1.0, YOLO_INPUT_SIZE as f32) as u32;let src_image = FirImageRef::new(decoded.dimensions.width,@@ -53,13 +100,13 @@ pub(crate) fn preprocess_yolo(decoded: &DecodedImage) -> MlResult<YoloInput> {let scaled_width_usize = scaled_width as usize;let scaled_height_usize = scaled_height as usize;- let pad_left = (YOLO_INPUT_WIDTH.saturating_sub(scaled_width_usize)) / 2;- let pad_top = (YOLO_INPUT_HEIGHT.saturating_sub(scaled_height_usize)) / 2;+ let pad_left = (YOLO_INPUT_SIZE.saturating_sub(scaled_width_usize)) / 2;+ let pad_top = (YOLO_INPUT_SIZE.saturating_sub(scaled_height_usize)) / 2;let pad_norm = PAD_VALUE / 255.0;- let mut output = vec![pad_norm; 3 * YOLO_INPUT_WIDTH * YOLO_INPUT_HEIGHT];- let green_offset = YOLO_INPUT_WIDTH * YOLO_INPUT_HEIGHT;- let blue_offset = 2 * YOLO_INPUT_WIDTH * YOLO_INPUT_HEIGHT;+ let mut output = vec![pad_norm; 3 * YOLO_INPUT_SIZE * YOLO_INPUT_SIZE];+ let green_offset = YOLO_INPUT_SIZE * YOLO_INPUT_SIZE;+ let blue_offset = 2 * YOLO_INPUT_SIZE * YOLO_INPUT_SIZE;let resized = resized_image.buffer();for y in 0..scaled_height_usize {@@ -67,7 +114,7 @@ pub(crate) fn preprocess_yolo(decoded: &DecodedImage) -> MlResult<YoloInput> {let src_idx = (y * scaled_width_usize + x) * 3;let dst_x = x + pad_left;let dst_y = y + pad_top;- let dst_idx = dst_y * YOLO_INPUT_WIDTH + dst_x;+ let dst_idx = dst_y * YOLO_INPUT_SIZE + dst_x;output[dst_idx] = resized[src_idx] as f32 / 255.0;output[dst_idx + green_offset] = resized[src_idx + 1] as f32 / 255.0;@@ -84,7 +131,7 @@ pub(crate) fn preprocess_yolo(decoded: &DecodedImage) -> MlResult<YoloInput> {})}-pub fn preprocess_clip(decoded: &DecodedImage) -> MlResult<Vec<f32>> {+pub(crate) fn preprocess_clip(decoded: &DecodedImage) -> MlResult<Vec<f32>> {if decoded.dimensions.width == 0 || decoded.dimensions.height == 0 {return Err(MlError::Preprocess("image dimensions cannot be zero".to_string(),@@ -93,9 +140,9 @@ pub fn preprocess_clip(decoded: &DecodedImage) -> MlResult<Vec<f32>> {let src_w = decoded.dimensions.width as f32;let src_h = decoded.dimensions.height as f32;- let scale = (CLIP_INPUT_WIDTH as f32 / src_w).max(CLIP_INPUT_HEIGHT as f32 / src_h);- let scaled_width = (src_w * scale).round().max(CLIP_INPUT_WIDTH as f32) as u32;- let scaled_height = (src_h * scale).round().max(CLIP_INPUT_HEIGHT as f32) as u32;+ let scale = (CLIP_IMAGE_INPUT_SIZE as f32 / src_w).max(CLIP_IMAGE_INPUT_SIZE as f32 / src_h);+ let scaled_width = (src_w * scale).round().max(CLIP_IMAGE_INPUT_SIZE as f32) as u32;+ let scaled_height = (src_h * scale).round().max(CLIP_IMAGE_INPUT_SIZE as f32) as u32;let src_image = FirImageRef::new(decoded.dimensions.width,@@ -105,18 +152,18 @@ pub fn preprocess_clip(decoded: &DecodedImage) -> MlResult<Vec<f32>> {).map_err(|e| MlError::Preprocess(format!("failed to create FIR source image: {e}")))?;- let start_x = (scaled_width.saturating_sub(CLIP_INPUT_WIDTH as u32) / 2) as f64;- let start_y = (scaled_height.saturating_sub(CLIP_INPUT_HEIGHT as u32) / 2) as f64;+ let start_x = (scaled_width.saturating_sub(CLIP_IMAGE_INPUT_SIZE as u32) / 2) as f64;+ let start_y = (scaled_height.saturating_sub(CLIP_IMAGE_INPUT_SIZE as u32) / 2) as f64;let horizontal_scale = decoded.dimensions.width as f64 / scaled_width as f64;let vertical_scale = decoded.dimensions.height as f64 / scaled_height as f64;let crop_left = start_x * horizontal_scale;let crop_top = start_y * vertical_scale;- let crop_width = CLIP_INPUT_WIDTH as f64 * horizontal_scale;- let crop_height = CLIP_INPUT_HEIGHT as f64 * vertical_scale;+ let crop_width = CLIP_IMAGE_INPUT_SIZE as f64 * horizontal_scale;+ let crop_height = CLIP_IMAGE_INPUT_SIZE as f64 * vertical_scale;let mut resized_image = FirImage::new(- CLIP_INPUT_WIDTH as u32,- CLIP_INPUT_HEIGHT as u32,+ CLIP_IMAGE_INPUT_SIZE as u32,+ CLIP_IMAGE_INPUT_SIZE as u32,PixelType::U8x3,);let mut resizer = Resizer::new();@@ -129,14 +176,14 @@ pub fn preprocess_clip(decoded: &DecodedImage) -> MlResult<Vec<f32>> {let resized = resized_image.buffer();- let mut output = vec![0f32; 3 * CLIP_INPUT_WIDTH * CLIP_INPUT_HEIGHT];- let green_offset = CLIP_INPUT_WIDTH * CLIP_INPUT_HEIGHT;- let blue_offset = 2 * CLIP_INPUT_WIDTH * CLIP_INPUT_HEIGHT;+ let mut output = vec![0f32; 3 * CLIP_IMAGE_INPUT_SIZE * CLIP_IMAGE_INPUT_SIZE];+ let green_offset = CLIP_IMAGE_INPUT_SIZE * CLIP_IMAGE_INPUT_SIZE;+ let blue_offset = 2 * CLIP_IMAGE_INPUT_SIZE * CLIP_IMAGE_INPUT_SIZE;- for y in 0..CLIP_INPUT_HEIGHT {- for x in 0..CLIP_INPUT_WIDTH {- let src_idx = (y * CLIP_INPUT_WIDTH + x) * 3;- let dst_idx = y * CLIP_INPUT_WIDTH + x;+ for y in 0..CLIP_IMAGE_INPUT_SIZE {+ for x in 0..CLIP_IMAGE_INPUT_SIZE {+ let src_idx = (y * CLIP_IMAGE_INPUT_SIZE + x) * 3;+ let dst_idx = y * CLIP_IMAGE_INPUT_SIZE + x;output[dst_idx] = resized[src_idx] as f32 / 255.0;output[dst_idx + green_offset] = resized[src_idx + 1] as f32 / 255.0;output[dst_idx + blue_offset] = resized[src_idx + 2] as f32 / 255.0;@@ -153,12 +200,89 @@ mod tests {images::{Image as FirImage, ImageRef as FirImageRef},};- use super::{CLIP_INPUT_HEIGHT, CLIP_INPUT_WIDTH, preprocess_clip};+ use super::{YOLO_INPUT_SIZE, YoloInput, preprocess_clip};use crate::ml::{+ clip::CLIP_IMAGE_INPUT_SIZE,error::{MlError, MlResult},+ onnx::PreparedF32Input,types::{DecodedImage, Dimensions},};+ #[test]+ fn yolo_geometry_matches_the_previous_letterbox_correction() {+ let input = YoloInput {+ tensor: PreparedF32Input::new(Vec::new()),+ scaled_width: YOLO_INPUT_SIZE,+ scaled_height: 320,+ pad_left: 0,+ pad_top: 160,+ };+ let mut actual_box = [0.1, 0.25, 0.9, 0.75];+ let mut actual_keypoints = [[0.2, 0.3], [0.5, 0.5], [0.8, 0.7]];+ let mut expected_box = actual_box;+ let mut expected_keypoints = actual_keypoints;++ legacy_correct_geometry(+ &mut expected_box,+ &mut expected_keypoints,+ input.scaled_width,+ input.scaled_height,+ input.pad_left,+ input.pad_top,+ );+ input.correct_box_and_keypoints(&mut actual_box, &mut actual_keypoints);++ assert_eq!(actual_box, expected_box);+ assert_eq!(actual_keypoints, expected_keypoints);+ }++ #[test]+ fn yolo_identity_geometry_does_not_round_coordinates() {+ let input = YoloInput {+ tensor: PreparedF32Input::new(Vec::new()),+ scaled_width: YOLO_INPUT_SIZE,+ scaled_height: YOLO_INPUT_SIZE,+ pad_left: 0,+ pad_top: 0,+ };+ let expected_box = [0.123_456_7, 0.234_567_8, 0.765_432_1, 0.876_543_2];+ let expected_keypoints = [[0.111_111_1, 0.222_222_2]];+ let mut actual_box = expected_box;+ let mut actual_keypoints = expected_keypoints;++ input.correct_box_and_keypoints(&mut actual_box, &mut actual_keypoints);++ assert_eq!(actual_box, expected_box);+ assert_eq!(actual_keypoints, expected_keypoints);+ }++ fn legacy_correct_geometry<const N: usize>(+ box_xyxy: &mut [f32; 4],+ keypoints: &mut [[f32; 2]; N],+ scaled_width: usize,+ scaled_height: usize,+ pad_left: usize,+ pad_top: usize,+ ) {+ 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| ((x * YOLO_INPUT_SIZE as f32 - pad_left) / scaled_width).clamp(0.0, 1.0);+ let transform_y =+ |y: f32| ((y * YOLO_INPUT_SIZE as f32 - 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 {+ point[0] = transform_x(point[0]);+ point[1] = transform_y(point[1]);+ }+ }+#[test]fn direct_clip_crop_matches_resize_then_crop() {for (width, height) in [@@ -198,9 +322,10 @@ mod tests {fn legacy_preprocess_clip(decoded: &DecodedImage) -> MlResult<Vec<f32>> {let src_w = decoded.dimensions.width as f32;let src_h = decoded.dimensions.height as f32;- let scale = (CLIP_INPUT_WIDTH as f32 / src_w).max(CLIP_INPUT_HEIGHT as f32 / src_h);- let scaled_width = (src_w * scale).round().max(CLIP_INPUT_WIDTH as f32) as u32;- let scaled_height = (src_h * scale).round().max(CLIP_INPUT_HEIGHT as f32) as u32;+ let scale =+ (CLIP_IMAGE_INPUT_SIZE as f32 / src_w).max(CLIP_IMAGE_INPUT_SIZE as f32 / src_h);+ let scaled_width = (src_w * scale).round().max(CLIP_IMAGE_INPUT_SIZE as f32) as u32;+ let scaled_height = (src_h * scale).round().max(CLIP_IMAGE_INPUT_SIZE as f32) as u32;let source = FirImageRef::new(decoded.dimensions.width,decoded.dimensions.height,@@ -214,14 +339,14 @@ mod tests {.resize(&source, &mut resized, Some(&options)).map_err(|error| MlError::Preprocess(error.to_string()))?;- let start_x = (scaled_width as usize - CLIP_INPUT_WIDTH) / 2;- let start_y = (scaled_height as usize - CLIP_INPUT_HEIGHT) / 2;- let pixel_count = CLIP_INPUT_WIDTH * CLIP_INPUT_HEIGHT;+ let start_x = (scaled_width as usize - CLIP_IMAGE_INPUT_SIZE) / 2;+ let start_y = (scaled_height as usize - CLIP_IMAGE_INPUT_SIZE) / 2;+ let pixel_count = CLIP_IMAGE_INPUT_SIZE * CLIP_IMAGE_INPUT_SIZE;let mut output = vec![0.0; 3 * pixel_count];- for y in 0..CLIP_INPUT_HEIGHT {- for x in 0..CLIP_INPUT_WIDTH {+ for y in 0..CLIP_IMAGE_INPUT_SIZE {+ for x in 0..CLIP_IMAGE_INPUT_SIZE {let source = ((start_y + y) * scaled_width as usize + start_x + x) * 3;- let destination = y * CLIP_INPUT_WIDTH + x;+ let destination = y * CLIP_IMAGE_INPUT_SIZE + x;output[destination] = resized.buffer()[source] as f32 / 255.0;output[pixel_count + destination] = resized.buffer()[source + 1] as f32 / 255.0;output[2 * pixel_count + destination] = resized.buffer()[source + 2] as f32 / 255.0;diff --git a/rust/crates/photos/src/ml/runtime.rs b/rust/crates/photos/src/ml/runtime.rsindex 33125dd908..246a0093b6 100644--- a/rust/crates/photos/src/ml/runtime.rs+++ b/rust/crates/photos/src/ml/runtime.rs@@ -63,11 +63,11 @@ struct ModelSlot {state: Mutex<ModelSlotState>,}-pub struct ModelSessionGuard<'a> {+pub(crate) struct ModelSessionGuard<'a> {state: MutexGuard<'a, ModelSlotState>,}-pub struct MlRuntimeView<'a> {+pub(crate) struct MlRuntimeView<'a> {runtime: &'a MlRuntime,model_paths: &'a ModelPaths,}@@ -213,7 +213,7 @@ impl ModelSlot {}#[derive(Debug)]-pub struct MlRuntime {+struct MlRuntime {face_detection: ModelSlot,face_embedding: ModelSlot,clip_image: ModelSlot,@@ -339,70 +339,70 @@ impl MlRuntime {}impl MlRuntimeView<'_> {- pub fn face_detection_session(&self) -> MlResult<ModelSessionGuard<'_>> {+ pub(crate) fn face_detection_session(&self) -> MlResult<ModelSessionGuard<'_>> {self.runtime.face_detection.session_guard_for(&self.model_paths.face_detection,"missing model path: faceDetectionModelPath is required when runFaces is true",)}- pub fn face_embedding_session(&self) -> MlResult<ModelSessionGuard<'_>> {+ pub(crate) fn face_embedding_session(&self) -> MlResult<ModelSessionGuard<'_>> {self.runtime.face_embedding.session_guard_for(&self.model_paths.face_embedding,"missing model path: faceEmbeddingModelPath is required when runFaces is true",)}- pub fn clip_image_session(&self) -> MlResult<ModelSessionGuard<'_>> {+ pub(crate) fn clip_image_session(&self) -> MlResult<ModelSessionGuard<'_>> {self.runtime.clip_image.session_guard_for(&self.model_paths.clip_image,"missing model path: clipImageModelPath is required when runClip is true",)}- pub fn clip_text_session(&self) -> MlResult<ModelSessionGuard<'_>> {+ pub(crate) fn clip_text_session(&self) -> MlResult<ModelSessionGuard<'_>> {self.runtime.clip_text.session_guard_for(&self.model_paths.clip_text,"missing model path: clipTextModelPath is required when running clip text",)}- pub fn pet_face_detection_session(&self) -> MlResult<ModelSessionGuard<'_>> {+ pub(crate) fn pet_face_detection_session(&self) -> MlResult<ModelSessionGuard<'_>> {self.runtime.pet_face_detection.session_guard_for(&self.model_paths.pet_face_detection,"missing model path: petFaceDetectionModelPath is required when runPets is true",)}- pub fn pet_face_embedding_dog_session(&self) -> MlResult<ModelSessionGuard<'_>> {+ pub(crate) fn pet_face_embedding_dog_session(&self) -> MlResult<ModelSessionGuard<'_>> {self.runtime.pet_face_embedding_dog.session_guard_for(&self.model_paths.pet_face_embedding_dog,"missing model path: petFaceEmbeddingDogModelPath is required",)}- pub fn pet_face_embedding_cat_session(&self) -> MlResult<ModelSessionGuard<'_>> {+ pub(crate) fn pet_face_embedding_cat_session(&self) -> MlResult<ModelSessionGuard<'_>> {self.runtime.pet_face_embedding_cat.session_guard_for(&self.model_paths.pet_face_embedding_cat,"missing model path: petFaceEmbeddingCatModelPath is required",)}- pub fn pet_body_detection_session(&self) -> MlResult<ModelSessionGuard<'_>> {+ pub(crate) fn pet_body_detection_session(&self) -> MlResult<ModelSessionGuard<'_>> {self.runtime.pet_body_detection.session_guard_for(&self.model_paths.pet_body_detection,"missing model path: petBodyDetectionModelPath is required when runPets is true",)}- pub fn pet_body_embedding_dog_session(&self) -> MlResult<ModelSessionGuard<'_>> {+ pub(crate) fn pet_body_embedding_dog_session(&self) -> MlResult<ModelSessionGuard<'_>> {self.runtime.pet_body_embedding_dog.session_guard_for(&self.model_paths.pet_body_embedding_dog,"missing model path: petBodyEmbeddingDogModelPath is required",)}- pub fn pet_body_embedding_cat_session(&self) -> MlResult<ModelSessionGuard<'_>> {+ pub(crate) fn pet_body_embedding_cat_session(&self) -> MlResult<ModelSessionGuard<'_>> {self.runtime.pet_body_embedding_cat.session_guard_for(&self.model_paths.pet_body_embedding_cat,"missing model path: petBodyEmbeddingCatModelPath is required",@@ -410,15 +410,15 @@ impl MlRuntimeView<'_> {}}-pub fn ensure_runtime(model_paths: &ModelPaths) {+pub(crate) fn ensure_runtime(model_paths: &ModelPaths) {GLOBAL_RUNTIME.configure_requested_models(model_paths);}-pub fn prepare_runtime(model_paths: &ModelPaths) {+pub(crate) fn prepare_runtime(model_paths: &ModelPaths) {GLOBAL_RUNTIME.prepare_indexing_models(model_paths);}-pub fn with_runtime<F, R>(model_paths: &ModelPaths, func: F) -> MlResult<R>+pub(crate) fn with_runtime<F, R>(model_paths: &ModelPaths, func: F) -> MlResult<R>whereF: for<'a> Fn(&MlRuntimeView<'a>) -> MlResult<R>,{@@ -443,7 +443,7 @@ where}}-pub fn release_runtime() {+pub(crate) fn release_runtime() {GLOBAL_RUNTIME.release_indexing_models();}diff --git a/rust/crates/photos/src/ml/types.rs b/rust/crates/photos/src/ml/types.rsindex 39413c7834..dc86685d00 100644--- a/rust/crates/photos/src/ml/types.rs+++ b/rust/crates/photos/src/ml/types.rs@@ -29,7 +29,7 @@ pub struct ClipResult {pub embedding: Vec<f32>,}-pub fn to_face_id(file_id: i64, box_xyxy: [f32; 4]) -> String {+pub(crate) fn to_face_id(file_id: i64, box_xyxy: [f32; 4]) -> String {fn to_face_segment(v: f32) -> String {let clamped = v.clamp(0.0, 0.999_999);let fixed = format!("{clamped:.5}");