Skip to content

armgit / ente

Public Imported from GitHub
0

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

Make ML indexing and sync mode-aware

Neeraj Guptab110cc017b22
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
index f500157fcf..714be89ea0 100644
--- 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
@@ -6,6 +6,7 @@ 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";
@@ -52,6 +53,10 @@ class FaceRecognitionService {
if (_isSyncing) {
return;
}
+ if (isOfflineMode) {
+ _logger.finest("Skipping person feedback sync in offline mode");
+ return;
+ }
_isSyncing = true;
try {
if (_shouldReconcilePeople) {
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 22107edf1a..1f184c76df 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
@@ -68,7 +68,7 @@ class MLIndexingIsolate extends SuperIsolate {
try {
final resultJsonString =
await runInIsolate(IsolateOperation.analyzeImage, {
- "enteFileID": instruction.file.uploadedFileID ?? -1,
+ "enteFileID": instruction.fileKey,
"filePath": filePath,
"runFaces": instruction.shouldRunFaces,
"runClip": instruction.shouldRunClip,
@@ -85,12 +85,12 @@ class MLIndexingIsolate extends SuperIsolate {
result = MLResult.fromJsonString(resultJsonString);
} catch (e, s) {
_logger.severe(
- "Could not analyze image with ID ${instruction.file.uploadedFileID} \n",
+ "Could not analyze image with ID ${instruction.fileKey} \n",
e,
s,
);
debugPrint(
- "This image with fileID ${instruction.file.uploadedFileID} has name ${instruction.file.displayName}.",
+ "This image with fileID ${instruction.fileKey} has name ${instruction.file.displayName}.",
);
rethrow;
}
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 44209bbb28..e27f685e63 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
@@ -8,8 +8,10 @@ import "package:logging/logging.dart";
import "package:photos/core/event_bus.dart";
import "package:photos/db/files_db.dart";
import "package:photos/db/ml/db.dart";
+import "package:photos/db/offline_files_db.dart";
import "package:photos/events/compute_control_event.dart";
import "package:photos/events/people_changed_event.dart";
+import "package:photos/models/ml/clip.dart";
import "package:photos/models/ml/face/face.dart";
import "package:photos/models/ml/ml_versions.dart";
import "package:photos/service_locator.dart";
@@ -20,6 +22,7 @@ import "package:photos/services/machine_learning/face_ml/person/person_service.d
import "package:photos/services/machine_learning/ml_indexing_isolate.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/video_preview_service.dart";
import "package:photos/utils/ml_util.dart";
import "package:photos/utils/network_util.dart";
@@ -53,7 +56,18 @@ class MLService {
_isRunningML || memoriesCacheService.isUpdatingMemories;
static const _kForceClusteringFaceCount = 8000;
- late final mlDataDB = MLDataDB.instance;
+ MLDataDB get _mlDataDB =>
+ isOfflineMode ? MLDataDB.offlineInstance : MLDataDB.instance;
+
+ MLDataDB _dbForMode(MLMode mode) {
+ return mode == MLMode.offline
+ ? MLDataDB.offlineInstance
+ : MLDataDB.instance;
+ }
+
+ bool _hasModeChanged(MLMode mode) {
+ return (isOfflineMode ? MLMode.offline : MLMode.online) != mode;
+ }
/// Only call this function once at app startup, after that you can directly call [runAllML]
Future<void> init() async {
@@ -125,6 +139,8 @@ class MLService {
Future<void> runAllML({bool force = false}) async {
try {
+ final MLMode mode = isOfflineMode ? MLMode.offline : MLMode.online;
+ final mlDataDB = _dbForMode(mode);
if (force) {
_mlControllerStatus = true;
}
@@ -132,6 +148,10 @@ class MLService {
if (!force && !computeController.requestCompute(ml: true)) return;
_isRunningML = true;
await sync();
+ if (_hasModeChanged(mode)) {
+ _logger.info("App mode changed during ML run, stopping");
+ return;
+ }
final int unclusteredFacesCount =
await mlDataDB.getUnclusteredFaceCount();
@@ -142,18 +162,30 @@ class MLService {
await clusterAllImages();
}
if (_mlControllerStatus == true) {
+ if (_hasModeChanged(mode)) {
+ _logger.info("App mode changed during ML run, stopping");
+ return;
+ }
// refresh discover section
magicCacheService.updateCache(forced: force).ignore();
// refresh memories section
memoriesCacheService.updateCache(forced: force).ignore();
}
if (canFetch()) {
- await fetchAndIndexAllImages();
+ await fetchAndIndexAllImages(mode: mode);
+ }
+ if (_hasModeChanged(mode)) {
+ _logger.info("App mode changed during ML run, stopping");
+ return;
}
if ((await mlDataDB.getUnclusteredFaceCount()) > 0) {
await clusterAllImages();
}
if (_mlControllerStatus == true) {
+ if (_hasModeChanged(mode)) {
+ _logger.info("App mode changed during ML run, stopping");
+ return;
+ }
// refresh discover section
magicCacheService.updateCache().ignore();
// refresh memories section (only runs if forced is true)
@@ -194,20 +226,26 @@ class MLService {
///
/// This function first fetches from remote and checks if the image has already been analyzed
/// with the lastest faceMlVersion and stored on remote or local database. If so, it skips the image.
- Future<void> fetchAndIndexAllImages() async {
+ Future<void> fetchAndIndexAllImages({required MLMode mode}) async {
if (!_canRunMLFunction(function: "Indexing")) return;
try {
_isIndexingOrClusteringRunning = true;
_logger.info('starting image indexing');
final Stream<List<FileMLInstruction>> instructionStream =
- fetchEmbeddingsAndInstructions(fileDownloadMlLimit);
+ fetchEmbeddingsAndInstructions(fileDownloadMlLimit, mode: mode);
int fileAnalyzedCount = 0;
final Stopwatch stopwatch = Stopwatch()..start();
stream:
await for (final chunk in instructionStream) {
+ if ((isOfflineMode ? MLMode.offline : MLMode.online) != mode) {
+ _logger.info(
+ "App mode changed during indexing, stopping current ML run",
+ );
+ break stream;
+ }
if (!localSettings.isMLLocalIndexingEnabled) {
await MLIndexingIsolate.instance.cleanupLocalIndexingModels();
continue;
@@ -221,6 +259,12 @@ class MLService {
}
final futures = <Future<bool>>[];
for (final instruction in chunk) {
+ if ((isOfflineMode ? MLMode.offline : MLMode.online) != mode) {
+ _logger.info(
+ "App mode changed during indexing, stopping current ML run",
+ );
+ break stream;
+ }
if (_shouldPauseIndexingAndClustering) {
_logger.info("indexAllImages() was paused, stopping");
break stream;
@@ -265,27 +309,32 @@ class MLService {
_clusteringIsHappening = true;
final clusterAllImagesTime = DateTime.now();
- _logger.info('Pulling remote feedback before actually clustering');
- await PersonService.instance.fetchRemoteClusterFeedback();
- final persons = await PersonService.instance.getPersons();
final faceIdNotToCluster = <String, List<String>>{};
- for (final person in persons) {
- if (person.data.rejectedFaceIDs.isNotEmpty) {
- final personClusters = person.data.assigned.map((e) => e.id).toList();
- for (final faceID in person.data.rejectedFaceIDs) {
- faceIdNotToCluster[faceID] = personClusters;
+ if (!isOfflineMode) {
+ _logger.info('Pulling remote feedback before actually clustering');
+ await PersonService.instance.fetchRemoteClusterFeedback();
+ final persons = await PersonService.instance.getPersons();
+ for (final person in persons) {
+ if (person.data.rejectedFaceIDs.isNotEmpty) {
+ final personClusters = person.data.assigned.map((e) => e.id).toList();
+ for (final faceID in person.data.rejectedFaceIDs) {
+ faceIdNotToCluster[faceID] = personClusters;
+ }
}
}
+ } else {
+ _logger.info("Skipping person metadata in offline mode");
}
try {
// Get a sense of the total number of faces in the database
- final int totalFaces = await mlDataDB.getTotalFaceCount();
- final fileIDToCreationTime =
- await FilesDB.instance.getFileIDToCreationTime();
+ final int totalFaces = await _mlDataDB.getTotalFaceCount();
+ final fileIDToCreationTime = isOfflineMode
+ ? await _getOfflineFileIdToCreationTime()
+ : await FilesDB.instance.getFileIDToCreationTime();
final startEmbeddingFetch = DateTime.now();
// read all embeddings
- final result = await mlDataDB.getFaceInfoForClustering(
+ final result = await _mlDataDB.getFaceInfoForClustering(
maxFaces: totalFaces,
);
final Set<int> missingFileIDs = {};
@@ -312,7 +361,7 @@ class MLService {
// Get the current cluster statistics
final Map<String, (Uint8List, int)> oldClusterSummaries =
- await mlDataDB.getAllClusterSummary();
+ await _mlDataDB.getAllClusterSummary();
if (clusterInBuckets) {
const int bucketSize = 10000;
@@ -371,9 +420,9 @@ class MLService {
return;
}
- await mlDataDB
+ await _mlDataDB
.updateFaceIdToClusterId(clusteringResult.newFaceIdToCluster);
- await mlDataDB
+ await _mlDataDB
.clusterSummaryUpdate(clusteringResult.newClusterSummaries);
Bus.instance.fire(PeopleChangedEvent());
for (final faceInfo in faceInfoForClustering) {
@@ -416,9 +465,9 @@ class MLService {
_logger.info(
'Updating ${clusteringResult.newFaceIdToCluster.length} FaceIDs with clusterIDs in the DB',
);
- await mlDataDB
+ await _mlDataDB
.updateFaceIdToClusterId(clusteringResult.newFaceIdToCluster);
- await mlDataDB
+ await _mlDataDB
.clusterSummaryUpdate(clusteringResult.newClusterSummaries);
Bus.instance.fire(PeopleChangedEvent());
_logger.info('Done updating FaceIDs with clusterIDs in the DB, in '
@@ -438,6 +487,7 @@ class MLService {
Future<bool> processImage(FileMLInstruction instruction) async {
bool actuallyRanML = false;
+ final mlDataDB = _dbForMode(instruction.mode);
try {
final String filePath = await getImagePathForML(instruction.file);
@@ -449,7 +499,7 @@ class MLService {
if (result == null) {
if (!_shouldPauseIndexingAndClustering) {
_logger.severe(
- "Failed to analyze image with uploadedFileID: ${instruction.file.uploadedFileID}",
+ "Failed to analyze image with fileID: ${instruction.fileKey}",
);
}
return actuallyRanML;
@@ -457,12 +507,15 @@ class MLService {
// Check anything actually ran
actuallyRanML = result.ranML;
if (!actuallyRanML) return actuallyRanML;
- // Prepare storing data on remote
- final FileDataEntity dataEntity = instruction.existingRemoteFileML ??
- FileDataEntity.empty(
- instruction.file.uploadedFileID!,
- DataType.mlData,
- );
+ final bool isOffline = instruction.isOffline;
+ // Prepare storing data on remote (online mode only)
+ final FileDataEntity? dataEntity = isOffline
+ ? null
+ : (instruction.existingRemoteFileML ??
+ FileDataEntity.empty(
+ instruction.file.uploadedFileID!,
+ DataType.mlData,
+ ));
// Faces results
final List<Face> faces = [];
if (result.facesRan) {
@@ -480,37 +533,53 @@ class MLService {
);
}
}
- dataEntity.putFace(
- RemoteFaceEmbedding(
- faces,
- faceMlVersion,
- client: client,
- height: result.decodedImageSize.height,
- width: result.decodedImageSize.width,
- ),
- );
+ if (!isOffline) {
+ dataEntity!.putFace(
+ RemoteFaceEmbedding(
+ faces,
+ faceMlVersion,
+ client: client,
+ height: result.decodedImageSize.height,
+ width: result.decodedImageSize.width,
+ ),
+ );
+ }
}
// Clip results
if (result.clipRan) {
- dataEntity.putClip(
- RemoteClipEmbedding(
- result.clip!.embedding,
- version: clipMlVersion,
- client: client,
- ),
+ if (!isOffline) {
+ dataEntity!.putClip(
+ RemoteClipEmbedding(
+ result.clip!.embedding,
+ version: clipMlVersion,
+ client: client,
+ ),
+ );
+ }
+ }
+ if (!isOffline) {
+ // Storing results on remote
+ await fileDataService.putFileData(
+ instruction.file,
+ dataEntity!,
);
}
- // Storing results on remote
- await fileDataService.putFileData(
- instruction.file,
- dataEntity,
- );
// Storing results locally
if (result.facesRan) await mlDataDB.bulkInsertFaces(faces);
if (result.clipRan) {
- await SemanticSearchService.instance.storeClipImageResult(
- result.clip!,
- );
+ if (isOffline) {
+ await mlDataDB.putClip([
+ ClipEmbedding(
+ fileID: result.fileId,
+ embedding: result.clip!.embedding,
+ version: clipMlVersion,
+ ),
+ ]);
+ } else {
+ await SemanticSearchService.instance.storeClipImageResult(
+ result.clip!,
+ );
+ }
}
_logger.info("ML result for fileID ${result.fileId} stored remote+local");
return actuallyRanML;
@@ -526,20 +595,24 @@ class MLService {
errorString.contains('FileSizeTooLargeForMobileIndexing');
if (acceptedIssue) {
_logger.severe(
- '$errorString for fileID ${instruction.file.uploadedFileID} (format $format, type $fileType, size $size), storing empty results so indexing does not get stuck',
+ '$errorString for fileID ${instruction.fileKey} (format $format, type $fileType, size $size), storing empty results so indexing does not get stuck',
e,
s,
);
await mlDataDB.bulkInsertFaces(
- [Face.empty(instruction.file.uploadedFileID!, error: true)],
- );
- await SemanticSearchService.instance.storeEmptyClipImageResult(
- instruction.file,
+ [Face.empty(instruction.fileKey, error: true)],
);
+ if (instruction.isOffline) {
+ await mlDataDB.putClip([ClipEmbedding.empty(instruction.fileKey)]);
+ } else {
+ await SemanticSearchService.instance.storeEmptyClipImageResult(
+ instruction.file,
+ );
+ }
return true;
}
_logger.severe(
- "Failed to index file for fileID ${instruction.file.uploadedFileID} (format $format, type $fileType, size $size). Not storing any results locally, which means it will be automatically retried later.",
+ "Failed to index file for fileID ${instruction.fileKey} (format $format, type $fileType, size $size). Not storing any results locally, which means it will be automatically retried later.",
e,
s,
);
@@ -583,6 +656,31 @@ class MLService {
return true;
}
+ Future<Map<int, int>> _getOfflineFileIdToCreationTime() async {
+ final files = await SearchService.instance.getAllFilesForSearch();
+ final localIdToCreation = <String, int>{};
+ for (final file in files) {
+ final localId = file.localID;
+ final creationTime = file.creationTime;
+ if (localId != null && localId.isNotEmpty && creationTime != null) {
+ localIdToCreation[localId] = creationTime;
+ }
+ }
+ if (localIdToCreation.isEmpty) return {};
+ final localIdToIntId =
+ await OfflineFilesDB.instance.getLocalIntIdsForLocalIds(
+ localIdToCreation.keys,
+ );
+ final map = <int, int>{};
+ localIdToIntId.forEach((localId, localIntId) {
+ final creationTime = localIdToCreation[localId];
+ if (creationTime != null) {
+ map[localIntId] = creationTime;
+ }
+ });
+ return map;
+ }
+
void _logStatus() {
final String status = '''
isInternalUser: ${flagService.internalUser}
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 f5c3e47cfe..3b561d3a12 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
@@ -6,6 +6,7 @@ import "package:photos/core/cache/lru_map.dart";
import "package:photos/core/event_bus.dart";
import "package:photos/db/files_db.dart";
import "package:photos/db/ml/db.dart";
+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";
@@ -17,6 +18,7 @@ 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";
import "package:synchronized/synchronized.dart";
@@ -29,13 +31,15 @@ class SemanticSearchService {
final LRUMap<String, List<double>> _queryEmbeddingCache = LRUMap(20);
static const kMinimumSimilarityThreshold = 0.175;
- late final mlDataDB = MLDataDB.instance;
+ MLDataDB get _mlDataDB =>
+ isOfflineMode ? MLDataDB.offlineInstance : MLDataDB.instance;
bool _hasInitialized = false;
bool _textModelIsLoaded = false;
final _cacheLock = Lock();
bool _imageEmbeddingsAreCached = false;
+ bool? _cachedEmbeddingsOffline;
Timer? _embeddingsCacheTimer;
final Duration _embeddingsCacheDuration = const Duration(seconds: 60);
@@ -47,7 +51,7 @@ class SemanticSearchService {
_logger.info("Initialized already");
return;
}
- final hasGivenConsent = flagService.hasGrantedMLConsent;
+ final hasGivenConsent = hasGrantedMLConsent;
if (!hasGivenConsent) return;
_logger.info("init called");
@@ -64,7 +68,7 @@ class SemanticSearchService {
}
bool isMagicSearchEnabledAndReady() {
- return flagService.hasGrantedMLConsent && _textModelIsLoaded;
+ return hasGrantedMLConsent && _textModelIsLoaded;
}
// searchScreenQuery should only be used for the user initiate query on the search screen.
@@ -73,7 +77,7 @@ class SemanticSearchService {
if (!isMagicSearchEnabledAndReady()) {
if (flagService.internalUser) {
_logger.info(
- "ML global consent: ${flagService.hasGrantedMLConsent}, loaded: $_textModelIsLoaded ",
+ "ML global consent: $hasGrantedMLConsent, loaded: $_textModelIsLoaded ",
);
}
return (query, <EnteFile>[]);
@@ -101,7 +105,7 @@ class SemanticSearchService {
}
Future<void> clearIndexes() async {
- await mlDataDB.deleteClipIndexes();
+ await _mlDataDB.deleteClipIndexes();
final preferences = await SharedPreferences.getInstance();
await preferences.remove("sync_time_embeddings_v3");
_logger.info("Indexes cleared");
@@ -110,16 +114,26 @@ class SemanticSearchService {
Future<void> _cacheClipVectors() async {
return _cacheLock.synchronized(() async {
_resetInactivityTimer();
+ if (_imageEmbeddingsAreCached) {
+ if (_cachedEmbeddingsOffline != isOfflineMode) {
+ await MLComputer.instance.clearImageEmbeddingsCache();
+ _imageEmbeddingsAreCached = false;
+ _cachedEmbeddingsOffline = null;
+ } else {
+ return;
+ }
+ }
if (_imageEmbeddingsAreCached) {
return;
}
final now = DateTime.now();
- final imageEmbeddings = await mlDataDB.getAllClipVectors();
+ final imageEmbeddings = await _mlDataDB.getAllClipVectors();
_logger.info(
"read all ${imageEmbeddings.length} embeddings from DB in ${DateTime.now().difference(now).inMilliseconds} ms",
);
await MLComputer.instance.cacheImageEmbeddings(imageEmbeddings);
_imageEmbeddingsAreCached = true;
+ _cachedEmbeddingsOffline = isOfflineMode;
return;
});
}
@@ -160,6 +174,14 @@ class SemanticSearchService {
fileIDToScoreMap[result.id] = result.score;
}
+ if (isOfflineMode) {
+ return _getOfflineMatchingFiles(
+ queryResults,
+ fileIDToScoreMap,
+ showThreshold,
+ );
+ }
+
final filesMap = await FilesDB.instance
.getFileIDToFileFromIDs(queryResults.map((e) => e.id).toList());
@@ -187,7 +209,49 @@ class SemanticSearchService {
_logger.info(results.length.toString() + " results");
if (deletedEntries.isNotEmpty) {
- unawaited(mlDataDB.deleteClipEmbeddings(deletedEntries));
+ unawaited(_mlDataDB.deleteClipEmbeddings(deletedEntries));
+ }
+
+ return results;
+ }
+
+ Future<List<EnteFile>> _getOfflineMatchingFiles(
+ List<QueryResult> queryResults,
+ Map<int, double> fileIDToScoreMap,
+ bool showThreshold,
+ ) async {
+ final localIdMap = await OfflineFilesDB.instance.getLocalIdsForIntIds(
+ queryResults.map((e) => e.id),
+ );
+ final allFiles = await SearchService.instance.getAllFilesForSearch();
+ final ignoredCollections =
+ CollectionsService.instance.getHiddenCollectionIds();
+ final localIdToFile = <String, EnteFile>{};
+ for (final file in allFiles) {
+ final localId = file.localID;
+ if (localId != null) {
+ localIdToFile[localId] = file;
+ }
+ }
+
+ final results = <EnteFile>[];
+ final deletedEntries = <int>[];
+ for (final result in queryResults) {
+ final localId = localIdMap[result.id];
+ final file = localId != null ? localIdToFile[localId] : null;
+ if (file != null && !ignoredCollections.contains(file.collectionID)) {
+ if (showThreshold) {
+ file.debugCaption =
+ "${fileIDToScoreMap[result.id]?.toStringAsFixed(3)}";
+ }
+ results.add(file);
+ } else {
+ deletedEntries.add(result.id);
+ }
+ }
+
+ if (deletedEntries.isNotEmpty) {
+ unawaited(_mlDataDB.deleteClipEmbeddings(deletedEntries));
}
return results;
@@ -249,12 +313,12 @@ class SemanticSearchService {
embedding: clipResult.embedding,
version: clipMlVersion,
);
- await mlDataDB.putClip([embedding]);
+ await _mlDataDB.putClip([embedding]);
}
Future<void> storeEmptyClipImageResult(EnteFile entefile) async {
final embedding = ClipEmbedding.empty(entefile.uploadedFileID!);
- await mlDataDB.putClip([embedding]);
+ await _mlDataDB.putClip([embedding]);
}
Future<List<double>> _getTextEmbedding(String query) async {
diff --git a/mobile/apps/photos/lib/services/sync/import/local_assets.dart b/mobile/apps/photos/lib/services/sync/import/local_assets.dart
index 6242426a29..49bf262438 100644
--- a/mobile/apps/photos/lib/services/sync/import/local_assets.dart
+++ b/mobile/apps/photos/lib/services/sync/import/local_assets.dart
@@ -96,15 +96,27 @@ Future<List<Tuple2<AssetPathEntity, String>>>
return result;
}
-Future<List<LocalPathAsset>> getAllLocalAssets() async {
+Future<List<LocalPathAsset>> getAllLocalAssets({bool? needsTitle}) async {
final filterOptionGroup = FilterOptionGroup();
+ final FilterOption imageFilterOption = needsTitle == null
+ ? const FilterOption(sizeConstraint: ignoreSizeConstraint)
+ : FilterOption(
+ needTitle: needsTitle,
+ sizeConstraint: ignoreSizeConstraint,
+ );
+ final FilterOption videoFilterOption = needsTitle == null
+ ? const FilterOption(sizeConstraint: ignoreSizeConstraint)
+ : FilterOption(
+ needTitle: needsTitle,
+ sizeConstraint: ignoreSizeConstraint,
+ );
filterOptionGroup.setOption(
AssetType.image,
- const FilterOption(sizeConstraint: ignoreSizeConstraint),
+ imageFilterOption,
);
filterOptionGroup.setOption(
AssetType.video,
- const FilterOption(sizeConstraint: ignoreSizeConstraint),
+ videoFilterOption,
);
filterOptionGroup.createTimeCond = DateTimeCond.def().copyWith(ignore: true);
final assetPaths = await PhotoManager.getAssetPathList(
diff --git a/mobile/apps/photos/lib/services/sync/local_sync_service.dart b/mobile/apps/photos/lib/services/sync/local_sync_service.dart
index 02ee233a3c..d67839e720 100644
--- a/mobile/apps/photos/lib/services/sync/local_sync_service.dart
+++ b/mobile/apps/photos/lib/services/sync/local_sync_service.dart
@@ -165,12 +165,15 @@ class LocalSyncService {
Future<bool> syncAll() async {
if (!Configuration.instance.isLoggedIn()) {
- _logger.warning("syncCall called when user is not logged in");
- return false;
+ if(!isOfflineMode) {
+ _logger.warning("syncAll called when user is not logged in");
+ return false;
+ }
}
final stopwatch = EnteWatch("localSyncAll")..start();
- final localAssets = await getAllLocalAssets();
+ final localAssets =
+ await getAllLocalAssets(needsTitle: isOfflineMode ? true : null);
_logger.info(
"Loading allLocalAssets ${localAssets.length} took ${stopwatch.elapsedMilliseconds}ms ",
);
diff --git a/mobile/apps/photos/lib/services/sync/sync_service.dart b/mobile/apps/photos/lib/services/sync/sync_service.dart
index 85bf021080..c9620b2f53 100644
--- a/mobile/apps/photos/lib/services/sync/sync_service.dart
+++ b/mobile/apps/photos/lib/services/sync/sync_service.dart
@@ -198,12 +198,13 @@ class SyncService {
_logger.info("[SYNC] Starting local sync");
await _localSyncService.sync();
if (isOfflineMode) {
+ await _localSyncService.syncAll();
_logger.info("[SYNC] Offline mode, skipping remote sync");
return;
}
final bool allowRemoteSync =
- _localSyncService.hasCompletedFirstImportOrBypassed();
+ _localSyncService.hasCompletedFirstImportOrBypassed() && !isOfflineMode;
if (allowRemoteSync) {
_logger.info("[SYNC] Starting remote sync");
diff --git a/mobile/apps/photos/lib/services/text_embeddings_cache_service.dart b/mobile/apps/photos/lib/services/text_embeddings_cache_service.dart
index 1fa450f751..6702fae2a0 100644
--- a/mobile/apps/photos/lib/services/text_embeddings_cache_service.dart
+++ b/mobile/apps/photos/lib/services/text_embeddings_cache_service.dart
@@ -1,5 +1,6 @@
import 'package:logging/logging.dart';
import 'package:photos/db/ml/db.dart';
+import "package:photos/service_locator.dart" show isOfflineMode;
import 'package:photos/services/machine_learning/ml_computer.dart';
class TextEmbeddingsCacheService {
@@ -9,9 +10,11 @@ class TextEmbeddingsCacheService {
static final instance = TextEmbeddingsCacheService._privateConstructor();
Future<List<double>> getEmbedding(String query) async {
+ final mlDataDB =
+ isOfflineMode ? MLDataDB.offlineInstance : MLDataDB.instance;
// 1. Check database cache
final dbResult =
- await MLDataDB.instance.getRepeatedTextEmbeddingCache(query);
+ await mlDataDB.getRepeatedTextEmbeddingCache(query);
if (dbResult != null) {
_logger.info('Text embedding cache hit for query');
return dbResult;
@@ -22,7 +25,7 @@ class TextEmbeddingsCacheService {
final embedding = await MLComputer.instance.runClipText(query);
// 3. Store in database cache
- await MLDataDB.instance.putRepeatedTextEmbeddingCache(query, embedding);
+ await mlDataDB.putRepeatedTextEmbeddingCache(query, embedding);
return embedding;
}
diff --git a/mobile/apps/photos/lib/ui/settings/debug/ml_debug_section_widget.dart b/mobile/apps/photos/lib/ui/settings/debug/ml_debug_section_widget.dart
index 8977931f57..87e38288b6 100644
--- a/mobile/apps/photos/lib/ui/settings/debug/ml_debug_section_widget.dart
+++ b/mobile/apps/photos/lib/ui/settings/debug/ml_debug_section_widget.dart
@@ -769,7 +769,11 @@ class _MLDebugSectionWidgetState extends State<MLDebugSectionWidget> {
onTap: () async {
try {
MLService.instance.debugIndexingDisabled = false;
- unawaited(MLService.instance.fetchAndIndexAllImages());
+ unawaited(
+ MLService.instance.fetchAndIndexAllImages(
+ mode: isOfflineMode ? MLMode.offline : MLMode.online,
+ ),
+ );
} catch (e, s) {
logger.warning('indexing failed ', e, s);
await showGenericErrorDialog(context: context, error: e);
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 3c8022cae9..fbed59e1b4 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
@@ -19,6 +19,7 @@ import "package:photos/ui/components/settings/settings_grouped_card.dart";
import "package:photos/ui/components/toggle_switch_widget.dart";
import "package:photos/ui/notification/toast.dart";
import "package:photos/utils/dialog_util.dart";
+import "package:photos/utils/ml_util.dart";
class MLDebugSettingsPage extends StatefulWidget {
const MLDebugSettingsPage({super.key});
@@ -586,7 +587,11 @@ class _MLDebugSettingsPageState extends State<MLDebugSettingsPage> {
Future<void> _onTriggerRunIndexing(BuildContext context) async {
try {
MLService.instance.debugIndexingDisabled = false;
- unawaited(MLService.instance.fetchAndIndexAllImages());
+ unawaited(
+ MLService.instance.fetchAndIndexAllImages(
+ mode: isOfflineMode ? MLMode.offline : MLMode.online,
+ ),
+ );
showShortToast(context, "Indexing started");
} catch (e, s) {
logger.warning('indexing failed ', e, s);
diff --git a/mobile/apps/photos/lib/utils/ml_util.dart b/mobile/apps/photos/lib/utils/ml_util.dart
index af401283fb..55bd042a75 100644
--- a/mobile/apps/photos/lib/utils/ml_util.dart
+++ b/mobile/apps/photos/lib/utils/ml_util.dart
@@ -7,6 +7,7 @@ import "package:logging/logging.dart";
import "package:photos/db/files_db.dart";
import "package:photos/db/ml/db.dart";
import "package:photos/db/ml/filedata.dart";
+import "package:photos/db/offline_files_db.dart";
import "package:photos/models/file/extensions/file_props.dart";
import "package:photos/models/file/file.dart";
import "package:photos/models/file/file_type.dart";
@@ -29,6 +30,7 @@ import "package:photos/utils/thumbnail_util.dart";
final _logger = Logger("MlUtil");
enum FileDataForML { thumbnailData, fileData }
+enum MLMode { online, offline }
class IndexStatus {
final int indexedItems, pendingItems;
@@ -39,23 +41,31 @@ class IndexStatus {
class FileMLInstruction {
final EnteFile file;
+ final MLMode mode;
+ final int? offlineFileKey;
bool shouldRunFaces;
bool shouldRunClip;
FileDataEntity? existingRemoteFileML;
FileMLInstruction({
required this.file,
+ required this.mode,
+ this.offlineFileKey,
required this.shouldRunFaces,
required this.shouldRunClip,
});
// Returns true if the file should be indexed for either faces or clip
bool get pendingML => shouldRunFaces || shouldRunClip;
+ bool get isOffline => mode == MLMode.offline;
+ int get fileKey => isOffline ? offlineFileKey! : file.uploadedFileID!;
}
Future<IndexStatus> getIndexStatus() async {
try {
- final mlDataDB = MLDataDB.instance;
- final int indexableFiles = await getIndexableFileCount();
+ final MLMode mode = isOfflineMode ? MLMode.offline : MLMode.online;
+ final mlDataDB =
+ mode == MLMode.offline ? MLDataDB.offlineInstance : MLDataDB.instance;
+ final int indexableFiles = await _getIndexableFileCount(mode: mode);
final int facesIndexedFiles = await mlDataDB.getFaceIndexedFileCount();
final int clipIndexedFiles = await mlDataDB.getClipIndexedFileCount();
final int indexedFiles = math.min(facesIndexedFiles, clipIndexedFiles);
@@ -103,6 +113,9 @@ Future<List<FileMLInstruction>> getFilesForMlIndexing() async {
if (enteFile.skipIndex) {
continue;
}
+ if (enteFile.uploadedFileID == null || enteFile.uploadedFileID == -1) {
+ continue;
+ }
if (queuedFiledIDs.contains(enteFile.uploadedFileID)) {
continue;
}
@@ -117,6 +130,7 @@ Future<List<FileMLInstruction>> getFilesForMlIndexing() async {
}
final instruction = FileMLInstruction(
file: enteFile,
+ mode: MLMode.online,
shouldRunFaces: shouldRunFaces,
shouldRunClip: shouldRunClip,
);
@@ -130,6 +144,9 @@ Future<List<FileMLInstruction>> getFilesForMlIndexing() async {
if (enteFile.skipIndex) {
continue;
}
+ if (enteFile.uploadedFileID == null || enteFile.uploadedFileID == -1) {
+ continue;
+ }
if (queuedFiledIDs.contains(enteFile.uploadedFileID)) {
continue;
}
@@ -143,6 +160,7 @@ Future<List<FileMLInstruction>> getFilesForMlIndexing() async {
}
final instruction = FileMLInstruction(
file: enteFile,
+ mode: MLMode.online,
shouldRunFaces: shouldRunFaces,
shouldRunClip: shouldRunClip,
);
@@ -179,9 +197,82 @@ Future<List<FileMLInstruction>> getFilesForMlIndexing() async {
return [...splitResult.matched, ...splitResult.unmatched];
}
+Future<List<FileMLInstruction>> getOfflineFilesForMlIndexing() async {
+ _logger.info('getOfflineFilesForMlIndexing called');
+ final mlDataDB = MLDataDB.offlineInstance;
+ final Map<int, int> faceIndexedFileIDs = await mlDataDB.faceIndexedFileIds();
+ final Map<int, int> clipIndexedFileIDs =
+ await mlDataDB.clipIndexedFileWithVersion();
+ final Set<int> queuedFileIDs = {};
+
+ final enteFiles = await SearchService.instance.getAllFilesForSearch();
+ final candidateFiles = <EnteFile>[];
+ final localIds = <String>[];
+ final List<FileMLInstruction> instructions = [];
+
+ for (final EnteFile enteFile in enteFiles) {
+ if (enteFile.fileType == FileType.other) {
+ continue;
+ }
+ if ((enteFile.localID ?? '').isEmpty ||
+ (enteFile.uploadedFileID != null && enteFile.uploadedFileID != -1)) {
+ continue;
+ }
+ final localID = enteFile.localID!;
+ candidateFiles.add(enteFile);
+ localIds.add(localID);
+ }
+
+ final localIdToIntId =
+ await OfflineFilesDB.instance.ensureLocalIntIds(localIds);
+
+ for (final enteFile in candidateFiles) {
+ final localID = enteFile.localID!;
+ final localIntId = localIdToIntId[localID];
+ if (localIntId == null) {
+ continue;
+ }
+ if (queuedFileIDs.contains(localIntId)) {
+ continue;
+ }
+ queuedFileIDs.add(localIntId);
+ final shouldRunFaces =
+ _shouldRunIndexingWithFileId(localIntId, faceIndexedFileIDs, faceMlVersion);
+ final shouldRunClip =
+ _shouldRunIndexingWithFileId(localIntId, clipIndexedFileIDs, clipMlVersion);
+ if (!shouldRunFaces && !shouldRunClip) {
+ continue;
+ }
+ instructions.add(
+ FileMLInstruction(
+ file: enteFile,
+ mode: MLMode.offline,
+ offlineFileKey: localIntId,
+ shouldRunFaces: shouldRunFaces,
+ shouldRunClip: shouldRunClip,
+ ),
+ );
+ }
+ _logger.info(
+ "Getting list of ${instructions.length} files to index for offline ML",
+ );
+ return instructions;
+}
+
Stream<List<FileMLInstruction>> fetchEmbeddingsAndInstructions(
- int yieldSize,
-) async* {
+ int yieldSize, {
+ required MLMode mode,
+}) async* {
+ if (mode == MLMode.offline) {
+ final List<FileMLInstruction> filesToIndex =
+ await getOfflineFilesForMlIndexing();
+ final List<List<FileMLInstruction>> chunks =
+ filesToIndex.chunks(yieldSize);
+ for (final batch in chunks) {
+ yield batch;
+ }
+ return;
+ }
final mlDataDB = MLDataDB.instance;
final List<FileMLInstruction> filesToIndex = await getFilesForMlIndexing();
final List<List<FileMLInstruction>> chunks =
@@ -323,6 +414,21 @@ Future<int> getIndexableFileCount() async {
return FilesDB.instance.remoteFileCount();
}
+Future<int> _getIndexableFileCount({required MLMode mode}) async {
+ if (mode == MLMode.offline) {
+ final files = await SearchService.instance.getAllFilesForSearch();
+ return files
+ .where(
+ (file) =>
+ (file.localID ?? '').isNotEmpty &&
+ (file.uploadedFileID == null || file.uploadedFileID == -1) &&
+ file.fileType != FileType.other,
+ )
+ .length;
+ }
+ return getIndexableFileCount();
+}
+
Future<String> getImagePathForML(EnteFile enteFile) async {
String? imagePath;
@@ -382,7 +488,16 @@ bool _shouldRunIndexing(
int newestVersion,
) {
final id = enteFile.uploadedFileID!;
- return !indexedFileIds.containsKey(id) || indexedFileIds[id]! < newestVersion;
+ return _shouldRunIndexingWithFileId(id, indexedFileIds, newestVersion);
+}
+
+bool _shouldRunIndexingWithFileId(
+ int fileId,
+ Map<int, int> indexedFileIds,
+ int newestVersion,
+) {
+ return !indexedFileIds.containsKey(fileId) ||
+ indexedFileIds[fileId]! < newestVersion;
}
void normalizeEmbedding(List<double> embedding) {