Skip to content

armgit / ente

Public Imported from GitHub
0

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

Add offline ML and memories databases

Neeraj Gupta882c44240a87
diff --git a/mobile/apps/photos/lib/db/memories_db.dart b/mobile/apps/photos/lib/db/memories_db.dart
index acee44fec9..8c55bafd58 100644
--- a/mobile/apps/photos/lib/db/memories_db.dart
+++ b/mobile/apps/photos/lib/db/memories_db.dart
@@ -15,10 +15,15 @@ class MemoriesDB {
static const columnFileID = 'file_id';
static const columnSeenTime = 'seen_time';
- MemoriesDB._privateConstructor();
+ final String _dbName;
+
+ MemoriesDB._privateConstructor({String dbName = _databaseName})
+ : _dbName = dbName;
static final MemoriesDB instance = MemoriesDB._privateConstructor();
+ static final MemoriesDB offlineInstance =
+ MemoriesDB._privateConstructor(dbName: "ente.memories.offline.db");
- static Future<Database>? _dbFuture;
+ Future<Database>? _dbFuture;
Future<Database> get database async {
_dbFuture ??= _initDatabase();
return _dbFuture!;
@@ -27,7 +32,7 @@ class MemoriesDB {
Future<Database> _initDatabase() async {
final Directory documentsDirectory =
await getApplicationDocumentsDirectory();
- final String path = join(documentsDirectory.path, _databaseName);
+ final String path = join(documentsDirectory.path, _dbName);
return await openDatabase(
path,
version: _databaseVersion,
@@ -47,12 +52,12 @@ class MemoriesDB {
}
Future<void> clearTable() async {
- final db = await instance.database;
+ final db = await database;
await db.delete(table);
}
Future<int> clearMemoriesSeenBeforeTime(int timestamp) async {
- final db = await instance.database;
+ final db = await database;
return db.delete(
table,
where: '$columnSeenTime < ?',
@@ -60,23 +65,31 @@ class MemoriesDB {
);
}
- Future<int> markMemoryAsSeen(Memory memory, int timestamp) async {
- final db = await instance.database;
+ Future<int> markMemoryAsSeen(
+ Memory memory,
+ int timestamp, {
+ int? seenTimeKey,
+ }) async {
+ final db = await database;
return await db.insert(
table,
- _getRowForSeenMemory(memory, timestamp),
+ _getRowForSeenMemory(memory, timestamp, seenTimeKey: seenTimeKey),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
Future<Map<int, int>> getSeenTimes() async {
- final db = await instance.database;
+ final db = await database;
return _convertToSeenTimes(await db.query(table));
}
- Map<String, dynamic> _getRowForSeenMemory(Memory memory, int timestamp) {
+ Map<String, dynamic> _getRowForSeenMemory(
+ Memory memory,
+ int timestamp, {
+ int? seenTimeKey,
+ }) {
final row = <String, dynamic>{};
- row[columnFileID] = memory.file.generatedID;
+ row[columnFileID] = seenTimeKey ?? memory.file.generatedID;
row[columnSeenTime] = timestamp;
return row;
}
diff --git a/mobile/apps/photos/lib/db/ml/clip_vector_db.dart b/mobile/apps/photos/lib/db/ml/clip_vector_db.dart
index 0ac9b4929a..57c5239889 100644
--- a/mobile/apps/photos/lib/db/ml/clip_vector_db.dart
+++ b/mobile/apps/photos/lib/db/ml/clip_vector_db.dart
@@ -13,20 +13,27 @@ import "package:shared_preferences/shared_preferences.dart";
class ClipVectorDB {
static final Logger _logger = Logger("ClipVectorDB");
- static const _databaseName = "ente.ml.vectordb.clip.usearch";
- static const _kMigrationKey = "clip_vectordb_migration";
+ final String _databaseName;
+ final String _migrationKey;
static final BigInt _embeddingDimension = BigInt.from(512);
static Logger get logger => _logger;
// Singleton pattern
- ClipVectorDB._privateConstructor();
- static final instance = ClipVectorDB._privateConstructor();
+ ClipVectorDB._privateConstructor(this._databaseName, this._migrationKey);
+ static final instance = ClipVectorDB._privateConstructor(
+ "ente.ml.vectordb.clip.usearch",
+ "clip_vectordb_migration",
+ );
+ static final offlineInstance = ClipVectorDB._privateConstructor(
+ "ente.ml.offline.vectordb.clip.usearch",
+ "clip_vectordb_migration_offline",
+ );
factory ClipVectorDB() => instance;
// only have a single app-wide reference to the database
- static Future<VectorDb>? _vectorDbFuture;
+ Future<VectorDb>? _vectorDbFuture;
Future<VectorDb> get _vectorDB async {
_vectorDbFuture ??= _initVectorDB();
@@ -69,7 +76,7 @@ class ClipVectorDB {
if (_migrationDone != null) return _migrationDone!;
_logger.info("Checking if ClipVectorDB migration has run");
final prefs = await SharedPreferences.getInstance();
- final migrationDone = prefs.getBool(_kMigrationKey) ?? false;
+ final migrationDone = prefs.getBool(_migrationKey) ?? false;
if (migrationDone) {
_logger.info("ClipVectorDB migration already done");
_migrationDone = true;
@@ -84,7 +91,7 @@ class ClipVectorDB {
Future<void> setMigrationDone() async {
_logger.info("Setting ClipVectorDB migration done");
final prefs = await SharedPreferences.getInstance();
- await prefs.setBool(_kMigrationKey, true);
+ await prefs.setBool(_migrationKey, true);
_migrationDone = true;
}
@@ -308,7 +315,7 @@ class ClipVectorDB {
_vectorDbFuture = null;
if (undoMigration) {
final prefs = await SharedPreferences.getInstance();
- await prefs.setBool(_kMigrationKey, false);
+ await prefs.setBool(_migrationKey, false);
_migrationDone = false;
_logger.info("Undid migration flag");
}
diff --git a/mobile/apps/photos/lib/db/ml/db.dart b/mobile/apps/photos/lib/db/ml/db.dart
index 684f3b7caa..e18dde8291 100644
--- a/mobile/apps/photos/lib/db/ml/db.dart
+++ b/mobile/apps/photos/lib/db/ml/db.dart
@@ -42,17 +42,30 @@ import 'package:sqlite_async/sqlite_async.dart';
class MLDataDB with SqlDbBase implements IMLDataDB<int> {
static final Logger _logger = Logger("MLDataDB");
- static const _databaseName = "ente.ml.db";
-
static Logger get logger => _logger;
// static const _databaseVersion = 1;
- MLDataDB._privateConstructor();
+ final String _databaseName;
+ final ClipVectorDB _clipVectorDB;
+ final List<String> _migrationScripts;
+
+ MLDataDB._privateConstructor({
+ String databaseName = "ente.ml.db",
+ ClipVectorDB? clipVectorDB,
+ List<String>? migrationScripts,
+ }) : _databaseName = databaseName,
+ _clipVectorDB = clipVectorDB ?? ClipVectorDB.instance,
+ _migrationScripts = migrationScripts ?? _defaultMigrationScripts;
static final MLDataDB instance = MLDataDB._privateConstructor();
+ static final MLDataDB offlineInstance = MLDataDB._privateConstructor(
+ databaseName: "ente.ml.offline.db",
+ clipVectorDB: ClipVectorDB.offlineInstance,
+ migrationScripts: _offlineMigrationScripts,
+ );
- static final _migrationScripts = [
+ static const List<String> _defaultMigrationScripts = [
createFacesTable,
createFaceClustersTable,
createClusterPersonTable,
@@ -64,9 +77,12 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
createFaceCacheTable,
createTextEmbeddingsCacheTable,
];
+ static const List<String> _offlineMigrationScripts = [
+ ..._defaultMigrationScripts,
+ ];
// only have a single app-wide reference to the database
- static Future<SqliteDatabase>? _sqliteAsyncDBFuture;
+ Future<SqliteDatabase>? _sqliteAsyncDBFuture;
Future<SqliteDatabase> get asyncDB async {
_sqliteAsyncDBFuture ??= _initSqliteAsyncDatabase();
@@ -96,7 +112,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
// a large number of faces.
@override
Future<void> bulkInsertFaces(List<Face> faces) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
const batchSize = 500;
final numBatches = (faces.length / batchSize).ceil();
for (int i = 0; i < numBatches; i++) {
@@ -134,7 +150,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
Future<void> updateFaceIdToClusterId(
Map<String, String> faceIDToClusterID,
) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
const batchSize = 500;
final numBatches = (faceIDToClusterID.length / batchSize).ceil();
for (int i = 0; i < numBatches; i++) {
@@ -158,7 +174,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
Future<Map<int, int>> faceIndexedFileIds({
int minimumMlVersion = faceMlVersion,
}) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final String query = '''
SELECT $fileIDColumn, $mlVersionColumn
FROM $facesTable
@@ -176,7 +192,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
Future<int> getFaceIndexedFileCount({
int minimumMlVersion = faceMlVersion,
}) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final String query =
'SELECT COUNT(DISTINCT $fileIDColumn) as count FROM $facesTable WHERE $mlVersionColumn >= $minimumMlVersion';
final List<Map<String, dynamic>> maps = await db.getAll(query);
@@ -185,7 +201,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<Map<String, int>> clusterIdToFaceCount() async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final List<Map<String, dynamic>> maps = await db.getAll(
'SELECT $clusterIDColumn, COUNT(*) as count FROM $faceClustersTable where $clusterIDColumn IS NOT NULL GROUP BY $clusterIDColumn ',
);
@@ -198,7 +214,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<Set<String>> getPersonIgnoredClusters(String personID) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
// find out clusterIds that are assigned to other persons using the clusters table
final List<Map<String, dynamic>> otherPersonMaps = await db.getAll(
'SELECT $clusterIDColumn FROM $clusterPersonTable WHERE $personIdColumn != ? AND $personIdColumn IS NOT NULL',
@@ -217,7 +233,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<Map<String, Set<String>>> getPersonToRejectedSuggestions() async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final List<Map<String, dynamic>> rejectMaps = await db.getAll(
'SELECT $personIdColumn, $clusterIDColumn FROM $notPersonFeedback',
);
@@ -232,7 +248,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<Set<String>> getPersonClusterIDs(String personID) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final List<Map<String, dynamic>> maps = await db.getAll(
'SELECT $clusterIDColumn FROM $clusterPersonTable WHERE $personIdColumn = ?',
[personID],
@@ -242,7 +258,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<Set<String>> getPersonsClusterIDs(List<String> personID) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final inParam = personID.map((e) => "'$e'").join(',');
final List<Map<String, dynamic>> maps = await db.getAll(
'SELECT $clusterIDColumn FROM $clusterPersonTable WHERE $personIdColumn IN ($inParam)',
@@ -252,7 +268,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<void> clearTable() async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
await db.execute(deleteFacesTable);
await db.execute(deleteFaceClustersTable);
@@ -261,17 +277,18 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
await db.execute(deleteNotPersonFeedbackTable);
await db.execute(deleteClipEmbeddingsTable);
await db.execute(deleteFileDataTable);
- if (await ClipVectorDB.instance.checkIfMigrationDone()) {
- await ClipVectorDB.instance.deleteIndexFile();
+ if (await _clipVectorDB.checkIfMigrationDone()) {
+ await _clipVectorDB.deleteIndexFile();
}
}
+
@override
Future<Iterable<Uint8List>> getFaceEmbeddingsForCluster(
String clusterID, {
int? limit,
}) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final List<Map<String, dynamic>> maps = await db.getAll(
'SELECT $embeddingColumn FROM $facesTable WHERE $faceIDColumn in (SELECT $faceIDColumn from $faceClustersTable where $clusterIDColumn = ?) ${limit != null ? 'LIMIT $limit' : ''}',
[clusterID],
@@ -284,7 +301,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
Iterable<String> clusterIDs, {
int? limit,
}) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final Map<String, List<Uint8List>> result = {};
final selectQuery = '''
@@ -320,7 +337,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
String? clusterID,
}) async {
// read person from db
- final db = await instance.asyncDB;
+ final db = await asyncDB;
if (personID != null) {
final List<int> fileId = [recentFileID];
int? avatarFileId;
@@ -400,7 +417,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<List<Face>?> getFacesForGivenFileID(int fileUploadID) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
const String query = '''
SELECT * FROM $facesTable
WHERE $fileIDColumn = ?
@@ -418,7 +435,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<Map<int, List<FaceWithoutEmbedding>>>
getFileIDsToFacesWithoutEmbedding() async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final List<Map<String, dynamic>> maps = await db.getAll(
'''
SELECT $faceIDColumn, $fileIDColumn, $faceScore, $faceDetectionColumn, $faceBlur FROM $facesTable
@@ -440,7 +457,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
Future<Map<String, Iterable<String>>> getClusterToFaceIDs(
Set<String> clusterIDs,
) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final Map<String, List<String>> result = {};
final List<Map<String, dynamic>> maps = await db.getAll(
@@ -462,7 +479,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<String?> getClusterIDForFaceID(String faceID) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final List<Map<String, dynamic>> maps = await db.getAll(
'SELECT $clusterIDColumn FROM $faceClustersTable WHERE $faceIDColumn = ?',
[faceID],
@@ -475,7 +492,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<Map<String, Iterable<String>>> getAllClusterIdToFaceIDs() async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final Map<String, List<String>> result = {};
final List<Map<String, dynamic>> maps = await db.getAll(
'SELECT $clusterIDColumn, $faceIDColumn FROM $faceClustersTable',
@@ -490,7 +507,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<Iterable<String>> getFaceIDsForCluster(String clusterID) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final List<Map<String, dynamic>> maps = await db.getAll(
'SELECT $faceIDColumn FROM $faceClustersTable '
'WHERE $faceClustersTable.$clusterIDColumn = ?',
@@ -503,7 +520,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
String clusterID, {
int limit = 10,
}) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final faceIdsResult = await db.getAll(
'SELECT $facesTable.$faceIDColumn FROM $facesTable '
'JOIN $faceClustersTable ON $facesTable.$faceIDColumn = $faceClustersTable.$faceIDColumn '
@@ -519,7 +536,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<Map<String, Map<String, Set<String>>>>
getPersonToClusterIdToFaceIds() async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final List<Map<String, dynamic>> maps = await db.getAll(
'SELECT $personIdColumn, $faceClustersTable.$clusterIDColumn, $faceIDColumn FROM $clusterPersonTable '
'INNER JOIN $faceClustersTable ON $clusterPersonTable.$clusterIDColumn = $faceClustersTable.$clusterIDColumn',
@@ -539,7 +556,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<Map<String, Set<String>>> getPersonToClusterIDs() async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final List<Map<String, dynamic>> maps = await db.getAll(
'SELECT $personIdColumn, $clusterIDColumn FROM $clusterPersonTable',
);
@@ -555,7 +572,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
Future<Map<String, String>> getFaceIdToPersonIdForFaces(
Iterable<String> faceIDs,
) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final List<Map<String, dynamic>> maps = await db.getAll(
'SELECT $faceIDColumn, $personIdColumn FROM $clusterPersonTable '
'INNER JOIN $faceClustersTable ON $clusterPersonTable.$clusterIDColumn = $faceClustersTable.$clusterIDColumn '
@@ -572,7 +589,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
Future<Map<String, Set<String>>> getClusterIdToFaceIdsForPerson(
String personID,
) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final List<Map<String, dynamic>> maps = await db.getAll(
'SELECT $faceClustersTable.$clusterIDColumn, $faceIDColumn FROM $clusterPersonTable '
'INNER JOIN $faceClustersTable ON $clusterPersonTable.$clusterIDColumn = $faceClustersTable.$clusterIDColumn '
@@ -590,7 +607,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<Set<String>> getFaceIDsForPerson(String personID) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final faceIdsResult = await db.getAll(
'SELECT $faceIDColumn FROM $faceClustersTable LEFT JOIN $clusterPersonTable '
'ON $faceClustersTable.$clusterIDColumn = $clusterPersonTable.$clusterIDColumn '
@@ -604,7 +621,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
String personID, {
int limit = 10,
}) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final faceIdsResult = await db.getAll(
'SELECT $facesTable.$faceIDColumn FROM $facesTable '
'JOIN $faceClustersTable ON $facesTable.$faceIDColumn = $faceClustersTable.$faceIDColumn '
@@ -619,7 +636,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<Iterable<double>> getBlurValuesForCluster(String clusterID) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
const String query = '''
SELECT $facesTable.$faceBlur
FROM $facesTable
@@ -642,7 +659,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
Future<Map<String, String?>> getFaceIdsToClusterIds(
Iterable<String> faceIds,
) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final List<Map<String, dynamic>> maps = await db.getAll(
'SELECT $faceIDColumn, $clusterIDColumn FROM $faceClustersTable where $faceIDColumn IN (${faceIds.map((id) => "'$id'").join(",")})',
);
@@ -656,7 +673,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<Map<int, Set<String>>> getFileIdToClusterIds() async {
final Map<int, Set<String>> result = {};
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final List<Map<String, dynamic>> maps = await db.getAll(
'SELECT $clusterIDColumn, $faceIDColumn FROM $faceClustersTable',
);
@@ -674,7 +691,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
Future<void> forceUpdateClusterIds(
Map<String, String> faceIDToClusterID,
) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
const String sql = '''
INSERT INTO $faceClustersTable ($faceIDColumn, $clusterIDColumn)
@@ -690,7 +707,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
Future<void> removeFaceIdToClusterId(
Map<String, String> faceIDToClusterID,
) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
const String sql = '''
DELETE FROM $faceClustersTable
WHERE $faceIDColumn = ? AND $clusterIDColumn = ?
@@ -702,7 +719,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<void> removePerson(String personID) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
await db.writeTransaction((tx) async {
try {
@@ -737,7 +754,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
w.logAndReset(
'reading as float offset: $offset, maxFaces: $maxFaces, batchSize: $batchSize',
);
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final List<FaceDbInfoForClustering> result = <FaceDbInfoForClustering>[];
while (true) {
@@ -787,7 +804,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
Iterable<String> faceIDs,
) async {
_logger.info('reading face embeddings for ${faceIDs.length} faces');
- final db = await instance.asyncDB;
+ final db = await asyncDB;
// Define the batch size
const batchSize = 10000;
@@ -823,7 +840,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<int> getTotalFaceCount() async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final List<Map<String, dynamic>> maps = await db.getAll(
'SELECT COUNT(*) as count FROM $facesTable WHERE $faceScore > $kMinimumQualityFaceScore AND $faceBlur > $kLaplacianHardThreshold',
);
@@ -832,7 +849,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<int> getErroredFaceCount() async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final List<Map<String, dynamic>> maps = await db.getAll(
'SELECT COUNT(*) as count FROM $facesTable WHERE $faceScore < 0',
);
@@ -841,7 +858,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<Set<int>> getErroredFileIDs() async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final List<Map<String, dynamic>> maps = await db.getAll(
'SELECT DISTINCT $fileIDColumn FROM $facesTable WHERE $faceScore < 0',
);
@@ -850,7 +867,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<void> deleteFaceIndexForFiles(List<int> fileIDs) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final String sql = '''
DELETE FROM $facesTable WHERE $fileIDColumn IN (${fileIDs.join(", ")})
''';
@@ -859,7 +876,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<int> getClusteredOrFacelessFileCount() async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final List<Map<String, dynamic>> clustered = await db.getAll(
'SELECT $faceIDColumn FROM $faceClustersTable',
);
@@ -898,7 +915,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<int> getUnclusteredFaceCount() async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
const String query = '''
SELECT f.$faceIDColumn
FROM $facesTable f
@@ -918,7 +935,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
required String personID,
required String clusterID,
}) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
const String sql = '''
INSERT INTO $clusterPersonTable ($personIdColumn, $clusterIDColumn) VALUES (?, ?) ON CONFLICT($personIdColumn, $clusterIDColumn) DO NOTHING
@@ -930,7 +947,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
Future<void> bulkAssignClusterToPersonID(
Map<String, String> clusterToPersonID,
) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
const String sql = '''
INSERT INTO $clusterPersonTable ($personIdColumn, $clusterIDColumn) VALUES (?, ?) ON CONFLICT($personIdColumn, $clusterIDColumn) DO NOTHING
@@ -945,7 +962,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
required String personID,
required String clusterID,
}) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
const String sql = '''
INSERT INTO $notPersonFeedback ($personIdColumn, $clusterIDColumn) VALUES (?, ?) ON CONFLICT DO NOTHING
@@ -957,7 +974,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
Future<void> bulkCaptureNotPersonFeedback(
Map<String, String> clusterToPersonID,
) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
const String sql = '''
INSERT INTO $notPersonFeedback ($personIdColumn, $clusterIDColumn) VALUES (?, ?) ON CONFLICT DO NOTHING
@@ -973,7 +990,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
required String personID,
required String clusterID,
}) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
const String sql = '''
DELETE FROM $notPersonFeedback WHERE $personIdColumn = ? AND $clusterIDColumn = ?
@@ -986,7 +1003,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
required String personID,
required String clusterID,
}) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
const String sql = '''
DELETE FROM $clusterPersonTable WHERE $personIdColumn = ? AND $clusterIDColumn = ?
@@ -997,7 +1014,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
// for a given personID, return a map of clusterID to fileIDs using join query
@override
Future<Map<int, Set<String>>> getFileIdToClusterIDSet(String personID) {
- final db = instance.asyncDB;
+ final db = asyncDB;
return db.then((db) async {
final List<Map<String, dynamic>> maps = await db.getAll(
'SELECT $faceClustersTable.$clusterIDColumn, $faceIDColumn FROM $faceClustersTable '
@@ -1021,7 +1038,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
Future<Map<int, Set<String>>> getFileIdToClusterIDSetForCluster(
Set<String> clusterIDs,
) {
- final db = instance.asyncDB;
+ final db = asyncDB;
return db.then((db) async {
final List<Map<String, dynamic>> maps = await db.getAll(
'''
@@ -1046,7 +1063,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
Future<void> clusterSummaryUpdate(
Map<String, (Uint8List, int)> summary,
) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
const String sql = '''
INSERT INTO $clusterSummaryTable ($clusterIDColumn, $avgColumn, $countColumn) VALUES (?, ?, ?) ON CONFLICT($clusterIDColumn) DO UPDATE SET $avgColumn = excluded.$avgColumn, $countColumn = excluded.$countColumn
@@ -1070,7 +1087,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<void> deleteClusterSummary(String clusterID) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
const String sqlDelete =
'DELETE FROM $clusterSummaryTable WHERE $clusterIDColumn = ?';
await db.execute(sqlDelete, [clusterID]);
@@ -1081,7 +1098,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
Future<Map<String, (Uint8List, int)>> getAllClusterSummary([
int? minClusterSize,
]) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final Map<String, (Uint8List, int)> result = {};
final rows = await db.getAll(
'SELECT * FROM $clusterSummaryTable${minClusterSize != null ? ' WHERE $countColumn >= $minClusterSize' : ''}',
@@ -1099,7 +1116,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
Future<Map<String, (Uint8List, int)>> getClusterToClusterSummary(
Iterable<String> clusterIDs,
) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final Map<String, (Uint8List, int)> result = {};
final rows = await db.getAll(
@@ -1118,7 +1135,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<Map<String, String>> getClusterIDToPersonID() async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final List<Map<String, dynamic>> maps = await db.getAll(
'SELECT $personIdColumn, $clusterIDColumn FROM $clusterPersonTable',
);
@@ -1133,7 +1150,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<void> dropClustersAndPersonTable({bool faces = false}) async {
try {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
if (faces) {
await db.execute(deleteFacesTable);
await db.execute(createFacesTable);
@@ -1161,7 +1178,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<void> dropFacesFeedbackTables() async {
try {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
// Drop the tables
await db.execute(deleteClusterPersonTable);
@@ -1177,7 +1194,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<List<int>> getFileIDsOfPersonID(String personID) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final result = await db.getAll(
'''
SELECT DISTINCT $facesTable.$fileIDColumn
@@ -1194,7 +1211,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<List<int>> getFileIDsOfClusterID(String clusterID) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final result = await db.getAll(
'''
SELECT DISTINCT $facesTable.$fileIDColumn
@@ -1210,7 +1227,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<Set<int>> getAllFileIDsOfFaceIDsNotInAnyCluster() async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final result = await db.getAll(
'''
SELECT DISTINCT file_id
@@ -1227,7 +1244,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
List<String>? exceptClusters,
}) async {
final notInParam = exceptClusters?.map((e) => "'$e'").join(',') ?? '';
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final result = await db.getAll('''
SELECT DISTINCT $facesTable.$fileIDColumn
FROM $facesTable
@@ -1241,7 +1258,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<List<EmbeddingVector>> getAllClipVectors() async {
Logger("ClipDB").info("reading all embeddings from DB");
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final results = await db
.getAll('SELECT $fileIDColumn, $embeddingColumn FROM $clipTable');
@@ -1260,7 +1277,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
}
Future<void> checkMigrateFillClipVectorDB({bool force = false}) async {
- final migrationDone = await ClipVectorDB.instance.checkIfMigrationDone();
+ final migrationDone = await _clipVectorDB.checkIfMigrationDone();
if (migrationDone && !force) {
_logger.info("ClipVectorDB migration not needed, already done");
return;
@@ -1269,19 +1286,19 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
// Get total count first to track progress
_logger.info("Getting total count of clip embeddings");
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final countResult =
await db.getAll('SELECT COUNT($fileIDColumn) as total FROM $clipTable');
final totalCount = countResult.first['total'] as int;
if (totalCount == 0) {
_logger.info("No clip embeddings to migrate");
- await ClipVectorDB.instance.setMigrationDone();
+ await _clipVectorDB.setMigrationDone();
return;
}
_logger.info("Total count of clip embeddings: $totalCount");
_logger.info("First time referencing ClipVectorDB rust index in migration");
- final clipVectorDB = ClipVectorDB.instance;
+ final clipVectorDB = _clipVectorDB;
await clipVectorDB.deleteAllEmbeddings();
_logger.info("ClipVectorDB rust index referenced");
_logger.info("ClipVectorDB all embeddings cleared");
@@ -1336,7 +1353,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
"Got ${fileIDs.length} valid embeddings, $weirdCount weird embeddings",
);
- await ClipVectorDB.instance
+ await _clipVectorDB
.bulkInsertEmbeddings(fileIDs: fileIDs, embeddings: embeddings);
_logger.info("Inserted ${fileIDs.length} embeddings to ClipVectorDB");
processedCount += fileIDs.length;
@@ -1355,7 +1372,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
_logger.info(
"migrated all $totalCount embeddings to ClipVectorDB in ${stopwatch.elapsed.inMilliseconds} ms, with $weirdCount weird embeddings not migrated",
);
- await ClipVectorDB.instance.setMigrationDone();
+ await _clipVectorDB.setMigrationDone();
_logger.info("ClipVectorDB migration done");
} catch (e, s) {
_logger.severe(
@@ -1375,7 +1392,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
// Get indexed FileIDs
@override
Future<Map<int, int>> clipIndexedFileWithVersion() async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final maps = await db
.getAll('SELECT $fileIDColumn , $mlVersionColumn FROM $clipTable');
final Map<int, int> result = {};
@@ -1389,7 +1406,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
Future<int> getClipIndexedFileCount({
int minimumMlVersion = clipMlVersion,
}) async {
- final db = await instance.asyncDB;
+ final db = await 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);
@@ -1399,15 +1416,15 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<void> putClip(List<ClipEmbedding> embeddings) async {
if (embeddings.isEmpty) return;
- final db = await instance.asyncDB;
+ final db = await asyncDB;
if (embeddings.length == 1) {
await db.execute(
'INSERT OR REPLACE INTO $clipTable ($fileIDColumn, $embeddingColumn, $mlVersionColumn) VALUES (?, ?, ?)',
_getRowFromEmbedding(embeddings.first),
);
if (flagService.enableVectorDb &&
- await ClipVectorDB.instance.checkIfMigrationDone()) {
- await ClipVectorDB.instance.insertEmbedding(
+ await _clipVectorDB.checkIfMigrationDone()) {
+ await _clipVectorDB.insertEmbedding(
fileID: embeddings.first.fileID,
embedding: embeddings.first.embedding,
);
@@ -1419,8 +1436,8 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
inputs,
);
if (flagService.enableVectorDb &&
- await ClipVectorDB.instance.checkIfMigrationDone()) {
- await ClipVectorDB.instance.bulkInsertEmbeddings(
+ await _clipVectorDB.checkIfMigrationDone()) {
+ await _clipVectorDB.bulkInsertEmbeddings(
fileIDs: embeddings.map((e) => e.fileID).toList(),
embeddings:
embeddings.map((e) => Float32List.fromList(e.embedding)).toList(),
@@ -1482,24 +1499,24 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<void> deleteClipEmbeddings(List<int> fileIDs) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
await db.execute(
'DELETE FROM $clipTable WHERE $fileIDColumn IN (${fileIDs.join(", ")})',
);
if (flagService.enableVectorDb &&
- await ClipVectorDB.instance.checkIfMigrationDone()) {
- await ClipVectorDB.instance.deleteEmbeddings(fileIDs);
+ await _clipVectorDB.checkIfMigrationDone()) {
+ await _clipVectorDB.deleteEmbeddings(fileIDs);
}
Bus.instance.fire(EmbeddingUpdatedEvent());
}
@override
Future<void> deleteClipIndexes() async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
await db.execute('DELETE FROM $clipTable');
if (flagService.enableVectorDb &&
- await ClipVectorDB.instance.checkIfMigrationDone()) {
- await ClipVectorDB.instance.deleteAllEmbeddings();
+ await _clipVectorDB.checkIfMigrationDone()) {
+ await _clipVectorDB.deleteAllEmbeddings();
}
Bus.instance.fire(EmbeddingUpdatedEvent());
}
@@ -1518,7 +1535,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
String personOrClusterId,
String faceID,
) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
await db.execute(
'''
INSERT OR REPLACE INTO $faceCacheTable ($personOrClusterIdColumn, $faceIDColumn)
@@ -1531,7 +1548,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
Future<String?> getFaceIdUsedForPersonOrCluster(
String personOrClusterId,
) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
final List<Map<String, dynamic>> maps = await db.getAll(
'''
SELECT $faceIDColumn FROM $faceCacheTable
@@ -1548,7 +1565,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
Future<void> removeFaceIdCachedForPersonOrCluster(
String personOrClusterID,
) async {
- final db = await instance.asyncDB;
+ final db = await asyncDB;
const String sql = '''
DELETE FROM $faceCacheTable
WHERE $personOrClusterIdColumn = ?
diff --git a/mobile/apps/photos/lib/db/ml/schema.dart b/mobile/apps/photos/lib/db/ml/schema.dart
index 96e0560ef6..e9575beb75 100644
--- a/mobile/apps/photos/lib/db/ml/schema.dart
+++ b/mobile/apps/photos/lib/db/ml/schema.dart
@@ -154,3 +154,15 @@ CREATE TABLE IF NOT EXISTS $textEmbeddingsCacheTable (
''';
const deleteTextEmbeddingsCacheTable = 'DELETE FROM $textEmbeddingsCacheTable';
+
+// ## OFFLINE FILE KEY MAP TABLE
+const offlineFileKeyMapTable = 'offline_file_key_map';
+const offlineFileKeyLocalIdColumn = 'local_id';
+const offlineFileKeyIntIdColumn = 'local_int_id';
+
+const createOfflineFileKeyMapTable = '''
+CREATE TABLE IF NOT EXISTS $offlineFileKeyMapTable (
+ $offlineFileKeyIntIdColumn INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
+ $offlineFileKeyLocalIdColumn TEXT NOT NULL UNIQUE
+);
+''';
diff --git a/mobile/apps/photos/lib/db/offline_files_db.dart b/mobile/apps/photos/lib/db/offline_files_db.dart
new file mode 100644
index 0000000000..03c98f5bcd
--- /dev/null
+++ b/mobile/apps/photos/lib/db/offline_files_db.dart
@@ -0,0 +1,126 @@
+import "package:logging/logging.dart";
+import "package:path/path.dart" show join;
+import "package:path_provider/path_provider.dart";
+import "package:photos/db/common/base.dart";
+import "package:photos/db/ml/schema.dart";
+import "package:sqlite_async/sqlite_async.dart";
+
+class OfflineFilesDB with SqlDbBase {
+ static final Logger _logger = Logger("OfflineFilesDB");
+
+ static const _databaseName = "ente.offline_files.db";
+
+ OfflineFilesDB._privateConstructor();
+
+ static final OfflineFilesDB instance = OfflineFilesDB._privateConstructor();
+
+ static const List<String> _migrationScripts = [
+ createOfflineFileKeyMapTable,
+ ];
+
+ Future<SqliteDatabase>? _sqliteAsyncDBFuture;
+
+ Future<SqliteDatabase> get asyncDB async {
+ _sqliteAsyncDBFuture ??= _initSqliteAsyncDatabase();
+ return _sqliteAsyncDBFuture!;
+ }
+
+ Future<SqliteDatabase> _initSqliteAsyncDatabase() async {
+ final documentsDirectory = await getApplicationDocumentsDirectory();
+ final String databaseDirectory =
+ join(documentsDirectory.path, _databaseName);
+ _logger.info("Opening offline files DB at $databaseDirectory");
+ final asyncDBConnection =
+ SqliteDatabase(path: databaseDirectory, maxReaders: 2);
+ await migrate(asyncDBConnection, _migrationScripts);
+ return asyncDBConnection;
+ }
+
+ Future<int> getOrCreateLocalIntId(String localId) async {
+ final db = await asyncDB;
+ final existing = await db.getAll(
+ 'SELECT $offlineFileKeyIntIdColumn FROM $offlineFileKeyMapTable WHERE $offlineFileKeyLocalIdColumn = ?',
+ [localId],
+ );
+ if (existing.isNotEmpty) {
+ return existing.first[offlineFileKeyIntIdColumn] as int;
+ }
+ await db.execute(
+ 'INSERT INTO $offlineFileKeyMapTable ($offlineFileKeyLocalIdColumn) VALUES (?)',
+ [localId],
+ );
+ final inserted = await db.getAll(
+ 'SELECT $offlineFileKeyIntIdColumn FROM $offlineFileKeyMapTable WHERE $offlineFileKeyLocalIdColumn = ?',
+ [localId],
+ );
+ return inserted.first[offlineFileKeyIntIdColumn] as int;
+ }
+
+ Future<String?> getLocalIdForIntId(int localIntId) async {
+ final db = await asyncDB;
+ final result = await db.getAll(
+ 'SELECT $offlineFileKeyLocalIdColumn FROM $offlineFileKeyMapTable WHERE $offlineFileKeyIntIdColumn = ?',
+ [localIntId],
+ );
+ if (result.isEmpty) return null;
+ return result.first[offlineFileKeyLocalIdColumn] as String?;
+ }
+
+ Future<Map<int, String>> getLocalIdsForIntIds(
+ Iterable<int> localIntIds,
+ ) async {
+ final ids = localIntIds.toList();
+ if (ids.isEmpty) return {};
+ final db = await asyncDB;
+ final inParam = List.filled(ids.length, '?').join(',');
+ final result = await db.getAll(
+ 'SELECT $offlineFileKeyIntIdColumn, $offlineFileKeyLocalIdColumn FROM $offlineFileKeyMapTable WHERE $offlineFileKeyIntIdColumn IN ($inParam)',
+ ids,
+ );
+ final mapping = <int, String>{};
+ for (final row in result) {
+ mapping[row[offlineFileKeyIntIdColumn] as int] =
+ row[offlineFileKeyLocalIdColumn] as String;
+ }
+ return mapping;
+ }
+
+ Future<Map<String, int>> getLocalIntIdsForLocalIds(
+ Iterable<String> localIds,
+ ) async {
+ final ids = localIds.toList();
+ if (ids.isEmpty) return {};
+ final db = await asyncDB;
+ final inParam = List.filled(ids.length, '?').join(',');
+ final result = await db.getAll(
+ 'SELECT $offlineFileKeyLocalIdColumn, $offlineFileKeyIntIdColumn FROM $offlineFileKeyMapTable WHERE $offlineFileKeyLocalIdColumn IN ($inParam)',
+ ids,
+ );
+ final mapping = <String, int>{};
+ for (final row in result) {
+ mapping[row[offlineFileKeyLocalIdColumn] as String] =
+ row[offlineFileKeyIntIdColumn] as int;
+ }
+ return mapping;
+ }
+
+ Future<Map<String, int>> ensureLocalIntIds(
+ Iterable<String> localIds,
+ ) async {
+ final ids = localIds.toSet().toList();
+ if (ids.isEmpty) return {};
+ final existing = await getLocalIntIdsForLocalIds(ids);
+ final missing = ids.where((id) => !existing.containsKey(id)).toList();
+ if (missing.isNotEmpty) {
+ final db = await asyncDB;
+ final inputs = missing.map((id) => [id]).toList();
+ await db.executeBatch(
+ 'INSERT OR IGNORE INTO $offlineFileKeyMapTable ($offlineFileKeyLocalIdColumn) VALUES (?)',
+ inputs,
+ );
+ final inserted = await getLocalIntIdsForLocalIds(missing);
+ existing.addAll(inserted);
+ }
+ return existing;
+ }
+}