Skip to content

armgit / ente

Public Imported from GitHub
0

💚 End-to-end encrypted cloud for everything.

Remove old dart ML code

laurenspriem1f17524fc759
diff --git a/infra/ml/test/README.md b/infra/ml/test/README.md
index ee2ea72b60..6f21986278 100644
--- a/infra/ml/test/README.md
+++ b/infra/ml/test/README.md
@@ -31,7 +31,6 @@ Common flags:
- `--render-detection-overlays` (generate annotated detection images under `out/parity/detections/<platform>/`; includes selected platforms plus `python` ground truth)
- `--reuse-mobile-application-binary` (reuse an existing built mobile binary when available; useful for repeated local parity runs without code changes)
- `--no-parallel-mobile-runners` (force sequential android/ios runner execution)
-- `--legacy` (mobile only; run the legacy Dart/ONNX ML pipeline instead of the default Rust ML pipeline)
Outputs go to `infra/ml/test/out/parity/` by default, including:
diff --git a/infra/ml/test/ground_truth/README.md b/infra/ml/test/ground_truth/README.md
index bb338500b7..9aa2ffb69b 100644
--- a/infra/ml/test/ground_truth/README.md
+++ b/infra/ml/test/ground_truth/README.md
@@ -4,7 +4,7 @@ This directory stores the Python ground-truth assets for the ML indexing parity
- `manifest.json`: corpus definition and per-item metadata.
- `schema.py`: strict shared result schema used by all runners.
-- `clip.py`, `face_detection.py`, `face_alignment.py`, `face_embedding.py`, `pipeline.py`: ONNX-backed Python reference pipeline that mirrors the mobile `analyzeImageStatic` flow using Pillow + OpenCV + ONNX Runtime.
+- `clip.py`, `face_detection.py`, `face_alignment.py`, `face_embedding.py`, `pipeline.py`: ONNX-backed Python reference pipeline for validating the production Rust ML indexing flow using Pillow + OpenCV + ONNX Runtime.
Runtime outputs (`goldens/*.json`, `goldens/results.json`, and `infra/ml/test/out/parity/**`) are generated on demand and are gitignored.
diff --git a/infra/ml/test/run_ml_parity_tests.sh b/infra/ml/test/run_ml_parity_tests.sh
index 53f7d75a9a..258f1f9309 100755
--- a/infra/ml/test/run_ml_parity_tests.sh
+++ b/infra/ml/test/run_ml_parity_tests.sh
@@ -17,7 +17,6 @@ VERBOSE=false
RENDER_DETECTION_OVERLAYS=false
REUSE_MOBILE_APPLICATION_BINARY=false
PARALLEL_MOBILE_RUNNERS=true
-USE_LEGACY_MOBILE_ML=false
LOCAL_MIRROR_PORT=""
LOCAL_MIRROR_PID=""
@@ -35,7 +34,6 @@ Flags:
--render-detection-overlays (default: disabled; render annotated face detection images to out/parity/detections/<platform>/)
--reuse-mobile-application-binary (default: disabled; reuse an existing built mobile binary when available)
--no-parallel-mobile-runners (default: disabled; run android/ios runners sequentially)
- --legacy (default: disabled; mobile only, run legacy Dart/ONNX ML pipeline instead of Rust)
EOF
}
@@ -65,10 +63,6 @@ while (($# > 0)); do
PARALLEL_MOBILE_RUNNERS=false
shift
;;
- --legacy)
- USE_LEGACY_MOBILE_ML=true
- shift
- ;;
-h|--help)
usage
exit 0
@@ -260,11 +254,6 @@ start_local_mirror_server() {
return 1
}
-MOBILE_ML_ROUTE="rust"
-if $USE_LEGACY_MOBILE_ML; then
- MOBILE_ML_ROUTE="legacy-dart"
-fi
-
echo "Running ML parity suite"
print_kv "platforms:" "$PLATFORMS"
print_kv "output_dir:" "$OUTPUT_DIR"
@@ -273,7 +262,7 @@ print_kv "render_detection_overlays:" "$RENDER_DETECTION_OVERLAYS"
print_kv "android_build_mode:" "${ML_PARITY_ANDROID_BUILD_MODE:-profile}"
print_kv "reuse_mobile_application_binary:" "$REUSE_MOBILE_APPLICATION_BINARY"
print_kv "parallel_mobile_runners:" "$PARALLEL_MOBILE_RUNNERS"
-print_kv "mobile_ml_route:" "$MOBILE_ML_ROUTE"
+print_kv "mobile_ml_route:" "rust"
declare -a selected_platforms=()
case "$PLATFORMS" in
@@ -908,7 +897,6 @@ run_mobile_runner() {
--no-dds
--dart-define=ML_PARITY_MANIFEST_B64="$MANIFEST_B64"
--dart-define=ML_PARITY_CODE_REVISION="$CODE_REVISION"
- --dart-define=ML_PARITY_USE_LEGACY_MOBILE_ML="$USE_LEGACY_MOBILE_ML"
)
if [[ -z "$resolved_device_id" ]]; then
diff --git a/mobile/apps/photos/android/app/build.gradle b/mobile/apps/photos/android/app/build.gradle
index 5e7a964d6a..b47050adc2 100644
--- a/mobile/apps/photos/android/app/build.gradle
+++ b/mobile/apps/photos/android/app/build.gradle
@@ -173,7 +173,6 @@ dependencies {
implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.0'
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava'
- implementation 'com.microsoft.onnxruntime:onnxruntime-android:1.27.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
diff --git a/mobile/apps/photos/integration_test/ml_parity_shared.dart b/mobile/apps/photos/integration_test/ml_parity_shared.dart
index 61ba9691dd..768b6d4dcc 100644
--- a/mobile/apps/photos/integration_test/ml_parity_shared.dart
+++ b/mobile/apps/photos/integration_test/ml_parity_shared.dart
@@ -9,12 +9,10 @@ import "package:path_provider/path_provider.dart";
import "package:photos/core/configuration.dart";
import "package:photos/core/network/network.dart";
import "package:photos/service_locator.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_service.dart";
import "package:photos/services/machine_learning/ml_indexing_isolate.dart";
import "package:photos/services/machine_learning/ml_model.dart";
+import "package:photos/services/machine_learning/ml_model_assets.dart";
import "package:photos/services/machine_learning/ml_result.dart";
-import "package:photos/services/machine_learning/semantic_search/clip/clip_image_encoder.dart";
import "package:photos/utils/isolate/isolate_operations.dart";
import "package:shared_preferences/shared_preferences.dart";
@@ -26,11 +24,6 @@ const _codeRevision = String.fromEnvironment(
const _localMirrorBaseUrl = String.fromEnvironment(
"ML_PARITY_LOCAL_MIRROR_BASE_URL",
);
-const _useLegacyMobileMl = bool.fromEnvironment(
- "ML_PARITY_USE_LEGACY_MOBILE_ML",
- defaultValue: false,
-);
-const _useRustMl = !_useLegacyMobileMl;
const _localModelMirrorRelativeDir = ".cache/local_model_mirror";
const _parityReportDataKey = "ml_parity_results_json";
@@ -57,7 +50,7 @@ class _ManifestItem {
class _ModelSpec {
final String schemaName;
- final MlModel model;
+ final MlModelAsset model;
const _ModelSpec({required this.schemaName, required this.model});
}
@@ -88,57 +81,46 @@ void runMLParityIntegrationTest({required String expectedPlatform}) {
await _stageModelsFromLocalMirror(appSupportDir);
final modelSpecs = _modelSpecs();
- final loadedModels = await _downloadAndLoadModels(
- modelSpecs: modelSpecs,
- loadLegacySessions: _useLegacyMobileMl,
- );
+ final loadedModels = await _downloadModels(modelSpecs);
- final runtime = _useRustMl
- ? "rust-ml"
- : (Platform.isAndroid
- ? "flutter-mobile-onnx-platform-plugin"
- : "flutter-mobile-onnx-ffi");
+ const runtime = "rust-ml";
final results = <Map<String, dynamic>>[];
final errors = <Map<String, dynamic>>[];
- try {
- for (int i = 0; i < manifestItems.length; i++) {
- final item = manifestItems[i];
- final stopwatch = Stopwatch()..start();
- try {
- final localFixturePath = await _downloadFixture(
- item: item,
- fixtureRoot: fixtureRoot,
- );
- final mlResult = await _analyzeImage(
- fileID: i + 1,
- filePath: localFixturePath,
- loadedModels: loadedModels,
- );
- stopwatch.stop();
- results.add(
- _toParityResult(
- fileID: item.fileID,
- mlResult: mlResult,
- expectedPlatform: expectedPlatform,
- runtime: runtime,
- models: loadedModels.modelMetadata,
- totalMS: stopwatch.elapsedMilliseconds,
- ),
- );
- } catch (error, stackTrace) {
- stopwatch.stop();
- final stackLines = stackTrace.toString().split("\n");
- errors.add({
- "file_id": item.fileID,
- "error": error.toString(),
- "timing_ms": stopwatch.elapsedMilliseconds,
- "stack": stackLines.isNotEmpty ? stackLines.first : "",
- });
- }
+ for (int i = 0; i < manifestItems.length; i++) {
+ final item = manifestItems[i];
+ final stopwatch = Stopwatch()..start();
+ try {
+ final localFixturePath = await _downloadFixture(
+ item: item,
+ fixtureRoot: fixtureRoot,
+ );
+ final mlResult = await _analyzeImage(
+ fileID: i + 1,
+ filePath: localFixturePath,
+ loadedModels: loadedModels,
+ );
+ stopwatch.stop();
+ results.add(
+ _toParityResult(
+ fileID: item.fileID,
+ mlResult: mlResult,
+ expectedPlatform: expectedPlatform,
+ runtime: runtime,
+ models: loadedModels.modelMetadata,
+ totalMS: stopwatch.elapsedMilliseconds,
+ ),
+ );
+ } catch (error, stackTrace) {
+ stopwatch.stop();
+ final stackLines = stackTrace.toString().split("\n");
+ errors.add({
+ "file_id": item.fileID,
+ "error": error.toString(),
+ "timing_ms": stopwatch.elapsedMilliseconds,
+ "stack": stackLines.isNotEmpty ? stackLines.first : "",
+ });
}
- } finally {
- await _releaseModels(loadedModels);
}
final outputPayload = {
@@ -197,86 +179,48 @@ List<_ModelSpec> _modelSpecs() {
return [
_ModelSpec(
schemaName: "face_detection",
- model: FaceDetectionService.instance,
+ model: FaceDetectionModel.instance,
),
_ModelSpec(
schemaName: "face_embedding",
- model: FaceEmbeddingService.instance,
+ model: FaceEmbeddingModel.instance,
),
- _ModelSpec(schemaName: "clip", model: ClipImageEncoder.instance),
+ _ModelSpec(schemaName: "clip", model: ClipImageModel.instance),
];
}
class _LoadedModels {
- final List<String> modelNames;
- final List<int> modelAddresses;
final Map<String, String> modelMetadata;
final Map<String, String> modelPathsBySchema;
const _LoadedModels({
- required this.modelNames,
- required this.modelAddresses,
required this.modelMetadata,
required this.modelPathsBySchema,
});
}
-Future<_LoadedModels> _downloadAndLoadModels({
- required List<_ModelSpec> modelSpecs,
- required bool loadLegacySessions,
-}) async {
+Future<_LoadedModels> _downloadModels(List<_ModelSpec> modelSpecs) async {
await _ensureModelNetworkContext();
- final modelNames = <String>[];
- final modelPaths = <String>[];
final modelMetadata = <String, String>{};
final modelPathsBySchema = <String, String>{};
for (final modelSpec in modelSpecs) {
- final (modelName, modelPath) = await modelSpec.model.getModelNameAndPath();
+ final modelPath = await modelSpec.model.getModelPath();
final modelFile = File(modelPath);
if (!modelFile.existsSync()) {
throw StateError(
- "Resolved model path does not exist for $modelName: $modelPath",
+ "Resolved model path does not exist for ${modelSpec.schemaName}: $modelPath",
);
}
- modelNames.add(modelName);
- modelPaths.add(modelFile.path);
modelPathsBySchema[modelSpec.schemaName] = modelFile.path;
final modelSHA256 = await _sha256HexOfFile(modelFile);
modelMetadata[modelSpec.schemaName] =
"${modelFile.uri.pathSegments.last}:$modelSHA256";
}
- if (!loadLegacySessions) {
- return _LoadedModels(
- modelNames: modelNames,
- modelAddresses: const <int>[],
- modelMetadata: modelMetadata,
- modelPathsBySchema: modelPathsBySchema,
- );
- }
-
- final loadedAddressesRaw =
- await MLIndexingIsolate.instance.runInIsolate(
- IsolateOperation.loadIndexingModels,
- {"modelNames": modelNames, "modelPaths": modelPaths},
- )
- as List<dynamic>;
-
- final modelAddresses = loadedAddressesRaw
- .map((address) => (address as num).toInt())
- .toList(growable: false);
- if (modelAddresses.length != modelNames.length) {
- throw StateError(
- "Model address count mismatch: expected ${modelNames.length}, got ${modelAddresses.length}",
- );
- }
-
return _LoadedModels(
- modelNames: modelNames,
- modelAddresses: modelAddresses,
modelMetadata: modelMetadata,
modelPathsBySchema: modelPathsBySchema,
);
@@ -303,17 +247,6 @@ Future<void> _ensureModelNetworkContext() async {
_modelNetworkContextInitialized = true;
}
-Future<void> _releaseModels(_LoadedModels loadedModels) async {
- if (loadedModels.modelAddresses.isEmpty) {
- return;
- }
- await MLIndexingIsolate.instance
- .runInIsolate(IsolateOperation.releaseIndexingModels, {
- "modelNames": loadedModels.modelNames,
- "modelAddresses": loadedModels.modelAddresses,
- });
-}
-
Future<void> _stageFixturesFromLocalMirror({
required List<_ManifestItem> manifestItems,
required Directory fixtureRoot,
@@ -489,52 +422,34 @@ Future<MLResult> _analyzeImage({
required String filePath,
required _LoadedModels loadedModels,
}) async {
- const useRustMl = _useRustMl;
final args = <String, dynamic>{
"enteFileID": fileID,
"filePath": filePath,
"runFaces": true,
"runClip": true,
- "useRustMl": useRustMl,
};
- if (useRustMl) {
- final faceDetectionModelPath =
- loadedModels.modelPathsBySchema["face_detection"];
- final faceEmbeddingModelPath =
- loadedModels.modelPathsBySchema["face_embedding"];
- final clipImageModelPath = loadedModels.modelPathsBySchema["clip"];
- if (faceDetectionModelPath == null ||
- faceEmbeddingModelPath == null ||
- clipImageModelPath == null) {
- throw StateError(
- "Missing model paths for Rust ML parity route: face_detection/face_embedding/clip",
- );
- }
- args.addAll({
- "faceDetectionModelPath": faceDetectionModelPath,
- "faceEmbeddingModelPath": faceEmbeddingModelPath,
- "clipImageModelPath": clipImageModelPath,
- "preferCoreml": Platform.isIOS,
- "preferNnapi": Platform.isAndroid,
- "preferXnnpack": Platform.isAndroid,
- "allowCpuFallback": true,
- });
- } else {
- if (loadedModels.modelAddresses.length < 3) {
- throw StateError(
- "Missing loaded model addresses for static parity route",
- );
- }
- final faceDetectionAddress = loadedModels.modelAddresses[0];
- final faceEmbeddingAddress = loadedModels.modelAddresses[1];
- final clipAddress = loadedModels.modelAddresses[2];
- args.addAll({
- "faceDetectionAddress": faceDetectionAddress,
- "faceEmbeddingAddress": faceEmbeddingAddress,
- "clipImageAddress": clipAddress,
- });
+ final faceDetectionModelPath =
+ loadedModels.modelPathsBySchema["face_detection"];
+ final faceEmbeddingModelPath =
+ loadedModels.modelPathsBySchema["face_embedding"];
+ final clipImageModelPath = loadedModels.modelPathsBySchema["clip"];
+ if (faceDetectionModelPath == null ||
+ faceEmbeddingModelPath == null ||
+ clipImageModelPath == null) {
+ throw StateError(
+ "Missing model paths for Rust ML parity route: face_detection/face_embedding/clip",
+ );
}
+ args.addAll({
+ "faceDetectionModelPath": faceDetectionModelPath,
+ "faceEmbeddingModelPath": faceEmbeddingModelPath,
+ "clipImageModelPath": clipImageModelPath,
+ "preferCoreml": Platform.isIOS,
+ "preferNnapi": Platform.isAndroid,
+ "preferXnnpack": Platform.isAndroid,
+ "allowCpuFallback": true,
+ });
final resultJSONString =
await MLIndexingIsolate.instance.runInIsolate(
diff --git a/mobile/apps/photos/ios/Podfile.lock b/mobile/apps/photos/ios/Podfile.lock
index c3c4ce8b1f..f596254e3e 100644
--- a/mobile/apps/photos/ios/Podfile.lock
+++ b/mobile/apps/photos/ios/Podfile.lock
@@ -14,8 +14,6 @@ PODS:
- cupertino_http (0.0.1):
- Flutter
- FlutterMacOS
- - dart_ui_isolate (0.0.1):
- - Flutter
- device_info_plus (0.0.1):
- Flutter
- ente_photos_rust (0.0.1):
@@ -259,7 +257,6 @@ DEPENDENCIES:
- camera_avfoundation (from `.symlinks/plugins/camera_avfoundation/ios`)
- connectivity_plus (from `.symlinks/plugins/connectivity_plus/ios`)
- cupertino_http (from `.symlinks/plugins/cupertino_http/darwin`)
- - dart_ui_isolate (from `.symlinks/plugins/dart_ui_isolate/ios`)
- device_info_plus (from `.symlinks/plugins/device_info_plus/ios`)
- ente_photos_rust (from `.symlinks/plugins/ente_photos_rust/ios`)
- ente_qr (from `.symlinks/plugins/ente_qr/ios`)
@@ -351,8 +348,6 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/connectivity_plus/ios"
cupertino_http:
:path: ".symlinks/plugins/cupertino_http/darwin"
- dart_ui_isolate:
- :path: ".symlinks/plugins/dart_ui_isolate/ios"
device_info_plus:
:path: ".symlinks/plugins/device_info_plus/ios"
ente_photos_rust:
@@ -470,7 +465,6 @@ SPEC CHECKSUMS:
camera_avfoundation: 5675ca25298b6f81fa0a325188e7df62cc217741
connectivity_plus: cb623214f4e1f6ef8fe7403d580fdad517d2f7dd
cupertino_http: 94ac07f5ff090b8effa6c5e2c47871d48ab7c86c
- dart_ui_isolate: 46f6714abe6891313267153ef6f9748d8ecfcab1
device_info_plus: 21fcca2080fbcd348be798aa36c3e5ed849eefbe
ente_photos_rust: 361e162c8d0d816ad94d8a80d41e8f8b96324d93
ente_qr: 86beaf5d2644705db9b565b32dd8b82c05fb36af
diff --git a/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj b/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj
index 24503adbb0..4629cb1e9a 100644
--- a/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj
+++ b/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj
@@ -635,7 +635,6 @@
"${BUILT_PRODUCTS_DIR}/camera_avfoundation/camera_avfoundation.framework",
"${BUILT_PRODUCTS_DIR}/connectivity_plus/connectivity_plus.framework",
"${BUILT_PRODUCTS_DIR}/cupertino_http/cupertino_http.framework",
- "${BUILT_PRODUCTS_DIR}/dart_ui_isolate/dart_ui_isolate.framework",
"${BUILT_PRODUCTS_DIR}/device_info_plus/device_info_plus.framework",
"${BUILT_PRODUCTS_DIR}/ente_photos_rust/ente_photos_rust.framework",
"${BUILT_PRODUCTS_DIR}/ente_qr/ente_qr.framework",
@@ -736,7 +735,6 @@
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/camera_avfoundation.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/connectivity_plus.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/cupertino_http.framework",
- "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/dart_ui_isolate.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/device_info_plus.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ente_photos_rust.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ente_qr.framework",
diff --git a/mobile/apps/photos/lib/service_locator.dart b/mobile/apps/photos/lib/service_locator.dart
index 122132629d..88d5744220 100644
--- a/mobile/apps/photos/lib/service_locator.dart
+++ b/mobile/apps/photos/lib/service_locator.dart
@@ -29,7 +29,7 @@ import "package:photos/services/entity_service.dart";
import "package:photos/services/filedata/filedata_service.dart";
import "package:photos/services/location_service.dart";
import "package:photos/services/machine_learning/compute_controller.dart";
-import "package:photos/services/machine_learning/face_ml/face_recognition_service.dart";
+import "package:photos/services/machine_learning/face_ml/person/person_feedback_service.dart";
import "package:photos/services/magic_cache_service.dart";
import "package:photos/services/memories_cache_service.dart";
import "package:photos/services/permission/service.dart";
@@ -226,10 +226,10 @@ ComputeController get computeController {
return _computeController!;
}
-FaceRecognitionService? _faceRecognitionService;
-FaceRecognitionService get faceRecognitionService {
- _faceRecognitionService ??= FaceRecognitionService();
- return _faceRecognitionService!;
+PersonFeedbackService? _personFeedbackService;
+PersonFeedbackService get personFeedbackService {
+ _personFeedbackService ??= PersonFeedbackService();
+ return _personFeedbackService!;
}
PermissionService? _permissionService;
diff --git a/mobile/apps/photos/lib/services/machine_learning/face_ml/face_alignment/similarity_transform.dart b/mobile/apps/photos/lib/services/machine_learning/face_ml/face_alignment/similarity_transform.dart
deleted file mode 100644
index e6eb7469be..0000000000
--- a/mobile/apps/photos/lib/services/machine_learning/face_ml/face_alignment/similarity_transform.dart
+++ /dev/null
@@ -1,147 +0,0 @@
-import 'dart:math' show atan2;
-import 'package:ml_linalg/linalg.dart';
-import 'package:photos/extensions/ml_linalg_extensions.dart';
-import 'package:photos/services/machine_learning/face_ml/face_alignment/alignment_result.dart';
-
-/// Class to compute the similarity transform between two sets of points.
-///
-/// The class estimates the parameters of the similarity transformation via the `estimate` function.
-/// After estimation, the transformation can be applied to an image using the `warpAffine` function.
-class SimilarityTransform {
- static const _mobilefacenetIdeal4Landmarks = [
- <double>[38.2946, 51.6963],
- <double>[73.5318, 51.5014],
- <double>[56.0252, 71.7366],
- <double>[56.1396, 92.2848],
- ];
- static const _mobilefacenetIdeal5Landmarks = [
- <double>[38.2946, 51.6963],
- <double>[73.5318, 51.5014],
- <double>[56.0252, 71.7366],
- <double>[41.5493, 92.3655],
- <double>[70.7299, 92.2041],
- ];
- static List<List<double>> get mobilefacenetIdealNormalized4 =>
- _mobilefacenetIdeal4Landmarks
- .map((list) => list.map((value) => value / 112.0).toList())
- .toList();
- static List<List<double>> get mobilefacenetIdealNormalized5 =>
- _mobilefacenetIdeal5Landmarks
- .map((list) => list.map((value) => value / 112.0).toList())
- .toList();
-
- SimilarityTransform();
-
- /// Function to estimate the parameters of the affine transformation.
- ///
- /// Returns a tuple of (AlignmentResult, bool). The bool indicates whether the parameters are valid or not.
- ///
- /// Runs efficiently in about 1-3 ms after initial warm-up.
- ///
- /// It takes the source and destination points as input and returns the
- /// parameters of the affine transformation as output. The function
- /// returns false if the parameters cannot be estimated. The function
- /// estimates the parameters by solving a least-squares problem using
- /// the Umeyama algorithm, via [_umeyama].
- static (AlignmentResult, bool) estimate(List<List<double>> src) {
- final (params, center, size, rotation) = _umeyama(
- src,
- mobilefacenetIdealNormalized5,
- true,
- );
- final alignmentResult = AlignmentResult(
- affineMatrix: params.to2DList(),
- center: center,
- size: size,
- rotation: rotation,
- );
- // We check for NaN in the transformation matrix params.
- final isNoNanInParam = !params.asFlattenedList.any(
- (element) => element.isNaN,
- );
- return (alignmentResult, isNoNanInParam);
- }
-
- static (Matrix, List<double>, double, double) _umeyama(
- List<List<double>> src,
- List<List<double>> dst, [
- bool estimateScale = true,
- ]) {
- final srcMat = Matrix.fromList(
- src,
- // .map((list) => list.map((value) => value.toDouble()).toList())
- // .toList(),
- );
- final dstMat = Matrix.fromList(dst);
- final num = srcMat.rowCount;
- final dim = srcMat.columnCount;
-
- // Compute mean of src and dst.
- final srcMean = srcMat.mean(Axis.columns);
- final dstMean = dstMat.mean(Axis.columns);
-
- // Subtract mean from src and dst.
- final srcDemean = srcMat.mapRows((vector) => vector - srcMean);
- final dstDemean = dstMat.mapRows((vector) => vector - dstMean);
-
- // Eq. (38).
- final A = (dstDemean.transpose() * srcDemean) / num;
-
- // Eq. (39).
- var d = Vector.filled(dim, 1.0);
- if (A.determinant() < 0) {
- d = d.set(dim - 1, -1);
- }
-
- var T = Matrix.identity(dim + 1);
-
- final svdResult = A.svd();
- final Matrix U = svdResult['U']!;
- final Vector S = svdResult['S']!;
- final Matrix V = svdResult['V']!;
-
- // Eq. (40) and (43).
- final rank = A.matrixRank();
- if (rank == 0) {
- return (T * double.nan, <double>[0, 0], 1, 0);
- } else if (rank == dim - 1) {
- if (U.determinant() * V.determinant() > 0) {
- T = T.setSubMatrix(0, dim, 0, dim, U * V);
- } else {
- final s = d[dim - 1];
- d = d.set(dim - 1, -1);
- final replacement = U * Matrix.diagonal(d.toList()) * V;
- T = T.setSubMatrix(0, dim, 0, dim, replacement);
- d = d.set(dim - 1, s);
- }
- } else {
- final replacement = U * Matrix.diagonal(d.toList()) * V;
- T = T.setSubMatrix(0, dim, 0, dim, replacement);
- }
- final Matrix simRotation = U * Matrix.diagonal(d.toList()) * V;
-
- var scale = 1.0;
- if (estimateScale) {
- // Eq. (41) and (42).
- scale = 1.0 / srcDemean.variance(Axis.columns).sum() * (S * d).sum();
- }
-
- final subTIndices = Iterable<int>.generate(dim, (index) => index);
- final subT = T.sample(rowIndices: subTIndices, columnIndices: subTIndices);
- final newSubT = dstMean - (subT * srcMean) * scale;
- T = T.setValues(0, dim, dim, dim + 1, newSubT);
- final newNewSubT =
- T.sample(rowIndices: subTIndices, columnIndices: subTIndices) * scale;
- T = T.setSubMatrix(0, dim, 0, dim, newNewSubT);
-
- // final List<double> translation = [T[0][2], T[1][2]];
- // final simRotation = replacement?;
- final size = 1 / scale;
- final rotation = atan2(simRotation[1][0], simRotation[0][0]);
- final meanTranslation = (dstMean - 0.5) * size;
- final centerMat = srcMean - meanTranslation;
- final List<double> center = [centerMat[0], centerMat[1]];
-
- return (T, center, size, rotation);
- }
-}
diff --git a/mobile/apps/photos/lib/services/machine_learning/face_ml/face_clustering/face_clustering_service.dart b/mobile/apps/photos/lib/services/machine_learning/face_ml/face_clustering/face_clustering_service.dart
index 5fd4f35654..a418f782c2 100644
--- a/mobile/apps/photos/lib/services/machine_learning/face_ml/face_clustering/face_clustering_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/face_ml/face_clustering/face_clustering_service.dart
@@ -79,9 +79,6 @@ class FaceClusteringService extends SuperIsolate {
static double defaultDistanceThreshold = kRecommendedDistanceThreshold;
- @override
- bool get isDartUiIsolate => false;
-
@override
String get isolateName => "FaceClusteringIsolate";
diff --git a/mobile/apps/photos/lib/services/machine_learning/face_ml/face_detection/face_detection_postprocessing.dart b/mobile/apps/photos/lib/services/machine_learning/face_ml/face_detection/face_detection_postprocessing.dart
deleted file mode 100644
index 624181a669..0000000000
--- a/mobile/apps/photos/lib/services/machine_learning/face_ml/face_detection/face_detection_postprocessing.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/apps/photos/lib/services/machine_learning/face_ml/face_detection/face_detection_service.dart b/mobile/apps/photos/lib/services/machine_learning/face_ml/face_detection/face_detection_service.dart
deleted file mode 100644
index 53ee9abd96..0000000000
--- a/mobile/apps/photos/lib/services/machine_learning/face_ml/face_detection/face_detection_service.dart
+++ /dev/null
@@ -1,253 +0,0 @@
-import "dart:async";
-import 'dart:typed_data' show Float32List, Uint8List;
-
-import 'package:logging/logging.dart';
-import "package:onnx_dart/onnx_dart.dart";
-import 'package:onnxruntime/onnxruntime.dart';
-import "package:photos/models/ml/face/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_postprocessing.dart";
-import "package:photos/services/machine_learning/face_ml/face_filtering/face_filtering_constants.dart";
-import "package:photos/services/machine_learning/ml_model.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].
-///
-/// Model size: ~30.8 MB.
-class FaceDetectionService extends MlModel {
- static const kRemoteBucketModelPath = "yolov5s_face_640_640_dynamic.onnx";
- static const kModelSha256 =
- "71a008707283b03db4881449a24f4da197f9dbd9ddaca5c91fcdb363fbf7e06f";
- static const _modelName = "YOLOv5Face";
-
- @override
- String get modelRemotePath => kModelBucketEndpoint + kRemoteBucketModelPath;
-
- @override
- String get modelSha256 => kModelSha256;
-
- @override
- Logger get logger => _logger;
- static final _logger = Logger('FaceDetectionService');
-
- @override
- String get modelName => _modelName;
-
- static const int kInputWidth = 640;
- static const int kInputHeight = 640;
- static const double kIouThreshold = 0.4;
- static const double kMinScoreSigmoidThreshold = kMinFaceDetectionScore;
- static const int kNumKeypoints = 5;
-
- // Singleton pattern
- FaceDetectionService._privateConstructor();
-
- static final instance = FaceDetectionService._privateConstructor();
-
- factory FaceDetectionService() => instance;
-
- /// Detects faces in the given image data.
- static Future<List<FaceDetectionRelative>> predict(
- Dimensions dimensions,
- Uint8List rawRgbaBytes,
- int sessionAddress,
- ) async {
- assert(
- !MlModel.usePlatformPlugin
- ? (sessionAddress != 0 && sessionAddress != -1)
- : true,
- 'sessionAddress should be valid',
- );
-
- final startTime = DateTime.now();
-
- final (inputImageList, scaledSize) = await preprocessImageYoloFace(
- dimensions,
- rawRgbaBytes,
- );
- final preprocessingTime = DateTime.now();
- final preprocessingMs = preprocessingTime
- .difference(startTime)
- .inMilliseconds;
-
- // Run inference
- List<List<List<double>>>? nestedResults = [];
- try {
- if (MlModel.usePlatformPlugin) {
- nestedResults = await _runPlatformPluginPredict(inputImageList);
- } else {
- nestedResults = _runFFIBasedPredict(sessionAddress, inputImageList);
- }
- final inferenceTime = DateTime.now();
- final inferenceMs = inferenceTime
- .difference(preprocessingTime)
- .inMilliseconds;
- _logger.info(
- 'Face detection is finished, in ${inferenceTime.difference(startTime).inMilliseconds} ms (preprocessing: $preprocessingMs ms, inference: $inferenceMs ms)',
- );
- } catch (e, s) {
- _logger.severe(
- 'Error while running inference (PlatformPlugin: ${MlModel.usePlatformPlugin})',
- e,
- s,
- );
- throw YOLOFaceInterpreterRunException();
- }
- try {
- final relativeDetections = _yoloPostProcessOutputs(
- nestedResults!,
- scaledSize,
- );
- return relativeDetections;
- } catch (e, s) {
- _logger.severe('Error while post processing', e, s);
- rethrow;
- }
- }
-
- static List<List<List<double>>>? _runFFIBasedPredict(
- int sessionAddress,
- Float32List inputImageList,
- ) {
- const inputShape = [1, 3, kInputHeight, kInputWidth];
- final inputOrt = OrtValueTensor.createTensorWithDataList(
- inputImageList,
- inputShape,
- );
- final inputs = {'input': inputOrt};
- final runOptions = OrtRunOptions();
- final session = OrtSession.fromAddress(sessionAddress);
- final List<OrtValue?> outputs = session.run(runOptions, inputs);
- final result =
- outputs[0]?.value as List<List<List<double>>>; // [1, 25200, 16]
- inputOrt.release();
- runOptions.release();
- for (var element in outputs) {
- element?.release();
- }
-
- return result;
- }
-
- static Future<List<List<List<double>>>> _runPlatformPluginPredict(
- Float32List inputImageList,
- ) async {
- final OnnxDart plugin = OnnxDart();
- final result = await plugin.predict(inputImageList, _modelName);
-
- final int resultLength = result!.length;
- assert(resultLength % 25200 * 16 == 0);
- const int outerLength = 1;
- const int middleLength = 25200;
- const int innerLength = 16;
- return List.generate(
- outerLength,
- (_) => List.generate(
- middleLength,
- (j) => result.sublist(j * innerLength, (j + 1) * innerLength).toList(),
- ),
- );
- }
-
- static List<FaceDetectionRelative> _yoloPostProcessOutputs(
- List<List<List<double>>> nestedResults,
- Dimensions scaledSize,
- ) {
- final firstResults = nestedResults[0]; // [25200, 16]
-
- // Filter output
- var relativeDetections = _yoloOnnxFilterExtractDetections(
- kMinScoreSigmoidThreshold,
- kInputWidth,
- kInputHeight,
- results: firstResults,
- );
-
- // Account for the fact that the aspect ratio was maintained
- for (final faceDetection in relativeDetections) {
- faceDetection.correctForMaintainedAspectRatio(
- const Dimensions(width: kInputWidth, height: kInputHeight),
- scaledSize,
- );
- }
-
- // Non-maximum suppression to remove duplicate detections
- relativeDetections = naiveNonMaxSuppression(
- detections: relativeDetections,
- iouThreshold: kIouThreshold,
- );
-
- return relativeDetections;
- }
-}
-
-List<FaceDetectionRelative> _yoloOnnxFilterExtractDetections(
- double minScoreSigmoidThreshold,
- int inputWidth,
- int inputHeight, {
- required List<List<double>> results, // // [detections, 16]
-}) {
- final outputDetections = <FaceDetectionRelative>[];
- final output = <List<double>>[];
-
- // Go through the raw output and check the scores
- for (final result in results) {
- // Filter out raw detections with low scores
- if (result[4] < minScoreSigmoidThreshold) {
- continue;
- }
-
- // Get the raw detection
- final rawDetection = List<double>.from(result);
-
- // Append the processed raw detection to the output
- output.add(rawDetection);
- }
-
- if (output.isEmpty) {
- return outputDetections;
- }
-
- for (final List<double> rawDetection in output) {
- // Get absolute bounding box coordinates in format [xMin, yMin, xMax, yMax] https://github.com/deepcam-cn/yolov5-face/blob/eb23d18defe4a76cc06449a61cd51004c59d2697/utils/general.py#L216
- final xMinAbs = rawDetection[0] - rawDetection[2] / 2;
- final yMinAbs = rawDetection[1] - rawDetection[3] / 2;
- final xMaxAbs = rawDetection[0] + rawDetection[2] / 2;
- final yMaxAbs = rawDetection[1] + rawDetection[3] / 2;
-
- // Get the relative bounding box coordinates in format [xMin, yMin, xMax, yMax]
- final box = [
- xMinAbs / inputWidth,
- yMinAbs / inputHeight,
- xMaxAbs / inputWidth,
- yMaxAbs / inputHeight,
- ];
-
- // Get the keypoints coordinates in format [x, y]
- final allKeypoints = <List<double>>[
- [rawDetection[5] / inputWidth, rawDetection[6] / inputHeight],
- [rawDetection[7] / inputWidth, rawDetection[8] / inputHeight],
- [rawDetection[9] / inputWidth, rawDetection[10] / inputHeight],
- [rawDetection[11] / inputWidth, rawDetection[12] / inputHeight],
- [rawDetection[13] / inputWidth, rawDetection[14] / inputHeight],
- ];
-
- // Get the score
- final score =
- rawDetection[4]; // Or should it be rawDetection[4]*rawDetection[15]?
-
- // Create the relative detection
- final detection = FaceDetectionRelative(
- score: score,
- box: box,
- allKeypoints: allKeypoints,
- );
-
- // Append the relative detection to the output
- outputDetections.add(detection);
- }
-
- return outputDetections;
-}
diff --git a/mobile/apps/photos/lib/services/machine_learning/face_ml/face_embedding/face_embedding_service.dart b/mobile/apps/photos/lib/services/machine_learning/face_ml/face_embedding/face_embedding_service.dart
deleted file mode 100644
index 5ff6909b41..0000000000
--- a/mobile/apps/photos/lib/services/machine_learning/face_ml/face_embedding/face_embedding_service.dart
+++ /dev/null
@@ -1,117 +0,0 @@
-import 'dart:typed_data' show Float32List;
-
-import 'package:logging/logging.dart';
-import "package:onnx_dart/onnx_dart.dart";
-import 'package:onnxruntime/onnxruntime.dart';
-import "package:photos/services/machine_learning/ml_model.dart";
-import "package:photos/utils/ml_util.dart";
-
-class MobileFaceNetInterpreterRunException implements Exception {}
-
-/// This class is responsible for running the face embedding model (MobileFaceNet) on ONNX runtime, and can be accessed through the singleton instance [FaceEmbeddingService.instance].
-///
-/// Model size: ~5.3 MB.
-class FaceEmbeddingService extends MlModel {
- static const kRemoteBucketModelPath = "mobilefacenet_opset15.onnx";
- static const kModelSha256 =
- "472a0f7e24d0b070cbbdc031b085bc2a06c70655b3bdefb87dbd69bc98662f45";
- static const String _modelName = "MobileFaceNet";
-
- @override
- String get modelRemotePath => kModelBucketEndpoint + kRemoteBucketModelPath;
-
- @override
- String get modelSha256 => kModelSha256;
-
- @override
- Logger get logger => _logger;
- static final _logger = Logger('FaceEmbeddingService');
-
- @override
- String get modelName => _modelName;
-
- static const int kInputSize = 112;
- static const int kEmbeddingSize = 192;
- static const int kNumChannels = 3;
- static const bool kPreWhiten = false;
-
- // Singleton pattern
- FaceEmbeddingService._privateConstructor();
- static final instance = FaceEmbeddingService._privateConstructor();
- factory FaceEmbeddingService() => instance;
-
- static Future<List<List<double>>> predict(
- Float32List input,
- int sessionAddress,
- ) async {
- if (!MlModel.usePlatformPlugin) {
- assert(sessionAddress != 0 && sessionAddress != -1);
- }
- try {
- if (MlModel.usePlatformPlugin) {
- return await _runPlatformPluginPredict(input);
- } else {
- return _runFFIBasedPredict(input, sessionAddress);
- }
- } catch (e, s) {
- _logger.severe(
- 'Error while running inference (PlatformPlugin: ${MlModel.usePlatformPlugin})',
- e,
- s,
- );
- throw MobileFaceNetInterpreterRunException();
- }
- }
-
- static List<List<double>> _runFFIBasedPredict(
- Float32List input,
- int sessionAddress,
- ) {
- final runOptions = OrtRunOptions();
- final int numberOfFaces = input.length ~/ (kInputSize * kInputSize * 3);
- final inputOrt = OrtValueTensor.createTensorWithDataList(input, [
- numberOfFaces,
- kInputSize,
- kInputSize,
- kNumChannels,
- ]);
- final inputs = {'img_inputs': inputOrt};
- final session = OrtSession.fromAddress(sessionAddress);
- final List<OrtValue?> outputs = session.run(runOptions, inputs);
- final embeddings = outputs[0]?.value as List<List<double>>;
-
- for (final embedding in embeddings) {
- normalizeEmbedding(embedding);
- }
- inputOrt.release();
- runOptions.release();
- for (var element in outputs) {
- element?.release();
- }
-
- return embeddings;
- }
-
- static Future<List<List<double>>> _runPlatformPluginPredict(
- Float32List inputImageList,
- ) async {
- final stopwatch = Stopwatch()..start();
- final OnnxDart plugin = OnnxDart();
- final int numberOfFaces =
- inputImageList.length ~/ (kInputSize * kInputSize * 3);
- final result = await plugin.predict(inputImageList, _modelName);
- final List<List<double>> embeddings = [];
- for (int i = 0; i < numberOfFaces; i++) {
- embeddings.add(
- result!.sublist(i * kEmbeddingSize, (i + 1) * kEmbeddingSize),
- );
- }
- for (final embedding in embeddings) {
- normalizeEmbedding(embedding);
- }
- _logger.info(
- 'MobileFaceNetPlatformPlugin interpreter.run is finished, in ${stopwatch.elapsedMilliseconds}ms',
- );
- return embeddings;
- }
-}
diff --git a/mobile/apps/photos/lib/services/machine_learning/face_ml/face_filtering/blur_detection_service.dart b/mobile/apps/photos/lib/services/machine_learning/face_ml/face_filtering/blur_detection_service.dart
deleted file mode 100644
index 1e5979097e..0000000000
--- a/mobile/apps/photos/lib/services/machine_learning/face_ml/face_filtering/blur_detection_service.dart
+++ /dev/null
@@ -1,151 +0,0 @@
-import "package:photos/services/machine_learning/face_ml/face_detection/detection.dart";
-import 'package:photos/services/machine_learning/face_ml/face_filtering/face_filtering_constants.dart';
-
-class BlurDetectionService {
- // singleton pattern
- BlurDetectionService._privateConstructor();
- static final instance = BlurDetectionService._privateConstructor();
- factory BlurDetectionService() => instance;
-
- static Future<(bool, double)> predictIsBlurGrayLaplacian(
- List<List<int>> grayImage, {
- int threshold = kLaplacianHardThreshold,
- FaceDirection faceDirection = FaceDirection.straight,
- }) async {
- final List<List<int>> laplacian = _applyLaplacian(
- grayImage,
- faceDirection: faceDirection,
- );
- final double variance = _calculateVariance(laplacian);
- return (variance < threshold, variance);
- }
-
- static double _calculateVariance(List<List<int>> matrix) {
- final int numRows = matrix.length;
- final int numCols = matrix[0].length;
- final int totalElements = numRows * numCols;
-
- // Calculate the mean
- double mean = 0;
- for (var row in matrix) {
- for (var value in row) {
- mean += value;
- }
- }
- mean /= totalElements;
-
- // Calculate the variance
- double variance = 0;
- for (var row in matrix) {
- for (var value in row) {
- final double diff = value - mean;
- variance += diff * diff;
- }
- }
- variance /= totalElements;
-
- return variance;
- }
-
- static List<List<int>> _padImage(
- List<List<int>> image, {
- int removeSideColumns = 56,
- FaceDirection faceDirection = FaceDirection.straight,
- }) {
- // Exception is removeSideColumns is not even
- if (removeSideColumns % 2 != 0) {
- throw Exception('removeSideColumns must be even');
- }
-
- final int numRows = image.length;
- final int numCols = image[0].length;
- final int paddedNumCols = numCols + 2 - removeSideColumns;
- final int paddedNumRows = numRows + 2;
-
- // Create a new matrix with extra padding
- final List<List<int>> paddedImage = List.generate(
- paddedNumRows,
- (i) => List.generate(paddedNumCols, (j) => 0, growable: false),
- growable: false,
- );
-
- // Copy original image into the center of the padded image, taking into account the face direction
- if (faceDirection == FaceDirection.straight) {
- for (int i = 0; i < numRows; i++) {
- for (int j = 0; j < (paddedNumCols - 2); j++) {
- paddedImage[i + 1][j + 1] =
- image[i][j + (removeSideColumns / 2).round()];
- }
- }
- // If the face is facing left, we only take the right side of the face image
- } else if (faceDirection == FaceDirection.left) {
- for (int i = 0; i < numRows; i++) {
- for (int j = 0; j < (paddedNumCols - 2); j++) {
- paddedImage[i + 1][j + 1] = image[i][j + removeSideColumns];
- }
- }
- // If the face is facing right, we only take the left side of the face image
- } else if (faceDirection == FaceDirection.right) {
- for (int i = 0; i < numRows; i++) {
- for (int j = 0; j < (paddedNumCols - 2); j++) {
- paddedImage[i + 1][j + 1] = image[i][j];
- }
- }
- }
-
- // Reflect padding
- // Top and bottom rows
- for (int j = 1; j <= (paddedNumCols - 2); j++) {
- paddedImage[0][j] = paddedImage[2][j]; // Top row
- paddedImage[numRows + 1][j] = paddedImage[numRows - 1][j]; // Bottom row
- }
- // Left and right columns
- for (int i = 0; i < numRows + 2; i++) {
- paddedImage[i][0] = paddedImage[i][2]; // Left column
- paddedImage[i][paddedNumCols - 1] =
- paddedImage[i][paddedNumCols - 3]; // Right column
- }
-
- return paddedImage;
- }
-
- static List<List<int>> _applyLaplacian(
- List<List<int>> image, {
- FaceDirection faceDirection = FaceDirection.straight,
- }) {
- final List<List<int>> paddedImage = _padImage(
- image,
- faceDirection: faceDirection,
- );
- final int numRows = paddedImage.length - 2;
- final int numCols = paddedImage[0].length - 2;
- final List<List<int>> outputImage = List.generate(
- numRows,
- (i) => List.generate(numCols, (j) => 0, growable: false),
- growable: false,
- );
-
- // Define the Laplacian kernel
- final List<List<int>> kernel = [
- [0, 1, 0],
- [1, -4, 1],
- [0, 1, 0],
- ];
-
- // Apply the kernel to each pixel
- for (int i = 0; i < numRows; i++) {
- for (int j = 0; j < numCols; j++) {
- int sum = 0;
- for (int ki = 0; ki < 3; ki++) {
- for (int kj = 0; kj < 3; kj++) {
- sum += paddedImage[i + ki][j + kj] * kernel[ki][kj];
- }
- }
- // Adjust the output value if necessary (e.g., clipping)
- outputImage[i][j] = sum; //.clamp(0, 255);
- }
- }
-
- return outputImage;
- }
-}
diff --git a/mobile/apps/photos/lib/services/machine_learning/face_ml/face_recognition_service.dart b/mobile/apps/photos/lib/services/machine_learning/face_ml/face_recognition_service.dart
deleted file mode 100644
index f9ca66dd81..0000000000
--- a/mobile/apps/photos/lib/services/machine_learning/face_ml/face_recognition_service.dart
+++ /dev/null
@@ -1,237 +0,0 @@
-import "dart:async" show unawaited;
-import "dart:typed_data" show Uint8List, Float32List;
-
-import "package:logging/logging.dart";
-import "package:photos/core/event_bus.dart";
-import "package:photos/events/diff_sync_complete_event.dart";
-import "package:photos/events/people_changed_event.dart";
-import "package:photos/models/ml/face/dimension.dart";
-import "package:photos/service_locator.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_service.dart";
-import "package:photos/services/machine_learning/face_ml/face_embedding/face_embedding_service.dart";
-import "package:photos/services/machine_learning/face_ml/person/person_service.dart";
-import "package:photos/services/machine_learning/ml_exceptions.dart";
-import "package:photos/services/machine_learning/ml_result.dart";
-import "package:photos/utils/image_ml_util.dart";
-
-class FaceRecognitionService {
- static final _logger = Logger("FaceRecognitionService");
-
- FaceRecognitionService() {
- _logger.info("FaceRecognitionService constructor");
- init();
- }
-
- bool _isInitialized = false;
-
- bool _shouldReconcilePeople = false;
- bool _isSyncing = false;
-
- Future<void> init() async {
- if (_isInitialized) {
- return;
- }
- _logger.info("init called");
-
- // Listen on DiffSync
- Bus.instance.on<DiffSyncCompleteEvent>().listen((event) async {
- unawaited(syncPersonFeedback());
- });
-
- // Listen on PeopleChanged
- Bus.instance.on<PeopleChangedEvent>().listen((event) {
- if (event.type == PeopleEventType.syncDone) return;
- _shouldReconcilePeople = true;
- });
-
- _isInitialized = true;
- _logger.info('init done');
- }
-
- Future<void> syncPersonFeedback() async {
- if (_isSyncing) {
- return;
- }
- if (isLocalGalleryMode) {
- _logger.finest("Skipping person feedback sync in local gallery mode");
- return;
- }
- _isSyncing = true;
- try {
- if (_shouldReconcilePeople) {
- await PersonService.instance.reconcileClusters();
- Bus.instance.fire(PeopleChangedEvent(type: PeopleEventType.syncDone));
- _shouldReconcilePeople = false;
- } else {
- final bool didChange = await PersonService.instance
- .fetchRemoteClusterFeedback();
- if (didChange) {
- _logger.info("people: got remote data update ");
- Bus.instance.fire(PeopleChangedEvent(type: PeopleEventType.syncDone));
- }
- }
- } finally {
- _isSyncing = false;
- }
- }
-
- static Future<List<FaceResult>> runFacesPipeline(
- int enteFileID,
- Dimensions dim,
- Uint8List rawRgbaBytes,
- int faceDetectionAddress,
- int faceEmbeddingAddress,
- ) async {
- final faceResults = <FaceResult>[];
- final startTime = DateTime.now();
-
- // Get the faces
- final List<FaceDetectionRelative> faceDetectionResult =
- await _detectFacesSync(
- enteFileID,
- dim,
- rawRgbaBytes,
- faceDetectionAddress,
- faceResults,
- );
- final detectFacesTime = DateTime.now();
- final detectFacesMs = detectFacesTime.difference(startTime).inMilliseconds;
-
- // If no faces were detected, return a result with no faces. Otherwise, continue.
- if (faceDetectionResult.isEmpty) {
- _logger.info(
- "Finished runFacesPipeline with fileID $enteFileID in $detectFacesMs ms (${faceDetectionResult.length} faces, detectFaces: $detectFacesMs ms)",
- );
- return [];
- }
-
- // Align the faces
- final Float32List faceAlignmentResult = await _alignFacesSync(
- dim,
- rawRgbaBytes,
- faceDetectionResult,
- faceResults,
- );
- final alignFacesTime = DateTime.now();
- final alignFacesMs = alignFacesTime
- .difference(detectFacesTime)
- .inMilliseconds;
-
- // Get the embeddings of the faces
- await _embedFacesSync(
- faceAlignmentResult,
- faceEmbeddingAddress,
- faceResults,
- );
- final embedFacesTime = DateTime.now();
- final embedFacesMs = embedFacesTime
- .difference(alignFacesTime)
- .inMilliseconds;
- final totalMs = DateTime.now().difference(startTime).inMilliseconds;
-
- _logger.info(
- "Finished runFacesPipeline with fileID $enteFileID in $totalMs ms (${faceDetectionResult.length} faces, detectFaces: $detectFacesMs ms, alignFaces: $alignFacesMs ms, embedFaces: $embedFacesMs ms)",
- );
-
- return faceResults;
- }
-
- /// Runs face recognition on the given image data.
- static Future<List<FaceDetectionRelative>> _detectFacesSync(
- int fileID,
- Dimensions dimensions,
- Uint8List rawRgbaBytes,
- int interpreterAddress,
- List<FaceResult> faceResults,
- ) async {
- try {
- // Get the bounding boxes of the faces
- final List<FaceDetectionRelative> faces =
- await FaceDetectionService.predict(
- dimensions,
- rawRgbaBytes,
- interpreterAddress,
- );
-
- // Add detected faces to the faceResults
- for (var i = 0; i < faces.length; i++) {
- faceResults.add(FaceResult.fromFaceDetection(faces[i], fileID));
- }
-
- return faces;
- } on YOLOFaceInterpreterRunException {
- throw CouldNotRunFaceDetector();
- } catch (e, s) {
- _logger.severe('Face detection failed', e, s);
- throw GeneralFaceMlException('Face detection failed: $e');
- }
- }
-
- /// Aligns multiple faces from the given image data.
- /// Returns a list of the aligned faces as image data.
- static Future<Float32List> _alignFacesSync(
- Dimensions dim,
- Uint8List rawRgbaBytes,
- List<FaceDetectionRelative> faces,
- List<FaceResult> faceResults,
- ) async {
- try {
- final (alignedFaces, alignmentResults, _, blurValues, _) =
- await preprocessToMobileFaceNetFloat32List(dim, rawRgbaBytes, faces);
-
- // Store the results
- if (alignmentResults.length != faces.length) {
- _logger.severe(
- "The amount of alignment results (${alignmentResults.length}) does not match the number of faces (${faces.length})",
- );
- throw Exception(
- "The amount of alignment results (${alignmentResults.length}) does not match the number of faces (${faces.length})",
- );
- }
- for (var i = 0; i < alignmentResults.length; i++) {
- faceResults[i].alignment = alignmentResults[i];
- faceResults[i].blurValue = blurValues[i];
- }
-
- return alignedFaces;
- } catch (e, s) {
- _logger.severe('Face alignment failed: $e $s');
- throw CouldNotWarpAffine();
- }
- }
-
- static Future<List<List<double>>> _embedFacesSync(
- Float32List facesList,
- int interpreterAddress,
- List<FaceResult> faceResults,
- ) async {
- try {
- // Get the embedding of the faces
- final List<List<double>> embeddings = await FaceEmbeddingService.predict(
- facesList,
- interpreterAddress,
- );
-
- // Store the results
- if (embeddings.length != faceResults.length) {
- _logger.severe(
- "The amount of embeddings (${embeddings.length}) does not match the number of faces (${faceResults.length})",
- );
- throw Exception(
- "The amount of embeddings (${embeddings.length}) does not match the number of faces (${faceResults.length})",
- );
- }
- for (var faceIndex = 0; faceIndex < faceResults.length; faceIndex++) {
- faceResults[faceIndex].embedding = embeddings[faceIndex];
- }
-
- return embeddings;
- } on MobileFaceNetInterpreterRunException {
- throw CouldNotRunFaceEmbeddor();
- } catch (e, s) {
- _logger.severe('Face embedding (batch) failed', e, s);
- throw GeneralFaceMlException('Face embedding (batch) failed: $e');
- }
- }
-}
diff --git a/mobile/apps/photos/lib/services/machine_learning/face_ml/person/person_feedback_service.dart b/mobile/apps/photos/lib/services/machine_learning/face_ml/person/person_feedback_service.dart
new file mode 100644
index 0000000000..294cc34c71
--- /dev/null
+++ b/mobile/apps/photos/lib/services/machine_learning/face_ml/person/person_feedback_service.dart
@@ -0,0 +1,53 @@
+import "dart:async" show unawaited;
+
+import "package:logging/logging.dart";
+import "package:photos/core/event_bus.dart";
+import "package:photos/events/diff_sync_complete_event.dart";
+import "package:photos/events/people_changed_event.dart";
+import "package:photos/service_locator.dart" show isLocalGalleryMode;
+import "package:photos/services/machine_learning/face_ml/person/person_service.dart";
+
+class PersonFeedbackService {
+ static final _logger = Logger("PersonFeedbackService");
+
+ PersonFeedbackService() {
+ Bus.instance.on<DiffSyncCompleteEvent>().listen((event) {
+ unawaited(syncPersonFeedback());
+ });
+ Bus.instance.on<PeopleChangedEvent>().listen((event) {
+ if (event.type != PeopleEventType.syncDone) {
+ _shouldReconcilePeople = true;
+ }
+ });
+ }
+
+ bool _shouldReconcilePeople = false;
+ bool _isSyncing = false;
+
+ Future<void> syncPersonFeedback() async {
+ if (_isSyncing) {
+ return;
+ }
+ if (isLocalGalleryMode) {
+ _logger.finest("Skipping person feedback sync in local gallery mode");
+ return;
+ }
+ _isSyncing = true;
+ try {
+ if (_shouldReconcilePeople) {
+ await PersonService.instance.reconcileClusters();
+ Bus.instance.fire(PeopleChangedEvent(type: PeopleEventType.syncDone));
+ _shouldReconcilePeople = false;
+ } else {
+ final didChange = await PersonService.instance
+ .fetchRemoteClusterFeedback();
+ if (didChange) {
+ _logger.info("people: got remote data update");
+ Bus.instance.fire(PeopleChangedEvent(type: PeopleEventType.syncDone));
+ }
+ }
+ } finally {
+ _isSyncing = false;
+ }
+ }
+}
diff --git a/mobile/apps/photos/lib/services/machine_learning/face_thumbnail_generator.dart b/mobile/apps/photos/lib/services/machine_learning/face_thumbnail_generator.dart
index 4a792c11ca..f42cf8a23d 100644
--- a/mobile/apps/photos/lib/services/machine_learning/face_thumbnail_generator.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/face_thumbnail_generator.dart
@@ -1,10 +1,7 @@
-import 'dart:async';
import 'dart:typed_data' show Uint8List;
import "package:logging/logging.dart";
import "package:photos/models/ml/face/box.dart";
-import "package:photos/service_locator.dart";
-import "package:photos/utils/image_ml_util.dart";
import "package:photos/utils/isolate/isolate_operations.dart";
import "package:photos/utils/isolate/super_isolate.dart";
@@ -14,9 +11,6 @@ class FaceThumbnailGenerator extends SuperIsolate {
Logger get logger => _logger;
final _logger = Logger('FaceThumbnailGenerator');
- @override
- bool get isDartUiIsolate => !flagService.useRustForFaceThumbnails;
-
@override
String get isolateName => "FaceThumbnailGenerator";
@@ -31,37 +25,23 @@ class FaceThumbnailGenerator extends SuperIsolate {
/// Generates face thumbnails for all [faceBoxes] in [imageData].
///
- /// Uses [generateFaceThumbnailsUsingCanvas] inside the isolate.
Future<List<Uint8List>> generateFaceThumbnails(
String imagePath,
List<FaceBox> faceBoxes,
) async {
try {
- final useRustForFaceThumbnails = flagService.useRustForFaceThumbnails;
_logger.info(
"Generating face thumbnails for ${faceBoxes.length} face boxes in $imagePath",
);
final List<Map<String, dynamic>> faceBoxesJson = faceBoxes
.map((box) => box.toJson())
.toList();
- final List<Uint8List> faces =
- await runInIsolate(IsolateOperation.generateFaceThumbnails, {
- 'imagePath': imagePath,
- 'faceBoxesList': faceBoxesJson,
- 'useRustForFaceThumbnails': useRustForFaceThumbnails,
- }).then((value) => value.cast<Uint8List>());
+ final List<Uint8List> faces = await runInIsolate(
+ IsolateOperation.generateFaceThumbnails,
+ {'imagePath': imagePath, 'faceBoxesList': faceBoxesJson},
+ ).then((value) => value.cast<Uint8List>());
_logger.info("Generated face thumbnails");
- if (useRustForFaceThumbnails) {
- // Rust path already emits compressed JPEG bytes.
- return faces;
- }
- final compressedFaces = await compressFaceThumbnails({
- 'listPngBytes': faces,
- });
- _logger.fine(
- "Compressed face thumbnails from sizes ${faces.map((e) => e.length / 1024).toList()} to ${compressedFaces.map((e) => e.length / 1024).toList()} kilobytes",
- );
- return compressedFaces;
+ return faces;
} catch (e, s) {
_logger.severe("Failed to generate face thumbnails", e, s);
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart b/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart
index a94c744238..2d67817955 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_computer.dart
@@ -7,11 +7,9 @@ import "package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart"
import "package:logging/logging.dart";
import "package:photos/core/errors.dart";
import "package:photos/models/ml/vector.dart";
-import "package:photos/service_locator.dart"
- show flagService, isLocalGalleryMode;
import "package:photos/services/machine_learning/ml_constants.dart";
+import "package:photos/services/machine_learning/ml_model_assets.dart";
import "package:photos/services/machine_learning/ml_model_download_service.dart";
-import "package:photos/services/machine_learning/semantic_search/clip/clip_text_encoder.dart";
import "package:photos/services/machine_learning/semantic_search/query_result.dart";
import "package:photos/services/remote_assets_service.dart";
import "package:photos/utils/isolate/isolate_operations.dart";
@@ -25,22 +23,16 @@ class MLComputer extends SuperIsolate {
final _logger = Logger('MLComputer');
final _initModelLock = Lock();
- bool _isClipTokenizerInitialized = false;
String? _clipTextModelPath;
String? _clipTextVocabPath;
Future<void>? _clipTextWarmupFuture;
- @override
- bool get isDartUiIsolate => false;
-
@override
String get isolateName => "MLComputerIsolate";
@override
bool get shouldAutomaticDispose => false;
- bool get _shouldUseRustMl => flagService.useRustForML || isLocalGalleryMode;
-
// Singleton pattern
MLComputer._privateConstructor();
static final MLComputer instance = MLComputer._privateConstructor();
@@ -78,33 +70,27 @@ class MLComputer extends SuperIsolate {
Future<List<double>> runClipText(String query) async {
try {
- final useRustMl = _shouldUseRustMl;
- await _ensureLoadedClipTextModel(useRustMl);
+ await _ensureLoadedClipTextModel();
final modelPath = _clipTextModelPath;
final vocabPath = _clipTextVocabPath;
- if (useRustMl && (modelPath == null || modelPath.trim().isEmpty)) {
+ if (modelPath == null || modelPath.trim().isEmpty) {
throw Exception(
"RustMLMissingModelPath: Missing required model path: clipTextModelPath",
);
}
- if (useRustMl && (vocabPath == null || vocabPath.trim().isEmpty)) {
+ if (vocabPath == null || vocabPath.trim().isEmpty) {
throw Exception(
"RustMLMissingModelPath: Missing required model path: clipTextVocabPath",
);
}
final isolateResult = await runInIsolate(IsolateOperation.runClipText, {
"text": query,
- "useRustMl": useRustMl,
- if (useRustMl) ...{
- "clipTextModelPath": modelPath,
- "clipTextVocabPath": vocabPath,
- "preferCoreml": Platform.isIOS,
- "preferNnapi": Platform.isAndroid,
- "preferXnnpack": Platform.isAndroid,
- "allowCpuFallback": true,
- } else ...{
- "address": ClipTextEncoder.instance.sessionAddress,
- },
+ "clipTextModelPath": modelPath,
+ "clipTextVocabPath": vocabPath,
+ "preferCoreml": Platform.isIOS,
+ "preferNnapi": Platform.isAndroid,
+ "preferXnnpack": Platform.isAndroid,
+ "allowCpuFallback": true,
});
if (isolateResult is RustCorruptModelCacheDeletedException) {
_clipTextModelPath = null;
@@ -148,37 +134,22 @@ class MLComputer extends SuperIsolate {
}
}
- Future<void> _ensureLoadedClipTextModel(bool useRustMl) async {
+ Future<void> _ensureLoadedClipTextModel() async {
return _initModelLock.synchronized(() async {
try {
if (_clipTextVocabPath == null) {
- final tokenizerRemotePath = ClipTextEncoder.instance.vocabRemotePath;
+ final tokenizerRemotePath = ClipTextModel.instance.vocabRemotePath;
_clipTextVocabPath = await RemoteAssetsService.instance.getAssetPath(
tokenizerRemotePath,
- expectedSha256: ClipTextEncoder.instance.vocabSha256,
+ expectedSha256: ClipTextModel.instance.vocabSha256,
);
}
- if (useRustMl &&
- _clipTextVocabPath != null &&
- _clipTextModelPath != null) {
- return;
- }
-
- if (!useRustMl &&
- _isClipTokenizerInitialized &&
- ClipTextEncoder.instance.isInitialized) {
+ if (_clipTextVocabPath != null && _clipTextModelPath != null) {
return;
}
- if (!useRustMl && !_isClipTokenizerInitialized) {
- await runInIsolate(IsolateOperation.initializeClipTokenizer, {
- 'vocabPath': _clipTextVocabPath!,
- });
- _isClipTokenizerInitialized = true;
- }
-
- final String? downloadedModelPath = await ClipTextEncoder.instance
+ final String? downloadedModelPath = await ClipTextModel.instance
.downloadModelSafe();
if (downloadedModelPath == null) {
throw WiFiUnavailableError(
@@ -187,19 +158,6 @@ class MLComputer extends SuperIsolate {
);
}
_clipTextModelPath = downloadedModelPath;
-
- if (useRustMl || ClipTextEncoder.instance.isInitialized) {
- return;
- }
-
- final String modelName = ClipTextEncoder.instance.modelName;
- final address =
- await runInIsolate(IsolateOperation.loadModel, {
- 'modelName': modelName,
- 'modelPath': downloadedModelPath,
- })
- as int;
- ClipTextEncoder.instance.storeSessionAddress(address);
} catch (e, s) {
_logger.severe("Could not load clip text model in MLComputer", e, s);
rethrow;
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_exceptions.dart b/mobile/apps/photos/lib/services/machine_learning/ml_exceptions.dart
index 17605f113a..855f7502dc 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_exceptions.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_exceptions.dart
@@ -1,14 +1,5 @@
import "package:photos/core/exceptions.dart";
-class GeneralFaceMlException implements Exception {
- final String message;
-
- GeneralFaceMlException(this.message);
-
- @override
- String toString() => 'GeneralFaceMlException: $message';
-}
-
class ThumbnailRetrievalException implements Exception {
final String message;
final StackTrace stackTrace;
@@ -22,9 +13,3 @@ class ThumbnailRetrievalException implements Exception {
}
class CouldNotRetrieveAnyFileData implements Exception, LocallyHandledError {}
-
-class CouldNotRunFaceDetector implements Exception {}
-
-class CouldNotWarpAffine implements Exception {}
-
-class CouldNotRunFaceEmbeddor implements Exception {}
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart b/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart
index 13071cf6e6..3bc9e695ef 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart
@@ -1,97 +1,63 @@
-import "dart:async";
import "dart:io" show Platform;
import "package:flutter/foundation.dart" show debugPrint, kDebugMode;
import "package:logging/logging.dart";
-import "package:photos/service_locator.dart"
- show flagService, isLocalGalleryMode, localSettings;
-import 'package:photos/services/machine_learning/face_ml/face_detection/face_detection_service.dart';
-import 'package:photos/services/machine_learning/face_ml/face_embedding/face_embedding_service.dart';
+import "package:photos/service_locator.dart" show flagService, localSettings;
+import "package:photos/services/machine_learning/ml_model_assets.dart";
import "package:photos/services/machine_learning/ml_model_download_service.dart";
import "package:photos/services/machine_learning/ml_models_overview.dart";
-import 'package:photos/services/machine_learning/ml_result.dart';
-import "package:photos/services/machine_learning/pet_ml/pet_model_services.dart";
-import "package:photos/services/machine_learning/semantic_search/clip/clip_image_encoder.dart";
+import "package:photos/services/machine_learning/ml_result.dart";
import "package:photos/services/remote_assets_service.dart";
import "package:photos/utils/isolate/isolate_operations.dart";
import "package:photos/utils/isolate/super_isolate.dart";
import "package:photos/utils/ml_util.dart";
import "package:synchronized/synchronized.dart";
-@pragma('vm:entry-point')
+@pragma("vm:entry-point")
class MLIndexingIsolate extends SuperIsolate {
@override
Logger get logger => _logger;
final _logger = Logger("MLIndexingIsolate");
- @override
- bool get isDartUiIsolate => !_shouldUseRustMl;
-
@override
String get isolateName => "MLIndexingIsolate";
@override
bool get shouldAutomaticDispose => true;
- bool get _shouldUseRustMl => flagService.useRustForML || isLocalGalleryMode;
-
- int _loadedModelsCount = 0;
- int _deloadedModelsCount = 0;
-
- final _initModelLock = Lock();
final _rustRuntimeLock = Lock();
-
Map<String, dynamic>? _cachedRustRuntimeArgs;
@override
- Future<void> onDispose() async {
- await releaseRustRuntime();
- await _releaseModels();
- }
+ Future<void> onDispose() => releaseRustRuntime();
@override
bool postFunctionlockStop(IsolateOperation operation) {
- if (operation == IsolateOperation.analyzeImage &&
- shouldPauseIndexingAndClustering) {
- return true;
- }
- return false;
+ return operation == IsolateOperation.analyzeImage &&
+ shouldPauseIndexingAndClustering;
}
bool shouldPauseIndexingAndClustering = false;
- // Singleton pattern
MLIndexingIsolate._privateConstructor();
static final instance = MLIndexingIsolate._privateConstructor();
factory MLIndexingIsolate() => instance;
- /// Analyzes the given image data by running the full pipeline for faces, using [analyzeImageStatic] in the isolate.
Future<MLResult?> analyzeImage(
FileMLInstruction instruction,
String filePath,
) async {
- late MLResult result;
-
try {
- final useRustMl = _shouldUseRustMl;
- final rustRuntimeArgs = useRustMl
- ? await _getCachedRustRuntimeArgs()
- : const <String, dynamic>{};
- _logger.info(
- "Analyzing image ${instruction.fileKey} via rust or legacy: ${useRustMl ? "RUST" : "LEGACY"}",
- );
+ final rustRuntimeArgs = await _getCachedRustRuntimeArgs();
+ _logger.info("Analyzing image ${instruction.fileKey} with Rust ML");
final isolateResult = await runInIsolate(IsolateOperation.analyzeImage, {
"enteFileID": instruction.fileKey,
"filePath": filePath,
- "useRustMl": useRustMl,
"runFaces": instruction.shouldRunFaces,
"runClip": instruction.shouldRunClip,
- "runPets": useRustMl && instruction.shouldRunPets,
+ "runPets": instruction.shouldRunPets,
...rustRuntimeArgs,
- "faceDetectionAddress": FaceDetectionService.instance.sessionAddress,
- "faceEmbeddingAddress": FaceEmbeddingService.instance.sessionAddress,
- "clipImageAddress": ClipImageEncoder.instance.sessionAddress,
});
if (isolateResult is RustCorruptModelCacheDeletedException) {
_logger.warning(
@@ -104,19 +70,18 @@ class MLIndexingIsolate extends SuperIsolate {
final resultJsonString = isolateResult as String?;
if (resultJsonString == null) {
if (!shouldPauseIndexingAndClustering) {
- _logger.severe('Analyzing image in isolate is giving back null');
+ _logger.severe("Analyzing image in isolate returned null");
}
return null;
}
- result = MLResult.fromJsonString(resultJsonString);
- result.usedRustMl = useRustMl;
+ return MLResult.fromJsonString(resultJsonString);
} catch (e, s) {
if (e is RustCorruptModelCacheDeletedException ||
isExpectedMlSkipError(e)) {
rethrow;
}
_logger.severe(
- "Could not analyze image with ID ${instruction.fileKey} \n",
+ "Could not analyze image with ID ${instruction.fileKey}",
e,
s,
);
@@ -127,14 +92,9 @@ class MLIndexingIsolate extends SuperIsolate {
}
rethrow;
}
-
- return result;
}
- Future<void> prepareRustRuntime() async {
- if (!_shouldUseRustMl) {
- return;
- }
+ Future<void> prepareRustRuntime() {
return _rustRuntimeLock.synchronized(() async {
final rustRuntimeArgs = await _buildRustRuntimeArgs();
final frozenRuntimeArgs = Map<String, dynamic>.unmodifiable(
@@ -169,181 +129,31 @@ class MLIndexingIsolate extends SuperIsolate {
await runInIsolate(IsolateOperation.releaseRustMlRuntime, {});
_cachedRustRuntimeArgs = null;
} catch (e, s) {
- _logger.warning("Could not release rust runtime in isolate", e, s);
- }
- });
- }
-
- Future<void> ensureLoadedModels(FileMLInstruction instruction) async {
- if (_shouldUseRustMl) {
- return;
- }
- return _initModelLock.synchronized(() async {
- final faceDetectionLoaded = FaceDetectionService.instance.isInitialized;
- final faceEmbeddingLoaded = FaceEmbeddingService.instance.isInitialized;
- final facesModelsLoaded = faceDetectionLoaded && faceEmbeddingLoaded;
- final clipModelsLoaded = ClipImageEncoder.instance.isInitialized;
-
- final shouldLoadFaces = instruction.shouldRunFaces && !facesModelsLoaded;
- final shouldLoadClip = instruction.shouldRunClip && !clipModelsLoaded;
- if (!shouldLoadFaces && !shouldLoadClip) {
- return;
- }
-
- _logger.info(
- 'Loading models. faces: $shouldLoadFaces, clip: $shouldLoadClip',
- );
- _loadedModelsCount++;
- _logger.info(
- "Loaded models count: $_loadedModelsCount, deloaded models count: $_deloadedModelsCount",
- );
- await MLIndexingIsolate.instance._loadModels(
- loadFaces: shouldLoadFaces,
- loadClip: shouldLoadClip,
- );
- _logger.info('Models loaded');
- });
- }
-
- Future<void> _loadModels({
- required bool loadFaces,
- required bool loadClip,
- }) async {
- if (!loadFaces && !loadClip) return;
- final List<MLModels> models = [];
- final List<String> modelNames = [];
- final List<String> modelPaths = [];
- if (loadFaces) {
- models.addAll([MLModels.faceDetection, MLModels.faceEmbedding]);
- final faceDetection = await FaceDetectionService.instance
- .getModelNameAndPath();
- modelNames.add(faceDetection.$1);
- modelPaths.add(faceDetection.$2);
- final faceEmbedding = await FaceEmbeddingService.instance
- .getModelNameAndPath();
- modelNames.add(faceEmbedding.$1);
- modelPaths.add(faceEmbedding.$2);
- }
- if (loadClip) {
- models.add(MLModels.clipImageEncoder);
- final clipImage = await ClipImageEncoder.instance.getModelNameAndPath();
- modelNames.add(clipImage.$1);
- modelPaths.add(clipImage.$2);
- }
-
- try {
- final addresses =
- await runInIsolate(IsolateOperation.loadIndexingModels, {
- "modelNames": modelNames,
- "modelPaths": modelPaths,
- })
- as List<int>;
- for (int i = 0; i < models.length; i++) {
- final model = models[i].model;
- final address = addresses[i];
- model.storeSessionAddress(address);
- }
- } catch (e, s) {
- _logger.severe("Could not load models in MLIndexingIsolate", e, s);
- rethrow;
- }
- }
-
- /// WARNING: This method is only for debugging purposes. It should not be used in production.
- Future<void> debugLoadSingleModel(MLModels model) {
- if (_shouldUseRustMl) {
- _logger.severe("Can't use legacy ML models when using rust");
- return Future.value();
- }
- return _initModelLock.synchronized(() async {
- final modelInstance = model.model;
- if (modelInstance.isInitialized) {
- _logger.info("Model ${model.name} already loaded");
- return;
- }
- final modelName = modelInstance.modelName;
- final modelPath = await modelInstance.downloadModelSafe();
- if (modelPath == null) {
- _logger.warning(
- "Could not download model '$modelName': WiFi unavailable",
- );
- return;
+ _logger.warning("Could not release Rust runtime in isolate", e, s);
}
- final address =
- await runInIsolate(IsolateOperation.loadModel, {
- "modelName": modelName,
- "modelPath": modelPath,
- })
- as int;
- modelInstance.storeSessionAddress(address);
});
}
Future<void> cleanupLocalIndexingModels({bool delete = false}) async {
await releaseRustRuntime();
if (!MLModelDownloadService.instance.areIndexingModelsDownloaded) return;
- await _releaseModels();
if (delete) {
- final List<String> remoteModelPaths = [];
-
- for (final model in MLModels.values) {
- if (!model.isIndexingModel) continue;
- final mlModel = model.model;
- remoteModelPaths.add(mlModel.modelRemotePath);
- }
+ final remoteModelPaths = <String>[
+ for (final model in MLModels.values)
+ if (model.isIndexingModel) model.model.modelRemotePath,
+ ];
await RemoteAssetsService.instance.cleanupSelectedModels(
remoteModelPaths,
);
-
MLModelDownloadService.instance.invalidateModelDownloadCache();
}
}
- Future<void> _releaseModels() async {
- if (_shouldUseRustMl) {
- _logger.severe("Can't release legacy ML models when using rust");
- return Future.value();
- }
- final List<String> modelNames = [];
- final List<int> modelAddresses = [];
- final List<MLModels> models = [];
- for (final model in MLModels.values) {
- if (!model.isIndexingModel) continue;
- final mlModel = model.model;
- if (mlModel.isInitialized) {
- models.add(model);
- modelNames.add(mlModel.modelName);
- modelAddresses.add(mlModel.sessionAddress);
- }
- }
- if (modelNames.isEmpty) return;
- try {
- _logger.info("Releasing models $modelNames");
- _deloadedModelsCount++;
- _logger.info(
- "Loaded models count: $_loadedModelsCount, deloaded models count: $_deloadedModelsCount",
- );
- await runInIsolate(IsolateOperation.releaseIndexingModels, {
- "modelNames": modelNames,
- "modelAddresses": modelAddresses,
- });
- for (final model in models) {
- model.model.releaseSessionAddress();
- }
- _logger.info("Indexing models released in isolate");
- } catch (e, s) {
- _logger.severe("Could not release models in MLIndexingIsolate", e, s);
- rethrow;
- }
- }
-
Future<Map<String, dynamic>> _buildRustRuntimeArgs() async {
- final faceDetection = await FaceDetectionService.instance
- .getModelNameAndPath();
- final faceEmbedding = await FaceEmbeddingService.instance
- .getModelNameAndPath();
- final clipImage = await ClipImageEncoder.instance.getModelNameAndPath();
+ final faceDetectionPath = await FaceDetectionModel.instance.getModelPath();
+ final faceEmbeddingPath = await FaceEmbeddingModel.instance.getModelPath();
+ final clipImagePath = await ClipImageModel.instance.getModelPath();
String petFaceDetectionPath = "";
String petFaceEmbeddingDogPath = "";
@@ -353,24 +163,24 @@ class MLIndexingIsolate extends SuperIsolate {
String petBodyEmbeddingCatPath = "";
if (flagService.petEnabled && localSettings.petRecognitionEnabled) {
- petFaceDetectionPath =
- (await PetFaceDetectionService.instance.getModelNameAndPath()).$2;
- petFaceEmbeddingDogPath =
- (await PetFaceEmbeddingDogService.instance.getModelNameAndPath()).$2;
- petFaceEmbeddingCatPath =
- (await PetFaceEmbeddingCatService.instance.getModelNameAndPath()).$2;
- petBodyDetectionPath =
- (await PetBodyDetectionService.instance.getModelNameAndPath()).$2;
- petBodyEmbeddingDogPath =
- (await PetBodyEmbeddingDogService.instance.getModelNameAndPath()).$2;
- petBodyEmbeddingCatPath =
- (await PetBodyEmbeddingCatService.instance.getModelNameAndPath()).$2;
+ petFaceDetectionPath = await PetFaceDetectionModel.instance
+ .getModelPath();
+ petFaceEmbeddingDogPath = await PetFaceEmbeddingDogModel.instance
+ .getModelPath();
+ petFaceEmbeddingCatPath = await PetFaceEmbeddingCatModel.instance
+ .getModelPath();
+ petBodyDetectionPath = await PetBodyDetectionModel.instance
+ .getModelPath();
+ petBodyEmbeddingDogPath = await PetBodyEmbeddingDogModel.instance
+ .getModelPath();
+ petBodyEmbeddingCatPath = await PetBodyEmbeddingCatModel.instance
+ .getModelPath();
}
return {
- "faceDetectionModelPath": faceDetection.$2,
- "faceEmbeddingModelPath": faceEmbedding.$2,
- "clipImageModelPath": clipImage.$2,
+ "faceDetectionModelPath": faceDetectionPath,
+ "faceEmbeddingModelPath": faceEmbeddingPath,
+ "clipImageModelPath": clipImagePath,
"petFaceDetectionModelPath": petFaceDetectionPath,
"petFaceEmbeddingDogModelPath": petFaceEmbeddingDogPath,
"petFaceEmbeddingCatModelPath": petFaceEmbeddingCatPath,
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_model.dart b/mobile/apps/photos/lib/services/machine_learning/ml_model.dart
index ec5a0cfe58..d59841ad9c 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_model.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_model.dart
@@ -1,17 +1,11 @@
-import "dart:io" show File, Platform;
-
import "package:logging/logging.dart";
-import "package:onnx_dart/onnx_dart.dart";
-import "package:onnxruntime/onnxruntime.dart";
import "package:photos/service_locator.dart" show isLocalGalleryMode;
-import "package:photos/services/machine_learning/onnx_env.dart";
import "package:photos/services/remote_assets_service.dart";
import "package:photos/utils/network_util.dart";
import "package:synchronized/synchronized.dart";
-abstract class MlModel {
- static final Logger isolateLogger = Logger("MlModel");
- Logger get logger;
+abstract class MlModelAsset {
+ static final _logger = Logger("MlModel");
String get kModelBucketEndpoint => "https://models.ente.com/";
@@ -19,31 +13,15 @@ abstract class MlModel {
String get modelSha256;
- String get modelName;
-
final _downloadModelLock = Lock();
- static final bool usePlatformPlugin = Platform.isAndroid;
-
- bool get isInitialized =>
- usePlatformPlugin ? _isNativePluginInitialized : _isFfiInitialized;
- int get sessionAddress =>
- usePlatformPlugin ? _nativePluginSessionIndex : _ffiSessionAddress;
-
- bool _isFfiInitialized = false;
- int _ffiSessionAddress = -1;
-
- bool _isNativePluginInitialized = false;
- int _nativePluginSessionIndex = -1;
-
/// WARNING: If [downloadModel] was not first called, this method will download the model first using high bandwidth.
- Future<(String, String)> getModelNameAndPath() async {
+ Future<String> getModelPath() async {
return _downloadModelLock.synchronized(() async {
- final path = await RemoteAssetsService.instance.getAssetPath(
+ return RemoteAssetsService.instance.getAssetPath(
modelRemotePath,
expectedSha256: modelSha256,
);
- return (modelName, path);
});
}
@@ -57,7 +35,7 @@ abstract class MlModel {
if (isLocalGalleryMode || await canUseHighBandwidth()) {
return await downloadModel();
} else {
- logger.warning(
+ _logger.warning(
'Cannot return model path as it is not available locally and high bandwidth is not available.',
);
return null;
@@ -85,123 +63,4 @@ abstract class MlModel {
}
});
}
-
- void storeSessionAddress(int address) {
- if (usePlatformPlugin) {
- _nativePluginSessionIndex = address;
- _isNativePluginInitialized = true;
- } else {
- _ffiSessionAddress = address;
- _isFfiInitialized = true;
- }
- }
-
- void releaseSessionAddress() {
- if (usePlatformPlugin) {
- _nativePluginSessionIndex = -1;
- _isNativePluginInitialized = false;
- } else {
- _ffiSessionAddress = -1;
- _isFfiInitialized = false;
- }
- }
-
- // Note: The platform plugin requires a dedicated isolate for loading the model to ensure thread safety and performance isolation.
- // In contrast, the current FFI-based plugin leverages the session memory address for session management, which does not require a dedicated isolate.
- static Future<int> loadModel(String modelName, String modelPath) async {
- isolateLogger.info(
- 'Start loading $modelName (platformPlugin: $usePlatformPlugin)',
- );
- final time = DateTime.now();
- try {
- late int result;
- if (usePlatformPlugin) {
- result = await _loadModelWithPlatformPlugin(modelName, modelPath);
- } else {
- result = await _loadModelWithFFI(modelName, modelPath);
- }
- final timeMs = DateTime.now().difference(time).inMilliseconds;
- isolateLogger.info(
- "$modelName model loaded in $timeMs ms (platformPlugin: $usePlatformPlugin)",
- );
- return result;
- } catch (e, s) {
- isolateLogger.severe(
- "Failed to load model $modelName (platformPlugin: $usePlatformPlugin)",
- e,
- s,
- );
- rethrow;
- }
- }
-
- static Future<int> _loadModelWithPlatformPlugin(
- String modelName,
- String modelPath,
- ) async {
- final OnnxDart plugin = OnnxDart();
- final String? ortVersionString = await plugin.getPlatformVersion();
- final bool? initResult = await plugin.init(modelName, modelPath);
- if (initResult == null || !initResult) {
- isolateLogger.severe("Failed to initialize $modelName with EntePlugin.");
- throw Exception("Failed to initialize $modelName with EntePlugin.");
- }
- isolateLogger.info("Initialized $modelName on $ortVersionString");
- return 0;
- }
-
- static Future<int> _loadModelWithFFI(
- String modelName,
- String modelPath,
- ) async {
- ONNXEnvFFI.instance.initONNX(modelName);
- try {
- final sessionOptions = OrtSessionOptions()
- ..setInterOpNumThreads(1)
- ..setIntraOpNumThreads(1)
- ..setSessionGraphOptimizationLevel(GraphOptimizationLevel.ortEnableAll);
- final session = OrtSession.fromFile(File(modelPath), sessionOptions);
- return session.address;
- } catch (e, s) {
- isolateLogger.severe("Failed to load model $modelName with FFI", e, s);
- rethrow;
- }
- }
-
- static Future<void> releaseModel(String modelName, int sessionAddress) async {
- try {
- if (usePlatformPlugin) {
- await _releaseModelWithPlatformPlugin(modelName);
- } else {
- await _releaseModelWithFFI(modelName, sessionAddress);
- }
- } catch (e, s) {
- isolateLogger.severe(
- "Failed to release model $modelName (platformPlugin: $usePlatformPlugin)",
- e,
- s,
- );
- }
- }
-
- static Future<void> _releaseModelWithPlatformPlugin(String modelName) async {
- final OnnxDart plugin = OnnxDart();
- final bool? initResult = await plugin.release(modelName);
- if (initResult == null || !initResult) {
- throw Exception("Failed to release $modelName with PlatformPlugin.");
- }
- }
-
- static Future<void> _releaseModelWithFFI(
- String modelName,
- int sessionAddress,
- ) async {
- if (sessionAddress == 0 || sessionAddress == -1) {
- return;
- }
- final session = OrtSession.fromAddress(sessionAddress);
- session.release();
- ONNXEnvFFI.instance.releaseONNX(modelName);
- return;
- }
}
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_model_assets.dart b/mobile/apps/photos/lib/services/machine_learning/ml_model_assets.dart
new file mode 100644
index 0000000000..a520178c46
--- /dev/null
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_model_assets.dart
@@ -0,0 +1,157 @@
+import "package:photos/services/machine_learning/ml_model.dart";
+
+class FaceDetectionModel extends MlModelAsset {
+ static const remoteFileName = "yolov5s_face_640_640_dynamic.onnx";
+ static const _sha256 =
+ "71a008707283b03db4881449a24f4da197f9dbd9ddaca5c91fcdb363fbf7e06f";
+
+ FaceDetectionModel._();
+ static final instance = FaceDetectionModel._();
+
+ @override
+ String get modelRemotePath => kModelBucketEndpoint + remoteFileName;
+
+ @override
+ String get modelSha256 => _sha256;
+}
+
+class FaceEmbeddingModel extends MlModelAsset {
+ static const remoteFileName = "mobilefacenet_opset15.onnx";
+ static const _sha256 =
+ "472a0f7e24d0b070cbbdc031b085bc2a06c70655b3bdefb87dbd69bc98662f45";
+
+ FaceEmbeddingModel._();
+ static final instance = FaceEmbeddingModel._();
+
+ @override
+ String get modelRemotePath => kModelBucketEndpoint + remoteFileName;
+
+ @override
+ String get modelSha256 => _sha256;
+}
+
+class ClipImageModel extends MlModelAsset {
+ static const remoteFileName = "mobileclip_s2_image.onnx";
+ static const _sha256 =
+ "ef54ec66c687603eb4dd303e20d9b67e81069d3133b1c69a70028c76718b7752";
+
+ ClipImageModel._();
+ static final instance = ClipImageModel._();
+
+ @override
+ String get modelRemotePath => kModelBucketEndpoint + remoteFileName;
+
+ @override
+ String get modelSha256 => _sha256;
+}
+
+class ClipTextModel extends MlModelAsset {
+ static const remoteFileName = "mobileclip_s2_text_opset18_quant.onnx";
+ static const _sha256 =
+ "d92f33dfcff83077fc2e0d3414250710efbb51795dfd89767bdbefb5fdc47322";
+ static const _vocabFileName = "bpe_simple_vocab_16e6.txt";
+ static const _vocabSha256 =
+ "67603cfda2e032ad77b5f8808af37789d590db664b26df8705d2bf8b3c553fc8";
+
+ ClipTextModel._();
+ static final instance = ClipTextModel._();
+
+ @override
+ String get modelRemotePath => kModelBucketEndpoint + remoteFileName;
+
+ @override
+ String get modelSha256 => _sha256;
+
+ String get vocabRemotePath => kModelBucketEndpoint + _vocabFileName;
+ String get vocabSha256 => _vocabSha256;
+}
+
+class PetFaceDetectionModel extends MlModelAsset {
+ static const remoteFileName = "yolov5s_pet_face_fp16_V2.onnx";
+ static const _sha256 =
+ "7876d97992eeb5f3a9f3b35eff5e0e133012928172a8b005093108d8c3ad2d1c";
+
+ PetFaceDetectionModel._();
+ static final instance = PetFaceDetectionModel._();
+
+ @override
+ String get modelRemotePath => kModelBucketEndpoint + remoteFileName;
+
+ @override
+ String get modelSha256 => _sha256;
+}
+
+class PetFaceEmbeddingDogModel extends MlModelAsset {
+ static const remoteFileName = "dog_face_embedding128.onnx";
+ static const _sha256 =
+ "fb04d781eb1f7adf6ce3432dc0c5873f16cc051b5c98c14c754afb39e2b92462";
+
+ PetFaceEmbeddingDogModel._();
+ static final instance = PetFaceEmbeddingDogModel._();
+
+ @override
+ String get modelRemotePath => kModelBucketEndpoint + remoteFileName;
+
+ @override
+ String get modelSha256 => _sha256;
+}
+
+class PetFaceEmbeddingCatModel extends MlModelAsset {
+ static const remoteFileName = "cat_face_embedding128.onnx";
+ static const _sha256 =
+ "32b10694a27f6404d2beaddbd64f07ad555f72dccb12ee60a7afe5dcf6aad6cd";
+
+ PetFaceEmbeddingCatModel._();
+ static final instance = PetFaceEmbeddingCatModel._();
+
+ @override
+ String get modelRemotePath => kModelBucketEndpoint + remoteFileName;
+
+ @override
+ String get modelSha256 => _sha256;
+}
+
+class PetBodyDetectionModel extends MlModelAsset {
+ static const remoteFileName = "yolov5s_object_fp16.onnx";
+ static const _sha256 =
+ "113f0c18632eb2c4f6deebcd40eb01c676492e9b43923c2d336e1b4012fce9ef";
+
+ PetBodyDetectionModel._();
+ static final instance = PetBodyDetectionModel._();
+
+ @override
+ String get modelRemotePath => kModelBucketEndpoint + remoteFileName;
+
+ @override
+ String get modelSha256 => _sha256;
+}
+
+class PetBodyEmbeddingDogModel extends MlModelAsset {
+ static const remoteFileName = "dog_body_embedding192.onnx";
+ static const _sha256 =
+ "1d85aa20358137e30f11c2d0baa9a2248b9997928d501fe15365d1fc57522770";
+
+ PetBodyEmbeddingDogModel._();
+ static final instance = PetBodyEmbeddingDogModel._();
+
+ @override
+ String get modelRemotePath => kModelBucketEndpoint + remoteFileName;
+
+ @override
+ String get modelSha256 => _sha256;
+}
+
+class PetBodyEmbeddingCatModel extends MlModelAsset {
+ static const remoteFileName = "cat_body_embedding192.onnx";
+ static const _sha256 =
+ "62fb5891e61be69a96510d8ec56e7525a9541b0283e54574d27c86c9b4a26ddf";
+
+ PetBodyEmbeddingCatModel._();
+ static final instance = PetBodyEmbeddingCatModel._();
+
+ @override
+ String get modelRemotePath => kModelBucketEndpoint + remoteFileName;
+
+ @override
+ String get modelSha256 => _sha256;
+}
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_model_download_service.dart b/mobile/apps/photos/lib/services/machine_learning/ml_model_download_service.dart
index c7c8dd7200..6a00017fe7 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_model_download_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_model_download_service.dart
@@ -4,8 +4,8 @@ import "package:connectivity_plus/connectivity_plus.dart";
import "package:logging/logging.dart";
import "package:photos/service_locator.dart"
show flagService, hasGrantedMLConsent, isLocalGalleryMode, localSettings;
+import "package:photos/services/machine_learning/ml_model_assets.dart";
import "package:photos/services/machine_learning/ml_models_overview.dart";
-import "package:photos/services/machine_learning/semantic_search/clip/clip_text_encoder.dart";
import "package:photos/services/remote_assets_service.dart";
import "package:photos/utils/network_util.dart";
import "package:synchronized/synchronized.dart";
@@ -35,10 +35,10 @@ class MLModelDownloadService {
Future<bool> canLoadClipTextModel() async {
final hasModel = await RemoteAssetsService.instance.hasAsset(
- ClipTextEncoder.instance.modelRemotePath,
+ ClipTextModel.instance.modelRemotePath,
);
final hasVocab = await RemoteAssetsService.instance.hasAsset(
- ClipTextEncoder.instance.vocabRemotePath,
+ ClipTextModel.instance.vocabRemotePath,
);
if (hasModel && hasVocab) {
return true;
@@ -152,17 +152,15 @@ class MLModelDownloadService {
for (final model in nonIndexingModels)
model.model.downloadModel(forceRefresh),
RemoteAssetsService.instance.getAssetPath(
- ClipTextEncoder.instance.vocabRemotePath,
+ ClipTextModel.instance.vocabRemotePath,
refetch: forceRefresh,
- expectedSha256: ClipTextEncoder.instance.vocabSha256,
+ expectedSha256: ClipTextModel.instance.vocabSha256,
),
];
}
bool get _shouldDownloadPetModels {
- return flagService.petEnabled &&
- localSettings.petRecognitionEnabled &&
- (flagService.useRustForML || isLocalGalleryMode);
+ return flagService.petEnabled && localSettings.petRecognitionEnabled;
}
void _listenForHighBandwidthModelDownloadRetry({
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_models_overview.dart b/mobile/apps/photos/lib/services/machine_learning/ml_models_overview.dart
index 2baefc5243..f1b080784c 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_models_overview.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_models_overview.dart
@@ -1,9 +1,5 @@
-import "package:photos/services/machine_learning/face_ml/face_detection/face_detection_service.dart";
-import "package:photos/services/machine_learning/face_ml/face_embedding/face_embedding_service.dart";
import "package:photos/services/machine_learning/ml_model.dart";
-import "package:photos/services/machine_learning/pet_ml/pet_model_services.dart";
-import "package:photos/services/machine_learning/semantic_search/clip/clip_image_encoder.dart";
-import "package:photos/services/machine_learning/semantic_search/clip/clip_text_encoder.dart";
+import "package:photos/services/machine_learning/ml_model_assets.dart";
enum MLModels {
faceDetection,
@@ -35,28 +31,28 @@ Iterable<MLModels> get nonIndexingModels =>
MLModels.values.where((model) => !model.isIndexingModel);
extension MLModelsExtension on MLModels {
- MlModel get model {
+ MlModelAsset get model {
switch (this) {
case MLModels.faceDetection:
- return FaceDetectionService.instance;
+ return FaceDetectionModel.instance;
case MLModels.faceEmbedding:
- return FaceEmbeddingService.instance;
+ return FaceEmbeddingModel.instance;
case MLModels.clipImageEncoder:
- return ClipImageEncoder.instance;
+ return ClipImageModel.instance;
case MLModels.clipTextEncoder:
- return ClipTextEncoder.instance;
+ return ClipTextModel.instance;
case MLModels.petFaceDetection:
- return PetFaceDetectionService.instance;
+ return PetFaceDetectionModel.instance;
case MLModels.petFaceEmbeddingDog:
- return PetFaceEmbeddingDogService.instance;
+ return PetFaceEmbeddingDogModel.instance;
case MLModels.petFaceEmbeddingCat:
- return PetFaceEmbeddingCatService.instance;
+ return PetFaceEmbeddingCatModel.instance;
case MLModels.petBodyDetection:
- return PetBodyDetectionService.instance;
+ return PetBodyDetectionModel.instance;
case MLModels.petBodyEmbeddingDog:
- return PetBodyEmbeddingDogService.instance;
+ return PetBodyEmbeddingDogModel.instance;
case MLModels.petBodyEmbeddingCat:
- return PetBodyEmbeddingCatService.instance;
+ return PetBodyEmbeddingCatModel.instance;
}
}
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 4c0928e268..e2994da84f 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_result.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_result.dart
@@ -17,10 +17,6 @@ class MLResult {
Dimensions decodedImageSize;
- /// Which runtime actually produced this result. Stamped by the caller of
- /// the indexing isolate; not serialized to/from the isolate JSON payload.
- bool usedRustMl = false;
-
bool get ranML => facesRan || clipRan || petsRan;
bool get facesRan => faces != null;
bool get clipRan => clip != null;
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
index 1726a4565c..dd2c119fbb 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
@@ -351,7 +351,7 @@ class MLService {
Future<void> sync() async {
await fileDataService.syncFDStatus();
- await faceRecognitionService.syncPersonFeedback();
+ await personFeedbackService.syncPersonFeedback();
}
Future<void> runAllML({bool force = false}) async {
@@ -498,8 +498,7 @@ class MLService {
await MLModelDownloadService.instance.ensureModelsDownloaded(
onlyIndexingModels: true,
);
- if ((flagService.useRustForML || isLocalGalleryMode) &&
- !rustRuntimePrepared) {
+ if (!rustRuntimePrepared) {
await MLIndexingIsolate.instance.prepareRustRuntime();
rustRuntimePrepared = true;
}
@@ -517,7 +516,6 @@ class MLService {
_logger.info("indexAllImages() was paused, stopping");
break stream;
}
- await MLIndexingIsolate.instance.ensureLoadedModels(instruction);
futures.add(processImage(instruction));
}
final awaitedFutures = await Future.wait(futures);
@@ -776,10 +774,7 @@ class MLService {
actuallyRanML = result.ranML;
if (!actuallyRanML) return actuallyRanML;
final bool isLocalGallery = instruction.isLocalGallery;
- // Bitmask describing properties of this index (e.g. which runtime
- // produced it), so remote indexes stay distinguishable between rust
- // and legacy during and after the rust ML rollout.
- final int remoteFlags = result.usedRustMl ? mlIndexFlagRuntimeRust : 0;
+ const int remoteFlags = mlIndexFlagRuntimeRust;
// Prepare storing data on remote (online mode only)
final FileDataEntity? dataEntity = isLocalGallery
? null
diff --git a/mobile/apps/photos/lib/services/machine_learning/onnx_env.dart b/mobile/apps/photos/lib/services/machine_learning/onnx_env.dart
deleted file mode 100644
index edb7d98a24..0000000000
--- a/mobile/apps/photos/lib/services/machine_learning/onnx_env.dart
+++ /dev/null
@@ -1,28 +0,0 @@
-import "package:onnxruntime/onnxruntime.dart";
-
-class ONNXEnvFFI {
- final Set<String> _loadedModels = {};
-
- // Singleton pattern
- ONNXEnvFFI._privateConstructor();
- static final instance = ONNXEnvFFI._privateConstructor();
- factory ONNXEnvFFI() => instance;
-
- void initONNX(String modelName) {
- if (_loadedModels.isEmpty) {
- OrtEnv.instance.init();
- }
- _loadedModels.add(modelName);
- }
-
- void releaseONNX(String modelName) {
- _loadedModels.remove(modelName);
- if (_loadedModels.isEmpty) {
- OrtEnv.instance.release();
- }
- }
-
- bool isInit() {
- return _loadedModels.isNotEmpty;
- }
-}
diff --git a/mobile/apps/photos/lib/services/machine_learning/pet_ml/pet_model_services.dart b/mobile/apps/photos/lib/services/machine_learning/pet_ml/pet_model_services.dart
deleted file mode 100644
index e4195e851e..0000000000
--- a/mobile/apps/photos/lib/services/machine_learning/pet_ml/pet_model_services.dart
+++ /dev/null
@@ -1,165 +0,0 @@
-import 'package:logging/logging.dart';
-import "package:photos/services/machine_learning/ml_model.dart";
-
-/// Pet face detection model (YOLOv5s-face with 3 keypoints, FP16).
-/// Model: yolov5s_pet_face_fp16_V2.onnx — detects pet faces with left_eye, right_eye, nose landmarks.
-///
-/// Model size: ~14.8 MB.
-class PetFaceDetectionService extends MlModel {
- static const kRemoteBucketModelPath = "yolov5s_pet_face_fp16_V2.onnx";
- static const kModelSha256 =
- "7876d97992eeb5f3a9f3b35eff5e0e133012928172a8b005093108d8c3ad2d1c";
- static const _modelName = "YOLOv5PetFace";
-
- @override
- String get modelRemotePath => kModelBucketEndpoint + kRemoteBucketModelPath;
-
- @override
- String get modelSha256 => kModelSha256;
-
- @override
- Logger get logger => _logger;
- static final _logger = Logger('PetFaceDetectionService');
-
- @override
- String get modelName => _modelName;
-
- PetFaceDetectionService._privateConstructor();
- static final instance = PetFaceDetectionService._privateConstructor();
- factory PetFaceDetectionService() => instance;
-}
-
-/// Dog face embedding model (BYOL 128-d).
-///
-/// Model size: ~4.1 MB.
-class PetFaceEmbeddingDogService extends MlModel {
- static const kRemoteBucketModelPath = "dog_face_embedding128.onnx";
- static const kModelSha256 =
- "fb04d781eb1f7adf6ce3432dc0c5873f16cc051b5c98c14c754afb39e2b92462";
- static const _modelName = "DogFaceByol128";
-
- @override
- String get modelRemotePath => kModelBucketEndpoint + kRemoteBucketModelPath;
-
- @override
- String get modelSha256 => kModelSha256;
-
- @override
- Logger get logger => _logger;
- static final _logger = Logger('PetFaceEmbeddingDogService');
-
- @override
- String get modelName => _modelName;
-
- PetFaceEmbeddingDogService._privateConstructor();
- static final instance = PetFaceEmbeddingDogService._privateConstructor();
- factory PetFaceEmbeddingDogService() => instance;
-}
-
-/// Cat face embedding model (BYOL 128-d).
-///
-/// Model size: ~4.1 MB.
-class PetFaceEmbeddingCatService extends MlModel {
- static const kRemoteBucketModelPath = "cat_face_embedding128.onnx";
- static const kModelSha256 =
- "32b10694a27f6404d2beaddbd64f07ad555f72dccb12ee60a7afe5dcf6aad6cd";
- static const _modelName = "CatFaceByol128";
-
- @override
- String get modelRemotePath => kModelBucketEndpoint + kRemoteBucketModelPath;
-
- @override
- String get modelSha256 => kModelSha256;
-
- @override
- Logger get logger => _logger;
- static final _logger = Logger('PetFaceEmbeddingCatService');
-
- @override
- String get modelName => _modelName;
-
- PetFaceEmbeddingCatService._privateConstructor();
- static final instance = PetFaceEmbeddingCatService._privateConstructor();
- factory PetFaceEmbeddingCatService() => instance;
-}
-
-/// Pet body detection model (YOLOv5s — COCO classes 15=cat, 16=dog).
-///
-/// Model size: ~15.0 MB.
-class PetBodyDetectionService extends MlModel {
- static const kRemoteBucketModelPath = "yolov5s_object_fp16.onnx";
- static const kModelSha256 =
- "113f0c18632eb2c4f6deebcd40eb01c676492e9b43923c2d336e1b4012fce9ef";
- static const _modelName = "YOLOv5sPetBody";
-
- @override
- String get modelRemotePath => kModelBucketEndpoint + kRemoteBucketModelPath;
-
- @override
- String get modelSha256 => kModelSha256;
-
- @override
- Logger get logger => _logger;
- static final _logger = Logger('PetBodyDetectionService');
-
- @override
- String get modelName => _modelName;
-
- PetBodyDetectionService._privateConstructor();
- static final instance = PetBodyDetectionService._privateConstructor();
- factory PetBodyDetectionService() => instance;
-}
-
-/// Dog body embedding model.
-///
-/// Model size: ~4.6 MB.
-class PetBodyEmbeddingDogService extends MlModel {
- static const kRemoteBucketModelPath = "dog_body_embedding192.onnx";
- static const kModelSha256 =
- "1d85aa20358137e30f11c2d0baa9a2248b9997928d501fe15365d1fc57522770";
- static const _modelName = "DogBody";
-
- @override
- String get modelRemotePath => kModelBucketEndpoint + kRemoteBucketModelPath;
-
- @override
- String get modelSha256 => kModelSha256;
-
- @override
- Logger get logger => _logger;
- static final _logger = Logger('PetBodyEmbeddingDogService');
-
- @override
- String get modelName => _modelName;
-
- PetBodyEmbeddingDogService._privateConstructor();
- static final instance = PetBodyEmbeddingDogService._privateConstructor();
- factory PetBodyEmbeddingDogService() => instance;
-}
-
-/// Cat body embedding model.
-///
-/// Model size: ~4.6 MB.
-class PetBodyEmbeddingCatService extends MlModel {
- static const kRemoteBucketModelPath = "cat_body_embedding192.onnx";
- static const kModelSha256 =
- "62fb5891e61be69a96510d8ec56e7525a9541b0283e54574d27c86c9b4a26ddf";
- static const _modelName = "CatBody";
-
- @override
- String get modelRemotePath => kModelBucketEndpoint + kRemoteBucketModelPath;
-
- @override
- String get modelSha256 => kModelSha256;
-
- @override
- Logger get logger => _logger;
- static final _logger = Logger('PetBodyEmbeddingCatService');
-
- @override
- String get modelName => _modelName;
-
- PetBodyEmbeddingCatService._privateConstructor();
- static final instance = PetBodyEmbeddingCatService._privateConstructor();
- factory PetBodyEmbeddingCatService() => instance;
-}
diff --git a/mobile/apps/photos/lib/services/machine_learning/semantic_search/clip/clip_image_encoder.dart b/mobile/apps/photos/lib/services/machine_learning/semantic_search/clip/clip_image_encoder.dart
deleted file mode 100644
index 58e790f853..0000000000
--- a/mobile/apps/photos/lib/services/machine_learning/semantic_search/clip/clip_image_encoder.dart
+++ /dev/null
@@ -1,107 +0,0 @@
-import "dart:typed_data" show Uint8List, Float32List;
-
-import "package:logging/logging.dart";
-import "package:onnx_dart/onnx_dart.dart";
-import "package:onnxruntime/onnxruntime.dart";
-import "package:photos/models/ml/face/dimension.dart";
-import "package:photos/services/machine_learning/ml_model.dart";
-import "package:photos/utils/image_ml_util.dart";
-import "package:photos/utils/ml_util.dart";
-
-/// MobileCLIP S2 image encoder used for semantic search image embeddings.
-///
-/// Model size: ~143.1 MB.
-class ClipImageEncoder extends MlModel {
- static const kRemoteBucketModelPath = "mobileclip_s2_image.onnx";
- static const kModelSha256 =
- "ef54ec66c687603eb4dd303e20d9b67e81069d3133b1c69a70028c76718b7752";
- static const _modelName = "ClipImageEncoder";
-
- @override
- String get modelRemotePath => kModelBucketEndpoint + kRemoteBucketModelPath;
-
- @override
- String get modelSha256 => kModelSha256;
-
- @override
- Logger get logger => _logger;
- static final _logger = Logger('ClipImageEncoder');
-
- @override
- String get modelName => _modelName;
-
- // Singleton pattern
- ClipImageEncoder._privateConstructor();
- static final instance = ClipImageEncoder._privateConstructor();
- factory ClipImageEncoder() => instance;
-
- static Future<List<double>> predict(
- Dimensions dim,
- Uint8List rawRgbaBytes,
- int sessionAddress, [
- int? enteFileID,
- ]) async {
- final startTime = DateTime.now();
- final inputList = await preprocessImageClip(dim, rawRgbaBytes);
- final preprocessingTime = DateTime.now();
- final preprocessingMs = preprocessingTime
- .difference(startTime)
- .inMilliseconds;
- late List<double> result;
- try {
- if (MlModel.usePlatformPlugin) {
- result = await _runPlatformPluginPredict(inputList);
- } else {
- result = _runFFIBasedPredict(inputList, sessionAddress);
- }
- } catch (e, stackTrace) {
- _logger.severe(
- "Clip image inference failed${enteFileID != null ? " with fileID $enteFileID" : ""} (PlatformPlugin: ${MlModel.usePlatformPlugin})",
- e,
- stackTrace,
- );
- rethrow;
- }
- final inferTime = DateTime.now();
- final inferenceMs = inferTime.difference(preprocessingTime).inMilliseconds;
- final totalMs = inferTime.difference(startTime).inMilliseconds;
- _logger.info(
- "Clip image predict took $totalMs ms${enteFileID != null ? " with fileID $enteFileID" : ""} (inference: $inferenceMs ms, preprocessing: $preprocessingMs ms)",
- );
- return result;
- }
-
- static List<double> _runFFIBasedPredict(
- Float32List inputList,
- int sessionAddress,
- ) {
- final inputOrt = OrtValueTensor.createTensorWithDataList(inputList, [
- 1,
- 3,
- 256,
- 256,
- ]);
- final inputs = {'input': inputOrt};
- final session = OrtSession.fromAddress(sessionAddress);
- final runOptions = OrtRunOptions();
- final outputs = session.run(runOptions, inputs);
- final embedding = (outputs[0]?.value as List<List<double>>)[0];
- inputOrt.release();
- runOptions.release();
- for (var element in outputs) {
- element?.release();
- }
- normalizeEmbedding(embedding);
- return embedding;
- }
-
- static Future<List<double>> _runPlatformPluginPredict(
- Float32List inputList,
- ) async {
- final OnnxDart plugin = OnnxDart();
- final result = await plugin.predict(inputList, _modelName);
- final List<double> embedding = result!.sublist(0, 512);
- normalizeEmbedding(embedding);
- return embedding;
- }
-}
diff --git a/mobile/apps/photos/lib/services/machine_learning/semantic_search/clip/clip_text_encoder.dart b/mobile/apps/photos/lib/services/machine_learning/semantic_search/clip/clip_text_encoder.dart
deleted file mode 100644
index 3ef1fd314d..0000000000
--- a/mobile/apps/photos/lib/services/machine_learning/semantic_search/clip/clip_text_encoder.dart
+++ /dev/null
@@ -1,102 +0,0 @@
-import "package:flutter/foundation.dart";
-import "package:logging/logging.dart";
-import "package:onnx_dart/onnx_dart.dart";
-import "package:onnxruntime/onnxruntime.dart";
-import "package:photos/services/machine_learning/ml_model.dart";
-import 'package:photos/services/machine_learning/semantic_search/clip/clip_text_tokenizer.dart';
-import "package:photos/utils/ml_util.dart";
-
-/// MobileCLIP S2 text encoder (quantized) used for semantic search text embeddings.
-///
-/// Model size: ~67.1 MB. Vocab file size: ~3.2 MB.
-class ClipTextEncoder extends MlModel {
- static const kRemoteBucketModelPath =
- "mobileclip_s2_text_opset18_quant.onnx"; // Quantized model
- static const kModelSha256 =
- "d92f33dfcff83077fc2e0d3414250710efbb51795dfd89767bdbefb5fdc47322";
- static const _kVocabRemotePath = "bpe_simple_vocab_16e6.txt";
- static const kVocabSha256 =
- "67603cfda2e032ad77b5f8808af37789d590db664b26df8705d2bf8b3c553fc8";
-
- static const _modelName = "ClipTextEncoder";
-
- @override
- String get modelRemotePath => kModelBucketEndpoint + kRemoteBucketModelPath;
-
- @override
- String get modelSha256 => kModelSha256;
-
- String get vocabRemotePath => kModelBucketEndpoint + _kVocabRemotePath;
- String get vocabSha256 => kVocabSha256;
-
- @override
- Logger get logger => _logger;
- static final _logger = Logger('ClipTextEncoder');
-
- @override
- String get modelName => _modelName;
-
- // Singleton pattern
- ClipTextEncoder._privateConstructor();
- static final instance = ClipTextEncoder._privateConstructor();
- factory ClipTextEncoder() => instance;
-
- static Future<List<double>> predict(Map args) async {
- final text = args["text"] as String;
- final address = args["address"] as int;
- final startTime = DateTime.now();
- final List<int> tokenize = await ClipTextTokenizer.instance.tokenize(text);
- final int32list = Int32List.fromList(tokenize);
- final tokenizeTime = DateTime.now();
- final tokenizeMs = tokenizeTime.difference(startTime).inMilliseconds;
- try {
- late List<double> embedding;
- if (MlModel.usePlatformPlugin) {
- embedding = await _runPlatformPluginPredict(int32list);
- } else {
- embedding = _runFFIBasedPredict(int32list, address);
- }
- final inferTime = DateTime.now();
- final inferMs = inferTime.difference(tokenizeTime).inMilliseconds;
- final totalMs = inferTime.difference(startTime).inMilliseconds;
- _logger.info(
- "Clip text predict took $totalMs ms (predict: $inferMs ms, tokenize: $tokenizeMs ms) for text: '$text'",
- );
- return embedding;
- } catch (e, s) {
- _logger.severe(
- "Clip text inference failed (PlatformPlugin: ${MlModel.usePlatformPlugin})",
- e,
- s,
- );
- rethrow;
- }
- }
-
- static List<double> _runFFIBasedPredict(Int32List int32list, int address) {
- final runOptions = OrtRunOptions();
- final data = List.filled(1, int32list);
- final inputOrt = OrtValueTensor.createTensorWithDataList(data, [1, 77]);
- final inputs = {'input': inputOrt};
- final session = OrtSession.fromAddress(address);
- final outputs = session.run(runOptions, inputs);
- final embedding = (outputs[0]?.value as List<List<double>>)[0];
- inputOrt.release();
- runOptions.release();
- for (var element in outputs) {
- element?.release();
- }
- normalizeEmbedding(embedding);
- return embedding;
- }
-
- static Future<List<double>> _runPlatformPluginPredict(
- Int32List int32list,
- ) async {
- final OnnxDart plugin = OnnxDart();
- final result = await plugin.predictInt(int32list, _modelName);
- final List<double> embedding = result!.sublist(0, 512);
- normalizeEmbedding(embedding);
- return embedding;
- }
-}
diff --git a/mobile/apps/photos/lib/services/machine_learning/semantic_search/clip/clip_text_tokenizer.dart b/mobile/apps/photos/lib/services/machine_learning/semantic_search/clip/clip_text_tokenizer.dart
deleted file mode 100644
index 02d1afc004..0000000000
--- a/mobile/apps/photos/lib/services/machine_learning/semantic_search/clip/clip_text_tokenizer.dart
+++ /dev/null
@@ -1,202 +0,0 @@
-import "dart:convert";
-import "dart:io" show File;
-import "dart:math";
-
-import "package:html_unescape/html_unescape.dart";
-import "package:logging/logging.dart";
-import "package:tuple/tuple.dart";
-
-class ClipTextTokenizer {
- final _logger = Logger("ClipTextTokenizer");
-
- static const int totalTokens = 77;
-
- late String vocabulary;
- late Map<int, String> byteEncoder;
- late Map<String, int> byteDecoder;
- late Map<int, String> decoder;
- late Map<String, int> encoder;
- late Map<Tuple2<String, String>, int> bpeRanks;
- Map<String, String> cache = <String, String>{
- '<|startoftext|>': '<|startoftext|>',
- '<|endoftext|>': '<|endoftext|>',
- };
-
- // Dart RegExpt does not support Unicode identifiers (\p{L} and \p{N})
- RegExp pat = RegExp(
- r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[a-zA-Z]+|[0-9]+|[^\s\p{L}\p{N}]+""",
- caseSensitive: false,
- multiLine: false,
- );
-
- late int sot;
- late int eot;
-
- bool _isInitialized = false;
-
- // Singleton pattern
- ClipTextTokenizer._privateConstructor();
- static final instance = ClipTextTokenizer._privateConstructor();
- factory ClipTextTokenizer() => instance;
-
- Future<List<int>> tokenize(String text) async {
- var tokens = _encode(text);
- tokens =
- [sot] + tokens.sublist(0, min(totalTokens - 2, tokens.length)) + [eot];
- return tokens + List.filled(totalTokens - tokens.length, 0);
- }
-
- Future<void> init(String vocabPath) async {
- if (_isInitialized) return;
- final vocabFile = File(vocabPath);
- final String vocabulary = await vocabFile.readAsString();
- this.vocabulary = vocabulary;
- byteEncoder = _bytesToUnicode();
- byteDecoder = byteEncoder.map((k, v) => MapEntry(v, k));
-
- var split = vocabulary.split('\n');
- split = split.sublist(1, 49152 - 256 - 2 + 1);
- final merges = split
- .map((merge) => Tuple2(merge.split(' ')[0], merge.split(' ')[1]))
- .toList();
-
- final vocab = byteEncoder.values.toList();
- vocab.addAll(vocab.map((v) => '$v</w>').toList());
-
- for (var merge = 0; merge < merges.length; merge++) {
- vocab.add(merges[merge].item1 + merges[merge].item2);
- }
- vocab.addAll(['<|startoftext|>', '<|endoftext|>']);
-
- // asMap returns the map as a Map<int, String>
- decoder = vocab.asMap();
- encoder = decoder.map((k, v) => MapEntry(v, k));
- bpeRanks = Map.fromIterables(
- merges.map((merge) => merge),
- List.generate(merges.length, (i) => i),
- );
-
- sot = encoder['<|startoftext|>']!;
- eot = encoder['<|endoftext|>']!;
- _logger.info("Clip text tokenizer initialized");
- _isInitialized = true;
- }
-
- List<int> _encode(String text) {
- final List<int> bpeTokens = [];
- text = _whitespaceClean(_basicClean(text)).toLowerCase();
- for (Match match in pat.allMatches(text)) {
- String token = match[0]!;
- token = utf8.encode(token).map((b) => byteEncoder[b]).join();
- _bpe(
- token,
- ).split(' ').forEach((bpeToken) => bpeTokens.add(encoder[bpeToken]!));
- }
- return bpeTokens;
- }
-
- String _bpe(String token) {
- if (cache.containsKey(token)) {
- return cache[token]!;
- }
- var word = token.split('').map((char) => char).toList();
- word[word.length - 1] = '${word.last}</w>';
- var pairs = _getPairs(word);
- if (pairs.isEmpty) {
- return '$token</w>';
- }
-
- while (true) {
- Tuple2<String, String> bigram = pairs.first;
- for (var pair in pairs) {
- final rank1 = bpeRanks[pair] ?? double.infinity;
- final rank2 = bpeRanks[bigram] ?? double.infinity;
-
- if (rank1 < rank2) {
- bigram = pair;
- }
- }
-
- if (!bpeRanks.containsKey(bigram)) {
- break;
- }
- final first = bigram.item1;
- final second = bigram.item2;
- final newWord = <String>[];
- var i = 0;
- while (i < word.length) {
- final j = word.sublist(i).indexOf(first);
- if (j == -1) {
- newWord.addAll(word.sublist(i));
- break;
- }
- newWord.addAll(word.sublist(i, i + j));
- i = i + j;
- if (word[i] == first && i < word.length - 1 && word[i + 1] == second) {
- newWord.add(first + second);
- i += 2;
- } else {
- newWord.add(word[i]);
- i += 1;
- }
- }
-
- word = newWord;
- if (word.length == 1) {
- break;
- } else {
- pairs = _getPairs(word);
- }
- }
- final wordStr = word.join(' ');
- cache[token] = wordStr;
- return wordStr;
- }
-
- Map<int, String> _bytesToUnicode() {
- final List<int> bs = [];
- for (int i = '!'.codeUnitAt(0); i <= '~'.codeUnitAt(0); i++) {
- bs.add(i);
- }
- for (int i = '¡'.codeUnitAt(0); i <= '¬'.codeUnitAt(0); i++) {
- bs.add(i);
- }
- for (int i = '®'.codeUnitAt(0); i <= 'ÿ'.codeUnitAt(0); i++) {
- bs.add(i);
- }
-
- final List<int> cs = List.from(bs);
- int n = 0;
- for (int b = 0; b < 256; b++) {
- if (!bs.contains(b)) {
- bs.add(b);
- cs.add(256 + n);
- n += 1;
- }
- }
-
- final List<String> ds = cs.map((n) => String.fromCharCode(n)).toList();
- return Map.fromIterables(bs, ds);
- }
-
- Set<Tuple2<String, String>> _getPairs(List<String> word) {
- final Set<Tuple2<String, String>> pairs = {};
- String prevChar = word[0];
- for (var i = 1; i < word.length; i++) {
- pairs.add(Tuple2(prevChar, word[i]));
- prevChar = word[i];
- }
- return pairs;
- }
-
- String _basicClean(String text) {
- final unescape = HtmlUnescape();
- text = unescape.convert(unescape.convert(text));
- return text.trim();
- }
-
- String _whitespaceClean(String text) {
- text = text.replaceAll(RegExp(r'\s+'), ' ');
- return text.trim();
- }
-}
diff --git a/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart b/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart
index 67fdae5a77..12bae2d8e1 100644
--- a/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart
@@ -11,13 +11,11 @@ import "package:photos/db/offline_files_db.dart";
import 'package:photos/events/embedding_updated_event.dart';
import "package:photos/models/file/file.dart";
import "package:photos/models/ml/clip.dart";
-import "package:photos/models/ml/face/dimension.dart";
import "package:photos/models/ml/ml_versions.dart";
import "package:photos/service_locator.dart";
import "package:photos/services/collections_service.dart";
import "package:photos/services/machine_learning/ml_computer.dart";
import "package:photos/services/machine_learning/ml_result.dart";
-import "package:photos/services/machine_learning/semantic_search/clip/clip_image_encoder.dart";
import "package:photos/services/machine_learning/semantic_search/query_result.dart";
import "package:photos/services/search_service.dart";
import "package:shared_preferences/shared_preferences.dart";
@@ -523,22 +521,4 @@ class SemanticSearchService {
}
});
}
-
- static Future<ClipResult> runClipImage(
- int enteFileID,
- Dimensions dimensions,
- Uint8List rawRgbaBytes,
- int clipImageAddress,
- ) async {
- final embedding = await ClipImageEncoder.predict(
- dimensions,
- rawRgbaBytes,
- clipImageAddress,
- enteFileID,
- );
-
- final clipResult = ClipResult(fileID: enteFileID, embedding: embedding);
-
- return clipResult;
- }
}
diff --git a/mobile/apps/photos/lib/ui/settings/debug/ml_debug_settings_page.dart b/mobile/apps/photos/lib/ui/settings/debug/ml_debug_settings_page.dart
index b39bb7a4fe..55e3695716 100644
--- a/mobile/apps/photos/lib/ui/settings/debug/ml_debug_settings_page.dart
+++ b/mobile/apps/photos/lib/ui/settings/debug/ml_debug_settings_page.dart
@@ -830,7 +830,7 @@ class _MLDebugSettingsPageState extends State<MLDebugSettingsPage> {
Future<void> _onSyncPersonMappings(BuildContext context) async {
try {
- await faceRecognitionService.syncPersonFeedback();
+ await personFeedbackService.syncPersonFeedback();
showShortToast(context, "Done");
} catch (e, s) {
logger.warning('sync person mappings failed ', e, s);
diff --git a/mobile/apps/photos/lib/ui/settings/ml/machine_learning_settings_page.dart b/mobile/apps/photos/lib/ui/settings/ml/machine_learning_settings_page.dart
index 0c40d0dd89..5ddd2ed7f2 100644
--- a/mobile/apps/photos/lib/ui/settings/ml/machine_learning_settings_page.dart
+++ b/mobile/apps/photos/lib/ui/settings/ml/machine_learning_settings_page.dart
@@ -7,13 +7,10 @@ import "package:photos/core/event_bus.dart";
import "package:photos/events/notification_event.dart";
import "package:photos/generated/l10n.dart";
import "package:photos/service_locator.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_service.dart";
import "package:photos/services/machine_learning/ml_indexing_isolate.dart";
+import "package:photos/services/machine_learning/ml_model_assets.dart";
import "package:photos/services/machine_learning/ml_model_download_service.dart";
import "package:photos/services/machine_learning/ml_service.dart";
-import "package:photos/services/machine_learning/semantic_search/clip/clip_image_encoder.dart";
-import "package:photos/services/machine_learning/semantic_search/clip/clip_text_encoder.dart";
import "package:photos/services/machine_learning/semantic_search/semantic_search_service.dart";
import "package:photos/services/remote_assets_service.dart";
import "package:photos/services/wake_lock_service.dart";
@@ -363,13 +360,13 @@ class _ModelLoadingStateState extends State<ModelLoadingState> {
) {
final String url = event.$1;
String title = "";
- if (url.contains(ClipImageEncoder.kRemoteBucketModelPath)) {
+ if (url.contains(ClipImageModel.remoteFileName)) {
title = "Image Model";
- } else if (url.contains(ClipTextEncoder.kRemoteBucketModelPath)) {
+ } else if (url.contains(ClipTextModel.remoteFileName)) {
title = "Text Model";
- } else if (url.contains(FaceDetectionService.kRemoteBucketModelPath)) {
+ } else if (url.contains(FaceDetectionModel.remoteFileName)) {
title = "Face Detection Model";
- } else if (url.contains(FaceEmbeddingService.kRemoteBucketModelPath)) {
+ } else if (url.contains(FaceEmbeddingModel.remoteFileName)) {
title = "Face Embedding Model";
}
if (title.isNotEmpty) {
diff --git a/mobile/apps/photos/lib/ui/settings/ml/ml_user_dev_screen.dart b/mobile/apps/photos/lib/ui/settings/ml/ml_user_dev_screen.dart
index c2ef7d5f69..968ad550e3 100644
--- a/mobile/apps/photos/lib/ui/settings/ml/ml_user_dev_screen.dart
+++ b/mobile/apps/photos/lib/ui/settings/ml/ml_user_dev_screen.dart
@@ -9,8 +9,6 @@ import "package:photos/events/people_changed_event.dart";
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/person/person_service.dart";
-import "package:photos/services/machine_learning/ml_indexing_isolate.dart";
-import "package:photos/services/machine_learning/ml_models_overview.dart";
import "package:photos/services/machine_learning/semantic_search/semantic_search_service.dart";
import "package:photos/theme/ente_theme.dart";
import "package:photos/ui/components/buttons/button_widget.dart";
@@ -215,96 +213,6 @@ class _MLUserDeveloperOptionsState extends State<MLUserDeveloperOptions> {
widget.mlIsEnabled
? _buildThresholdsCard(context)
: const SizedBox.shrink(),
- widget.mlIsEnabled
- ? const SizedBox(height: 24)
- : const SizedBox.shrink(),
- ButtonWidget(
- buttonType: ButtonType.neutral,
- labelText: "Load face detection model",
- onTap: () async {
- try {
- await MLIndexingIsolate.instance.debugLoadSingleModel(
- MLModels.faceDetection,
- );
- } catch (e, s) {
- _logger.severe(
- "Could not load face detection model",
- e,
- s,
- );
- await showGenericErrorDialog(
- context: context,
- error: e,
- );
- }
- },
- ),
- const SizedBox(height: 24),
- ButtonWidget(
- buttonType: ButtonType.neutral,
- labelText: "Load face recognition model",
- onTap: () async {
- try {
- await MLIndexingIsolate.instance.debugLoadSingleModel(
- MLModels.faceEmbedding,
- );
- } catch (e, s) {
- _logger.severe(
- "Could not load face detection model",
- e,
- s,
- );
- await showGenericErrorDialog(
- context: context,
- error: e,
- );
- }
- },
- ),
- const SizedBox(height: 24),
- ButtonWidget(
- buttonType: ButtonType.neutral,
- labelText: "Load clip image model",
- onTap: () async {
- try {
- await MLIndexingIsolate.instance.debugLoadSingleModel(
- MLModels.clipImageEncoder,
- );
- } catch (e, s) {
- _logger.severe(
- "Could not load face detection model",
- e,
- s,
- );
- await showGenericErrorDialog(
- context: context,
- error: e,
- );
- }
- },
- ),
- const SizedBox(height: 24),
- ButtonWidget(
- buttonType: ButtonType.neutral,
- labelText: "Load clip text model",
- onTap: () async {
- try {
- await MLIndexingIsolate.instance.debugLoadSingleModel(
- MLModels.clipTextEncoder,
- );
- } catch (e, s) {
- _logger.severe(
- "Could not load face detection model",
- e,
- s,
- );
- await showGenericErrorDialog(
- context: context,
- error: e,
- );
- }
- },
- ),
const SafeArea(child: SizedBox(height: 12)),
],
),
diff --git a/mobile/apps/photos/lib/utils/image_decode_util.dart b/mobile/apps/photos/lib/utils/image_decode_util.dart
new file mode 100644
index 0000000000..78210f2745
--- /dev/null
+++ b/mobile/apps/photos/lib/utils/image_decode_util.dart
@@ -0,0 +1,32 @@
+import "dart:io" show File;
+import "dart:typed_data" show Uint8List;
+
+import "package:image/image.dart" as image;
+import "package:logging/logging.dart";
+
+final _logger = Logger("ImageDecodeUtil");
+
+Future<Uint8List?> createSafeJpegDecodeFallbackBytes({
+ required String imagePath,
+}) async {
+ final imageData = await File(imagePath).readAsBytes();
+ return createSafeJpegDecodeFallbackBytesFromData(imageData);
+}
+
+Uint8List? createSafeJpegDecodeFallbackBytesFromData(Uint8List imageData) {
+ try {
+ final decoded = image.decodeImage(imageData);
+ if (decoded == null) {
+ return null;
+ }
+ return Uint8List.fromList(image.encodeJpg(decoded, quality: 95));
+ } catch (e) {
+ final firstLine = e.toString().split("\n").first.trim();
+ _logger.warning(
+ firstLine.isEmpty
+ ? "Safe JPEG conversion failed"
+ : "Safe JPEG conversion failed: $firstLine",
+ );
+ return null;
+ }
+}
diff --git a/mobile/apps/photos/lib/utils/image_ml_util.dart b/mobile/apps/photos/lib/utils/image_ml_util.dart
deleted file mode 100644
index 6f4f286717..0000000000
--- a/mobile/apps/photos/lib/utils/image_ml_util.dart
+++ /dev/null
@@ -1,808 +0,0 @@
-import "dart:async";
-import "dart:io" show File, Platform;
-import "dart:math" show exp, max, min, pi;
-import "dart:typed_data" show Float32List, Uint8List;
-import "dart:ui";
-
-import "package:exif_reader/exif_reader.dart";
-import 'package:flutter/painting.dart' as paint show decodeImageFromList;
-import "package:flutter_image_compress/flutter_image_compress.dart";
-import "package:image/image.dart" as img;
-import "package:logging/logging.dart";
-import 'package:ml_linalg/linalg.dart';
-import "package:photos/models/ml/face/box.dart";
-import "package:photos/models/ml/face/dimension.dart";
-import 'package:photos/services/machine_learning/face_ml/face_alignment/alignment_result.dart';
-import 'package:photos/services/machine_learning/face_ml/face_alignment/similarity_transform.dart';
-import 'package:photos/services/machine_learning/face_ml/face_detection/detection.dart';
-import 'package:photos/services/machine_learning/face_ml/face_filtering/blur_detection_service.dart';
-import "package:photos/utils/file_util.dart";
-
-/// All of the functions in this file are helper functions for using inside an isolate.
-/// Don't use them outside of a isolate, unless you are okay with UI jank!!!!
-
-final _logger = Logger("ImageMlUtil");
-
-/// These are 8 bit unsigned integers in range 0-255 for each RGB channel
-typedef RGB = (int, int, int);
-
-const gaussianKernelSize = 5;
-const gaussianKernelRadius = gaussianKernelSize ~/ 2;
-const gaussianSigma = 10.0;
-final List<List<double>> gaussianKernel = create2DGaussianKernel(
- gaussianKernelSize,
- gaussianSigma,
-);
-
-const maxKernelSize = gaussianKernelSize;
-const maxKernelRadius = maxKernelSize ~/ 2;
-
-// Face thumbnail compression constants
-const int _faceThumbnailCompressionQuality = 90;
-const int _faceThumbnailMinDimension = 512;
-
-class DecodedImage {
- final Dimensions dimensions;
- final Image? image;
- final Uint8List? rawRgbaBytes;
-
- const DecodedImage({required this.dimensions, this.image, this.rawRgbaBytes});
-}
-
-Future<DecodedImage> decodeImageFromPath(
- String imagePath, {
- required bool includeRgbaBytes,
- required bool includeDartUiImage,
-}) async {
- final imageData = await File(imagePath).readAsBytes();
- final format = imagePath.split('.').last.toLowerCase();
- final bool skipExifRead =
- Platform.isIOS &&
- format == 'jxl'; // JXL on iOS has issues with EXIF reading
- Map<String, IfdTag> exifData = <String, IfdTag>{};
- if (skipExifRead) {
- _logger.info('Skipping EXIF read for JXL on iOS');
- } else {
- exifData = _normalizeExifResult(await readExifFromBytes(imageData));
- }
- final int orientation =
- exifData['Image Orientation']?.values.firstAsInt() ?? 1;
- if (orientation > 1 && includeRgbaBytes) {
- if (format == 'heic' || format == 'heif') {
- _logger.info(
- "Decoding HEIC/HEIF image with EXIF orientation $orientation",
- );
- } else {
- _logger.warning(
- "Decoding image with EXIF orientation $orientation, for format $format",
- );
- }
- }
-
- late Image image;
- try {
- image = await decodeImageFromData(imageData);
- } catch (e, s) {
- if (isRawImageExtension(format)) {
- _logger.warning(
- "Skipping JPEG conversion for RAW image format $format because flutter_image_compress is known to crash on unsupported RAW input",
- e,
- s,
- );
- throw Exception(
- 'InvalidImageFormatException: Error decoding image of format $format',
- );
- }
- _logger.info(
- 'Cannot decode $format on ${Platform.isAndroid ? "Android" : "iOS"}, converting to jpeg',
- );
- try {
- final Uint8List? convertedData =
- await FlutterImageCompress.compressWithFile(
- imagePath,
- format: CompressFormat.jpeg,
- minWidth: 20000, // High value to ensure image is not scaled down
- minHeight: 20000, // High value to ensure image is not scaled down
- );
- image = await decodeImageFromData(convertedData!);
- _logger.info('Conversion successful, jpeg decoded');
- if (image.width >= 20000 || image.height >= 20000) {
- // Failing and storing empty result when the image dimensions are higher than max compression limits
- _logger.severe(
- 'Image res too high, W:${image.width} H:${image.height}',
- );
- throw Exception('Res too high W:${image.width} H:${image.height}');
- }
- } catch (e) {
- _logger.severe(
- 'Error decoding image of format $format on ${Platform.isAndroid ? "Android" : "iOS"}',
- e,
- s,
- );
- throw Exception(
- 'InvalidImageFormatException: Error decoding image of format $format',
- );
- }
- }
- if (!includeRgbaBytes) {
- return DecodedImage(
- dimensions: Dimensions(width: image.width, height: image.height),
- image: includeDartUiImage ? image : null,
- );
- }
- final rawRgbaBytes = await _getRawRgbaBytes(image);
- return DecodedImage(
- dimensions: Dimensions(width: image.width, height: image.height),
- image: includeDartUiImage ? image : null,
- rawRgbaBytes: rawRgbaBytes,
- );
-}
-
-Map<String, IfdTag> _normalizeExifResult(dynamic result) {
- if (result is Map<String, IfdTag>) {
- return result;
- }
- final dynamic tags = result.tags;
- if (tags is Map<String, IfdTag>) {
- return tags;
- }
- throw ArgumentError("Unsupported EXIF result type: ${result.runtimeType}");
-}
-
-Future<Uint8List?> createSafeJpegDecodeFallbackBytes({
- required String imagePath,
-}) async {
- final imageData = await File(imagePath).readAsBytes();
- return createSafeJpegDecodeFallbackBytesFromData(imageData);
-}
-
-Uint8List? createSafeJpegDecodeFallbackBytesFromData(Uint8List imageData) {
- try {
- final decoded = img.decodeImage(imageData);
- if (decoded == null) {
- return null;
- }
- final jpeg = img.encodeJpg(decoded, quality: 95);
- return Uint8List.fromList(jpeg);
- } catch (e) {
- final firstLine = e.toString().split('\n').first.trim();
- _logger.warning(
- firstLine.isEmpty
- ? "Safe JPEG conversion failed"
- : "Safe JPEG conversion failed: $firstLine",
- );
- return null;
- }
-}
-
-/// Decodes [Uint8List] image data to an ui.[Image] object.
-Future<Image> decodeImageFromData(Uint8List imageData) async {
- // Decoding using flutter paint. This is the fastest and easiest method.
- final Image image = await paint.decodeImageFromList(imageData);
- return image;
-
- // // Similar decoding as above, but without using flutter paint. This is not faster than the above.
- // final Codec codec = await instantiateImageCodecFromBuffer(
- // await ImmutableBuffer.fromUint8List(imageData),
- // );
- // final FrameInfo frameInfo = await codec.getNextFrame();
- // return frameInfo.image;
-
- // Decoding using the ImageProvider, same as `image_pixels` package. This is not faster than the above.
- // final Completer<Image> completer = Completer<Image>();
- // final ImageProvider provider = MemoryImage(imageData);
- // final ImageStream stream = provider.resolve(const ImageConfiguration());
- // final ImageStreamListener listener =
- // ImageStreamListener((ImageInfo info, bool _) {
- // completer.complete(info.image);
- // });
- // stream.addListener(listener);
- // final Image image = await completer.future;
- // stream.removeListener(listener);
- // return image;
-}
-
-Future<Uint8List> _getRawRgbaBytes(Image image) async {
- return await _getByteDataFromImage(image, format: ImageByteFormat.rawRgba);
-}
-
-/// Encodes an [Image] object to a [Uint8List], in the png format.
-/// Can be used with `Image.memory()`.
-Future<Uint8List> _encodeImageToPng(Image image) async {
- return await _getByteDataFromImage(image, format: ImageByteFormat.png);
-}
-
-/// Returns the [ByteData] object of the image, in rawRgba format.
-///
-/// Throws an exception if the image could not be converted to ByteData.
-Future<Uint8List> _getByteDataFromImage(
- Image image, {
- required ImageByteFormat format,
-}) async {
- final byteData = await image.toByteData(format: format);
- if (byteData == null) {
- _logger.severe('Failed to get byte data in $format from image');
- throw Exception('Failed to get byte data in $format from image');
- }
- return byteData.buffer.asUint8List();
-}
-
-/// Generates a face thumbnail from [imageData] and [faceBoxes].
-///
-/// Returns a [Uint8List] image, in png format.
-Future<List<Uint8List>> generateFaceThumbnailsUsingCanvas(
- String imagePath,
- List<FaceBox> faceBoxes,
-) async {
- int i = 0; // Index of the faceBox, initialized here for logging purposes
- try {
- final decodedImage = await decodeImageFromPath(
- imagePath,
- includeRgbaBytes: false,
- includeDartUiImage: true,
- );
- final dimensions = decodedImage.dimensions;
- final Image? img = decodedImage.image;
- if (img == null) {
- _logger.severe('Image is null, cannot generate face thumbnails');
- return [];
- }
- final futureFaceThumbnails = <Future<Uint8List>>[];
- for (final faceBox in faceBoxes) {
- // Note that the faceBox values are relative to the image size, so we need to convert them to absolute values first
- final double xMinAbs = faceBox.x * dimensions.width;
- final double yMinAbs = faceBox.y * dimensions.height;
- final double widthAbs = faceBox.width * dimensions.width;
- final double heightAbs = faceBox.height * dimensions.height;
-
- // Calculate the crop values by adding some padding around the face and making sure it's centered
- const regularPadding = 0.4;
- const minimumPadding = 0.1;
- final num xCrop = (xMinAbs - widthAbs * regularPadding);
- final num xOvershoot = min(0, xCrop).abs() / widthAbs;
- final num widthCrop =
- widthAbs * (1 + 2 * regularPadding) -
- 2 * min(xOvershoot, regularPadding - minimumPadding) * widthAbs;
- final num yCrop = (yMinAbs - heightAbs * regularPadding);
- final num yOvershoot = min(0, yCrop).abs() / heightAbs;
- final num heightCrop =
- heightAbs * (1 + 2 * regularPadding) -
- 2 * min(yOvershoot, regularPadding - minimumPadding) * heightAbs;
-
- // Prevent the face from going out of image bounds
- final xCropSafe = xCrop.clamp(0, dimensions.width);
- final yCropSafe = yCrop.clamp(0, dimensions.height);
- final widthCropSafe = widthCrop.clamp(0, dimensions.width - xCropSafe);
- final heightCropSafe = heightCrop.clamp(0, dimensions.height - yCropSafe);
-
- futureFaceThumbnails.add(
- _cropAndEncodeCanvas(
- img,
- x: xCropSafe.toDouble(),
- y: yCropSafe.toDouble(),
- width: widthCropSafe.toDouble(),
- height: heightCropSafe.toDouble(),
- ),
- );
- i++;
- }
- final List<Uint8List> faceThumbnails = await Future.wait(
- futureFaceThumbnails,
- );
- return faceThumbnails;
- } catch (e, s) {
- _logger.severe(
- 'Error generating face thumbnails. cropImage problematic input argument: ${i}th facebox: ${faceBoxes[i].toString()}',
- e,
- s,
- );
- return [];
- }
-}
-
-Future<(Float32List, Dimensions)> preprocessImageYoloFace(
- Dimensions dim,
- Uint8List rawRgbaBytes,
-) async {
- const requiredWidth = 640;
- const requiredHeight = 640;
- final scale = min(requiredWidth / dim.width, requiredHeight / dim.height);
- final scaledWidth = (dim.width * scale).round().clamp(0, requiredWidth);
- final scaledHeight = (dim.height * scale).round().clamp(0, requiredHeight);
-
- final processedBytes = Float32List(3 * requiredHeight * requiredWidth);
-
- final buffer = Float32List.view(processedBytes.buffer);
- int pixelIndex = 0;
- const int channelOffsetGreen = requiredHeight * requiredWidth;
- const int channelOffsetBlue = 2 * requiredHeight * requiredWidth;
- for (var h = 0; h < requiredHeight; h++) {
- for (var w = 0; w < requiredWidth; w++) {
- late RGB pixel;
- if (w >= scaledWidth || h >= scaledHeight) {
- pixel = const (114, 114, 114);
- } else {
- pixel = _getPixelBilinear(w / scale, h / scale, dim, rawRgbaBytes);
- }
- buffer[pixelIndex] = pixel.$1 / 255;
- buffer[pixelIndex + channelOffsetGreen] = pixel.$2 / 255;
- buffer[pixelIndex + channelOffsetBlue] = pixel.$3 / 255;
- pixelIndex++;
- }
- }
-
- return (processedBytes, Dimensions(width: scaledWidth, height: scaledHeight));
-}
-
-Future<Float32List> preprocessImageClip(
- Dimensions dim,
- Uint8List rawRgbaBytes,
-) async {
- const int requiredWidth = 256;
- const int requiredHeight = 256;
- const int requiredSize = 3 * requiredWidth * requiredHeight;
- final scale = max(requiredWidth / dim.width, requiredHeight / dim.height);
- final bool useAntiAlias = scale < 0.8;
- final scaledWidth = (dim.width * scale).round();
- final scaledHeight = (dim.height * scale).round();
- final widthOffset = max(0, scaledWidth - requiredWidth) / 2;
- final heightOffset = max(0, scaledHeight - requiredHeight) / 2;
-
- final processedBytes = Float32List(requiredSize);
- final buffer = Float32List.view(processedBytes.buffer);
- int pixelIndex = 0;
- const int greenOff = requiredHeight * requiredWidth;
- const int blueOff = 2 * requiredHeight * requiredWidth;
- for (var h = 0 + heightOffset; h < scaledHeight - heightOffset; h++) {
- for (var w = 0 + widthOffset; w < scaledWidth - widthOffset; w++) {
- final RGB pixel = _getPixelBilinear(
- w / scale,
- h / scale,
- dim,
- rawRgbaBytes,
- antiAlias: useAntiAlias,
- );
- buffer[pixelIndex] = pixel.$1 / 255;
- buffer[pixelIndex + greenOff] = pixel.$2 / 255;
- buffer[pixelIndex + blueOff] = pixel.$3 / 255;
- pixelIndex++;
- }
- }
-
- return processedBytes;
-}
-
-Future<(Float32List, List<AlignmentResult>, List<bool>, List<double>, Size)>
-preprocessToMobileFaceNetFloat32List(
- Dimensions dim,
- Uint8List rawRgbaBytes,
- List<FaceDetectionRelative> relativeFaces, {
- int width = 112,
- int height = 112,
-}) async {
- final Size originalSize = Size(dim.width.toDouble(), dim.height.toDouble());
-
- final List<FaceDetectionAbsolute> absoluteFaces =
- relativeToAbsoluteDetections(
- relativeDetections: relativeFaces,
- imageWidth: dim.width,
- imageHeight: dim.height,
- );
-
- final alignedImagesFloat32List = Float32List(
- 3 * width * height * absoluteFaces.length,
- );
- final alignmentResults = <AlignmentResult>[];
- final isBlurs = <bool>[];
- final blurValues = <double>[];
-
- int alignedImageIndex = 0;
- for (final face in absoluteFaces) {
- final (alignmentResult, correctlyEstimated) = SimilarityTransform.estimate(
- face.allKeypoints,
- );
- if (!correctlyEstimated) {
- _logger.severe(
- 'Face alignment failed because not able to estimate SimilarityTransform, for face: $face',
- );
- throw Exception(
- 'Face alignment failed because not able to estimate SimilarityTransform',
- );
- }
- alignmentResults.add(alignmentResult);
-
- _warpAffineFloat32List(
- dim,
- rawRgbaBytes,
- alignmentResult.affineMatrix,
- alignedImagesFloat32List,
- alignedImageIndex,
- );
-
- final faceGrayMatrix = _createGrayscaleIntMatrixFromNormalized2List(
- alignedImagesFloat32List,
- alignedImageIndex,
- );
-
- alignedImageIndex += 3 * width * height;
- final (
- isBlur,
- blurValue,
- ) = await BlurDetectionService.predictIsBlurGrayLaplacian(
- faceGrayMatrix,
- faceDirection: face.getFaceDirection(),
- );
- isBlurs.add(isBlur);
- blurValues.add(blurValue);
- }
- return (
- alignedImagesFloat32List,
- alignmentResults,
- isBlurs,
- blurValues,
- originalSize,
- );
-}
-
-/// Reads the pixel color at the specified coordinates.
-RGB _readPixelColor(int x, int y, Dimensions dim, Uint8List rgbaBytes) {
- if (y < 0 || y >= dim.height || x < 0 || x >= dim.width) {
- if (y < -maxKernelRadius ||
- y >= dim.height + maxKernelRadius ||
- x < -maxKernelRadius ||
- x >= dim.width + maxKernelRadius) {
- _logger.severe(
- '`readPixelColor`: Invalid pixel coordinates, out of bounds. x: $x, y: $y',
- );
- }
- return const (114, 114, 114);
- }
-
- assert(rgbaBytes.lengthInBytes == 4 * dim.width * dim.height);
-
- final int byteOffset = 4 * (dim.width * y + x);
- return (
- rgbaBytes[byteOffset], // red
- rgbaBytes[byteOffset + 1], // green
- rgbaBytes[byteOffset + 2], // blue
- );
-}
-
-RGB _getPixelBlurred(int x, int y, Dimensions dim, Uint8List rgbaBytes) {
- double r = 0, g = 0, b = 0;
- for (int ky = 0; ky < gaussianKernelSize; ky++) {
- for (int kx = 0; kx < gaussianKernelSize; kx++) {
- final int px = (x - gaussianKernelRadius + kx);
- final int py = (y - gaussianKernelRadius + ky);
-
- final RGB pixelRgbTuple = _readPixelColor(px, py, dim, rgbaBytes);
- final double weight = gaussianKernel[ky][kx];
-
- r += pixelRgbTuple.$1 * weight;
- g += pixelRgbTuple.$2 * weight;
- b += pixelRgbTuple.$3 * weight;
- }
- }
- return (r.round(), g.round(), b.round());
-}
-
-List<List<int>> _createGrayscaleIntMatrixFromNormalized2List(
- Float32List imageList,
- int startIndex, {
- int width = 112,
- int height = 112,
-}) {
- return List.generate(
- height,
- (y) => List.generate(width, (x) {
- // 0.299 ∙ Red + 0.587 ∙ Green + 0.114 ∙ Blue
- final pixelIndex = startIndex + 3 * (y * width + x);
- return (0.299 * ((imageList[pixelIndex] + 1) * 127.5) +
- 0.587 * ((imageList[pixelIndex + 1] + 1) * 127.5) +
- 0.114 * ((imageList[pixelIndex + 2] + 1) * 127.5))
- .round()
- .clamp(0, 255);
- }),
- );
-}
-
-Future<Image> _cropImage(
- Image image, {
- required double x,
- required double y,
- required double width,
- required double height,
-}) async {
- final recorder = PictureRecorder();
- final canvas = Canvas(
- recorder,
- Rect.fromPoints(const Offset(0, 0), Offset(width, height)),
- );
-
- canvas.drawImageRect(
- image,
- Rect.fromPoints(Offset(x, y), Offset(x + width, y + height)),
- Rect.fromPoints(const Offset(0, 0), Offset(width, height)),
- Paint()..filterQuality = FilterQuality.medium,
- );
-
- final picture = recorder.endRecording();
- return picture.toImage(width.toInt(), height.toInt());
-}
-
-void _warpAffineFloat32List(
- Dimensions dim,
- Uint8List rawRgbaBytes,
- List<List<double>> affineMatrix,
- Float32List outputList,
- int startIndex, {
- int width = 112,
- int height = 112,
-}) {
- if (width != 112 || height != 112) {
- throw Exception(
- 'Width and height must be 112, other transformations are not supported yet.',
- );
- }
-
- final transformationMatrix = affineMatrix
- .map(
- (row) => row.map((e) {
- if (e != 1.0) {
- return e * 112;
- } else {
- return 1.0;
- }
- }).toList(),
- )
- .toList();
-
- final A = Matrix.fromList([
- [transformationMatrix[0][0], transformationMatrix[0][1]],
- [transformationMatrix[1][0], transformationMatrix[1][1]],
- ]);
- final aInverse = A.inverse();
- // final aInverseMinus = aInverse * -1;
- final B = Vector.fromList([
- transformationMatrix[0][2],
- transformationMatrix[1][2],
- ]);
- final b00 = B[0];
- final b10 = B[1];
- final a00Prime = aInverse[0][0];
- final a01Prime = aInverse[0][1];
- final a10Prime = aInverse[1][0];
- final a11Prime = aInverse[1][1];
-
- for (int yTrans = 0; yTrans < height; ++yTrans) {
- for (int xTrans = 0; xTrans < width; ++xTrans) {
- // Perform inverse affine transformation (original implementation, intuitive but slow)
- // final X = aInverse * (Vector.fromList([xTrans, yTrans]) - B);
- // final X = aInverseMinus * (B - [xTrans, yTrans]);
- // final xList = X.asFlattenedList;
- // num xOrigin = xList[0];
- // num yOrigin = xList[1];
-
- // Perform inverse affine transformation (fast implementation, less intuitive)
- final num xOrigin = (xTrans - b00) * a00Prime + (yTrans - b10) * a01Prime;
- final num yOrigin = (xTrans - b00) * a10Prime + (yTrans - b10) * a11Prime;
-
- final RGB pixel = _getPixelBicubic(xOrigin, yOrigin, dim, rawRgbaBytes);
-
- // Set the new pixel
- outputList[startIndex + 3 * (yTrans * width + xTrans)] =
- (pixel.$1 / 127.5) - 1;
- outputList[startIndex + 3 * (yTrans * width + xTrans) + 1] =
- (pixel.$2 / 127.5) - 1;
- outputList[startIndex + 3 * (yTrans * width + xTrans) + 2] =
- (pixel.$3 / 127.5) - 1;
- }
- }
-}
-
-Future<Uint8List> _cropAndEncodeCanvas(
- Image image, {
- required double x,
- required double y,
- required double width,
- required double height,
-}) async {
- final croppedImage = await _cropImage(
- image,
- x: x,
- y: y,
- width: width,
- height: height,
- );
- return await _encodeImageToPng(croppedImage);
-}
-
-Future<List<Uint8List>> compressFaceThumbnails(Map args) async {
- final listPngBytes = args['listPngBytes'] as List<Uint8List>;
- final List<Future<Uint8List>> compressedBytesList = [];
- try {
- for (final pngBytes in listPngBytes) {
- final compressedBytes = FlutterImageCompress.compressWithList(
- pngBytes,
- quality: _faceThumbnailCompressionQuality,
- format: CompressFormat.jpeg,
- minWidth: _faceThumbnailMinDimension,
- minHeight: _faceThumbnailMinDimension,
- );
- compressedBytesList.add(compressedBytes);
- }
- return await Future.wait(compressedBytesList);
- } catch (e, s) {
- _logger.warning(
- 'Failed to compress face thumbnail, using original. Size: ${listPngBytes.map((e) => e.length).toList()} bytes',
- e,
- s,
- );
- rethrow;
- }
-}
-
-RGB _getPixelBilinear(
- num fx,
- num fy,
- Dimensions dim,
- Uint8List rawRgbaBytes, {
- bool antiAlias = false,
-}) {
- // Clamp to image boundaries
- fx = fx.clamp(0, dim.width - 1);
- fy = fy.clamp(0, dim.height - 1);
-
- // Get the surrounding coordinates and their weights
- final int x0 = fx.floor();
- final int x1 = fx.ceil();
- final int y0 = fy.floor();
- final int y1 = fy.ceil();
- final dx = fx - x0;
- final dy = fy - y0;
- final dx1 = 1.0 - dx;
- final dy1 = 1.0 - dy;
-
- // Get the original pixels (with gaussian blur if antialias)
- final RGB Function(int, int, Dimensions, Uint8List) readPixel = antiAlias
- ? _getPixelBlurred
- : _readPixelColor;
- final RGB pixel1 = readPixel(x0, y0, dim, rawRgbaBytes);
- final RGB pixel2 = readPixel(x1, y0, dim, rawRgbaBytes);
- final RGB pixel3 = readPixel(x0, y1, dim, rawRgbaBytes);
- final RGB pixel4 = readPixel(x1, y1, dim, rawRgbaBytes);
-
- int bilinear(num val1, num val2, num val3, num val4) =>
- (val1 * dx1 * dy1 + val2 * dx * dy1 + val3 * dx1 * dy + val4 * dx * dy)
- .round();
-
- // Calculate the weighted sum of pixels
- final int r = bilinear(pixel1.$1, pixel2.$1, pixel3.$1, pixel4.$1);
- final int g = bilinear(pixel1.$2, pixel2.$2, pixel3.$2, pixel4.$2);
- final int b = bilinear(pixel1.$3, pixel2.$3, pixel3.$3, pixel4.$3);
-
- return (r, g, b);
-}
-
-/// Get the pixel value using Bicubic Interpolation. Code taken mainly from https://github.com/brendan-duncan/image/blob/6e407612752ffdb90b28cd5863c7f65856349348/lib/src/image/image.dart#L697
-RGB _getPixelBicubic(num fx, num fy, Dimensions dim, Uint8List rawRgbaBytes) {
- fx = fx.clamp(0, dim.width - 1);
- fy = fy.clamp(0, dim.height - 1);
-
- final x = fx.toInt() - (fx >= 0.0 ? 0 : 1);
- final px = x - 1;
- final nx = x + 1;
- final ax = x + 2;
- final y = fy.toInt() - (fy >= 0.0 ? 0 : 1);
- final py = y - 1;
- final ny = y + 1;
- final ay = y + 2;
- final dx = fx - x;
- final dy = fy - y;
- num cubic(num dx, num ipp, num icp, num inp, num iap) =>
- icp +
- 0.5 *
- (dx * (-ipp + inp) +
- dx * dx * (2 * ipp - 5 * icp + 4 * inp - iap) +
- dx * dx * dx * (-ipp + 3 * icp - 3 * inp + iap));
-
- final icc = _readPixelColor(x, y, dim, rawRgbaBytes);
-
- final ipp = px < 0 || py < 0
- ? icc
- : _readPixelColor(px, py, dim, rawRgbaBytes);
- final icp = px < 0 ? icc : _readPixelColor(x, py, dim, rawRgbaBytes);
- final inp = py < 0 || nx >= dim.width
- ? icc
- : _readPixelColor(nx, py, dim, rawRgbaBytes);
- final iap = ax >= dim.width || py < 0
- ? icc
- : _readPixelColor(ax, py, dim, rawRgbaBytes);
-
- final ip0 = cubic(dx, ipp.$1, icp.$1, inp.$1, iap.$1);
- final ip1 = cubic(dx, ipp.$2, icp.$2, inp.$2, iap.$2);
- final ip2 = cubic(dx, ipp.$3, icp.$3, inp.$3, iap.$3);
- // final ip3 = cubic(dx, ipp.a, icp.a, inp.a, iap.a);
-
- final ipc = px < 0 ? icc : _readPixelColor(px, y, dim, rawRgbaBytes);
- final inc = nx >= dim.width ? icc : _readPixelColor(nx, y, dim, rawRgbaBytes);
- final iac = ax >= dim.width ? icc : _readPixelColor(ax, y, dim, rawRgbaBytes);
-
- final ic0 = cubic(dx, ipc.$1, icc.$1, inc.$1, iac.$1);
- final ic1 = cubic(dx, ipc.$2, icc.$2, inc.$2, iac.$2);
- final ic2 = cubic(dx, ipc.$3, icc.$3, inc.$3, iac.$3);
- // final ic3 = cubic(dx, ipc.a, icc.a, inc.a, iac.a);
-
- final ipn = px < 0 || ny >= dim.height
- ? icc
- : _readPixelColor(px, ny, dim, rawRgbaBytes);
- final icn = ny >= dim.height
- ? icc
- : _readPixelColor(x, ny, dim, rawRgbaBytes);
- final inn = nx >= dim.width || ny >= dim.height
- ? icc
- : _readPixelColor(nx, ny, dim, rawRgbaBytes);
- final ian = ax >= dim.width || ny >= dim.height
- ? icc
- : _readPixelColor(ax, ny, dim, rawRgbaBytes);
-
- final in0 = cubic(dx, ipn.$1, icn.$1, inn.$1, ian.$1);
- final in1 = cubic(dx, ipn.$2, icn.$2, inn.$2, ian.$2);
- final in2 = cubic(dx, ipn.$3, icn.$3, inn.$3, ian.$3);
- // final in3 = cubic(dx, ipn.a, icn.a, inn.a, ian.a);
-
- final ipa = px < 0 || ay >= dim.height
- ? icc
- : _readPixelColor(px, ay, dim, rawRgbaBytes);
- final ica = ay >= dim.height
- ? icc
- : _readPixelColor(x, ay, dim, rawRgbaBytes);
- final ina = nx >= dim.width || ay >= dim.height
- ? icc
- : _readPixelColor(nx, ay, dim, rawRgbaBytes);
- final iaa = ax >= dim.width || ay >= dim.height
- ? icc
- : _readPixelColor(ax, ay, dim, rawRgbaBytes);
-
- final ia0 = cubic(dx, ipa.$1, ica.$1, ina.$1, iaa.$1);
- final ia1 = cubic(dx, ipa.$2, ica.$2, ina.$2, iaa.$2);
- final ia2 = cubic(dx, ipa.$3, ica.$3, ina.$3, iaa.$3);
- // final ia3 = cubic(dx, ipa.a, ica.a, ina.a, iaa.a);
-
- final c0 = cubic(dy, ip0, ic0, in0, ia0).clamp(0, 255).toInt();
- final c1 = cubic(dy, ip1, ic1, in1, ia1).clamp(0, 255).toInt();
- final c2 = cubic(dy, ip2, ic2, in2, ia2).clamp(0, 255).toInt();
- // final c3 = cubic(dy, ip3, ic3, in3, ia3);
-
- return (c0, c1, c2); // (red, green, blue)
-}
-
-List<List<double>> create2DGaussianKernel(int size, double sigma) {
- final List<List<double>> kernel = List.generate(
- size,
- (_) => List<double>.filled(size, 0),
- );
- double sum = 0.0;
- final int center = size ~/ 2;
-
- for (int y = 0; y < size; y++) {
- for (int x = 0; x < size; x++) {
- final int dx = x - center;
- final int dy = y - center;
- final double g =
- (1 / (2 * pi * sigma * sigma)) *
- exp(-(dx * dx + dy * dy) / (2 * sigma * sigma));
- kernel[y][x] = g;
- sum += g;
- }
- }
-
- // Normalize the kernel
- for (int y = 0; y < size; y++) {
- for (int x = 0; x < size; x++) {
- kernel[y][x] /= sum;
- }
- }
-
- return kernel;
-}
diff --git a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
index be50757422..123b17d56e 100644
--- a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
+++ b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
@@ -10,17 +10,13 @@ import "package:photos/models/ml/face/box.dart";
import "package:photos/models/ml/vector.dart";
import "package:photos/services/machine_learning/face_ml/face_clustering/face_clustering_service.dart";
import "package:photos/services/machine_learning/ml_constants.dart";
-import "package:photos/services/machine_learning/ml_model.dart";
import "package:photos/services/machine_learning/ml_result.dart";
-import "package:photos/services/machine_learning/semantic_search/clip/clip_text_encoder.dart";
-import "package:photos/services/machine_learning/semantic_search/clip/clip_text_tokenizer.dart";
import "package:photos/services/machine_learning/semantic_search/query_result.dart";
import "package:photos/src/rust/api/image_processing_api.dart"
as rust_image_processing;
import "package:photos/src/rust/api/ml_indexing_api.dart" as rust_ml;
import "package:photos/src/rust/api/usearch_api.dart" as rust_usearch;
import "package:photos/src/rust/frb_generated.dart" show EntePhotosRust;
-import "package:photos/utils/image_ml_util.dart";
import "package:photos/utils/ml_util.dart";
final Map<String, dynamic> _isolateCache = {};
@@ -46,21 +42,9 @@ enum IsolateOperation {
/// [MLIndexingIsolate]
releaseRustMlRuntime,
- /// [MLIndexingIsolate]
- loadIndexingModels,
-
- /// [MLIndexingIsolate]
- releaseIndexingModels,
-
/// [MLComputer]
generateFaceThumbnails,
- /// [MLComputer]
- loadModel,
-
- /// [MLComputer]
- initializeClipTokenizer,
-
/// [MLComputer]
runClipText,
@@ -127,15 +111,10 @@ Future<dynamic> isolateFunction(
/// MLIndexingIsolate
case IsolateOperation.analyzeImage:
- final bool useRustMl = args["useRustMl"] as bool? ?? false;
- if (useRustMl) {
- await _ensureRustLoaded();
- }
+ await _ensureRustLoaded();
final MLResult result;
try {
- result = useRustMl
- ? await analyzeImageRust(args)
- : await analyzeImageStatic(args);
+ result = await analyzeImageRust(args);
} on rust_ml.RustMlError_CorruptModel catch (e) {
final file = File(e.field0);
if (await file.exists()) {
@@ -156,29 +135,6 @@ Future<dynamic> isolateFunction(
await _releaseRustRuntime();
return true;
- /// MLIndexingIsolate
- case IsolateOperation.loadIndexingModels:
- final modelNames = args['modelNames'] as List<String>;
- final modelPaths = args['modelPaths'] as List<String>;
- final addresses = <int>[];
- for (int i = 0; i < modelNames.length; i++) {
- final int address = await MlModel.loadModel(
- modelNames[i],
- modelPaths[i],
- );
- addresses.add(address);
- }
- return List<int>.from(addresses, growable: false);
-
- /// MLIndexingIsolate
- case IsolateOperation.releaseIndexingModels:
- final modelNames = args['modelNames'] as List<String>;
- final modelAddresses = args['modelAddresses'] as List<int>;
- for (int i = 0; i < modelNames.length; i++) {
- await MlModel.releaseModel(modelNames[i], modelAddresses[i]);
- }
- return true;
-
/// Cases for MLIndexingIsolate stop here
/// Cases for MLComputer start here
@@ -186,58 +142,30 @@ Future<dynamic> isolateFunction(
/// MLComputer
case IsolateOperation.generateFaceThumbnails:
final imagePath = args['imagePath'] as String;
- final useRustForFaceThumbnails =
- args['useRustForFaceThumbnails'] as bool? ?? false;
final faceBoxesJson = args['faceBoxesList'] as List<Map<String, dynamic>>;
final List<FaceBox> faceBoxes = faceBoxesJson
.map((json) => FaceBox.fromJson(json))
.toList();
- if (useRustForFaceThumbnails) {
- await _ensureRustLoaded();
- final rustFaceBoxes = faceBoxes
- .map(
- (box) => rust_image_processing.RustFaceBox(
- x: box.x,
- y: box.y,
- width: box.width,
- height: box.height,
- ),
- )
- .toList(growable: false);
- final List<Uint8List> results = await rust_image_processing
- .generateFaceThumbnails(
- imagePath: imagePath,
- faceBoxes: rustFaceBoxes,
- );
- return List.from(results);
- }
- final List<Uint8List> results = await generateFaceThumbnailsUsingCanvas(
- imagePath,
- faceBoxes,
- );
+ await _ensureRustLoaded();
+ final rustFaceBoxes = faceBoxes
+ .map(
+ (box) => rust_image_processing.RustFaceBox(
+ x: box.x,
+ y: box.y,
+ width: box.width,
+ height: box.height,
+ ),
+ )
+ .toList(growable: false);
+ final List<Uint8List> results = await rust_image_processing
+ .generateFaceThumbnails(
+ imagePath: imagePath,
+ faceBoxes: rustFaceBoxes,
+ );
return List.from(results);
- /// MLComputer
- case IsolateOperation.loadModel:
- final modelName = args['modelName'] as String;
- final modelPath = args['modelPath'] as String;
- final int address = await MlModel.loadModel(modelName, modelPath);
- return address;
-
- /// MLComputer
- case IsolateOperation.initializeClipTokenizer:
- final vocabPath = args["vocabPath"] as String;
- await ClipTextTokenizer.instance.init(vocabPath);
- return true;
-
/// MLComputer
case IsolateOperation.runClipText:
- final useRustMl = args["useRustMl"] as bool? ?? false;
- if (!useRustMl) {
- final textEmbedding = await ClipTextEncoder.predict(args);
- return List<double>.from(textEmbedding, growable: false);
- }
-
await _ensureRustLoaded();
final text = args["text"] as String;
final clipTextModelPath = args["clipTextModelPath"] as String?;
diff --git a/mobile/apps/photos/lib/utils/isolate/super_isolate.dart b/mobile/apps/photos/lib/utils/isolate/super_isolate.dart
index 8e32cc1a64..b109ccac6c 100644
--- a/mobile/apps/photos/lib/utils/isolate/super_isolate.dart
+++ b/mobile/apps/photos/lib/utils/isolate/super_isolate.dart
@@ -1,7 +1,6 @@
import 'dart:async';
import 'dart:isolate';
-import "package:dart_ui_isolate/dart_ui_isolate.dart";
import "package:flutter/foundation.dart" show kDebugMode;
import "package:flutter/services.dart";
import "package:logging/logging.dart";
@@ -21,11 +20,10 @@ abstract class SuperIsolate {
final _initIsolateLock = Lock();
final _functionLock = Lock();
- bool get isDartUiIsolate;
bool get shouldAutomaticDispose;
String get isolateName;
- late dynamic _isolate;
+ late Isolate _isolate;
late ReceivePort _receivePort;
late SendPort _mainSendPort;
@@ -38,23 +36,17 @@ abstract class SuperIsolate {
_receivePort = ReceivePort();
- // Get the root token before spawning the isolate
final rootToken = RootIsolateToken.instance;
- if (rootToken == null && !isDartUiIsolate) {
+ if (rootToken == null) {
logger.severe('Failed to get RootIsolateToken');
return;
}
try {
- _isolate = isDartUiIsolate
- ? await DartUiIsolate.spawn(_isolateMain, [
- _receivePort.sendPort,
- null,
- ])
- : await Isolate.spawn(_isolateMain, [
- _receivePort.sendPort,
- rootToken,
- ], debugName: isolateName);
+ _isolate = await Isolate.spawn(_isolateMain, [
+ _receivePort.sendPort,
+ rootToken,
+ ], debugName: isolateName);
_mainSendPort = await _receivePort.first as SendPort;
if (shouldAutomaticDispose) _resetInactivityTimer();
diff --git a/mobile/apps/photos/lib/utils/ml_util.dart b/mobile/apps/photos/lib/utils/ml_util.dart
index 829f7a2c87..53c1677e21 100644
--- a/mobile/apps/photos/lib/utils/ml_util.dart
+++ b/mobile/apps/photos/lib/utils/ml_util.dart
@@ -1,5 +1,5 @@
import "dart:io" show Directory, File, Platform;
-import "dart:math" as math show sqrt, min, max;
+import "dart:math" as math show min, max;
import "package:dio/dio.dart";
import "package:ente_pure_utils/ente_pure_utils.dart";
@@ -26,15 +26,13 @@ import "package:photos/services/filedata/model/file_data.dart";
import "package:photos/services/filedata/model/response.dart";
import "package:photos/services/machine_learning/face_ml/face_alignment/alignment_result.dart";
import "package:photos/services/machine_learning/face_ml/face_detection/detection.dart";
-import "package:photos/services/machine_learning/face_ml/face_recognition_service.dart";
import "package:photos/services/machine_learning/ml_exceptions.dart";
import "package:photos/services/machine_learning/ml_result.dart";
-import "package:photos/services/machine_learning/semantic_search/semantic_search_service.dart";
import "package:photos/services/search_service.dart";
import "package:photos/services/sync/local_sync_service.dart";
import "package:photos/src/rust/api/ml_indexing_api.dart" as rust_ml;
import "package:photos/utils/file_util.dart";
-import "package:photos/utils/image_ml_util.dart";
+import "package:photos/utils/image_decode_util.dart";
import "package:photos/utils/network_util.dart";
import "package:photos/utils/thumbnail_util.dart";
@@ -115,8 +113,7 @@ Future<IndexStatus> getIndexStatus() async {
int indexedFiles = math.min(facesIndexedFiles, clipIndexedFiles);
if (flagService.petEnabled &&
localSettings.petRecognitionEnabled &&
- localSettings.isMLLocalIndexingEnabled &&
- (flagService.useRustForML || isLocalGalleryMode)) {
+ localSettings.isMLLocalIndexingEnabled) {
final int petIndexedFiles = await mlDataDB.getPetIndexedFileCount();
indexedFiles = math.min(indexedFiles, petIndexedFiles);
}
@@ -150,8 +147,7 @@ _getOnlineFilesForMlIndexingCandidates() async {
final bool petEnabled =
flagService.petEnabled &&
localSettings.petRecognitionEnabled &&
- localSettings.isMLLocalIndexingEnabled &&
- (flagService.useRustForML || isLocalGalleryMode);
+ localSettings.isMLLocalIndexingEnabled;
final Map<int, int> petIndexedFileIDs = petEnabled
? await mlDataDB.petIndexedFileIds()
: const {};
@@ -298,9 +294,7 @@ Future<List<FileMLInstruction>> getLocalGalleryFilesForMlIndexing() async {
final Map<int, int> clipIndexedFileIDs = await mlDataDB
.clipIndexedFileWithVersion();
final bool petEnabled =
- flagService.petEnabled &&
- localSettings.petRecognitionEnabled &&
- (flagService.useRustForML || isLocalGalleryMode);
+ flagService.petEnabled && localSettings.petRecognitionEnabled;
final Map<int, int> petIndexedFileIDs = petEnabled
? await mlDataDB.petIndexedFileIds()
: const {};
@@ -763,91 +757,6 @@ bool _shouldRunIndexingWithFileId(
indexedFileIds[fileId]! < newestVersion;
}
-void normalizeEmbedding(List<double> embedding) {
- double normalization = 0;
- for (int i = 0; i < embedding.length; i++) {
- normalization += embedding[i] * embedding[i];
- }
- final double sqrtNormalization = math.sqrt(normalization);
- for (int i = 0; i < embedding.length; i++) {
- embedding[i] = embedding[i] / sqrtNormalization;
- }
-}
-
-Future<MLResult> analyzeImageStatic(Map args) async {
- try {
- final int enteFileID = args["enteFileID"] as int;
- final String imagePath = args["filePath"] as String;
- final bool runFaces = args["runFaces"] as bool;
- final bool runClip = args["runClip"] as bool;
- final int faceDetectionAddress = args["faceDetectionAddress"] as int;
- final int faceEmbeddingAddress = args["faceEmbeddingAddress"] as int;
- final int clipImageAddress = args["clipImageAddress"] as int;
-
- _logger.info(
- "Start analyzeImageStatic for fileID $enteFileID (runFaces: $runFaces, runClip: $runClip)",
- );
- final startTime = DateTime.now();
-
- // Decode the image once to use for both face detection and alignment
- final decodedImage = await decodeImageFromPath(
- imagePath,
- includeRgbaBytes: true,
- includeDartUiImage: false,
- );
- final rawRgbaBytes = decodedImage.rawRgbaBytes!;
- final imageDimensions = decodedImage.dimensions;
- final result = MLResult.fromEnteFileID(enteFileID);
- result.decodedImageSize = imageDimensions;
- if (!runFaces) result.faces = null;
- final decodeTime = DateTime.now();
- final decodeMs = decodeTime.difference(startTime).inMilliseconds;
-
- String faceMsString = "", clipMsString = "";
- final pipelines = await Future.wait([
- runFaces
- ? FaceRecognitionService.runFacesPipeline(
- enteFileID,
- imageDimensions,
- rawRgbaBytes,
- faceDetectionAddress,
- faceEmbeddingAddress,
- ).then((result) {
- faceMsString =
- ", faces: ${DateTime.now().difference(decodeTime).inMilliseconds} ms";
- return result;
- })
- : Future.value(null),
- runClip
- ? SemanticSearchService.runClipImage(
- enteFileID,
- imageDimensions,
- rawRgbaBytes,
- clipImageAddress,
- ).then((result) {
- clipMsString =
- ", clip: ${DateTime.now().difference(decodeTime).inMilliseconds} ms";
- return result;
- })
- : Future.value(null),
- ]);
-
- if (pipelines[0] != null) result.faces = pipelines[0] as List<FaceResult>;
- if (pipelines[1] != null) result.clip = pipelines[1] as ClipResult;
-
- final totalMs = DateTime.now().difference(startTime).inMilliseconds;
-
- _logger.info(
- 'Finished analyzeImageStatic for fileID $enteFileID, in $totalMs ms (decode: $decodeMs ms$faceMsString$clipMsString)',
- );
-
- return result;
- } catch (e, s) {
- _logger.severe("Could not analyze image", e, s);
- rethrow;
- }
-}
-
Future<MLResult> analyzeImageRust(Map args) async {
try {
final int enteFileID = args["enteFileID"] as int;
diff --git a/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart b/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart
index 7d215b7b87..485976f32e 100644
--- a/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart
+++ b/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart
@@ -104,12 +104,8 @@ class FlagService {
bool get enableMemoryShareLink => true;
- bool get useRustForML => true;
-
bool get enableMLInBackground => true;
- bool get useRustForFaceThumbnails => true;
-
bool get useRustForHeicDecoder => internalUser;
bool get petEnabled => internalUser;
diff --git a/mobile/apps/photos/plugins/onnx_dart/.metadata b/mobile/apps/photos/plugins/onnx_dart/.metadata
deleted file mode 100644
index cf57c0cccc..0000000000
--- a/mobile/apps/photos/plugins/onnx_dart/.metadata
+++ /dev/null
@@ -1,30 +0,0 @@
-# This file tracks properties of this Flutter project.
-# Used by Flutter tool to assess capabilities and perform upgrades etc.
-#
-# This file should be version controlled and should not be manually edited.
-
-version:
- revision: "761747bfc538b5af34aa0d3fac380f1bc331ec49"
- channel: "[user-branch]"
-
-project_type: plugin
-
-# Tracks metadata for the flutter migrate command
-migration:
- platforms:
- - platform: root
- create_revision: 761747bfc538b5af34aa0d3fac380f1bc331ec49
- base_revision: 761747bfc538b5af34aa0d3fac380f1bc331ec49
- - platform: android
- create_revision: 761747bfc538b5af34aa0d3fac380f1bc331ec49
- base_revision: 761747bfc538b5af34aa0d3fac380f1bc331ec49
-
- # User provided section
-
- # List of Local paths (relative to this file) that should be
- # ignored by the migrate tool.
- #
- # Files that are not part of the templates will be ignored by default.
- unmanaged_files:
- - 'lib/main.dart'
- - 'ios/Runner.xcodeproj/project.pbxproj'
diff --git a/mobile/apps/photos/plugins/onnx_dart/android/build.gradle b/mobile/apps/photos/plugins/onnx_dart/android/build.gradle
deleted file mode 100644
index 5932438b3e..0000000000
--- a/mobile/apps/photos/plugins/onnx_dart/android/build.gradle
+++ /dev/null
@@ -1,72 +0,0 @@
-group = "io.ente.photos.onnx_dart"
-version = "1.0-SNAPSHOT"
-
-buildscript {
- ext.kotlin_version = "1.7.10"
- repositories {
- google()
- mavenCentral()
- }
-
- dependencies {
- classpath("com.android.tools.build:gradle:7.3.0")
- classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")
- }
-}
-
-allprojects {
- repositories {
- google()
- mavenCentral()
- }
-}
-
-apply plugin: "com.android.library"
-apply plugin: "kotlin-android"
-
-android {
- if (project.android.hasProperty("namespace")) {
- namespace = "io.ente.photos.onnx_dart"
- }
-
- compileSdk = 34
-
- compileOptions {
- sourceCompatibility = JavaVersion.VERSION_1_8
- targetCompatibility = JavaVersion.VERSION_1_8
- }
-
- kotlinOptions {
- jvmTarget = "1.8"
- }
-
- sourceSets {
- main.java.srcDirs += "src/main/kotlin"
- test.java.srcDirs += "src/test/kotlin"
- }
-
- defaultConfig {
- minSdk = 21
- }
-
- dependencies {
- testImplementation("org.jetbrains.kotlin:kotlin-test")
- testImplementation("org.mockito:mockito-core:5.0.0")
-
- implementation("com.microsoft.onnxruntime:onnxruntime-android") {
- version { strictly("1.22.0") }
- }
- }
-
- testOptions {
- unitTests.all {
- useJUnitPlatform()
-
- testLogging {
- events "passed", "skipped", "failed", "standardOut", "standardError"
- outputs.upToDateWhen {false}
- showStandardStreams = true
- }
- }
- }
-}
diff --git a/mobile/apps/photos/plugins/onnx_dart/android/gradle/wrapper/gradle-wrapper.properties b/mobile/apps/photos/plugins/onnx_dart/android/gradle/wrapper/gradle-wrapper.properties
deleted file mode 100644
index 1af9e0930b..0000000000
--- a/mobile/apps/photos/plugins/onnx_dart/android/gradle/wrapper/gradle-wrapper.properties
+++ /dev/null
@@ -1,7 +0,0 @@
-distributionBase=GRADLE_USER_HOME
-distributionPath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
-networkTimeout=10000
-validateDistributionUrl=true
-zipStoreBase=GRADLE_USER_HOME
-zipStorePath=wrapper/dists
diff --git a/mobile/apps/photos/plugins/onnx_dart/android/settings.gradle b/mobile/apps/photos/plugins/onnx_dart/android/settings.gradle
deleted file mode 100644
index d207db8c75..0000000000
--- a/mobile/apps/photos/plugins/onnx_dart/android/settings.gradle
+++ /dev/null
@@ -1 +0,0 @@
-rootProject.name = 'onnx_dart'
diff --git a/mobile/apps/photos/plugins/onnx_dart/android/src/main/AndroidManifest.xml b/mobile/apps/photos/plugins/onnx_dart/android/src/main/AndroidManifest.xml
deleted file mode 100644
index 7582c8c286..0000000000
--- a/mobile/apps/photos/plugins/onnx_dart/android/src/main/AndroidManifest.xml
+++ /dev/null
@@ -1,3 +0,0 @@
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="io.ente.photos.onnx_dart">
-</manifest>
diff --git a/mobile/apps/photos/plugins/onnx_dart/android/src/main/kotlin/io/ente/photos/onnx_dart/OnnxDartPlugin.kt b/mobile/apps/photos/plugins/onnx_dart/android/src/main/kotlin/io/ente/photos/onnx_dart/OnnxDartPlugin.kt
deleted file mode 100644
index 56294c6c2f..0000000000
--- a/mobile/apps/photos/plugins/onnx_dart/android/src/main/kotlin/io/ente/photos/onnx_dart/OnnxDartPlugin.kt
+++ /dev/null
@@ -1,266 +0,0 @@
-package io.ente.photos.onnx_dart
-
-import android.content.Context
-import java.nio.IntBuffer
-import androidx.annotation.NonNull
-import ai.onnxruntime.*
-import java.util.EnumMap
-import io.flutter.embedding.engine.plugins.FlutterPlugin
-import io.flutter.plugin.common.MethodCall
-import io.flutter.plugin.common.MethodChannel
-import io.flutter.plugin.common.MethodChannel.MethodCallHandler
-import io.flutter.plugin.common.MethodChannel.Result
-import kotlinx.coroutines.*
-import java.nio.FloatBuffer
-import java.util.concurrent.ConcurrentHashMap
-import android.util.Log
-import java.io.File
-import java.nio.ByteBuffer
-import java.nio.ByteOrder
-import java.util.concurrent.ConcurrentLinkedQueue
-
-/** OnnxDartPlugin */
-class OnnxDartPlugin: FlutterPlugin, MethodCallHandler {
- /// The MethodChannel that will the communication between Flutter and native Android
- ///
- /// This local reference serves to register the plugin with the Flutter Engine and unregister it
- /// when the Flutter Engine is detached from the Activity
- private lateinit var channel : MethodChannel
-
- private val TAG = OnnxDartPlugin::class.java.name
-
-
- private var faceOrtEnv: OrtEnvironment = OrtEnvironment.getEnvironment()
- private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
- private val sessionMap = ConcurrentHashMap<ModelType, ModelState>()
- private lateinit var context: Context
-
- enum class ModelType {
- ClipTextEncoder, ClipImageEncoder, YOLOv5Face, MobileFaceNet
- }
- companion object {
- const val DEFAULT_SESSION_COUNT = 1
- const val FACENET_SINGLE_INPUT_SIZE = 112*112*3
- }
-
-
-
- data class ModelState(
- var isInitialized: Boolean = false,
- val sessionAddresses: ConcurrentHashMap<Int, OrtSession> = ConcurrentHashMap(),
- // number of sessions that should have been created for given model
- var sessionsCount: Int = DEFAULT_SESSION_COUNT
- )
-
- override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
- channel = MethodChannel(flutterPluginBinding.binaryMessenger, "onnx_dart")
- channel.setMethodCallHandler(this)
- context = flutterPluginBinding.applicationContext
- }
-
- override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
- channel.setMethodCallHandler(null)
- }
-
-
- override fun onMethodCall(call: MethodCall, result: Result) {
- when (call.method) {
- "getPlatformVersion" -> {
- var env = OrtEnvironment.getEnvironment()
- var OrtVersion = env.getVersion()
- Log.d(TAG, "Android: ${android.os.Build.VERSION.RELEASE}, OrtVersion: $OrtVersion")
- result.success("Android: ${android.os.Build.VERSION.RELEASE}, OrtVersion: $OrtVersion")
- }
- "init" -> {
- val modelType = call.argument<String>("modelType")
- val modelPath = call.argument<String>("modelPath")
- val sessionsCount = call.argument<Int>("sessionsCount") ?: DEFAULT_SESSION_COUNT
-
- if (modelType == null || modelPath == null) {
- result.error("INVALID_ARGUMENT", "Model type or path is missing", null)
- return
- }
-
- init(ModelType.valueOf(modelType), modelPath, sessionsCount, result)
- }
- "release" -> {
- val modelType = call.argument<String>("modelType")
- if (modelType == null) {
- result.error("INVALID_ARGUMENT", "Model type is missing", null)
- return
- }
- release(ModelType.valueOf(modelType), result)
- }
- "predict" -> {
- val sessionAddress = call.argument<Int>("sessionAddress")
- val modelType = call.argument<String>("modelType")
- val inputDataArray = call.argument<FloatArray>("inputData")
- val inputIntDataArray = call.argument<IntArray>("inputDataInt")
- val inputUint8DataArray = call.argument<ByteArray>("inputDataUint8")
- val inputShapeArray = call.argument<IntArray>("inputShapeList")
-
- if (sessionAddress == null || modelType == null || (inputDataArray == null && inputIntDataArray == null && inputUint8DataArray == null)) {
- result.error("INVALID_ARGUMENT", "Session address, model type, or input data is missing", null)
- return
- }
-
- predict(ModelType.valueOf(modelType), sessionAddress, inputDataArray, inputIntDataArray, inputUint8DataArray, inputShapeArray, result)
- }
- else -> {
- result.notImplemented()
- }
- }
- }
-
-
- private fun init(modelType: ModelType, modelPath: String, sessionsCount: Int, result: Result) {
- Log.d(TAG, " v: $modelType, path: $modelPath, sessionsCount: $sessionsCount")
- scope.launch {
- val modelState: ModelState
- if (sessionMap.containsKey(modelType)) {
- modelState = sessionMap[modelType]!!
- } else {
- modelState = ModelState()
- sessionMap[modelType] = modelState
- }
- if (!modelState.isInitialized) {
- for (i in 0 until sessionsCount) {
- val session = createSession(faceOrtEnv, modelPath)
- if (session != null) {
- modelState.sessionAddresses[i] = session
- }
- }
- modelState.isInitialized = true
- modelState.sessionsCount = sessionsCount
- withContext(Dispatchers.Main) {
- Log.d(TAG, "Model initialized: $modelType")
- result.success(true)
- }
- } else {
- withContext(Dispatchers.Main) {
- result.success(false)
- }
- }
- }
- }
-
- private fun release(modelType: ModelType, result: Result) {
- scope.launch {
- val modelState = sessionMap[modelType]
- modelState?.let {
- it.sessionAddresses.forEach { entry: Map.Entry<Int, OrtSession> ->
- entry.value.close()
- }
- it.sessionAddresses.clear()
- it.isInitialized = false
- }
- withContext(Dispatchers.Main) {
- result.success(true)
- }
- }
- }
-
- private fun predict(modelType: ModelType, sessionAddress: Int, inputDataFloat: FloatArray? = null, inputDataInt: IntArray? = null, inputUint8DataArray: ByteArray? = null, inputShapeArray: IntArray? = null, result: Result) {
- assert((inputDataFloat != null).xor((inputDataInt != null).xor(inputUint8DataArray != null))) { "Exactly one of inputDataFloat, inputDataInt or inputUint8DataArray must be provided" }
-
- scope.launch {
- val modelState = sessionMap[modelType]
- val session = modelState?.sessionAddresses?.get(sessionAddress)
- if (session == null) {
- withContext(Dispatchers.Main) {
- result.error("SESSION_NOT_FOUND", "Session not found for address: $sessionAddress", null)
- }
- return@launch
- }
-
- try {
- val env = OrtEnvironment.getEnvironment()
- var inputTensorShape: LongArray = longArrayOf(1, 3, 640, 640)
- when (modelType) {
- ModelType.MobileFaceNet -> {
- val totalSize = inputDataFloat!!.size.toLong() / FACENET_SINGLE_INPUT_SIZE
- inputTensorShape = longArrayOf(totalSize, 112, 112, 3)
- }
- ModelType.ClipImageEncoder -> {
- inputTensorShape = longArrayOf(1, 3, 256, 256)
- }
- ModelType.ClipTextEncoder -> {
- inputTensorShape = longArrayOf(1, 77)
- }
- ModelType.YOLOv5Face -> {
- inputTensorShape = longArrayOf(1, 3, 640, 640)
- }
- }
-
- val inputTensor = when {
- inputDataFloat != null -> OnnxTensor.createTensor(env, FloatBuffer.wrap(inputDataFloat), inputTensorShape)
- inputDataInt != null -> OnnxTensor.createTensor(env, IntBuffer.wrap(inputDataInt), inputTensorShape)
- inputUint8DataArray != null -> OnnxTensor.createTensor(env, ByteBuffer.wrap(inputUint8DataArray), inputTensorShape, OnnxJavaType.UINT8)
- else -> throw IllegalArgumentException("No input data provided")
- }
- val inputs = mutableMapOf<String, OnnxTensor>()
- if (modelType == ModelType.MobileFaceNet) {
- inputs["img_inputs"] = inputTensor
- } else {
- inputs["input"] = inputTensor
- }
- val outputs = session.run(inputs)
- if (modelType == ModelType.YOLOv5Face) {
- val outputTensor = (outputs[0].value as Array<Array<FloatArray>>).get(0)
- val flatList = outputTensor.flattenToFloatArray()
- withContext(Dispatchers.Main) {
- result.success(flatList)
- }
- } else {
- val outputTensor = (outputs[0].value as Array<FloatArray>)
- val flatList = outputTensor.flattenToFloatArray()
- withContext(Dispatchers.Main) {
- result.success(flatList)
- }
- }
-
- outputs.close()
- inputTensor.close()
- } catch (e: OrtException) {
- withContext(Dispatchers.Main) {
- result.error("PREDICTION_ERROR", "Error during prediction: ${e.message} ${e.stackTraceToString()}", null)
- }
- } catch (e: Exception) {
- Log.e(TAG, "Error during prediction: ${e.message}", e)
- withContext(Dispatchers.Main) {
- result.error("UNHANDLED_ERROR", "Error during prediction: ${e.message}", null)
- }
- }
- }
- }
-
- private fun createSession(env: OrtEnvironment, modalPath: String): OrtSession? {
- val sessionOptions = OrtSession.SessionOptions()
- sessionOptions.setInterOpNumThreads(1)
- sessionOptions.setIntraOpNumThreads(1)
- sessionOptions.setOptimizationLevel(OrtSession.SessionOptions.OptLevel.ALL_OPT)
- return env.createSession(modalPath, sessionOptions)
- }
-
- private fun releaseAllSessions() {
- sessionMap.forEach { (_, modelState) ->
- modelState.sessionAddresses.forEach { entry ->
- entry.value.close()
- }
- modelState.sessionAddresses.clear()
- }
- sessionMap.clear()
- }
-
- private fun Array<FloatArray>.flattenToFloatArray(): FloatArray {
- val outputSize = this.sumOf { it.size }
- val result = FloatArray(outputSize)
- var index = 0
- for (inner in this) {
- for (value in inner) {
- result[index++] = value
- }
- }
- return result
- }
-}
diff --git a/mobile/apps/photos/plugins/onnx_dart/lib/onnx_dart.dart b/mobile/apps/photos/plugins/onnx_dart/lib/onnx_dart.dart
deleted file mode 100644
index 16cfb9f660..0000000000
--- a/mobile/apps/photos/plugins/onnx_dart/lib/onnx_dart.dart
+++ /dev/null
@@ -1,72 +0,0 @@
-import 'dart:typed_data';
-
-import 'package:onnx_dart/onnx_dart_platform_interface.dart';
-
-class OnnxDart {
- Future<String?> getPlatformVersion() {
- return OnnxDartPlatform.instance.getPlatformVersion();
- }
-
- Future<bool?> init(
- String modelType,
- String modelPath, {
- int sessionsCount = 1,
- }) {
- return OnnxDartPlatform.instance.init(
- modelType,
- modelPath,
- sessionsCount: sessionsCount,
- );
- }
-
- Future<bool?> release(String modelType) {
- return OnnxDartPlatform.instance.release(modelType);
- }
-
- Future<Float32List?> predict(
- Float32List inputData,
- String modelType, {
- int sessionAddress = 0,
- }) async {
- final result = await OnnxDartPlatform.instance.predict(
- inputData,
- null,
- null,
- modelType,
- sessionAddress: sessionAddress,
- );
- return result;
- }
-
- Future<Float32List?> predictInt(
- Int32List inputDataInt,
- String modelType, {
- int sessionAddress = 0,
- }) async {
- final result = await OnnxDartPlatform.instance.predict(
- null,
- inputDataInt,
- null,
- modelType,
- sessionAddress: sessionAddress,
- );
- return result;
- }
-
- Future<Float32List?> predictRgba(
- Uint8List inputBytes,
- Int32List inputShape,
- String modelType, {
- int sessionAddress = 0,
- }) async {
- final result = await OnnxDartPlatform.instance.predict(
- null,
- null,
- inputBytes,
- modelType,
- sessionAddress: sessionAddress,
- inputShapeList: inputShape,
- );
- return result;
- }
-}
diff --git a/mobile/apps/photos/plugins/onnx_dart/lib/onnx_dart_method_channel.dart b/mobile/apps/photos/plugins/onnx_dart/lib/onnx_dart_method_channel.dart
deleted file mode 100644
index 108bbc1e3c..0000000000
--- a/mobile/apps/photos/plugins/onnx_dart/lib/onnx_dart_method_channel.dart
+++ /dev/null
@@ -1,59 +0,0 @@
-import 'package:flutter/foundation.dart';
-import 'package:flutter/services.dart';
-import 'package:onnx_dart/onnx_dart_platform_interface.dart';
-
-/// An implementation of [OnnxDartPlatform] that uses method channels.
-class MethodChannelOnnxDart extends OnnxDartPlatform {
- /// The method channel used to interact with the native platform.
- @visibleForTesting
- final methodChannel = const MethodChannel('onnx_dart');
-
- @override
- Future<String?> getPlatformVersion() async {
- final version = await methodChannel.invokeMethod<String>(
- 'getPlatformVersion',
- );
- return version;
- }
-
- @override
- Future<bool?> init(
- String modelType,
- String modelPath, {
- int sessionsCount = 1,
- }) async {
- final result = await methodChannel.invokeMethod<bool>('init', {
- 'modelType': modelType,
- 'modelPath': modelPath,
- 'sessionsCount': sessionsCount,
- });
- return result;
- }
-
- @override
- Future<bool?> release(String modelType) async {
- final bool? result = await methodChannel.invokeMethod<bool>('release', {
- 'modelType': modelType,
- });
- return result;
- }
-
- @override
- Future<Float32List?> predict(
- Float32List? inputData,
- Int32List? inputDataInt,
- Uint8List? inputDataUint8,
- String modelType, {
- int sessionAddress = 0,
- Int32List? inputShapeList,
- }) {
- return methodChannel.invokeMethod<Float32List?>('predict', {
- 'sessionAddress': sessionAddress,
- 'inputData': inputData,
- 'inputDataInt': inputDataInt,
- 'inputDataUint8': inputDataUint8,
- 'modelType': modelType,
- "inputShapeList": inputShapeList,
- });
- }
-}
diff --git a/mobile/apps/photos/plugins/onnx_dart/lib/onnx_dart_platform_interface.dart b/mobile/apps/photos/plugins/onnx_dart/lib/onnx_dart_platform_interface.dart
deleted file mode 100644
index 82a6107a09..0000000000
--- a/mobile/apps/photos/plugins/onnx_dart/lib/onnx_dart_platform_interface.dart
+++ /dev/null
@@ -1,53 +0,0 @@
-import 'dart:typed_data';
-
-import 'package:onnx_dart/onnx_dart_method_channel.dart';
-import 'package:plugin_platform_interface/plugin_platform_interface.dart';
-
-abstract class OnnxDartPlatform extends PlatformInterface {
- /// Constructs a OnnxDartPlatform.
- OnnxDartPlatform() : super(token: _token);
-
- static final Object _token = Object();
-
- static OnnxDartPlatform _instance = MethodChannelOnnxDart();
-
- /// The default instance of [OnnxDartPlatform] to use.
- ///
- /// Defaults to [MethodChannelOnnxDart].
- static OnnxDartPlatform get instance => _instance;
-
- /// Platform-specific implementations should set this with their own
- /// platform-specific class that extends [OnnxDartPlatform] when
- /// they register themselves.
- static set instance(OnnxDartPlatform instance) {
- PlatformInterface.verifyToken(instance, _token);
- _instance = instance;
- }
-
- Future<String?> getPlatformVersion() {
- throw UnimplementedError('platformVersion() has not been implemented.');
- }
-
- Future<bool?> init(
- String modelType,
- String modelPath, {
- int sessionsCount = 1,
- }) {
- throw UnimplementedError('init() has not been implemented.');
- }
-
- Future<bool?> release(String modelType) {
- throw UnimplementedError('release() has not been implemented.');
- }
-
- Future<Float32List?> predict(
- Float32List? inputData,
- Int32List? inputDataInt,
- Uint8List? inputDataRgba,
- String modelType, {
- int sessionAddress = 0,
- Int32List? inputShapeList,
- }) {
- throw UnimplementedError('predict() has not been implemented.');
- }
-}
diff --git a/mobile/apps/photos/plugins/onnx_dart/pubspec.yaml b/mobile/apps/photos/plugins/onnx_dart/pubspec.yaml
deleted file mode 100644
index 33feebf8ab..0000000000
--- a/mobile/apps/photos/plugins/onnx_dart/pubspec.yaml
+++ /dev/null
@@ -1,38 +0,0 @@
-name: onnx_dart
-
-resolution: workspace
-environment:
- sdk: ">=3.10.0 <4.0.0"
- flutter: '>=3.3.0'
-
-dependencies:
- flutter:
- sdk: flutter
- plugin_platform_interface: 2.1.8
-
-dev_dependencies:
- flutter_lints: 6.0.0
- flutter_test:
- sdk: flutter
-
-
-# For information on the generic Dart part of this file, see the
-# following page: https://dart.dev/tools/pub/pubspec
-
-# The following section is specific to Flutter packages.
-flutter:
- # This section identifies this Flutter project as a plugin project.
- # The 'pluginClass' specifies the class (in Java, Kotlin, Swift, Objective-C, etc.)
- # which should be registered in the plugin registry. This is required for
- # using method channels.
- # The Android 'package' specifies package in which the registered class is.
- # This is required for using method channels on Android.
- # The 'ffiPlugin' specifies that native code should be built and bundled.
- # This is required for using `dart:ffi`.
- # All these are used by the tooling to maintain consistency when
- # adding or updating assets for this project.
- plugin:
- platforms:
- android:
- package: io.ente.photos.onnx_dart
- pluginClass: OnnxDartPlugin
diff --git a/mobile/apps/photos/pubspec.yaml b/mobile/apps/photos/pubspec.yaml
index 02c537dcc1..604c648c1e 100644
--- a/mobile/apps/photos/pubspec.yaml
+++ b/mobile/apps/photos/pubspec.yaml
@@ -45,7 +45,6 @@ dependencies:
convert: 3.1.2
crypto: 3.0.7
cupertino_icons: 1.0.8
- dart_ui_isolate: 1.1.1
defer_pointer: 0.0.2
device_info_plus: 11.5.0
dio: 5.9.2
@@ -188,12 +187,6 @@ dependencies:
native_video_editor:
path: ../../packages/native_video_editor
native_video_player: 4.0.0
- onnx_dart:
- path: plugins/onnx_dart
- onnxruntime:
- git:
- url: https://github.com/ente/onnxruntime.git
- ref: 212b2cab85647c6d2ffee213dc3b875ef2bf6504
open_mail_app: # replace plugin, git is archived
git:
url: https://github.com/ente/open-mail-app-flutter.git
diff --git a/mobile/packages/ente_pure_utils/lib/src/stop_watch.dart b/mobile/packages/ente_pure_utils/lib/src/stop_watch.dart
index 0a07cd7779..9ce4075275 100644
--- a/mobile/packages/ente_pure_utils/lib/src/stop_watch.dart
+++ b/mobile/packages/ente_pure_utils/lib/src/stop_watch.dart
@@ -33,7 +33,7 @@ class EnteWatch extends Stopwatch {
// TimerLogger helps in quickly including the timeTaken for various operation.
// The timeTaken is logged only if it exceeds the logThreshold. With each call to toString, the timer is reset.
// Usage:
-// final TimeLogger tlog = TimeLogger(context: "FaceRecognitionService");
+// final TimeLogger tlog = TimeLogger(context: "PhotoProcessingService");
// _logger.info("some operation $tlog");
// _logger.info("another operation $tlog");
class TimeLogger {
diff --git a/mobile/pubspec.lock b/mobile/pubspec.lock
index 5c54634605..dc2db17ac9 100644
--- a/mobile/pubspec.lock
+++ b/mobile/pubspec.lock
@@ -548,14 +548,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.1.3"
- dart_ui_isolate:
- dependency: transitive
- description:
- name: dart_ui_isolate
- sha256: bd531558002a00de0ac7dd73c84887dd01e652bd254d3098d7763881535196d7
- url: "https://pub.dev"
- source: hosted
- version: "1.1.1"
dbus:
dependency: transitive
description:
@@ -2008,15 +2000,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.1.0"
- onnxruntime:
- dependency: transitive
- description:
- path: "."
- ref: "212b2cab85647c6d2ffee213dc3b875ef2bf6504"
- resolved-ref: "212b2cab85647c6d2ffee213dc3b875ef2bf6504"
- url: "https://github.com/ente/onnxruntime.git"
- source: git
- version: "1.4.1"
open_file:
dependency: transitive
description:
diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml
index a518044b0d..a59b59e11e 100644
--- a/mobile/pubspec.yaml
+++ b/mobile/pubspec.yaml
@@ -11,7 +11,6 @@ workspace:
- apps/photos/plugins/ente_cast
- apps/photos/plugins/ente_crypto
- apps/photos/plugins/ente_feature_flag
- - apps/photos/plugins/onnx_dart
- packages/accounts
- packages/account_deletion
- packages/backup_exclusion