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 | class DuplicateFileFinder:
"""
A class to find and manage duplicate files.
"""
__slots__ = ("db_path", "batch_size", "algorithm", "partial_hash_size", "ignore_hidden")
db_path: Path
batch_size: int
algorithm: str
partial_hash_size: int
ignore_hidden: bool
def __init__(
self,
batch_size: int = 1000,
algorithm: str = "sha256",
partial_hash_size: int = 8192,
ignore_hidden: bool = False,
db_path: Path | str = "deduper.db",
):
"""
Initialize the DuplicateFileFinder.
Args:
batch_size: Number of files to process before committing to the database
algorithm: Hashing algorithm to use (md5, sha256)
partial_hash_size: Number of bytes to read for partial hashing, default 8KB
ignore_hidden: Whether to ignore hidden files
db_path: Path to the SQLite database file
"""
if isinstance(db_path, str):
db_path = Path(db_path).absolute()
self.db_path = db_path
self.batch_size = batch_size
self.algorithm = algorithm
self.partial_hash_size = partial_hash_size
self.ignore_hidden = ignore_hidden
self._init_database() # TODO: should we store settings in db?
def _init_database(self):
"""Initialize the SQLite database schema."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
path TEXT NOT NULL UNIQUE, -- unique, absolute file path
filename TEXT, -- file name without path or extension
extension TEXT, -- file extension
partial_hash TEXT NOT NULL, -- hash of the first chunk of the file
hash TEXT, -- full file hash, if needed
size INTEGER NOT NULL, -- file size in bytes
scan_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_partial_hash_and_size ON files(partial_hash, size)
""")
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_hash ON files(hash)
""")
# New table for unreadable files
cursor.execute("""
CREATE TABLE IF NOT EXISTS unreadable_files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
path TEXT NOT NULL, -- absolute file path
error_type TEXT NOT NULL, -- type of error encountered
scan_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.commit()
conn.close()
def scan_directory(self, directory: Path | str, recursive: bool = True, extensions: list[str] | None = None) -> int:
"""
Scan a directory for files and store their information in the database.
Args:
directory: Directory path to scan
recursive: Whether to scan subdirectories recursively
extensions: List of file extensions to include (e.g., ['.txt', '.jpg']). If None, include all files.
Returns:
Number of files scanned
"""
if isinstance(directory, str):
directory = Path(directory)
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
files_scanned = 0
for root, dirs, files in os.walk(directory):
if not recursive:
dirs.clear()
for file in files:
file_path = Path(root) / file
if self.ignore_hidden and file_path.name.startswith("."):
continue
if extensions is None or file_path.suffix.lower() in extensions:
self._store_file(cursor, file_path)
files_scanned += 1
if files_scanned % self.batch_size == 0:
conn.commit()
conn.commit()
# After scanning, update full hashes for candidates
self._update_partial_hashes(cursor)
conn.commit()
conn.close()
return files_scanned
def _log_unreadable_file(self, cursor, file_path: Path, error_type: str):
"""Log unreadable file information in the database."""
abs_path = str(file_path.resolve())
cursor.execute(
"""
INSERT INTO unreadable_files (path, error_type)
VALUES (?, ?)
""",
(abs_path, error_type),
)
def _store_file(self, cursor, file_path: Path):
"""Store file information in the database."""
try:
file_size = file_path.stat().st_size
abs_path = str(file_path.resolve())
filename = file_path.stem
extension = file_path.suffix.lower()
partial_hash = calculate_partial_hash(file_path)
cursor.execute(
"""
INSERT OR REPLACE INTO files (path, filename, extension, partial_hash, hash, size)
VALUES (?, ?, ?, ?, NULL, ?)
""",
(abs_path, filename, extension, partial_hash, file_size),
)
except (OSError, PermissionError) as e:
self._log_unreadable_file(cursor, file_path, type(e).__name__)
def get_scanned_files(self) -> Iterator[str]:
"""
Yield all files stored in the database in batches.
Yields:
File paths (str)
"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("SELECT path FROM files")
while True:
rows = cursor.fetchmany(self.batch_size)
if not rows:
break
for row in rows:
yield row[0]
conn.close()
def find_duplicates(self) -> dict[str, "DuplicateGroup"]:
"""
Find all duplicate files in the database.
Returns:
Dictionary mapping hash to DuplicateGroup
"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
# Only update full hashes for files missing them, not every time
self._update_partial_hashes(cursor)
conn.commit()
# Now find duplicates by full hash
cursor.execute("""
SELECT hash, path, size
FROM files
WHERE hash IN (
SELECT hash
FROM files
WHERE hash IS NOT NULL
GROUP BY hash
HAVING COUNT(*) > 1
)
ORDER BY hash, path
""")
groups: dict[str, list[tuple[str, int]]] = {}
for hash_val, path, size in cursor.fetchall():
if hash_val not in groups:
groups[hash_val] = []
groups[hash_val].append((path, size))
duplicates: dict[str, DuplicateGroup] = {}
for hash_val, files in groups.items():
file_paths = [p for p, _ in files]
file_size = files[0][1] if files else 0
duplicates[hash_val] = DuplicateGroup(hash_=hash_val, file_size=file_size, file_paths=tuple(file_paths))
conn.close()
return duplicates
def _update_partial_hashes(self, cursor):
"""
Find all (partial_hash, size) groups with more than one file, and for each,
compute and store full hashes for files missing them.
"""
cursor.execute(
"""
SELECT partial_hash, size
FROM files
GROUP BY partial_hash, size
HAVING COUNT(*) > 1
"""
)
candidates = cursor.fetchall()
for partial_hash, size in candidates:
cursor.execute(
"SELECT path, hash FROM files WHERE partial_hash = ? AND size = ?",
(partial_hash, size),
)
rows = cursor.fetchall()
for path, full_hash in rows:
if full_hash:
continue # Full hash already computed
file_path = Path(path)
try:
computed_hash = calculate_hash(file_path)
cursor.execute("UPDATE files SET hash = ? WHERE path = ?", (computed_hash, path))
except Exception:
continue
def get_duplicate_groups(self) -> list["DuplicateGroup"]:
"""
Get duplicate files as a list of DuplicateGroup.
Returns:
List of DuplicateGroup instances
"""
duplicates = self.find_duplicates()
return list(duplicates.values())
def delete_duplicates(self, keep_first: bool = True, dry_run: bool = True) -> list[str]:
"""
Delete duplicate files, keeping one copy.
Args:
keep_first: If True, keep the first file (alphabetically), else keep the last
dry_run: If True, only return files that would be deleted without deleting
Returns:
List of file paths that were (or would be) deleted
"""
duplicates = self.find_duplicates()
deleted_files = []
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
for group in duplicates.values():
keep_path = group.file_paths[0] if keep_first else group.file_paths[-1]
files_to_delete = group.delete_duplicates(keep_path, dry_run=dry_run)
if not dry_run:
for file_path in files_to_delete:
cursor.execute("DELETE FROM files WHERE path = ?", (file_path,))
deleted_files.extend(files_to_delete)
if not dry_run:
conn.commit()
conn.close()
return deleted_files
def clear_database(self):
"""Clear all entries from the database."""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("DELETE FROM files")
cursor.execute("DELETE FROM unreadable_files")
conn.commit()
conn.close()
def get_statistics(self) -> dict[str, int | str]:
"""
Get statistics about scanned files and duplicates.
Returns:
Dictionary with statistics
"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM files")
total_files = cursor.fetchone()[0]
cursor.execute("""
SELECT COUNT(DISTINCT hash)
FROM files
WHERE hash IN (
SELECT hash
FROM files
GROUP BY hash
HAVING COUNT(*) > 1
)
""")
duplicate_groups = cursor.fetchone()[0]
cursor.execute("""
SELECT COUNT(*)
FROM files
WHERE hash IN (
SELECT hash
FROM files
GROUP BY hash
HAVING COUNT(*) > 1
)
""")
duplicate_files = cursor.fetchone()[0]
cursor.execute("SELECT SUM(size) FROM files")
total_size = cursor.fetchone()[0] or 0
conn.close()
return {
"total_files": total_files,
"duplicate_groups": duplicate_groups,
"duplicate_files": duplicate_files,
"unique_files": total_files - duplicate_files,
"total_size_bytes": total_size,
"total_size": format_size(total_size),
}
def get_statistics_by_extension(self) -> dict[str, dict[str, int]]:
"""
Get statistics grouped by file extension.
Returns:
Dictionary mapping extension to statistics (count, total_size)
"""
conn = sqlite3.connect(self.db_path)
cursor = conn.cursor()
cursor.execute("""
SELECT
extension,
COUNT(*) as count,
SUM(size) as total_size
FROM files
GROUP BY extension
ORDER BY count DESC
""")
result = {}
for ext, count, total_size in cursor.fetchall():
# Use empty string as key for files without extension
key = ext if ext else ""
result[key] = {
"count": count,
"total_size_bytes": total_size or 0,
"total_size": format_size(total_size or 0),
}
conn.close()
return result
|