Skip to content

armgit / ente

Public Imported from GitHub
0

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

[mob] Refactor

Neeraj Guptac64af87e33a8
diff --git a/mobile/lib/db/ml/db.dart b/mobile/lib/db/ml/db.dart
index bb68833a43..0242d82269 100644
--- a/mobile/lib/db/ml/db.dart
+++ b/mobile/lib/db/ml/db.dart
@@ -928,8 +928,7 @@ class MLDataDB extends IMLDataDB<int> {
for (final map in maps) {
final clusterID = map[clusterIDColumn] as String;
final String faceID = map[faceIDColumn] as String;
- final fileID = getFileIdFromFaceId<int>
- (faceID);
+ final fileID = getFileIdFromFaceId<int>(faceID);
result[fileID] = (result[fileID] ?? {})..add(clusterID);
}
return result;
@@ -1160,7 +1159,7 @@ class MLDataDB extends IMLDataDB<int> {
@override
Future<List<EmbeddingVector>> getAllClipVectors() async {
Logger("ClipDB").info("reading all embeddings from DB");
- final db = await MLDataDB.instance.asyncDB;
+ final db = await instance.asyncDB;
final results = await db.getAll('SELECT * FROM $clipTable');
return _convertToVectors(results);
}
@@ -1168,7 +1167,7 @@ class MLDataDB extends IMLDataDB<int> {
// Get indexed FileIDs
@override
Future<Map<int, int>> clipIndexedFileWithVersion() async {
- final db = await MLDataDB.instance.asyncDB;
+ final db = await instance.asyncDB;
final maps = await db
.getAll('SELECT $fileIDColumn , $mlVersionColumn FROM $clipTable');
final Map<int, int> result = {};
@@ -1182,7 +1181,7 @@ class MLDataDB extends IMLDataDB<int> {
Future<int> getClipIndexedFileCount({
int minimumMlVersion = clipMlVersion,
}) async {
- final db = await MLDataDB.instance.asyncDB;
+ final db = await instance.asyncDB;
final String query =
'SELECT COUNT(DISTINCT $fileIDColumn) as count FROM $clipTable WHERE $mlVersionColumn >= $minimumMlVersion';
final List<Map<String, dynamic>> maps = await db.getAll(query);
@@ -1192,7 +1191,7 @@ class MLDataDB extends IMLDataDB<int> {
@override
Future<void> putClip(List<ClipEmbedding> embeddings) async {
if (embeddings.isEmpty) return;
- final db = await MLDataDB.instance.asyncDB;
+ final db = await instance.asyncDB;
if (embeddings.length == 1) {
await db.execute(
'INSERT OR REPLACE INTO $clipTable ($fileIDColumn, $embeddingColumn, $mlVersionColumn) VALUES (?, ?, ?)',
@@ -1210,7 +1209,7 @@ class MLDataDB extends IMLDataDB<int> {
@override
Future<void> deleteClipEmbeddings(List<int> fileIDs) async {
- final db = await MLDataDB.instance.asyncDB;
+ final db = await instance.asyncDB;
await db.execute(
'DELETE FROM $clipTable WHERE $fileIDColumn IN (${fileIDs.join(", ")})',
);
@@ -1219,7 +1218,7 @@ class MLDataDB extends IMLDataDB<int> {
@override
Future<void> deleteClipIndexes() async {
- final db = await MLDataDB.instance.asyncDB;
+ final db = await instance.asyncDB;
await db.execute('DELETE FROM $clipTable');
Bus.instance.fire(EmbeddingUpdatedEvent());
}
diff --git a/mobile/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart b/mobile/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart
index cbd5a9d805..8310349537 100644
--- a/mobile/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart
+++ b/mobile/lib/services/machine_learning/face_ml/feedback/cluster_feedback.dart
@@ -39,6 +39,7 @@ class ClusterFeedbackService<T> {
final Logger _logger = Logger("ClusterFeedbackService");
final _computer = Computer.shared();
ClusterFeedbackService._privateConstructor();
+ late final faceMLDB = MLDataDB.instance;
static final ClusterFeedbackService instance =
ClusterFeedbackService._privateConstructor();
@@ -78,11 +79,11 @@ class ClusterFeedbackService<T> {
// Get the files for the suggestions
final suggestionClusterIDs = foundSuggestions.map((e) => e.$1).toSet();
final Map<int, Set<String>> fileIdToClusterID =
- await MLDataDB.instance.getFileIdToClusterIDSetForCluster(
+ await faceMLDB.getFileIdToClusterIDSetForCluster(
suggestionClusterIDs,
);
final clusterIdToFaceIDs =
- await MLDataDB.instance.getClusterToFaceIDs(suggestionClusterIDs);
+ await faceMLDB.getClusterToFaceIDs(suggestionClusterIDs);
final Map<String, List<EnteFile>> clusterIDToFiles = {};
final allFiles = await SearchService.instance.getAllFilesForSearch();
for (final f in allFiles) {
@@ -141,15 +142,14 @@ class ClusterFeedbackService<T> {
try {
_logger.info('removeFilesFromPerson called');
// Get the relevant faces to be removed
- final faceIDs = await MLDataDB.instance
+ final faceIDs = await faceMLDB
.getFaceIDsForPerson(p.remoteID)
.then((iterable) => iterable.toList());
faceIDs.retainWhere((faceID) {
final fileID = getFileIdFromFaceId<int>(faceID);
return files.any((file) => file.uploadedFileID == fileID);
});
- final embeddings =
- await MLDataDB.instance.getFaceEmbeddingMapForFaces(faceIDs);
+ final embeddings = await faceMLDB.getFaceEmbeddingMapForFaces(faceIDs);
if (faceIDs.isEmpty || embeddings.isEmpty) {
_logger.severe(
@@ -175,17 +175,15 @@ class ClusterFeedbackService<T> {
final newFaceIdToClusterID = clusterResult.newFaceIdToCluster;
// Update the deleted faces
- await MLDataDB.instance.forceUpdateClusterIds(newFaceIdToClusterID);
- await MLDataDB.instance
- .clusterSummaryUpdate(clusterResult.newClusterSummaries);
+ await faceMLDB.forceUpdateClusterIds(newFaceIdToClusterID);
+ await faceMLDB.clusterSummaryUpdate(clusterResult.newClusterSummaries);
// Make sure the deleted faces don't get suggested in the future
final notClusterIdToPersonId = <String, String>{};
for (final clusterId in newFaceIdToClusterID.values.toSet()) {
notClusterIdToPersonId[clusterId] = p.remoteID;
}
- await MLDataDB.instance
- .bulkCaptureNotPersonFeedback(notClusterIdToPersonId);
+ await faceMLDB.bulkCaptureNotPersonFeedback(notClusterIdToPersonId);
// Update remote so new sync does not undo this change
await PersonService.instance
@@ -207,15 +205,14 @@ class ClusterFeedbackService<T> {
_logger.info('removeFilesFromCluster called');
try {
// Get the relevant faces to be removed
- final faceIDs = await MLDataDB.instance
+ final faceIDs = await faceMLDB
.getFaceIDsForCluster(clusterID)
.then((iterable) => iterable.toList());
faceIDs.retainWhere((faceID) {
final fileID = getFileIdFromFaceId<int>(faceID);
return files.any((file) => file.uploadedFileID == fileID);
});
- final embeddings =
- await MLDataDB.instance.getFaceEmbeddingMapForFaces(faceIDs);
+ final embeddings = await faceMLDB.getFaceEmbeddingMapForFaces(faceIDs);
if (faceIDs.isEmpty || embeddings.isEmpty) {
_logger.severe(
@@ -241,9 +238,8 @@ class ClusterFeedbackService<T> {
final newFaceIdToClusterID = clusterResult.newFaceIdToCluster;
// Update the deleted faces
- await MLDataDB.instance.forceUpdateClusterIds(newFaceIdToClusterID);
- await MLDataDB.instance
- .clusterSummaryUpdate(clusterResult.newClusterSummaries);
+ await faceMLDB.forceUpdateClusterIds(newFaceIdToClusterID);
+ await faceMLDB.clusterSummaryUpdate(clusterResult.newClusterSummaries);
Bus.instance.fire(
PeopleChangedEvent(
@@ -265,7 +261,7 @@ class ClusterFeedbackService<T> {
for (final faceID in faceIDs) {
faceIDToClusterID[faceID] = clusterID;
}
- await MLDataDB.instance.forceUpdateClusterIds(faceIDToClusterID);
+ await faceMLDB.forceUpdateClusterIds(faceIDToClusterID);
Bus.instance.fire(PeopleChangedEvent());
return;
}
@@ -274,9 +270,8 @@ class ClusterFeedbackService<T> {
PersonEntity p, {
required String personClusterID,
}) async {
- final faceMlDb = MLDataDB.instance;
- final faceIDs = await faceMlDb.getFaceIDsForCluster(personClusterID);
- final ignoredClusters = await faceMlDb.getPersonIgnoredClusters(p.remoteID);
+ final faceIDs = await faceMLDB.getFaceIDsForCluster(personClusterID);
+ final ignoredClusters = await faceMLDB.getPersonIgnoredClusters(p.remoteID);
if (faceIDs.length < 2 * kMinimumClusterSizeSearchResult) {
final fileIDs = faceIDs.map(getFileIdFromFaceId<int>).toSet();
if (fileIDs.length < kMinimumClusterSizeSearchResult) {
@@ -286,7 +281,7 @@ class ClusterFeedbackService<T> {
return false;
}
}
- final allClusterIdsToCountMap = (await faceMlDb.clusterIdToFaceCount());
+ final allClusterIdsToCountMap = (await faceMLDB.clusterIdToFaceCount());
_logger.info(
'${kDebugMode ? p.data.name : "private"} has existing clusterID $personClusterID, checking if we can automatically merge more',
);
@@ -323,7 +318,7 @@ class ClusterFeedbackService<T> {
for (final suggestion in suggestions) {
final clusterID = suggestion.$1;
- await MLDataDB.instance.assignClusterToPerson(
+ await faceMLDB.assignClusterToPerson(
personID: p.remoteID,
clusterID: clusterID,
);
@@ -340,8 +335,7 @@ class ClusterFeedbackService<T> {
}) async {
if (person.data.rejectedFaceIDs != null &&
person.data.rejectedFaceIDs!.isNotEmpty) {
- final clusterFaceIDs =
- await MLDataDB.instance.getFaceIDsForCluster(clusterID);
+ final clusterFaceIDs = await faceMLDB.getFaceIDsForCluster(clusterID);
final rejectedLengthBefore = person.data.rejectedFaceIDs!.length;
person.data.rejectedFaceIDs!
.removeWhere((faceID) => clusterFaceIDs.contains(faceID));
@@ -353,7 +347,7 @@ class ClusterFeedbackService<T> {
await PersonService.instance.updatePerson(person);
}
}
- await MLDataDB.instance.assignClusterToPerson(
+ await faceMLDB.assignClusterToPerson(
personID: person.remoteID,
clusterID: clusterID,
);
@@ -367,8 +361,7 @@ class ClusterFeedbackService<T> {
}
Future<List<(String, int)>> checkForMixedClusters() async {
- final faceMlDb = MLDataDB.instance;
- final allClusterToFaceCount = await faceMlDb.clusterIdToFaceCount();
+ final allClusterToFaceCount = await faceMLDB.clusterIdToFaceCount();
final clustersToInspect = <String>[];
for (final clusterID in allClusterToFaceCount.keys) {
if (allClusterToFaceCount[clusterID]! > 20 &&
@@ -385,9 +378,9 @@ class ClusterFeedbackService<T> {
final inspectionStart = DateTime.now();
for (final clusterID in clustersToInspect) {
final int originalClusterSize = allClusterToFaceCount[clusterID]!;
- final faceIDs = await faceMlDb.getFaceIDsForCluster(clusterID);
+ final faceIDs = await faceMLDB.getFaceIDsForCluster(clusterID);
- final embeddings = await faceMlDb.getFaceEmbeddingMapForFaces(faceIDs);
+ final embeddings = await faceMLDB.getFaceEmbeddingMapForFaces(faceIDs);
final clusterResult =
await FaceClusteringService.instance.predictWithinClusterComputer(
@@ -431,7 +424,7 @@ class ClusterFeedbackService<T> {
if (biggestRatio < 0.5 || secondBiggestRatio > 0.2) {
final faceIdsOfCluster =
- await faceMlDb.getFaceIDsForCluster(clusterID);
+ await faceMLDB.getFaceIDsForCluster(clusterID);
final uniqueFileIDs =
faceIdsOfCluster.map(getFileIdFromFaceId<int>).toSet();
susClusters.add((clusterID, uniqueFileIDs.length));
@@ -465,12 +458,10 @@ class ClusterFeedbackService<T> {
_logger.info(
'breakUpCluster called for cluster $clusterID with dbscan $useDbscan',
);
- final faceMlDb = MLDataDB.instance;
-
- final faceIDs = await faceMlDb.getFaceIDsForCluster(clusterID);
+ final faceIDs = await faceMLDB.getFaceIDsForCluster(clusterID);
final originalFaceIDsSet = faceIDs.toSet();
- final embeddings = await faceMlDb.getFaceEmbeddingMapForFaces(faceIDs);
+ final embeddings = await faceMLDB.getFaceEmbeddingMapForFaces(faceIDs);
if (embeddings.isEmpty) {
_logger.warning('No embeddings found for cluster $clusterID');
@@ -528,18 +519,15 @@ class ClusterFeedbackService<T> {
}) async {
final w = (kDebugMode ? EnteWatch('getSuggestions') : null)?..start();
// Get all the cluster data
- final faceMlDb = MLDataDB.instance;
- final allClusterIdsToCountMap = await faceMlDb.clusterIdToFaceCount();
- final ignoredClusters = await faceMlDb.getPersonIgnoredClusters(p.remoteID);
- final personClusters = await faceMlDb.getPersonClusterIDs(p.remoteID);
- final personFaceIDs =
- await MLDataDB.instance.getFaceIDsForPerson(p.remoteID);
+ final allClusterIdsToCountMap = await faceMLDB.clusterIdToFaceCount();
+ final ignoredClusters = await faceMLDB.getPersonIgnoredClusters(p.remoteID);
+ final personClusters = await faceMLDB.getPersonClusterIDs(p.remoteID);
+ final personFaceIDs = await faceMLDB.getFaceIDsForPerson(p.remoteID);
final personFileIDs = personFaceIDs.map(getFileIdFromFaceId<int>).toSet();
w?.log(
'${p.data.name} has ${personClusters.length} existing clusters, getting all database data done',
);
- final allClusterIdToFaceIDs =
- await MLDataDB.instance.getAllClusterIdToFaceIDs();
+ final allClusterIdToFaceIDs = await faceMLDB.getAllClusterIdToFaceIDs();
w?.log('getAllClusterIdToFaceIDs done');
// First only do a simple check on the big clusters, if the person does not have small clusters yet
@@ -578,7 +566,7 @@ class ClusterFeedbackService<T> {
final overlap = personFileIDs.intersection(suggestionSet);
if (overlap.isNotEmpty &&
((overlap.length / suggestionSet.length) > 0.5)) {
- await MLDataDB.instance.captureNotPersonFeedback(
+ await faceMLDB.captureNotPersonFeedback(
personID: p.remoteID,
clusterID: suggestion.$1,
);
@@ -625,7 +613,7 @@ class ClusterFeedbackService<T> {
final List<Uint8List> personEmbeddingsProto = [];
for (final clusterID in personClusters) {
final Iterable<Uint8List> embeddings =
- await MLDataDB.instance.getFaceEmbeddingsForCluster(clusterID);
+ await faceMLDB.getFaceEmbeddingsForCluster(clusterID);
personEmbeddingsProto.addAll(embeddings);
}
final List<Uint8List> sampledEmbeddingsProto =
@@ -648,7 +636,7 @@ class ClusterFeedbackService<T> {
double minMedianDistance = maxMedianDistance;
for (final otherClusterId in otherClusterIdsCandidates) {
final Iterable<Uint8List> otherEmbeddingsProto =
- await MLDataDB.instance.getFaceEmbeddingsForCluster(
+ await faceMLDB.getFaceEmbeddingsForCluster(
otherClusterId,
);
final sampledOtherEmbeddingsProto = _randomSampleWithoutReplacement(
@@ -724,13 +712,12 @@ class ClusterFeedbackService<T> {
}) async {
final w = (kDebugMode ? EnteWatch('_getUpdateClusterAvg') : null)?..start();
final startTime = DateTime.now();
- final faceMlDb = MLDataDB.instance;
_logger.info(
'start getUpdateClusterAvg for ${allClusterIdsToCountMap.length} clusters, minClusterSize $minClusterSize, maxClusterInCurrentRun $maxClusterInCurrentRun',
);
final Map<String, (Uint8List, int)> clusterToSummary =
- await faceMlDb.getAllClusterSummary(minClusterSize);
+ await faceMLDB.getAllClusterSummary(minClusterSize);
final Map<String, (Uint8List, int)> updatesForClusterSummary = {};
w?.log(
@@ -801,7 +788,7 @@ class ClusterFeedbackService<T> {
}
final Map<String, Iterable<Uint8List>> clusterEmbeddings =
- await MLDataDB.instance.getFaceEmbeddingsForClusters(clusterIdsToRead);
+ await faceMLDB.getFaceEmbeddingsForClusters(clusterIdsToRead);
w?.logAndReset(
'read $currentPendingRead embeddings for ${clusterEmbeddings.length} clusters',
@@ -823,7 +810,7 @@ class ClusterFeedbackService<T> {
// store the intermediate updates
indexedInCurrentRun++;
if (updatesForClusterSummary.length > 100) {
- await faceMlDb.clusterSummaryUpdate(updatesForClusterSummary);
+ await faceMLDB.clusterSummaryUpdate(updatesForClusterSummary);
updatesForClusterSummary.clear();
if (kDebugMode) {
_logger.info(
@@ -834,7 +821,7 @@ class ClusterFeedbackService<T> {
clusterAvg[clusterID] = avgNormalized;
}
if (updatesForClusterSummary.isNotEmpty) {
- await faceMlDb.clusterSummaryUpdate(updatesForClusterSummary);
+ await faceMLDB.clusterSummaryUpdate(updatesForClusterSummary);
}
w?.logAndReset('done computing avg ');
_logger.info(
@@ -912,12 +899,11 @@ class ClusterFeedbackService<T> {
}
}
final startTime = DateTime.now();
- final faceMlDb = MLDataDB.instance;
// Get the cluster averages for the person's clusters and the suggestions' clusters
- final personClusters = await faceMlDb.getPersonClusterIDs(person.remoteID);
+ final personClusters = await faceMLDB.getPersonClusterIDs(person.remoteID);
final Map<String, (Uint8List, int)> personClusterToSummary =
- await faceMlDb.getClusterToClusterSummary(personClusters);
+ await faceMLDB.getClusterToClusterSummary(personClusters);
final clusterSummaryCallTime = DateTime.now();
// remove personClusters that don't have any summary
@@ -961,7 +947,7 @@ class ClusterFeedbackService<T> {
}
final clusterID = suggestion.clusterIDToMerge;
final faceIDs = suggestion.faceIDsInCluster;
- final faceIdToEmbeddingMap = await faceMlDb.getFaceEmbeddingMapForFaces(
+ final faceIdToEmbeddingMap = await faceMLDB.getFaceEmbeddingMapForFaces(
faceIDs,
);
final faceIdToVectorMap = faceIdToEmbeddingMap.map(
@@ -1018,7 +1004,7 @@ class ClusterFeedbackService<T> {
// Logging the cluster summary for the cluster
if (logClusterSummary) {
- final summaryMap = await MLDataDB.instance.getClusterToClusterSummary(
+ final summaryMap = await faceMLDB.getClusterToClusterSummary(
[clusterID, biggestClusterID],
);
final summary = summaryMap[clusterID];
@@ -1064,8 +1050,8 @@ class ClusterFeedbackService<T> {
// Median distance
const sampleSize = 100;
- final Iterable<Uint8List> biggestEmbeddings = await MLDataDB.instance
- .getFaceEmbeddingsForCluster(biggestClusterID);
+ final Iterable<Uint8List> biggestEmbeddings =
+ await faceMLDB.getFaceEmbeddingsForCluster(biggestClusterID);
final List<Uint8List> biggestSampledEmbeddingsProto =
_randomSampleWithoutReplacement(
biggestEmbeddings,
@@ -1082,7 +1068,7 @@ class ClusterFeedbackService<T> {
.toList(growable: false);
final Iterable<Uint8List> currentEmbeddings =
- await MLDataDB.instance.getFaceEmbeddingsForCluster(clusterID);
+ await faceMLDB.getFaceEmbeddingsForCluster(clusterID);
final List<Uint8List> currentSampledEmbeddingsProto =
_randomSampleWithoutReplacement(
currentEmbeddings,
@@ -1128,7 +1114,7 @@ class ClusterFeedbackService<T> {
// Logging the blur values for the cluster
if (logBlurValues) {
- final List<double> blurValues = await MLDataDB.instance
+ final List<double> blurValues = await faceMLDB
.getBlurValuesForCluster(clusterID)
.then((value) => value.toList());
final blurValuesIntegers =
diff --git a/mobile/lib/services/machine_learning/face_ml/person/person_service.dart b/mobile/lib/services/machine_learning/face_ml/person/person_service.dart
index 5589843d4f..a642bd9a71 100644
--- a/mobile/lib/services/machine_learning/face_ml/person/person_service.dart
+++ b/mobile/lib/services/machine_learning/face_ml/person/person_service.dart
@@ -188,7 +188,7 @@ class PersonService {
orElse: () => ClusterInfo(id: "noSuchClusterInRemotePerson", faces: {}),
);
if (clusterInfo.id == "noSuchClusterInRemotePerson") {
- await MLDataDB.instance.removeClusterToPerson(
+ await faceMLDataDB.removeClusterToPerson(
personID: personID,
clusterID: clusterID,
);
@@ -385,7 +385,7 @@ class PersonService {
}
Future<PersonEntity> updateAvatar(PersonEntity p, EnteFile file) async {
- final Face? face = await MLDataDB.instance.getCoverFaceForPerson(
+ final Face? face = await faceMLDataDB.getCoverFaceForPerson(
recentFileID: file.uploadedFileID!,
personID: p.remoteID,
);
diff --git a/mobile/lib/services/machine_learning/ml_service.dart b/mobile/lib/services/machine_learning/ml_service.dart
index 623e46c29e..8d8c40375a 100644
--- a/mobile/lib/services/machine_learning/ml_service.dart
+++ b/mobile/lib/services/machine_learning/ml_service.dart
@@ -53,6 +53,7 @@ class MLService {
bool _shouldPauseIndexingAndClustering = false;
static const _kForceClusteringFaceCount = 8000;
+ late final faceMLDB = MLDataDB.instance;
/// Only call this function once at app startup, after that you can directly call [runAllML]
Future<void> init() async {
@@ -132,7 +133,7 @@ class MLService {
await sync();
final int unclusteredFacesCount =
- await MLDataDB.instance.getUnclusteredFaceCount();
+ await faceMLDB.getUnclusteredFaceCount();
if (unclusteredFacesCount > _kForceClusteringFaceCount) {
_logger.info(
"There are $unclusteredFacesCount unclustered faces, doing clustering first",
@@ -146,7 +147,7 @@ class MLService {
if (canFetch()) {
await fetchAndIndexAllImages();
}
- if ((await MLDataDB.instance.getUnclusteredFaceCount()) > 0) {
+ if ((await faceMLDB.getUnclusteredFaceCount()) > 0) {
await clusterAllImages();
}
if (_mlControllerStatus == true) {
@@ -274,12 +275,12 @@ class MLService {
try {
// Get a sense of the total number of faces in the database
- final int totalFaces = await MLDataDB.instance.getTotalFaceCount();
+ final int totalFaces = await faceMLDB.getTotalFaceCount();
final fileIDToCreationTime =
await FilesDB.instance.getFileIDToCreationTime();
final startEmbeddingFetch = DateTime.now();
// read all embeddings
- final result = await MLDataDB.instance.getFaceInfoForClustering(
+ final result = await faceMLDB.getFaceInfoForClustering(
maxFaces: totalFaces,
);
final Set<int> missingFileIDs = {};
@@ -306,7 +307,7 @@ class MLService {
// Get the current cluster statistics
final Map<String, (Uint8List, int)> oldClusterSummaries =
- await MLDataDB.instance.getAllClusterSummary();
+ await faceMLDB.getAllClusterSummary();
if (clusterInBuckets) {
const int bucketSize = 10000;
@@ -365,9 +366,9 @@ class MLService {
return;
}
- await MLDataDB.instance
+ await faceMLDB
.updateFaceIdToClusterId(clusteringResult.newFaceIdToCluster);
- await MLDataDB.instance
+ await faceMLDB
.clusterSummaryUpdate(clusteringResult.newClusterSummaries);
Bus.instance.fire(PeopleChangedEvent());
for (final faceInfo in faceInfoForClustering) {
@@ -410,9 +411,9 @@ class MLService {
_logger.info(
'Updating ${clusteringResult.newFaceIdToCluster.length} FaceIDs with clusterIDs in the DB',
);
- await MLDataDB.instance
+ await faceMLDB
.updateFaceIdToClusterId(clusteringResult.newFaceIdToCluster);
- await MLDataDB.instance
+ await faceMLDB
.clusterSummaryUpdate(clusteringResult.newClusterSummaries);
Bus.instance.fire(PeopleChangedEvent());
_logger.info('Done updating FaceIDs with clusterIDs in the DB, in '
@@ -501,9 +502,9 @@ class MLService {
);
_logger.info("ML results for fileID ${result.fileId} stored on remote");
// Storing results locally
- if (result.facesRan) await MLDataDB.instance.bulkInsertFaces(faces);
+ if (result.facesRan) await faceMLDB.bulkInsertFaces(faces);
if (result.clipRan) {
- await SemanticSearchService.storeClipImageResult(
+ await SemanticSearchService.instance.storeClipImageResult(
result.clip!,
);
}
@@ -524,10 +525,10 @@ class MLService {
e,
s,
);
- await MLDataDB.instance.bulkInsertFaces(
+ await faceMLDB.bulkInsertFaces(
[Face.empty(instruction.file.uploadedFileID!, error: true)],
);
- await SemanticSearchService.storeEmptyClipImageResult(
+ await SemanticSearchService.instance.storeEmptyClipImageResult(
instruction.file,
);
return true;
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 a920d3bd4c..afeb23d4d0 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
@@ -34,6 +34,7 @@ class SemanticSearchService {
static final Computer _computer = Computer.shared();
final LRUMap<String, List<double>> _queryEmbeddingCache = LRUMap(20);
static const kMinimumSimilarityThreshold = 0.175;
+ late final faceMLDB = MLDataDB.instance;
bool _hasInitialized = false;
bool _textModelIsLoaded = false;
@@ -105,7 +106,7 @@ class SemanticSearchService {
}
Future<void> clearIndexes() async {
- await MLDataDB.instance.deleteClipIndexes();
+ await faceMLDB.deleteClipIndexes();
final preferences = await SharedPreferences.getInstance();
await preferences.remove("sync_time_embeddings_v3");
_logger.info("Indexes cleared");
@@ -115,7 +116,7 @@ class SemanticSearchService {
if (_cachedImageEmbeddingVectors != null) {
return _cachedImageEmbeddingVectors!;
}
- _cachedImageEmbeddingVectors ??= MLDataDB.instance.getAllClipVectors();
+ _cachedImageEmbeddingVectors ??= faceMLDB.getAllClipVectors();
_logger.info("read all embeddings from DB");
return _cachedImageEmbeddingVectors!;
@@ -180,7 +181,7 @@ class SemanticSearchService {
_logger.info(results.length.toString() + " results");
if (deletedEntries.isNotEmpty) {
- unawaited(MLDataDB.instance.deleteClipEmbeddings(deletedEntries));
+ unawaited(faceMLDB.deleteClipEmbeddings(deletedEntries));
}
return results;
@@ -214,18 +215,18 @@ class SemanticSearchService {
_logger.info("Clip text model loaded");
}
- static Future<void> storeClipImageResult(ClipResult clipResult) async {
+ Future<void> storeClipImageResult(ClipResult clipResult) async {
final embedding = ClipEmbedding(
fileID: clipResult.fileID,
embedding: clipResult.embedding,
version: clipMlVersion,
);
- await MLDataDB.instance.putClip([embedding]);
+ await faceMLDB.putClip([embedding]);
}
- static Future<void> storeEmptyClipImageResult(EnteFile entefile) async {
+ Future<void> storeEmptyClipImageResult(EnteFile entefile) async {
final embedding = ClipEmbedding.empty(entefile.uploadedFileID!);
- await MLDataDB.instance.putClip([embedding]);
+ await faceMLDB.putClip([embedding]);
}
Future<List<double>> _getTextEmbedding(String query) async {
diff --git a/mobile/lib/ui/settings/debug/ml_debug_section_widget.dart b/mobile/lib/ui/settings/debug/ml_debug_section_widget.dart
index 6651a30920..16f2510b47 100644
--- a/mobile/lib/ui/settings/debug/ml_debug_section_widget.dart
+++ b/mobile/lib/ui/settings/debug/ml_debug_section_widget.dart
@@ -33,6 +33,7 @@ class _MLDebugSectionWidgetState extends State<MLDebugSectionWidget> {
Timer? _timer;
bool isExpanded = false;
final Logger logger = Logger("MLDebugSectionWidget");
+ late final faceMLDB = MLDataDB.instance;
@override
void initState() {
super.initState();
@@ -239,7 +240,7 @@ class _MLDebugSectionWidgetState extends State<MLDebugSectionWidget> {
sectionOptionSpacing,
MenuItemWidget(
captionedTextWidget: FutureBuilder<double>(
- future: MLDataDB.instance.getClusteredToIndexableFilesRatio(),
+ future: faceMLDB.getClusteredToIndexableFilesRatio(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return CaptionedTextWidget(
@@ -310,7 +311,7 @@ class _MLDebugSectionWidgetState extends State<MLDebugSectionWidget> {
trailingIcon: Icons.chevron_right_outlined,
trailingIconIsMuted: true,
onTap: () async {
- final emptyFaces = await MLDataDB.instance.getErroredFaceCount();
+ final emptyFaces = await faceMLDB.getErroredFaceCount();
showShortToast(context, '$emptyFaces empty faces');
},
),
@@ -332,7 +333,7 @@ class _MLDebugSectionWidgetState extends State<MLDebugSectionWidget> {
firstButtonLabel: "Yes, confirm",
firstButtonOnTap: () async {
try {
- await MLDataDB.instance.dropFacesFeedbackTables();
+ await faceMLDB.dropFacesFeedbackTables();
Bus.instance.fire(PeopleChangedEvent());
showShortToast(context, "Done");
} catch (e, s) {
@@ -365,7 +366,7 @@ class _MLDebugSectionWidgetState extends State<MLDebugSectionWidget> {
for (final PersonEntity p in persons) {
await PersonService.instance.deletePerson(p.remoteID);
}
- await MLDataDB.instance.dropClustersAndPersonTable();
+ await faceMLDB.dropClustersAndPersonTable();
Bus.instance.fire(PeopleChangedEvent());
showShortToast(context, "Done");
} catch (e, s) {
@@ -393,8 +394,7 @@ class _MLDebugSectionWidgetState extends State<MLDebugSectionWidget> {
firstButtonLabel: "Yes, confirm",
firstButtonOnTap: () async {
try {
- await MLDataDB.instance
- .dropClustersAndPersonTable(faces: true);
+ await faceMLDB.dropClustersAndPersonTable(faces: true);
Bus.instance.fire(PeopleChangedEvent());
showShortToast(context, "Done");
} catch (e, s) {
diff --git a/mobile/lib/ui/settings/ml/ml_user_dev_screen.dart b/mobile/lib/ui/settings/ml/ml_user_dev_screen.dart
index 4876da400a..730f7d8bf3 100644
--- a/mobile/lib/ui/settings/ml/ml_user_dev_screen.dart
+++ b/mobile/lib/ui/settings/ml/ml_user_dev_screen.dart
@@ -1,6 +1,7 @@
import "package:flutter/material.dart";
import "package:logging/logging.dart";
import "package:photos/core/event_bus.dart";
+import "package:photos/db/ml/base.dart";
import "package:photos/db/ml/db.dart";
import "package:photos/events/people_changed_event.dart";
import "package:photos/service_locator.dart";
@@ -26,6 +27,7 @@ class MLUserDeveloperOptions extends StatefulWidget {
}
class _MLUserDeveloperOptionsState extends State<MLUserDeveloperOptions> {
+ late final IMLDataDB<int> faceMLDB = MLDataDB.instance;
@override
Widget build(BuildContext context) {
final colorScheme = getEnteColorScheme(context);
@@ -78,7 +80,9 @@ class _MLUserDeveloperOptionsState extends State<MLUserDeveloperOptions> {
onChanged: () async {
try {
await localSettings.toggleRemoteFetch();
- _logger.info('Remote fetch is turned ${localSettings.remoteFetchEnabled ? 'on' : 'off'}');
+ _logger.info(
+ 'Remote fetch is turned ${localSettings.remoteFetchEnabled ? 'on' : 'off'}',
+ );
if (mounted) {
setState(() {});
}
@@ -118,9 +122,9 @@ class _MLUserDeveloperOptionsState extends State<MLUserDeveloperOptions> {
Future<void> deleteEmptyIndices(BuildContext context) async {
try {
- final Set<int> emptyFileIDs = await MLDataDB.instance.getErroredFileIDs();
- await MLDataDB.instance.deleteFaceIndexForFiles(emptyFileIDs.toList());
- await MLDataDB.instance.deleteClipEmbeddings(emptyFileIDs.toList());
+ final Set<int> emptyFileIDs = await faceMLDB.getErroredFileIDs();
+ await faceMLDB.deleteFaceIndexForFiles(emptyFileIDs.toList());
+ await faceMLDB.deleteClipEmbeddings(emptyFileIDs.toList());
showShortToast(context, "Deleted ${emptyFileIDs.length} entries");
} catch (e) {
// ignore: unawaited_futures
@@ -133,7 +137,7 @@ class _MLUserDeveloperOptionsState extends State<MLUserDeveloperOptions> {
Future<void> deleteAllLocalML(BuildContext context) async {
try {
- await MLDataDB.instance.dropClustersAndPersonTable(faces: true);
+ await faceMLDB.dropClustersAndPersonTable(faces: true);
await SemanticSearchService.instance.clearIndexes();
Bus.instance.fire(PeopleChangedEvent());
showShortToast(context, "All local ML cleared");
diff --git a/mobile/lib/ui/viewer/file_details/face_widget.dart b/mobile/lib/ui/viewer/file_details/face_widget.dart
index 06784105e8..a72b5f8278 100644
--- a/mobile/lib/ui/viewer/file_details/face_widget.dart
+++ b/mobile/lib/ui/viewer/file_details/face_widget.dart
@@ -57,6 +57,7 @@ class _FaceWidgetState extends State<FaceWidget> {
}
Widget _buildFaceImageGenerated(bool givenFaces) {
+ late final mlDataDB = MLDataDB.instance;
return FutureBuilder<Map<String, Uint8List>?>(
future: givenFaces
? widget.faceCrops
@@ -76,11 +77,11 @@ class _FaceWidgetState extends State<FaceWidget> {
);
if (widget.person == null && widget.clusterID == null) {
// Double check that it doesn't belong to an existing clusterID.
- final existingClusterID = await MLDataDB.instance
- .getClusterIDForFaceID(widget.face.faceID);
+ final existingClusterID =
+ await mlDataDB.getClusterIDForFaceID(widget.face.faceID);
if (existingClusterID != null) {
final fileIdsToClusterIds =
- await MLDataDB.instance.getFileIdToClusterIds();
+ await mlDataDB.getFileIdToClusterIds();
final files =
await SearchService.instance.getAllFilesForSearch();
final clusterFiles = files
@@ -105,7 +106,7 @@ class _FaceWidgetState extends State<FaceWidget> {
// The face score is too low for automatic clustering,
// assigning a manual new clusterID so that the user can cluster it manually
final String clusterID = newClusterID();
- await MLDataDB.instance.updateFaceIdToClusterId(
+ await mlDataDB.updateFaceIdToClusterId(
{widget.face.faceID: clusterID},
);
await Navigator.of(context).push(
diff --git a/mobile/lib/ui/viewer/file_details/faces_item_widget.dart b/mobile/lib/ui/viewer/file_details/faces_item_widget.dart
index a7c2a78018..8db2589aa2 100644
--- a/mobile/lib/ui/viewer/file_details/faces_item_widget.dart
+++ b/mobile/lib/ui/viewer/file_details/faces_item_widget.dart
@@ -46,6 +46,7 @@ class _FacesItemWidgetState extends State<FacesItemWidget> {
EnteFile file,
bool editMode,
) async {
+ late final mlDataDB = MLDataDB.instance;
try {
if (file.uploadedFileID == null) {
return [
@@ -57,7 +58,7 @@ class _FacesItemWidgetState extends State<FacesItemWidget> {
}
final List<Face>? faces =
- await MLDataDB.instance.getFacesForGivenFileID(file.uploadedFileID!);
+ await mlDataDB.getFacesForGivenFileID(file.uploadedFileID!);
if (faces == null) {
return [
ChipButtonWidget(
@@ -83,12 +84,11 @@ class _FacesItemWidgetState extends State<FacesItemWidget> {
];
}
- final faceIdsToClusterIds = await MLDataDB.instance
+ final faceIdsToClusterIds = await mlDataDB
.getFaceIdsToClusterIds(faces.map((face) => face.faceID));
final Map<String, PersonEntity> persons =
await PersonService.instance.getPersonsMap();
- final clusterIDToPerson =
- await MLDataDB.instance.getClusterIDToPersonID();
+ final clusterIDToPerson = await mlDataDB.getClusterIDToPersonID();
// Sort faces by name and score
final faceIdToPersonID = <String, String>{};
diff --git a/mobile/lib/utils/hierarchical_search_util.dart b/mobile/lib/utils/hierarchical_search_util.dart
index f66f88653a..afc3df2711 100644
--- a/mobile/lib/utils/hierarchical_search_util.dart
+++ b/mobile/lib/utils/hierarchical_search_util.dart
@@ -31,6 +31,7 @@ Future<List<EnteFile>> getFilteredFiles(
List<HierarchicalSearchFilter> filters,
) async {
final logger = Logger("HierarchicalSearchUtil");
+ final faceMLDB = MLDataDB.instance;
late final List<EnteFile> filteredFiles;
final files = await SearchService.instance.getAllFilesForHierarchicalSearch();
final resultsNeverComputedFilters = <HierarchicalSearchFilter>[];
@@ -42,12 +43,12 @@ Future<List<EnteFile>> getFilteredFiles(
if (filter is FaceFilter && filter.matchedUploadedIDs.isEmpty) {
try {
if (filter.personId != null) {
- final fileIDs = await MLDataDB.instance.getFileIDsOfPersonID(
+ final fileIDs = await faceMLDB.getFileIDsOfPersonID(
filter.personId!,
);
filter.matchedUploadedIDs.addAll(fileIDs);
} else if (filter.clusterId != null) {
- final fileIDs = await MLDataDB.instance.getFileIDsOfClusterID(
+ final fileIDs = await faceMLDB.getFileIDsOfClusterID(
filter.clusterId!,
);
filter.matchedUploadedIDs.addAll(fileIDs);
@@ -80,19 +81,19 @@ Future<List<EnteFile>> getFilteredFiles(
}
}
- await MLDataDB.instance
+ await faceMLDB
.getPersonsClusterIDs(selectedPersonIDs)
.then((clusterIDs) {
selectedClusterIDs.addAll(clusterIDs);
});
final fileIDsToAvoid =
- await MLDataDB.instance.getAllFilesAssociatedWithAllClusters(
+ await faceMLDB.getAllFilesAssociatedWithAllClusters(
exceptClusters: selectedClusterIDs,
);
final filesOfFaceIDsNotInAnyCluster =
- await MLDataDB.instance.getAllFileIDsOfFaceIDsNotInAnyCluster();
+ await faceMLDB.getAllFileIDsOfFaceIDsNotInAnyCluster();
fileIDsToAvoid.addAll(filesOfFaceIDsNotInAnyCluster);
@@ -349,13 +350,13 @@ Future<List<FaceFilter>> curateFaceFilters(
List<EnteFile> files,
) async {
try {
+ final mlDataDB = MLDataDB.instance;
final faceFilters = <FaceFilter>[];
final Map<int, Set<String>> fileIdToClusterID =
- await MLDataDB.instance.getFileIdToClusterIds();
+ await mlDataDB.getFileIdToClusterIds();
final Map<String, PersonEntity> personIdToPerson =
await PersonService.instance.getPersonsMap();
- final clusterIDToPersonID =
- await MLDataDB.instance.getClusterIDToPersonID();
+ final clusterIDToPersonID = await mlDataDB.getClusterIDToPersonID();
final Map<String, List<EnteFile>> clusterIdToFiles = {};
final Map<String, List<EnteFile>> personIdToFiles = {};
diff --git a/mobile/lib/utils/ml_util.dart b/mobile/lib/utils/ml_util.dart
index c0fea1afe7..ccfe5ec4bc 100644
--- a/mobile/lib/utils/ml_util.dart
+++ b/mobile/lib/utils/ml_util.dart
@@ -55,11 +55,10 @@ class FileMLInstruction {
Future<IndexStatus> getIndexStatus() async {
try {
+ final faceMLDB = MLDataDB.instance;
final int indexableFiles = (await getIndexableFileIDs()).length;
- final int facesIndexedFiles =
- await MLDataDB.instance.getFaceIndexedFileCount();
- final int clipIndexedFiles =
- await MLDataDB.instance.getClipIndexedFileCount();
+ final int facesIndexedFiles = await faceMLDB.getFaceIndexedFileCount();
+ final int clipIndexedFiles = await faceMLDB.getClipIndexedFileCount();
final int indexedFiles = math.min(facesIndexedFiles, clipIndexedFiles);
final showIndexedFiles = math.min(indexedFiles, indexableFiles);
@@ -83,16 +82,15 @@ int _lastFetchTimeForOthersIndexed = 0;
/// Return a list of file instructions for files that should be indexed for ML
Future<List<FileMLInstruction>> getFilesForMlIndexing() async {
_logger.info('getFilesForMlIndexing called');
+ final faceMLDB = MLDataDB.instance;
final time = DateTime.now();
// Get indexed fileIDs for each ML service
- final Map<int, int> faceIndexedFileIDs =
- await MLDataDB.instance.faceIndexedFileIds();
+ final Map<int, int> faceIndexedFileIDs = await faceMLDB.faceIndexedFileIds();
final Map<int, int> clipIndexedFileIDs =
- await MLDataDB.instance.clipIndexedFileWithVersion();
+ await faceMLDB.clipIndexedFileWithVersion();
final Set<int> queuedFiledIDs = {};
- final Set<int> filesWithFDStatus =
- await MLDataDB.instance.getFileIDsWithFDData();
+ final Set<int> filesWithFDStatus = await faceMLDB.getFileIDsWithFDData();
// Get all regular files and all hidden files
final enteFiles = await SearchService.instance.getAllFilesForSearch();
@@ -185,6 +183,7 @@ Future<List<FileMLInstruction>> getFilesForMlIndexing() async {
Stream<List<FileMLInstruction>> fetchEmbeddingsAndInstructions(
int yieldSize,
) async* {
+ final faceMLDB = MLDataDB.instance;
final List<FileMLInstruction> filesToIndex = await getFilesForMlIndexing();
final List<List<FileMLInstruction>> chunks =
filesToIndex.chunks(embeddingFetchLimit);
@@ -247,8 +246,8 @@ Stream<List<FileMLInstruction>> fetchEmbeddingsAndInstructions(
}
}
}
- await MLDataDB.instance.bulkInsertFaces(faces);
- await MLDataDB.instance.putClip(clipEmbeddings);
+ await faceMLDB.bulkInsertFaces(faces);
+ await faceMLDB.putClip(clipEmbeddings);
}
// Yield any remaining instructions
if (batchToYield.isNotEmpty) {