forked from AOSSIE-Org/PictoPy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfolders.py
More file actions
428 lines (354 loc) · 12.1 KB
/
folders.py
File metadata and controls
428 lines (354 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
import sqlite3
import os
import uuid
from typing import List, Tuple, Dict, Optional
from app.config.settings import DATABASE_PATH
# Type definitions
FolderId = str
FolderPath = str
FolderData = Tuple[FolderId, FolderPath, Optional[FolderId], int, bool, Optional[bool]]
FolderMap = Dict[FolderPath, Tuple[FolderId, Optional[FolderId]]]
FolderIdPath = Tuple[FolderId, str]
def db_create_folders_table() -> None:
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS folders (
folder_id TEXT PRIMARY KEY,
parent_folder_id TEXT,
folder_path TEXT UNIQUE,
last_modified_time INTEGER,
AI_Tagging BOOLEAN,
taggingCompleted BOOLEAN,
FOREIGN KEY (parent_folder_id) REFERENCES folders(folder_id) ON DELETE CASCADE
)
"""
)
conn.commit()
conn.close()
def db_insert_folders_batch(folders_data: List[FolderData]) -> None:
"""
Insert multiple folders in a single database transaction.
folders_data: list of tuples (folder_id, folder_path,
parent_folder_id,last_modified_time, AI_Tagging, taggingCompleted)
"""
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
try:
cursor.executemany(
"""INSERT OR IGNORE INTO folders (folder_id, folder_path, parent_folder_id, last_modified_time, AI_Tagging, taggingCompleted) VALUES (?, ?, ?, ?, ?, ?)""",
folders_data,
)
conn.commit()
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
def db_insert_folder(
folder_path: FolderPath,
parent_folder_id: Optional[FolderId] = None,
AI_Tagging: bool = False,
taggingCompleted: Optional[bool] = None,
folder_id: Optional[FolderId] = None,
) -> FolderId:
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
abs_folder_path = os.path.abspath(folder_path)
if not os.path.isdir(abs_folder_path):
raise ValueError(f"Error: '{folder_path}' is not a valid directory.")
cursor.execute(
"SELECT folder_id FROM folders WHERE folder_path = ?",
(abs_folder_path,),
)
existing_folder = cursor.fetchone()
if existing_folder:
result = existing_folder[0]
conn.close()
return result
# Time is in Unix format
last_modified_time = int(os.path.getmtime(abs_folder_path))
if folder_id is None:
folder_id = str(uuid.uuid4())
cursor.execute(
"INSERT INTO folders (folder_id, folder_path, parent_folder_id, last_modified_time, AI_Tagging, taggingCompleted) VALUES (?, ?, ?, ?, ?, ?)",
(
folder_id,
abs_folder_path,
parent_folder_id,
last_modified_time,
AI_Tagging,
taggingCompleted,
),
)
conn.commit()
conn.close()
return folder_id
def db_get_folder_id_from_path(folder_path: FolderPath) -> Optional[FolderId]:
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
abs_folder_path = os.path.abspath(folder_path)
cursor.execute(
"SELECT folder_id FROM folders WHERE folder_path = ?",
(abs_folder_path,),
)
result = cursor.fetchone()
conn.close()
return result[0] if result else None
def db_get_folder_path_from_id(folder_id: FolderId) -> Optional[FolderPath]:
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
cursor.execute(
"SELECT folder_path FROM folders WHERE folder_id = ?",
(folder_id,),
)
result = cursor.fetchone()
conn.close()
return result[0] if result else None
def db_get_all_folders() -> List[FolderPath]:
with sqlite3.connect(DATABASE_PATH) as conn:
rows = conn.execute("SELECT folder_path FROM folders").fetchall()
return [row[0] for row in rows] if rows else []
def db_get_all_folder_ids() -> List[FolderId]:
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
cursor.execute("SELECT folder_id from folders")
rows = cursor.fetchall()
return [row[0] for row in rows] if rows else []
def db_delete_folders_batch(folder_ids: List[FolderId]) -> int:
"""
Delete multiple folders in a single database transaction.
folder_ids: list of folder IDs to delete
Returns the number of folders deleted
"""
if not folder_ids:
return 0
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
try:
# Enable foreign keys for cascading deletes
cursor.execute("PRAGMA foreign_keys = ON;")
conn.commit()
# Create placeholders for the IN clause
placeholders = ",".join("?" * len(folder_ids))
cursor.execute(
f"DELETE FROM folders WHERE folder_id IN ({placeholders})",
folder_ids,
)
deleted_count = cursor.rowcount
conn.commit()
return deleted_count
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
def db_delete_folder(folder_path: FolderPath) -> None:
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
abs_folder_path = os.path.abspath(folder_path)
cursor.execute(
"PRAGMA foreign_keys = ON;"
) # Important for deleting rows in image_id_mapping and images table because they reference this folder_id
conn.commit()
cursor.execute(
"SELECT folder_id FROM folders WHERE folder_path = ?",
(abs_folder_path,),
)
existing_folder = cursor.fetchone()
if not existing_folder:
conn.close()
raise ValueError(
f"Error: Folder '{folder_path}' does not exist in the database."
)
cursor.execute(
"DELETE FROM folders WHERE folder_path = ?",
(abs_folder_path,),
)
conn.commit()
conn.close()
def db_update_parent_ids_for_subtree(
root_folder_path: FolderPath, folder_map: FolderMap
) -> None:
"""
Update parent_folder_id for all folders in the subtree rooted at root_folder_path.
Only updates folders whose parent_folder_id is NULL.
folder_map: dict mapping folder_path to tuple of (folder_id, parent_id)
"""
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
try:
for folder_path, (folder_id, parent_id) in folder_map.items():
if parent_id:
cursor.execute(
"""
UPDATE folders
SET parent_folder_id = ?
WHERE folder_path = ? AND parent_folder_id IS NULL
""",
(parent_id, folder_path),
)
conn.commit()
finally:
conn.close()
def db_folder_exists(folder_path: FolderPath) -> bool:
"""
Check if a folder exists in the database.
Returns True if the folder exists, False otherwise.
"""
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
try:
abs_path = os.path.abspath(folder_path)
cursor.execute(
"SELECT folder_id FROM folders WHERE folder_path = ?", (abs_path,)
)
result = cursor.fetchone()
return bool(result)
finally:
conn.close()
def db_find_parent_folder_id(folder_path: FolderPath) -> Optional[FolderId]:
"""
Find the folder_id of the parent folder by checking if the parent path exists in the DB.
Returns the parent folder_id if found, None otherwise.
"""
parent_path = os.path.dirname(folder_path)
if not parent_path or parent_path == folder_path: # Root directory
return None
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
try:
cursor.execute(
"SELECT folder_id FROM folders WHERE folder_path = ?", (parent_path,)
)
result = cursor.fetchone()
return result[0] if result else None
finally:
conn.close()
def db_update_ai_tagging_batch(
folder_ids: List[FolderId], ai_tagging_enabled: bool
) -> int:
"""
Update AI_Tagging status for multiple folders in a single transaction.
folder_ids: list of folder IDs to update
ai_tagging_enabled: boolean value to set for AI_Tagging
Returns the number of folders updated
"""
if not folder_ids:
return 0
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
try:
# Create placeholders for the IN clause
placeholders = ",".join("?" * len(folder_ids))
cursor.execute(
f"UPDATE folders SET AI_Tagging = ? WHERE folder_id IN ({placeholders})",
[ai_tagging_enabled] + folder_ids,
)
updated_count = cursor.rowcount
conn.commit()
return updated_count
except Exception as e:
conn.rollback()
raise e
finally:
conn.close()
def db_enable_ai_tagging_batch(folder_ids: List[FolderId]) -> int:
"""
Enable AI tagging for multiple folders.
folder_ids: list of folder IDs to enable AI tagging for
Returns the number of folders updated
"""
return db_update_ai_tagging_batch(folder_ids, True)
def db_disable_ai_tagging_batch(folder_ids: List[FolderId]) -> int:
"""
Disable AI tagging for multiple folders.
folder_ids: list of folder IDs to disable AI tagging for
Returns the number of folders updated
"""
return db_update_ai_tagging_batch(folder_ids, False)
def db_get_folder_ids_by_path_prefix(root_path: str) -> List[FolderIdPath]:
"""Get all folder IDs and paths whose path starts with the given root path."""
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
try:
# Use path LIKE with wildcard to match all subfolders
cursor.execute(
"""
SELECT folder_id, folder_path FROM folders
WHERE folder_path LIKE ? || '%'
""",
(root_path,),
)
return cursor.fetchall()
finally:
conn.close()
def db_get_folder_ids_by_paths(
folder_paths: List[FolderPath],
) -> Dict[FolderPath, FolderId]:
"""
Get folder IDs for multiple folder paths in a single database query.
Args:
folder_paths: List of folder paths to look up
Returns:
Dictionary mapping folder paths to their corresponding folder IDs
"""
if not folder_paths:
return {}
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
try:
# Convert all paths to absolute paths
abs_paths = [os.path.abspath(path) for path in folder_paths]
# Create placeholders for the IN clause
placeholders = ",".join("?" * len(abs_paths))
cursor.execute(
f"SELECT folder_path, folder_id FROM folders WHERE folder_path IN ({placeholders})",
abs_paths,
)
results = cursor.fetchall()
# Create a mapping from folder_path to folder_id
path_to_id = {folder_path: folder_id for folder_path, folder_id in results}
return path_to_id
finally:
conn.close()
def db_get_all_folder_details() -> (
List[Tuple[str, str, Optional[str], int, bool, Optional[bool]]]
):
"""
Get all folder details including folder_id, folder_path, parent_folder_id,
last_modified_time, AI_Tagging, and taggingCompleted.
Returns list of tuples with all folder information.
"""
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
try:
cursor.execute(
"""
SELECT folder_id, folder_path, parent_folder_id, last_modified_time, AI_Tagging, taggingCompleted
FROM folders
ORDER BY folder_path
"""
)
return cursor.fetchall()
finally:
conn.close()
def db_get_direct_child_folders(parent_folder_id: str) -> List[Tuple[str, str]]:
"""
Get all direct child folders (not subfolders) for a given parent folder.
Returns list of tuples (folder_id, folder_path).
"""
conn = sqlite3.connect(DATABASE_PATH)
cursor = conn.cursor()
try:
cursor.execute(
"""
SELECT folder_id, folder_path FROM folders
WHERE parent_folder_id = ?
""",
(parent_folder_id,),
)
return cursor.fetchall()
finally:
conn.close()