Skip to content

armgit / ente

Public Imported from GitHub
0

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

[mob][droid] Refactor

Neeraj Gupta9318182160a1
diff --git a/mobile/lib/services/machine_learning/face_ml/face_detection/face_detection_service.dart b/mobile/lib/services/machine_learning/face_ml/face_detection/face_detection_service.dart
index 749a5b7a46..688f8e6439 100644
--- a/mobile/lib/services/machine_learning/face_ml/face_detection/face_detection_service.dart
+++ b/mobile/lib/services/machine_learning/face_ml/face_detection/face_detection_service.dart
@@ -17,6 +17,7 @@ class YOLOFaceInterpreterRunException implements Exception {}
/// This class is responsible for running the face detection model (YOLOv5Face) on ONNX runtime, and can be accessed through the singleton instance [FaceDetectionService.instance].
class FaceDetectionService extends MlModel {
static const kRemoteBucketModelPath = "yolov5s_face_640_640_dynamic.onnx";
+ static const _modelName = "YOLOv5Face";
@override
String get modelRemotePath => kModelBucketEndpoint + kRemoteBucketModelPath;
@@ -26,7 +27,7 @@ class FaceDetectionService extends MlModel {
static final _logger = Logger('FaceDetectionService');
@override
- String get modelName => "YOLOv5Face";
+ String get modelName => _modelName;
static const int kInputWidth = 640;
static const int kInputHeight = 640;
@@ -43,12 +44,11 @@ class FaceDetectionService extends MlModel {
static Future<List<FaceDetectionRelative>> predict(
ui.Image image,
ByteData imageByteData,
- int sessionAddress,
- ) async {
+ int sessionAddress, {
+ bool useEntePlugin = false,
+ }) async {
assert(
- !MlModel.useCustomPlugin
- ? (sessionAddress != 0 && sessionAddress != -1)
- : true,
+ !useEntePlugin ? (sessionAddress != 0 && sessionAddress != -1) : true,
'sessionAddress should be valid',
);
@@ -77,7 +77,7 @@ class FaceDetectionService extends MlModel {
List<List<List<double>>>? nestedResults = [];
try {
- if (MlModel.useCustomPlugin) {
+ if (useEntePlugin) {
nestedResults = await _runCustomPlugin(inputImageList);
} else {
nestedResults = _runJNIBasedPlugin(
diff --git a/mobile/lib/services/machine_learning/face_ml/face_recognition_service.dart b/mobile/lib/services/machine_learning/face_ml/face_recognition_service.dart
index 532f655f98..281292b6ff 100644
--- a/mobile/lib/services/machine_learning/face_ml/face_recognition_service.dart
+++ b/mobile/lib/services/machine_learning/face_ml/face_recognition_service.dart
@@ -237,6 +237,7 @@ class FaceRecognitionService {
image,
imageByteData,
interpreterAddress,
+ useEntePlugin: true,
);
// Add detected faces to the faceResults
diff --git a/mobile/lib/services/machine_learning/ml_model.dart b/mobile/lib/services/machine_learning/ml_model.dart
index d4e299d4d9..ec2e729974 100644
--- a/mobile/lib/services/machine_learning/ml_model.dart
+++ b/mobile/lib/services/machine_learning/ml_model.dart
@@ -16,40 +16,64 @@ abstract class MlModel {
String get modelName;
+ // isInitialized is used to check if the model is loaded by the ffi based
+ // plugin
bool isInitialized = false;
+
+ bool isNativePluginInitialized = false;
int sessionAddress = 0;
final computer = Computer.shared();
- static bool useCustomPlugin = Platform.isAndroid;
- Future<void> init() async {
+ // Initializes the model.
+ // If `useEntePlugin` is set to true, the custom plugin is used for initialization.
+ // Note: The custom 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.
+ Future<void> loadModel({bool useEntePlugin = false}) async {
+ final model = await RemoteAssetsService.instance.getAsset(modelRemotePath);
+ if (useEntePlugin) {
+ await _loadModelWithEntePlugin(modelName, model.path);
+ } else {
+ await _loadModelWithFFI(modelName, model.path);
+ }
+ }
+
+ Future<void> _loadModelWithEntePlugin(
+ String modelName,
+ String modelPath,
+ ) async {
+ if (!isNativePluginInitialized) {
+ logger.info('Initializing model with Ente Plugin');
+ final OnnxDart plugin = OnnxDart();
+ final bool? initResult = await plugin.init(modelName, modelPath);
+ isNativePluginInitialized = initResult ?? false;
+ if (isNativePluginInitialized) {
+ logger.info("Model initialized successfully with Ente Plugin.");
+ } else {
+ logger.severe("Failed to initialize model with Ente Plugin.");
+ }
+ } else {
+ logger.info("Model already initialized with Ente Plugin.");
+ }
+ }
+
+ Future<void> _loadModelWithFFI(String modelName, String modelPath) async {
if (!isInitialized) {
- logger.info('init is called');
- final model =
- await RemoteAssetsService.instance.getAsset(modelRemotePath);
+ logger.info('Initializing model with FFI');
final startTime = DateTime.now();
- try {
- if (useCustomPlugin) {
- final OnnxDart plugin = OnnxDart();
- final bool? initResult = await plugin.init(modelName, model.path);
- isInitialized = initResult ?? false;
- } else {
- await ONNXEnv.instance.initONNX(modelName);
- sessionAddress = await computer.compute(
- _loadModel,
- param: {
- "modelPath": model.path,
- },
- );
- isInitialized = true;
- }
- final endTime = DateTime.now();
- logger.info(
- "model loaded, took: ${(endTime.millisecondsSinceEpoch - startTime.millisecondsSinceEpoch).toString()}ms",
- );
- } catch (e, s) {
- logger.severe('model not loaded', e, s);
- }
+ sessionAddress = await computer.compute(
+ _loadModel,
+ param: {
+ "modelPath": modelPath,
+ },
+ );
+ isInitialized = true;
+ final endTime = DateTime.now();
+ logger.info(
+ "Model loaded with FFI, took: ${(endTime.millisecondsSinceEpoch - startTime.millisecondsSinceEpoch).toString()}ms",
+ );
+ } else {
+ logger.info("Model already initialized with FFI.");
}
}
diff --git a/mobile/lib/services/machine_learning/ml_service.dart b/mobile/lib/services/machine_learning/ml_service.dart
index da9658d6c1..b28354d96b 100644
--- a/mobile/lib/services/machine_learning/ml_service.dart
+++ b/mobile/lib/services/machine_learning/ml_service.dart
@@ -526,17 +526,17 @@ class MLService {
// Initialize models
try {
- await FaceDetectionService.instance.init();
+ await FaceDetectionService.instance.loadModel();
} catch (e, s) {
_logger.severe("Could not initialize yolo onnx", e, s);
}
try {
- await FaceEmbeddingService.instance.init();
+ await FaceEmbeddingService.instance.loadModel();
} catch (e, s) {
_logger.severe("Could not initialize mobilefacenet", e, s);
}
try {
- await ClipImageEncoder.instance.init();
+ await ClipImageEncoder.instance.loadModel();
} catch (e, s) {
_logger.severe("Could not initialize clip image", e, s);
}
diff --git a/mobile/lib/services/machine_learning/semantic_search/semantic_search_service.dart b/mobile/lib/services/machine_learning/semantic_search/semantic_search_service.dart
index e7486a2071..cf1626bc0c 100644
--- a/mobile/lib/services/machine_learning/semantic_search/semantic_search_service.dart
+++ b/mobile/lib/services/machine_learning/semantic_search/semantic_search_service.dart
@@ -261,7 +261,7 @@ class SemanticSearchService {
Future<void> _loadTextModel() async {
_logger.info("Initializing ML framework");
try {
- await ClipTextEncoder.instance.init();
+ await ClipTextEncoder.instance.loadModel();
_textModelIsLoaded = true;
} catch (e, s) {
_logger.severe("Clip text loading failed", e, s);