forked from philipbl/duplicate-images
/
duplicate_finder.py
executable file
·529 lines (420 loc) · 16 KB
/
duplicate_finder.py
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
#!/usr/bin/env python3
"""
A tool to find and remove duplicate pictures.
Usage:
duplicate_finder.py add <path> ... [--db=<db_path>] [--parallel=<num_processes>]
duplicate_finder.py remove <path> ... [--db=<db_path>]
duplicate_finder.py clear [--db=<db_path>]
duplicate_finder.py show [--db=<db_path>]
duplicate_finder.py cleanup [--db=<db_path>]
duplicate_finder.py find [--print] [--delete] [--match-time] [--trash=<trash_path>] \
[--db=<db_path>] [--threshold=<num>]
duplicate_finder.py -h | --help
Options:
-h, --help Show this screen
--db=<db_path> The location of the database or a MongoDB URI. (default: ./db)
--parallel=<num_processes> The number of parallel processes to run to hash the files
(default: number of CPUs).
find:
--threshold=<num> Hash matching threshold. Number of different bits in Hamming \
distance. False positives are possible.
--print Only print duplicate files rather than displaying HTML file
--delete Move all found duplicate files to the trash. This option \
takes priority over --print.
--match-time Adds the extra constraint that duplicate images must have the
same capture times in order to be considered.
--trash=<trash_path> Where files will be put when they are deleted (default: ./Trash)
"""
import concurrent.futures
from contextlib import contextmanager
import os
import math
from pprint import pprint
import shutil
from subprocess import Popen, PIPE, TimeoutExpired
import sys
from tempfile import TemporaryDirectory
import webbrowser
import binascii
import io
from jinja2 import FileSystemLoader, Environment
from flask import Flask, Response
from flask_cors import CORS
from more_itertools import chunked
import pymongo
from PIL import Image
import pybktree
from termcolor import cprint
from hashers import BinaryHasher, ImageHasher, VideoHasher # , VideoBarcodeHasher
from utils import ProgressBarPrinter
def get_hashers() -> list:
"""Return array of active hashers"""
return [
BinaryHasher(),
ImageHasher(),
VideoHasher(ImageHasher()),
# VideoBarcodeHasher(ImageHasher()),
]
@contextmanager
def connect_to_db(db_conn_string='./db'):
"""Connect to mongo"""
p = None
# Determine db_conn_string is a mongo URI or a path
# If this is a URI
if 'mongodb://' == db_conn_string[:10] \
or 'mongodb+srv://' == db_conn_string[:14]:
client = pymongo.MongoClient(db_conn_string)
cprint("Connected server...", "yellow")
db = client.image_database
images = db.images
# If this is not a URI
else:
if not os.path.isdir(db_conn_string):
os.makedirs(db_conn_string)
p = Popen(['mongod', '--dbpath', db_conn_string],
stdout=PIPE, stderr=PIPE)
try:
p.wait(timeout=2)
stdout, _ = p.communicate()
cprint("Error starting mongod", "red")
cprint(stdout.decode(), "red")
sys.exit()
except TimeoutExpired:
pass
cprint("Started database...", "yellow")
client = pymongo.MongoClient()
db = client.image_database
images = db.images
# Create index on hash field
images.create_index([("hashes", pymongo.ASCENDING)], unique=False)
yield images
client.close()
if p is not None:
cprint("Stopped database...", "yellow")
p.terminate()
def get_files(path: str):
"""
Check path recursively for files and yield full path.
:param path:
:return: yield absolute path
"""
if os.path.isfile(path):
yield path
path = os.path.abspath(path)
for root, _, files in os.walk(path):
for file in files:
file = os.path.join(root, file)
yield file
def hash_file(file_path: str):
"""Hash file with all hashers"""
hashes = []
meta = {}
hashers = get_hashers()
try:
for hasher in hashers:
if hasher.is_applicable(file_path):
with open(file_path, 'rb') as file_object:
try:
(new_hashes, new_meta) = hasher.hash(file_object)
hashes = hashes + new_hashes
meta = meta | new_meta
except Exception as e:
cprint(f'\tHashing error "{e}" of {type(hasher).__name__} at {file_path}',
"red")
cprint(f'\tHashed {file_path}', "blue")
except OSError:
cprint(f'\tUnable to open {file_path}', "red")
return None
if len(hashes) == 0:
return None
return file_path, (
hashes,
meta
)
def hash_files_parallel(files, num_processes=None):
"""Hash files in parallel in subprocesses"""
with concurrent.futures.ProcessPoolExecutor(max_workers=num_processes) as executor:
for result in executor.map(hash_file, files):
if result is not None:
yield result
def _add_to_database(file_path: str, hashes_meta: tuple, db):
"""Add hashes and meta information of a file to database"""
(hashes, meta) = hashes_meta
try:
db.insert_one({"_id": file_path,
"hashes": hashes,
"meta": meta,
})
except pymongo.errors.DuplicateKeyError:
cprint(f'Duplicate key: {file_path}', "red")
def _in_database(file, db):
"""Return if file exists in database"""
return db.count_documents({"_id": file}) > 0
def new_files(files, db):
"""yield only new files, already hashed files are skipped"""
for file_path in files:
if _in_database(file_path, db):
cprint(f'\tAlready hashed {file_path}', "green")
else:
yield file_path
def add(paths, db, num_processes=None):
"""Loop through files and add hash them"""
for path in paths:
cprint(f'Hashing {path}', "blue")
files = get_files(path)
files = new_files(files, db)
for result in hash_files_parallel(files, num_processes):
_add_to_database(*result, db=db)
cprint("...done", "blue")
def remove(paths, db):
"""Remove file from database"""
for path in paths:
files = get_files(path)
for file in files:
remove_file(file, db)
def remove_file(file, db):
"""Remove file from database"""
db.delete_one({'_id': file})
def clear(db):
"""Clear database"""
db.drop()
def show(db):
"""Show all files from the databse"""
total = db.count_documents({})
pprint(list(db.find()))
print(f'Total: {total}')
def cleanup(db):
"""Clean disappeared files from the database"""
count = 0
files = db.find()
for _id in files:
file_name = _id['_id']
if not os.path.exists(file_name):
remove_file(file_name, db)
count += 1
cprint(f'Cleanup removed {count} files', 'yellow')
def same_time(dup):
"""Check if capture_time meta attribute is the same"""
items = dup['items']
if len({(i['meta']['capture_time'] if 'capture_time' in i['meta'] else '') for i in items}) > 1:
return False
return True
def find(db, match_time=False):
"""Find duplictes by equal hashes"""
dups = db.aggregate([
{"$unwind": "$hashes"},
{
"$group": {
"_id": "$hashes",
"total": {"$sum": 1},
"file_size": {"$max": "$meta.file_size"},
"items": {
"$push": {
"file_name": "$_id",
"meta": "$meta",
}
}
}
},
{
"$match": {
"total": {"$gt": 1}
}
},
{"$sort": {"file_size": -1}}
])
if match_time:
dups = (d for d in dups if same_time(d))
return make_duplcated_groups_unique(dups)
def make_duplcated_groups_unique(dups):
"""Deduplicate results by removing same groups of duplicates matched by multiple hashes"""
cprint('Removing same groups of duplicates having multiple matching hashes...')
deduplicated = []
unique_groups = set()
for dup in dups:
group_ids = ' '.join(sorted(x['file_name'] for x in dup['items']))
if group_ids not in unique_groups:
unique_groups.add(group_ids)
deduplicated.append(dup)
return deduplicated
def _build_binary_tree(cursor, pbp: ProgressBarPrinter) -> pybktree.BKTree:
"""Build binary tree for fuzzy searches."""
cprint('Building fuzzy tree...')
# Build a tree
tree = pybktree.BKTree(pybktree.hamming_distance)
for document in cursor:
pbp.print().inc()
for doc_hash in document['hashes']:
int_hash = int.from_bytes(doc_hash, "big")
tree.add(int_hash)
return tree
def _get_similar_hashes(doc_hashes, tree: pybktree.BKTree, threshold: int) -> set:
"""Get similar hashes from tree."""
similar = {}
for doc_hash in doc_hashes:
int_hash = int.from_bytes(doc_hash, "big")
new_similar = tree.find(int_hash, threshold)
if len(new_similar) > 1: # length == 1 when it is exact match to itself
new_similar = set(new_similar) # Make unique
similar[doc_hash] = list(
map(lambda item: binascii.unhexlify(hex(item[1])[2:]), new_similar)
)
return similar
def _get_similars_from_tree(db, tree: pybktree.BKTree, cursor,
pbp: ProgressBarPrinter, threshold: int):
"""Get fuzzy matched semilar duplicates."""
cprint('\rSearching duplicates...')
dups = []
deduplicated = set()
for document in cursor:
pbp.print().inc()
hashes_to_dedup = set(document['hashes']) - deduplicated
deduplicated.update(document['hashes'])
similar_hashes = _get_similar_hashes(hashes_to_dedup, tree, threshold)
if len(similar_hashes) > 0:
max_size = document['meta']['file_size']
for doc_hashes in similar_hashes.values():
deduplicated.update(doc_hashes)
similars = []
similars_name = set()
for item in db.find({'hashes': {'$in': doc_hashes}}):
if item['_id'] in similars_name:
continue
similars_name.add(item['_id'])
item['file_name'] = item['_id']
similars.append(item)
max_size = max_size if item['meta']['file_size'] <= max_size \
else item['meta']['file_size']
dups.append({
'_id': list(similar_hashes.keys()),
'total': len(similars),
'items': similars,
'file_size': max_size
})
return make_duplcated_groups_unique(dups)
def find_threshold(db, threshold=1):
"""Find duplicates by number of bits of Humming distance"""
cprint('Finding fuzzy duplicates, it might take a while...')
cnt = db.count_documents({})
all_documents = db.find()
pbp = ProgressBarPrinter(cnt)
tree = _build_binary_tree(all_documents, pbp)
pbp.reset()
all_documents.rewind()
return _get_similars_from_tree(db, tree, all_documents, pbp, threshold)
def delete_duplicates(duplicates, db):
"""Delete duplicates except the first one"""
results = [delete_duplicate_file(x['file_name'], db)
for dup in duplicates for x in dup['items'][1:]]
cprint(f'Deleted {results.count(True)}/{len(results)} files', 'yellow')
def delete_duplicate_file(file_name, db, trash="./Trash/"):
"""Delete duplicated file and from the database"""
cprint(f'Moving {file_name} to {trash}', 'yellow')
if not os.path.exists(trash):
os.makedirs(trash)
try:
shutil.move(file_name, trash + os.path.basename(file_name))
remove_file(file_name, db)
except FileNotFoundError:
cprint(f'File not found {file_name}', 'red')
return False
except Exception as e:
cprint(f'Error: {str(e)}', 'red')
return False
return True
def transpose_duplicagtes(duplicates):
"""Transpose duplictes to render in columns"""
for group in duplicates:
items_clount = len(group['items'])
row = {
'id': [''] * items_clount,
'file_name': [''] * items_clount,
}
index = 0
for image in group['items']:
row['id'][index] = image['file_name']
row['file_name'][index] = image['file_name']
for key, value in image['meta'].items():
if key not in row:
row[key] = [''] * items_clount
row[key][index] = value
index += 1
group['items'] = row
return duplicates
def display_duplicates(duplicates, db, trash="./Trash/"):
"""Displays duplicates in browser"""
duplicates = transpose_duplicagtes(duplicates)
app = Flask(__name__)
CORS(app)
def render(duplicates, current, total):
env = Environment(loader=FileSystemLoader('template'))
env.filters['hash'] = hash
template = env.get_template('index.html')
return template.render(duplicates=duplicates,
current=current,
total=total)
with TemporaryDirectory() as folder:
if len(duplicates) == 0:
env = Environment(loader=FileSystemLoader('template'))
template = env.get_template('no_duplicates.html')
with open(f'{folder}/0.html', 'w', encoding="utf-8") as f:
f.write(template.render())
else:
# Generate all of the HTML files
chunk_size = 25
for i, dups_page in enumerate(chunked(duplicates, chunk_size)):
with open(f'{folder}/{i}.html', 'w', encoding="utf-8") as f:
f.write(render(dups_page,
current=i,
total=math.ceil(len(duplicates) / chunk_size)
)
)
webbrowser.open(f'file://{folder}/0.html')
@app.route('/picture/<path:file_name>', methods=['DELETE'])
def delete_picture_(file_name, trash=trash):
return str(delete_duplicate_file('/' + file_name, db, trash))
@app.route('/heic-transform/<path:file_name>', methods=['GET'])
def transcode_heic_(file_name):
heif_image = Image.open('/' + file_name)
encoded = io.BytesIO()
heif_image.save(encoded, format='JPEG')
return Response(encoded.getvalue(), mimetype='image/jpeg')
app.run()
if __name__ == '__main__':
from docopt import docopt
args = docopt(__doc__)
if args['--trash']:
TRASH = args['--trash']
else:
TRASH = "./Trash/"
if args['--db']:
DB_PATH = args['--db']
else:
DB_PATH = "./db"
if args['--parallel']:
NUM_PROCESSES = int(args['--parallel'])
else:
NUM_PROCESSES = None
with connect_to_db(db_conn_string=DB_PATH) as main_db:
if args['add']:
add(args['<path>'], main_db, NUM_PROCESSES)
elif args['remove']:
remove(args['<path>'], main_db)
elif args['clear']:
clear(main_db)
elif args['cleanup']:
cleanup(main_db)
elif args['show']:
show(main_db)
elif args['find']:
if args['--threshold'] is not None:
main_dups = find_threshold(main_db, int(args['--threshold']))
else:
main_dups = find(main_db, args['--match-time'])
if args['--delete']:
delete_duplicates(main_dups, main_db)
elif args['--print']:
pprint(main_dups)
print(f'Number of duplicates: {len(main_dups)}')
else:
display_duplicates(main_dups, db=main_db)