Skip to content

armgit / ente

Public Imported from GitHub
0

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

Fix review issues across pet ML pipeline

Amrithesh Kakkoth Enteceaa1500eb62
diff --git a/mobile/apps/photos/lib/db/ml/db.dart b/mobile/apps/photos/lib/db/ml/db.dart
index cee53220f4..8884c6a1c1 100644
--- a/mobile/apps/photos/lib/db/ml/db.dart
+++ b/mobile/apps/photos/lib/db/ml/db.dart
@@ -318,6 +318,10 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
List<DBPetFace> dbPetFaces,
List<PetFaceResult> petFaces,
) async {
+ assert(
+ dbPetFaces.length == petFaces.length,
+ 'dbPetFaces.length (${dbPetFaces.length}) != petFaces.length (${petFaces.length})',
+ );
try {
final db = await asyncDB;
// Group by species
@@ -379,6 +383,10 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
List<DBPetBody> dbPetBodies,
List<PetBodyResult> petBodies,
) async {
+ assert(
+ dbPetBodies.length == petBodies.length,
+ 'dbPetBodies.length (${dbPetBodies.length}) != petBodies.length (${petBodies.length})',
+ );
try {
final db = await asyncDB;
// Group by species (0 = dog, 1 = cat)
@@ -2363,7 +2371,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
}) async {
final db = await asyncDB;
final String query = '''
- SELECT $fileIDColumn, $mlVersionColumn
+ SELECT DISTINCT $fileIDColumn, $mlVersionColumn
FROM $petFacesTable
WHERE $mlVersionColumn >= $minimumMlVersion
''';
@@ -2457,33 +2465,31 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
}
}
- // Delete from ID mapping tables.
- if (faceIdsToRemove.isNotEmpty) {
- final placeholders =
- List.filled(faceIdsToRemove.length, '?').join(',');
- await db.execute(
- 'DELETE FROM $petFaceVectorIdMappingTable '
- 'WHERE $petFaceIDColumn IN ($placeholders)',
- faceIdsToRemove,
+ // Delete mapping table entries and detection rows atomically.
+ await db.writeTransaction((tx) async {
+ if (faceIdsToRemove.isNotEmpty) {
+ final placeholders = List.filled(faceIdsToRemove.length, '?').join(',');
+ await tx.execute(
+ 'DELETE FROM $petFaceVectorIdMappingTable '
+ 'WHERE $petFaceIDColumn IN ($placeholders)',
+ faceIdsToRemove,
+ );
+ }
+ if (bodyIdsToRemove.isNotEmpty) {
+ final placeholders = List.filled(bodyIdsToRemove.length, '?').join(',');
+ await tx.execute(
+ 'DELETE FROM $petBodyVectorIdMappingTable '
+ 'WHERE $petBodyIDColumn IN ($placeholders)',
+ bodyIdsToRemove,
+ );
+ }
+ await tx.execute(
+ 'DELETE FROM $petFacesTable WHERE $fileIDColumn IN ($ids)',
);
- }
- if (bodyIdsToRemove.isNotEmpty) {
- final placeholders =
- List.filled(bodyIdsToRemove.length, '?').join(',');
- await db.execute(
- 'DELETE FROM $petBodyVectorIdMappingTable '
- 'WHERE $petBodyIDColumn IN ($placeholders)',
- bodyIdsToRemove,
+ await tx.execute(
+ 'DELETE FROM $petBodiesTable WHERE $fileIDColumn IN ($ids)',
);
- }
-
- // Delete the detection rows themselves.
- await db.execute(
- 'DELETE FROM $petFacesTable WHERE $fileIDColumn IN ($ids)',
- );
- await db.execute(
- 'DELETE FROM $petBodiesTable WHERE $fileIDColumn IN ($ids)',
- );
+ });
}
@override
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_result.dart b/mobile/apps/photos/lib/services/machine_learning/ml_result.dart
index 9ffd28d79c..38e121022a 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_result.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_result.dart
@@ -199,12 +199,12 @@ int? tryGetFileIdFromFaceId(String faceId) {
}
class PetFaceResult {
- late FaceDetectionRelative detection;
- late AlignmentResult alignment;
- late int species;
- late Embedding embedding;
- late int fileId;
- late String petFaceId;
+ final FaceDetectionRelative detection;
+ final AlignmentResult alignment;
+ final int species;
+ final Embedding embedding;
+ final int fileId;
+ final String petFaceId;
PetFaceResult({
required this.fileId,
@@ -237,11 +237,11 @@ class PetFaceResult {
}
class PetBodyResult {
- late List<double> boxXyxy;
- late double score;
- late int cocoClass;
- late String petBodyId;
- late Embedding embedding;
+ final List<double> boxXyxy;
+ final double score;
+ final int cocoClass;
+ final String petBodyId;
+ final Embedding embedding;
PetBodyResult({
required this.boxXyxy,
@@ -261,8 +261,9 @@ class PetBodyResult {
static PetBodyResult fromJson(Map<String, dynamic> json) {
return PetBodyResult(
- boxXyxy: (json['boxXyxy'] as List).cast<double>(),
- score: json['score'],
+ boxXyxy:
+ (json['boxXyxy'] as List).map((e) => (e as num).toDouble()).toList(),
+ score: (json['score'] as num).toDouble(),
cocoClass: json['cocoClass'],
petBodyId: json['petBodyId'],
embedding: Embedding.from(json['embedding']),
diff --git a/mobile/apps/photos/lib/ui/settings/debug/debug_settings_page.dart b/mobile/apps/photos/lib/ui/settings/debug/debug_settings_page.dart
index 7f6e83d4e3..d002a4d47a 100644
--- a/mobile/apps/photos/lib/ui/settings/debug/debug_settings_page.dart
+++ b/mobile/apps/photos/lib/ui/settings/debug/debug_settings_page.dart
@@ -117,12 +117,10 @@ class _DebugSettingsPageState extends State<DebugSettingsPage> {
),
trailingWidget: ToggleSwitchWidget(
value: () =>
- localSettings
- .isBGDebugNotificationsEnabled,
+ localSettings.isBGDebugNotificationsEnabled,
onChanged: () async {
- final newValue =
- !localSettings
- .isBGDebugNotificationsEnabled;
+ final newValue = !localSettings
+ .isBGDebugNotificationsEnabled;
await localSettings
.setBGDebugNotificationsEnabled(
newValue,
diff --git a/mobile/apps/photos/lib/ui/viewer/file_details/file_info_pets_item_widget.dart b/mobile/apps/photos/lib/ui/viewer/file_details/file_info_pets_item_widget.dart
index 7530dddfc7..c62c56dc52 100644
--- a/mobile/apps/photos/lib/ui/viewer/file_details/file_info_pets_item_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file_details/file_info_pets_item_widget.dart
@@ -4,11 +4,13 @@ import "dart:typed_data";
import "package:flutter/material.dart";
import "package:logging/logging.dart";
import "package:photos/db/ml/db.dart";
+import "package:photos/db/offline_files_db.dart";
import "package:photos/generated/intl/app_localizations.dart";
import "package:photos/models/file/file.dart";
import "package:photos/models/ml/face/box.dart";
import "package:photos/models/ml/face/detection.dart";
import "package:photos/models/ml/face/face.dart";
+import "package:photos/service_locator.dart" show isOfflineMode;
import "package:photos/theme/ente_theme.dart";
import "package:photos/theme/text_style.dart";
import "package:photos/ui/common/loading_widget.dart";
@@ -39,13 +41,25 @@ class _PetsItemWidgetState extends State<PetsItemWidget> {
Future<void> _loadPetFaces() async {
try {
- final fileKey = widget.file.uploadedFileID;
- if (fileKey == null) {
- if (mounted) setState(() => _isLoading = false);
- return;
+ final bool isOffline = isOfflineMode;
+ int? fileKey;
+ if (isOffline) {
+ final localId = widget.file.localID;
+ if (localId == null || localId.isEmpty) {
+ if (mounted) setState(() => _isLoading = false);
+ return;
+ }
+ fileKey = await OfflineFilesDB.instance.getOrCreateLocalIntId(localId);
+ } else {
+ fileKey = widget.file.uploadedFileID;
+ if (fileKey == null) {
+ if (mounted) setState(() => _isLoading = false);
+ return;
+ }
}
- final dbPetFaces = await MLDataDB.instance.getPetFacesForFileID(fileKey);
+ final mlDataDB = isOffline ? MLDataDB.offlineInstance : MLDataDB.instance;
+ final dbPetFaces = await mlDataDB.getPetFacesForFileID(fileKey);
if (dbPetFaces == null || dbPetFaces.isEmpty) {
if (mounted) setState(() => _isLoading = false);
return;
diff --git a/mobile/apps/photos/rust/src/ml/onnx.rs b/mobile/apps/photos/rust/src/ml/onnx.rs
index 4c9f60b817..76ade597ef 100644
--- a/mobile/apps/photos/rust/src/ml/onnx.rs
+++ b/mobile/apps/photos/rust/src/ml/onnx.rs
@@ -124,11 +124,7 @@ pub fn run_f32<const N: usize>(
input_shape: [i64; N],
) -> MlResult<(Vec<i64>, Vec<f32>)> {
let outputs = if session_expects_f16(session) {
- // Convert f32->f16 in-place: drop the f32 vec first to avoid holding both.
- let f16_input: Vec<half::f16> = {
- let converted: Vec<half::f16> = input.into_iter().map(half::f16::from_f32).collect();
- converted
- };
+ let f16_input: Vec<half::f16> = input.into_iter().map(half::f16::from_f32).collect();
let input_tensor = Tensor::<half::f16>::from_array((input_shape, f16_input))?;
session.run(ort::inputs![input_tensor]?)?
} else {
@@ -159,14 +155,24 @@ pub fn run_f32_data<const N: usize>(
input: Vec<f32>,
input_shape: [i64; N],
) -> MlResult<Vec<f32>> {
- let input_tensor = Tensor::<f32>::from_array((input_shape, input))?;
- let outputs = session.run(ort::inputs![input_tensor]?)?;
+ let outputs = if session_expects_f16(session) {
+ let f16_input: Vec<half::f16> = input.into_iter().map(half::f16::from_f32).collect();
+ let input_tensor = Tensor::<half::f16>::from_array((input_shape, f16_input))?;
+ session.run(ort::inputs![input_tensor]?)?
+ } else {
+ let input_tensor = Tensor::<f32>::from_array((input_shape, input))?;
+ session.run(ort::inputs![input_tensor]?)?
+ };
if outputs.is_empty() {
return Err(MlError::Ort("missing first output tensor".to_string()));
}
let output = &outputs[0];
- let tensor = output.try_extract_tensor::<f32>()?;
- Ok(tensor.iter().copied().collect::<Vec<_>>())
+ if let Ok(tensor) = output.try_extract_tensor::<f32>() {
+ Ok(tensor.iter().copied().collect::<Vec<_>>())
+ } else {
+ let tensor = output.try_extract_tensor::<half::f16>()?;
+ Ok(tensor.iter().map(|v: &half::f16| v.to_f32()).collect::<Vec<_>>())
+ }
}
pub fn run_i32_f32<const N: usize>(
diff --git a/mobile/apps/photos/rust/src/ml/pet/align.rs b/mobile/apps/photos/rust/src/ml/pet/align.rs
index 6474695d65..9210c3aea0 100644
--- a/mobile/apps/photos/rust/src/ml/pet/align.rs
+++ b/mobile/apps/photos/rust/src/ml/pet/align.rs
@@ -30,7 +30,6 @@ pub fn run_pet_face_alignment(
decoded: &DecodedImage,
detections: &[PetFaceDetection],
) -> MlResult<(Vec<Vec<f32>>, Vec<PetFaceResult>)> {
- let source = rgb_image_from_decoded(decoded)?;
let img_w = decoded.dimensions.width;
let img_h = decoded.dimensions.height;
let img_wf = img_w as f32;
@@ -79,26 +78,41 @@ pub fn run_pet_face_alignment(
if crop_w == 0 || crop_h == 0 {
continue;
}
- crop_and_resize_rgb(&source, cx1, cy1, crop_w, crop_h)?
+ crop_and_resize_decoded(decoded, 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;
+ // Rotate only a padded region around the face, not the full image.
+ let bw = (box_x2 - box_x1) as f32;
+ let bh = (box_y2 - box_y1) as f32;
+ let pad = (bw.max(bh) * (CROP_EXPAND + 0.5)).ceil() as i32;
+
+ let region_x1 = (box_x1 - pad).max(0) as u32;
+ let region_y1 = (box_y1 - pad).max(0) as u32;
+ let region_x2 = ((box_x2 + pad) as u32).min(img_w);
+ let region_y2 = ((box_y2 + pad) as u32).min(img_h);
+ let region_w = region_x2 - region_x1;
+ let region_h = region_y2 - region_y1;
+ if region_w == 0 || region_h == 0 {
+ continue;
+ }
+
+ let region = extract_rgb_region(decoded, region_x1, region_y1, region_w, region_h)?;
+
+ // Face center relative to the extracted region
+ let local_cx = (box_x1 + box_x2) as f64 / 2.0 - region_x1 as f64;
+ let local_cy = (box_y1 + box_y2) as f64 / 2.0 - region_y1 as f64;
let rotated = rotate_around_center(
- &source,
+ &region,
angle_rad as f64,
- face_cx,
- face_cy,
+ local_cx,
+ local_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;
+ // Crop coordinates relative to the region
+ let nx1 = (box_x1 as f32 - bw * CROP_EXPAND - region_x1 as f32).max(0.0) as u32;
+ let ny1 = (box_y1 as f32 - bh * CROP_EXPAND - region_y1 as f32).max(0.0) as u32;
+ let nx2 = (box_x2 as f32 + bw * CROP_EXPAND - region_x1 as f32).min(region_w as f32) as u32;
+ let ny2 = (box_y2 as f32 + bh * CROP_EXPAND - region_y1 as f32).min(region_h as f32) as u32;
let crop_w = nx2.saturating_sub(nx1);
let crop_h = ny2.saturating_sub(ny1);
if crop_w == 0 || crop_h == 0 {
@@ -229,13 +243,66 @@ fn crop_and_resize_rgb(
.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,
- decoded.dimensions.height,
- decoded.rgb.clone(),
- )
- .ok_or_else(|| MlError::Preprocess("failed to build RGB source image for pet alignment".to_string()))
+/// Extract a rectangular region from the decoded image without cloning
+/// the entire buffer.
+fn extract_rgb_region(
+ decoded: &DecodedImage,
+ x: u32,
+ y: u32,
+ w: u32,
+ h: u32,
+) -> MlResult<RgbImage> {
+ let img_w = decoded.dimensions.width;
+ let mut buf = Vec::with_capacity((w * h * 3) as usize);
+ for row in y..(y + h) {
+ let start = ((row * img_w + x) * 3) as usize;
+ let end = start + (w * 3) as usize;
+ if end > decoded.rgb.len() {
+ return Err(MlError::Preprocess(format!(
+ "region row {row} out of bounds (end={end}, len={})", decoded.rgb.len()
+ )));
+ }
+ buf.extend_from_slice(&decoded.rgb[start..end]);
+ }
+ ImageBuffer::<Rgb<u8>, _>::from_raw(w, h, buf)
+ .ok_or_else(|| MlError::Preprocess("failed to build region image".to_string()))
+}
+
+/// Crop directly from decoded image bytes and resize β€” avoids building a
+/// full-size RgbImage when no rotation is needed.
+fn crop_and_resize_decoded(
+ decoded: &DecodedImage,
+ x: u32,
+ y: u32,
+ w: u32,
+ h: u32,
+) -> MlResult<RgbImage> {
+ let img_w = decoded.dimensions.width;
+ let mut crop_bytes = Vec::with_capacity((w * h * 3) as usize);
+ for row in y..(y + h) {
+ let start = ((row * img_w + x) * 3) as usize;
+ let end = start + (w * 3) as usize;
+ if end > decoded.rgb.len() {
+ return Err(MlError::Preprocess(format!(
+ "crop row {row} out of bounds (end={end}, len={})", decoded.rgb.len()
+ )));
+ }
+ crop_bytes.extend_from_slice(&decoded.rgb[start..end]);
+ }
+
+ 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()))
}
/// Convert an aligned pet face image to ImageNet-normalized CHW tensor.
diff --git a/mobile/apps/photos/rust/src/ml/pet/detect.rs b/mobile/apps/photos/rust/src/ml/pet/detect.rs
index 1dd9d67d07..29e42c7bdc 100644
--- a/mobile/apps/photos/rust/src/ml/pet/detect.rs
+++ b/mobile/apps/photos/rust/src/ml/pet/detect.rs
@@ -46,12 +46,13 @@ pub fn run_pet_face_detection(
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)
+ // Flat output: total_elements, must infer row_len.
+ // Prefer the smallest valid row length to avoid false matches
+ // (e.g. 143 is divisible by both 11 and 13).
let total = output_data.len();
- if total % 13 == 0 { 13 }
+ if total % 11 == 0 { 11 }
else if total % 12 == 0 { 12 }
- else if total % 11 == 0 { 11 }
+ else if total % 13 == 0 { 13 }
else {
return Err(MlError::Postprocess(format!(
"unexpected pet face detector output size: {} (shape: {:?})",
@@ -207,9 +208,8 @@ pub fn run_pet_body_detection(
Ok(naive_nms_pet_body(detections, BODY_IOU_THRESHOLD))
}
-fn correct_for_maintained_aspect_ratio_3kp(
+fn correct_box_for_aspect_ratio(
box_xyxy: &mut [f32; 4],
- keypoints: &mut [[f32; 2]; 3],
scaled_width: usize,
scaled_height: usize,
pad_left: usize,
@@ -237,20 +237,18 @@ fn correct_for_maintained_aspect_ratio_3kp(
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(
+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
@@ -259,20 +257,15 @@ fn correct_box_for_aspect_ratio(
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) };
+ |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) / scaled_height).clamp(0.0, 1.0) };
+ |y: f32| -> f32 { ((y * INPUT_HEIGHT - pad_top as f32) / scaled_height as f32).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 calculate_iou_4(a: &[f32; 4], b: &[f32; 4]) -> f32 {
@@ -300,20 +293,26 @@ fn naive_nms_pet_face(
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;
+ let n = detections.len();
+ let mut suppressed = vec![false; n];
+ for i in 0..n {
+ if suppressed[i] {
+ continue;
+ }
+ for j in (i + 1)..n {
+ if suppressed[j] {
+ continue;
+ }
+ if calculate_iou_4(&detections[i].box_xyxy, &detections[j].box_xyxy) >= iou_threshold {
+ suppressed[j] = true;
}
}
- i += 1;
}
detections
+ .into_iter()
+ .zip(suppressed)
+ .filter_map(|(d, s)| if s { None } else { Some(d) })
+ .collect()
}
fn naive_nms_pet_body(
@@ -321,22 +320,28 @@ fn naive_nms_pet_body(
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 n = detections.len();
+ let mut suppressed = vec![false; n];
+ for i in 0..n {
+ if suppressed[i] {
+ continue;
+ }
+ for j in (i + 1)..n {
+ if suppressed[j] {
+ continue;
+ }
// Only suppress within the same COCO class so a dog and cat
// occupying the same region are both retained.
- if detections[i].coco_class == detections[j].coco_class {
- let iou = calculate_iou_4(&detections[i].box_xyxy, &detections[j].box_xyxy);
- if iou >= iou_threshold {
- detections.remove(j);
- continue;
- }
+ if detections[i].coco_class == detections[j].coco_class
+ && calculate_iou_4(&detections[i].box_xyxy, &detections[j].box_xyxy) >= iou_threshold
+ {
+ suppressed[j] = true;
}
- j += 1;
}
- i += 1;
}
detections
+ .into_iter()
+ .zip(suppressed)
+ .filter_map(|(d, s)| if s { None } else { Some(d) })
+ .collect()
}
diff --git a/mobile/apps/photos/rust/src/ml/pet/embed.rs b/mobile/apps/photos/rust/src/ml/pet/embed.rs
index dfd5c46464..dc2f22c0cf 100644
--- a/mobile/apps/photos/rust/src/ml/pet/embed.rs
+++ b/mobile/apps/photos/rust/src/ml/pet/embed.rs
@@ -102,6 +102,12 @@ pub fn run_pet_face_embedding(
)));
}
let embedding_size = output.len() / batch;
+ if embedding_size == 0 || output.len() != batch * embedding_size {
+ return Err(MlError::Postprocess(format!(
+ "pet face embedding output not evenly divisible: len={}, batch={batch}",
+ output.len()
+ )));
+ }
for (batch_idx, &orig_idx) in indices.iter().enumerate() {
let start = batch_idx * embedding_size;
@@ -199,6 +205,12 @@ pub fn run_pet_body_embedding(
)));
}
let embedding_size = output.len() / batch;
+ if embedding_size == 0 || output.len() != batch * embedding_size {
+ return Err(MlError::Postprocess(format!(
+ "pet body embedding output not evenly divisible: len={}, batch={batch}",
+ output.len()
+ )));
+ }
for (batch_idx, &orig_idx) in indices.iter().enumerate() {
let start = batch_idx * embedding_size;