ml_framework.dart 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. import "dart:async";
  2. import "dart:io";
  3. import "package:connectivity_plus/connectivity_plus.dart";
  4. import "package:logging/logging.dart";
  5. import "package:photos/core/errors.dart";
  6. import "package:photos/core/event_bus.dart";
  7. import "package:photos/core/network/network.dart";
  8. import "package:photos/events/event.dart";
  9. import "package:photos/services/remote_assets_service.dart";
  10. abstract class MLFramework {
  11. static const kImageEncoderEnabled = true;
  12. static const kMaximumRetrials = 3;
  13. static final _logger = Logger("MLFramework");
  14. final bool shouldDownloadOverMobileData;
  15. InitializationState _state = InitializationState.notInitialized;
  16. final _initializationCompleter = Completer<void>();
  17. MLFramework(this.shouldDownloadOverMobileData) {
  18. Connectivity()
  19. .onConnectivityChanged
  20. .listen((ConnectivityResult result) async {
  21. _logger.info("Connectivity changed to $result");
  22. if (_state == InitializationState.waitingForNetwork &&
  23. await _canDownload()) {
  24. unawaited(init());
  25. }
  26. });
  27. }
  28. InitializationState get initializationState => _state;
  29. set _initState(InitializationState state) {
  30. Bus.instance.fire(MLFrameworkInitializationUpdateEvent(state));
  31. _logger.info("Init state is $state");
  32. _state = state;
  33. }
  34. /// Returns the path of the Image Model hosted remotely
  35. String getImageModelRemotePath();
  36. /// Returns the path of the Text Model hosted remotely
  37. String getTextModelRemotePath();
  38. /// Loads the Image Model stored at [path] into the framework
  39. Future<void> loadImageModel(String path);
  40. /// Loads the Text Model stored at [path] into the framework
  41. Future<void> loadTextModel(String path);
  42. /// Returns the Image Embedding for a file stored at [imagePath]
  43. Future<List<double>> getImageEmbedding(String imagePath);
  44. /// Returns the Text Embedding for [text]
  45. Future<List<double>> getTextEmbedding(String text);
  46. /// Downloads the models from remote, caches them and loads them into the
  47. /// framework. Override this method if you would like to control the
  48. /// initialization. For eg. if you wish to load the model from `/assets`
  49. /// instead of a CDN.
  50. Future<void> init() async {
  51. try {
  52. await Future.wait([_initImageModel(), _initTextModel()]);
  53. } catch (e, s) {
  54. _logger.warning(e, s);
  55. if (e is WiFiUnavailableError) {
  56. return _initializationCompleter.future;
  57. } else {
  58. rethrow;
  59. }
  60. }
  61. _initState = InitializationState.initialized;
  62. _initializationCompleter.complete();
  63. }
  64. // Releases any resources held by the framework
  65. Future<void> release() async {}
  66. /// Returns the cosine similarity between [imageEmbedding] and [textEmbedding]
  67. double computeScore(List<double> imageEmbedding, List<double> textEmbedding) {
  68. assert(
  69. imageEmbedding.length == textEmbedding.length,
  70. "The two embeddings should have the same length",
  71. );
  72. double score = 0;
  73. for (int index = 0; index < imageEmbedding.length; index++) {
  74. score += imageEmbedding[index] * textEmbedding[index];
  75. }
  76. return score;
  77. }
  78. // ---
  79. // Private methods
  80. // ---
  81. Future<void> _initImageModel() async {
  82. if (!kImageEncoderEnabled) {
  83. return;
  84. }
  85. _initState = InitializationState.initializingImageModel;
  86. final imageModel =
  87. await RemoteAssetsService.instance.getAsset(getImageModelRemotePath());
  88. await loadImageModel(imageModel.path);
  89. _initState = InitializationState.initializedImageModel;
  90. }
  91. Future<void> _initTextModel() async {
  92. _initState = InitializationState.initializingTextModel;
  93. final textModel =
  94. await RemoteAssetsService.instance.getAsset(getTextModelRemotePath());
  95. await loadTextModel(textModel.path);
  96. _initState = InitializationState.initializedTextModel;
  97. }
  98. Future<void> _downloadFile(
  99. String url,
  100. String savePath, {
  101. int trialCount = 1,
  102. }) async {
  103. if (!await _canDownload()) {
  104. _initState = InitializationState.waitingForNetwork;
  105. throw WiFiUnavailableError();
  106. }
  107. _logger.info("Downloading " + url);
  108. final existingFile = File(savePath);
  109. if (await existingFile.exists()) {
  110. await existingFile.delete();
  111. }
  112. try {
  113. await NetworkClient.instance.getDio().download(url, savePath);
  114. } catch (e, s) {
  115. _logger.severe(e, s);
  116. if (trialCount < kMaximumRetrials) {
  117. return _downloadFile(url, savePath, trialCount: trialCount + 1);
  118. } else {
  119. rethrow;
  120. }
  121. }
  122. }
  123. Future<bool> _canDownload() async {
  124. final connectivityResult = await (Connectivity().checkConnectivity());
  125. return connectivityResult != ConnectivityResult.mobile ||
  126. shouldDownloadOverMobileData;
  127. }
  128. }
  129. class MLFrameworkInitializationUpdateEvent extends Event {
  130. final InitializationState state;
  131. MLFrameworkInitializationUpdateEvent(this.state);
  132. }
  133. enum InitializationState {
  134. notInitialized,
  135. waitingForNetwork,
  136. downloadingImageModel,
  137. initializingImageModel,
  138. initializedImageModel,
  139. downloadingTextModel,
  140. initializingTextModel,
  141. initializedTextModel,
  142. initialized,
  143. }