isolate_utils.dart 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import 'dart:isolate';
  2. import "dart:typed_data";
  3. import 'package:image/image.dart' as imgLib;
  4. import 'package:photos/services/object_detection/tflite/cocossd_classifier.dart';
  5. import "package:photos/services/object_detection/tflite/mobilenet_classifier.dart";
  6. import 'package:tflite_flutter/tflite_flutter.dart';
  7. /// Manages separate Isolate instance for inference
  8. class IsolateUtils {
  9. static const String debugName = "InferenceIsolate";
  10. late SendPort _sendPort;
  11. final _receivePort = ReceivePort();
  12. SendPort get sendPort => _sendPort;
  13. Future<void> start() async {
  14. await Isolate.spawn<SendPort>(
  15. entryPoint,
  16. _receivePort.sendPort,
  17. debugName: debugName,
  18. );
  19. _sendPort = await _receivePort.first;
  20. }
  21. static void entryPoint(SendPort sendPort) async {
  22. final port = ReceivePort();
  23. sendPort.send(port.sendPort);
  24. await for (final IsolateData isolateData in port) {
  25. final classifier = isolateData.type == ClassifierType.cocossd
  26. ? CocoSSDClassifier(
  27. interpreter:
  28. Interpreter.fromAddress(isolateData.interpreterAddress),
  29. labels: isolateData.labels,
  30. )
  31. : MobileNetClassifier(
  32. interpreter:
  33. Interpreter.fromAddress(isolateData.interpreterAddress),
  34. labels: isolateData.labels,
  35. );
  36. final image = imgLib.decodeImage(isolateData.input);
  37. final results = classifier.predict(image!);
  38. isolateData.responsePort.send(results);
  39. }
  40. }
  41. }
  42. /// Bundles data to pass between Isolate
  43. class IsolateData {
  44. Uint8List input;
  45. int interpreterAddress;
  46. List<String> labels;
  47. ClassifierType type;
  48. late SendPort responsePort;
  49. IsolateData(
  50. this.input,
  51. this.interpreterAddress,
  52. this.labels,
  53. this.type,
  54. );
  55. }
  56. enum ClassifierType {
  57. cocossd,
  58. mobilenet,
  59. }