π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mob][photos] Cleanup detections
laurenspriem25515c4403fa
diff --git a/mobile/lib/services/machine_learning/face_ml/face_detection/detection.dart b/mobile/lib/services/machine_learning/face_ml/face_detection/detection.dartindex de8535c871..ec68f06a26 100644--- a/mobile/lib/services/machine_learning/face_ml/face_detection/detection.dart+++ b/mobile/lib/services/machine_learning/face_ml/face_detection/detection.dart@@ -33,27 +33,6 @@ abstract class Detection {String toString();}-@Deprecated('Old method only used in other deprecated methods')-extension BBoxExtension on List<double> {- void roundBoxToDouble() {- final widthRounded = (this[2] - this[0]).roundToDouble();- final heightRounded = (this[3] - this[1]).roundToDouble();- this[0] = this[0].roundToDouble();- this[1] = this[1].roundToDouble();- this[2] = this[0] + widthRounded;- this[3] = this[1] + heightRounded;- }-- // double get xMinBox =>- // isNotEmpty ? this[0] : throw IndexError.withLength(0, length);- // double get yMinBox =>- // length >= 2 ? this[1] : throw IndexError.withLength(1, length);- // double get xMaxBox =>- // length >= 3 ? this[2] : throw IndexError.withLength(2, length);- // double get yMaxBox =>- // length >= 4 ? this[3] : throw IndexError.withLength(3, length);-}-/// This class represents a face detection with relative coordinates in the range [0, 1]./// The coordinates are relative to the image size. The pattern for the coordinates is always [x, y], where x is the horizontal coordinate and y is the vertical coordinate.///@@ -101,23 +80,8 @@ class FaceDetectionRelative extends Detection {.toList(),super(score: score);- factory FaceDetectionRelative.zero() {- return FaceDetectionRelative(- score: 0,- box: <double>[0, 0, 0, 0],- allKeypoints: <List<double>>[- [0, 0],- [0, 0],- [0, 0],- [0, 0],- [0, 0],- ],- );- }-/// This is used to initialize the FaceDetectionRelative object with default values./// This constructor is useful because it can be used to initialize a FaceDetectionRelative object as a constant.- /// Contrary to the `FaceDetectionRelative.zero()` constructor, this one gives immutable attributes [box] and [allKeypoints].FaceDetectionRelative.defaultInitialization(): box = const <double>[0, 0, 0, 0],allKeypoints = const <List<double>>[@@ -129,74 +93,6 @@ class FaceDetectionRelative extends Detection {],super.empty();- FaceDetectionRelative getNearestDetection(- List<FaceDetectionRelative> detections,- ) {- if (detections.isEmpty) {- throw ArgumentError("The detection list cannot be empty.");- }-- var nearestDetection = detections[0];- var minDistance = double.infinity;-- // Calculate the center of the current instance- final centerX1 = (xMinBox + xMaxBox) / 2;- final centerY1 = (yMinBox + yMaxBox) / 2;-- for (var detection in detections) {- final centerX2 = (detection.xMinBox + detection.xMaxBox) / 2;- final centerY2 = (detection.yMinBox + detection.yMaxBox) / 2;- final distance =- sqrt(pow(centerX2 - centerX1, 2) + pow(centerY2 - centerY1, 2));- if (distance < minDistance) {- minDistance = distance;- nearestDetection = detection;- }- }- return nearestDetection;- }-- void transformRelativeToOriginalImage(- List<double> fromBox, // [xMin, yMin, xMax, yMax]- List<double> toBox, // [xMin, yMin, xMax, yMax]- ) {- // Return if all elements of fromBox and toBox are equal- for (int i = 0; i < fromBox.length; i++) {- if (fromBox[i] != toBox[i]) {- break;- }- if (i == fromBox.length - 1) {- return;- }- }-- // Account for padding- final double paddingXRatio =- (fromBox[0] - toBox[0]) / (toBox[2] - toBox[0]);- final double paddingYRatio =- (fromBox[1] - toBox[1]) / (toBox[3] - toBox[1]);-- // Calculate the scaling and translation- final double scaleX = (fromBox[2] - fromBox[0]) / (1 - 2 * paddingXRatio);- final double scaleY = (fromBox[3] - fromBox[1]) / (1 - 2 * paddingYRatio);- final double translateX = fromBox[0] - paddingXRatio * scaleX;- final double translateY = fromBox[1] - paddingYRatio * scaleY;-- // Transform Box- _transformBox(box, scaleX, scaleY, translateX, translateY);-- // Transform All Keypoints- for (int i = 0; i < allKeypoints.length; i++) {- allKeypoints[i] = _transformPoint(- allKeypoints[i],- scaleX,- scaleY,- translateX,- translateY,- );- }- }-void correctForMaintainedAspectRatio(Dimensions originalSize,Dimensions newSize,@@ -311,16 +207,6 @@ class FaceDetectionRelative extends Detection {return faceID;}- /// This method is used to generate a faceID for a face detection that was manually added by the user.- static String toFaceIDEmpty({required int fileID}) {- return fileID.toString() + '_0';- }-- /// This method is used to check if a faceID corresponds to a manually added face detection and not an actual face detection.- static bool isFaceIDEmpty(String faceID) {- return faceID.split('_')[1] == '0';- }-@overrideString toString() {return 'FaceDetectionRelative( with relative coordinates: \n score: $score \n Box: xMinBox: $xMinBox, yMinBox: $yMinBox, xMaxBox: $xMaxBox, yMaxBox: $yMaxBox, \n Keypoints: leftEye: $leftEye, rightEye: $rightEye, nose: $nose, leftMouth: $leftMouth, rightMouth: $rightMouth \n )';@@ -348,6 +234,7 @@ class FaceDetectionRelative extends Detection {/// The width of the bounding box of the face detection, in relative range [0, 1].double get width => xMaxBox - xMinBox;+@override/// The height of the bounding box of the face detection, in relative range [0, 1].@@ -399,40 +286,11 @@ class FaceDetectionAbsolute extends Detection {);}- FaceDetectionAbsolute.defaultInitialization()- : box = const <double>[0, 0, 0, 0],- allKeypoints = const <List<double>>[- [0, 0],- [0, 0],- [0, 0],- [0, 0],- [0, 0],- ],- super.empty();-@overrideString toString() {return 'FaceDetectionAbsolute( with absolute coordinates: \n score: $score \n Box: xMinBox: $xMinBox, yMinBox: $yMinBox, xMaxBox: $xMaxBox, yMaxBox: $yMaxBox, \n Keypoints: leftEye: $leftEye, rightEye: $rightEye, nose: $nose, leftMouth: $leftMouth, rightMouth: $rightMouth \n )';}- Map<String, dynamic> toJson() {- return {- 'score': score,- 'box': box,- 'allKeypoints': allKeypoints,- };- }-- factory FaceDetectionAbsolute.fromJson(Map<String, dynamic> json) {- return FaceDetectionAbsolute(- score: (json['score'] as num).toDouble(),- box: List<double>.from(json['box']),- allKeypoints: (json['allKeypoints'] as List)- .map((item) => List<double>.from(item))- .toList(),- );- }-static FaceDetectionAbsolute empty = FaceDetectionAbsolute._zero();@override@@ -498,19 +356,3 @@ List<FaceDetectionAbsolute> relativeToAbsoluteDetections({return absoluteDetections;}--/// Returns an enlarged version of the [box] by a factor of [factor].-List<double> getEnlargedRelativeBox(List<double> box, [double factor = 2]) {- final boxCopy = List<double>.from(box, growable: false);- // The four values of the box in order are: [xMinBox, yMinBox, xMaxBox, yMaxBox].-- final width = boxCopy[2] - boxCopy[0];- final height = boxCopy[3] - boxCopy[1];-- boxCopy[0] -= width * (factor - 1) / 2;- boxCopy[1] -= height * (factor - 1) / 2;- boxCopy[2] += width * (factor - 1) / 2;- boxCopy[3] += height * (factor - 1) / 2;-- return boxCopy;-}diff --git a/mobile/lib/services/machine_learning/face_ml/face_detection/face_detection_exceptions.dart b/mobile/lib/services/machine_learning/face_ml/face_detection/face_detection_exceptions.dartdeleted file mode 100644index ed2f977913..0000000000--- a/mobile/lib/services/machine_learning/face_ml/face_detection/face_detection_exceptions.dart+++ /dev/null@@ -1,3 +0,0 @@-class YOLOFaceInterpreterInitializationException implements Exception {}--class YOLOFaceInterpreterRunException implements Exception {}diff --git a/mobile/lib/services/machine_learning/face_ml/face_detection/yolo_filter_extract_detections.dart b/mobile/lib/services/machine_learning/face_ml/face_detection/face_detection_postprocessing.dartsimilarity index 64%rename from mobile/lib/services/machine_learning/face_ml/face_detection/yolo_filter_extract_detections.dartrename to mobile/lib/services/machine_learning/face_ml/face_detection/face_detection_postprocessing.dartindex ec546533ab..417b99e8e4 100644--- a/mobile/lib/services/machine_learning/face_ml/face_detection/yolo_filter_extract_detections.dart+++ b/mobile/lib/services/machine_learning/face_ml/face_detection/face_detection_postprocessing.dart@@ -1,4 +1,5 @@import 'dart:developer' as dev show log;+import 'dart:math' as math show max, min;import 'package:photos/services/machine_learning/face_ml/face_detection/detection.dart';@@ -93,3 +94,49 @@ List<FaceDetectionRelative> yoloOnnxFilterExtractDetections(return outputDetections;}++List<FaceDetectionRelative> naiveNonMaxSuppression({+ required List<FaceDetectionRelative> detections,+ required double iouThreshold,+}) {+ // Sort the detections by score, the highest first+ detections.sort((a, b) => b.score.compareTo(a.score));++ // Loop through the detections and calculate the IOU+ for (var i = 0; i < detections.length - 1; i++) {+ for (var j = i + 1; j < detections.length; j++) {+ final iou = _calculateIOU(detections[i], detections[j]);+ if (iou >= iouThreshold) {+ detections.removeAt(j);+ j--;+ }+ }+ }+ return detections;+}++double _calculateIOU(+ FaceDetectionRelative detectionA,+ FaceDetectionRelative detectionB,+) {+ final areaA = detectionA.width * detectionA.height;+ final areaB = detectionB.width * detectionB.height;++ final intersectionMinX = math.max(detectionA.xMinBox, detectionB.xMinBox);+ final intersectionMinY = math.max(detectionA.yMinBox, detectionB.yMinBox);+ final intersectionMaxX = math.min(detectionA.xMaxBox, detectionB.xMaxBox);+ final intersectionMaxY = math.min(detectionA.yMaxBox, detectionB.yMaxBox);++ final intersectionWidth = intersectionMaxX - intersectionMinX;+ final intersectionHeight = intersectionMaxY - intersectionMinY;++ if (intersectionWidth < 0 || intersectionHeight < 0) {+ return 0.0; // If boxes do not overlap, IoU is 0+ }++ final intersectionArea = intersectionWidth * intersectionHeight;++ final unionArea = areaA + areaB - intersectionArea;++ return intersectionArea / unionArea;+}diff --git a/mobile/lib/services/machine_learning/face_ml/face_detection/face_detection_service.dart b/mobile/lib/services/machine_learning/face_ml/face_detection/face_detection_service.dartindex 974a3855ed..455f4e9c8d 100644--- a/mobile/lib/services/machine_learning/face_ml/face_detection/face_detection_service.dart+++ b/mobile/lib/services/machine_learning/face_ml/face_detection/face_detection_service.dart@@ -9,12 +9,12 @@ import 'package:logging/logging.dart';import 'package:onnxruntime/onnxruntime.dart';import "package:photos/face/model/dimension.dart";import 'package:photos/services/machine_learning/face_ml/face_detection/detection.dart';-import 'package:photos/services/machine_learning/face_ml/face_detection/face_detection_exceptions.dart';-import 'package:photos/services/machine_learning/face_ml/face_detection/naive_non_max_suppression.dart';-import 'package:photos/services/machine_learning/face_ml/face_detection/yolo_filter_extract_detections.dart';+import "package:photos/services/machine_learning/face_ml/face_detection/face_detection_postprocessing.dart";import "package:photos/services/remote_assets_service.dart";import "package:photos/utils/image_ml_util.dart";+class YOLOFaceInterpreterRunException implements Exception {}+/// This class is responsible for running the face detection model (YOLOv5Face) on ONNX runtime, and can be accessed through the singleton instance [FaceDetectionService.instance].class FaceDetectionService {static final _logger = Logger('FaceDetectionService');diff --git a/mobile/lib/services/machine_learning/face_ml/face_detection/naive_non_max_suppression.dart b/mobile/lib/services/machine_learning/face_ml/face_detection/naive_non_max_suppression.dartdeleted file mode 100644index 624181a669..0000000000--- a/mobile/lib/services/machine_learning/face_ml/face_detection/naive_non_max_suppression.dart+++ /dev/null@@ -1,49 +0,0 @@-import 'dart:math' as math show max, min;--import 'package:photos/services/machine_learning/face_ml/face_detection/detection.dart';--List<FaceDetectionRelative> naiveNonMaxSuppression({- required List<FaceDetectionRelative> detections,- required double iouThreshold,-}) {- // Sort the detections by score, the highest first- detections.sort((a, b) => b.score.compareTo(a.score));-- // Loop through the detections and calculate the IOU- for (var i = 0; i < detections.length - 1; i++) {- for (var j = i + 1; j < detections.length; j++) {- final iou = _calculateIOU(detections[i], detections[j]);- if (iou >= iouThreshold) {- detections.removeAt(j);- j--;- }- }- }- return detections;-}--double _calculateIOU(- FaceDetectionRelative detectionA,- FaceDetectionRelative detectionB,-) {- final areaA = detectionA.width * detectionA.height;- final areaB = detectionB.width * detectionB.height;-- final intersectionMinX = math.max(detectionA.xMinBox, detectionB.xMinBox);- final intersectionMinY = math.max(detectionA.yMinBox, detectionB.yMinBox);- final intersectionMaxX = math.min(detectionA.xMaxBox, detectionB.xMaxBox);- final intersectionMaxY = math.min(detectionA.yMaxBox, detectionB.yMaxBox);-- final intersectionWidth = intersectionMaxX - intersectionMinX;- final intersectionHeight = intersectionMaxY - intersectionMinY;-- if (intersectionWidth < 0 || intersectionHeight < 0) {- return 0.0; // If boxes do not overlap, IoU is 0- }-- final intersectionArea = intersectionWidth * intersectionHeight;-- final unionArea = areaA + areaB - intersectionArea;-- return intersectionArea / unionArea;-}diff --git a/mobile/lib/services/machine_learning/face_ml/face_ml_service.dart b/mobile/lib/services/machine_learning/face_ml/face_ml_service.dartindex 435fd4dddd..d87993d180 100644--- a/mobile/lib/services/machine_learning/face_ml/face_ml_service.dart+++ b/mobile/lib/services/machine_learning/face_ml/face_ml_service.dart@@ -33,7 +33,6 @@ import "package:photos/service_locator.dart";import 'package:photos/services/machine_learning/face_ml/face_clustering/face_clustering_service.dart';import "package:photos/services/machine_learning/face_ml/face_clustering/face_db_info_for_clustering.dart";import 'package:photos/services/machine_learning/face_ml/face_detection/detection.dart';-import 'package:photos/services/machine_learning/face_ml/face_detection/face_detection_exceptions.dart';import 'package:photos/services/machine_learning/face_ml/face_detection/face_detection_service.dart';import 'package:photos/services/machine_learning/face_ml/face_embedding/face_embedding_exceptions.dart';import 'package:photos/services/machine_learning/face_ml/face_embedding/face_embedding_service.dart';@@ -1141,8 +1140,6 @@ class FaceMlService {}return faces;- } on YOLOFaceInterpreterInitializationException {- throw CouldNotInitializeFaceDetector();} on YOLOFaceInterpreterRunException {throw CouldNotRunFaceDetector();} catch (e) {