-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathidem.py
More file actions
2657 lines (2307 loc) · 103 KB
/
idem.py
File metadata and controls
2657 lines (2307 loc) · 103 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
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
idem.py — Find duplicate images and videos.
Three modes:
Perceptual (default): computes pHash + dHash to find visually similar images.
Video (--video): samples frames with ffmpeg to find visually similar videos,
including re-encodes at different resolutions or bitrates. Requires ffmpeg
on PATH. Can be combined with the default image scan.
Exact (--exact): uses SHA-256 checksums for byte-for-byte duplicates; covers
all media files. Reads and updates all_media_sha_hash_db.csv instead of the phash cache.
Supported image formats: JPEG, PNG, GIF, BMP, TIFF, WebP, HEIC/HEIF.
Supported video formats: MP4, MOV, AVI, MKV, WMV, WebM, FLV, etc.
Not supported in perceptual mode:
- RAW camera files (.cr2, .nef, .arw, .dng, etc.) — use processed exports.
Usage:
python idem.py <directory> [--threshold N] [--delta SIZE] [--cache PATH] [--review] [--page-size N] [--limit N]
python idem.py <directory> --video [--threshold N] [--review] [--page-size N] [--limit N]
python idem.py <directory> --exact [--review] [--page-size N] [--limit N]
python idem.py <directory> [--exact] --interactive
Threshold guide (perceptual mode):
0 exact visual duplicates only
5 same image, minor JPEG re-saves
10 same image, different resolution or format (default)
20 loose — risk of false positives
Threshold guide (--video mode, mean frame Hamming distance):
0 same frames, different container or codec only
5 same video, minor re-encode or colour grade change
10 same video, different resolution or bitrate (default)
20 loose — risk of false positives
"""
import argparse
import csv
import hashlib
import json
import os
import re
import shutil
import sys
import tempfile
from pathlib import Path
# Ensure Unicode output works on Windows (cp1252 → utf-8).
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
try:
from PIL import Image, ImageFile
import imagehash
ImageFile.LOAD_TRUNCATED_IMAGES = True # recover from broken JPEG data streams
except ImportError:
print("Error: Pillow and imagehash are required.", file=sys.stderr)
print(" pip install Pillow imagehash", file=sys.stderr)
sys.exit(1)
try:
import pybktree
except ImportError:
print("Error: pybktree is required.", file=sys.stderr)
print(" pip install pybktree", file=sys.stderr)
sys.exit(1)
# ── Constants ──────────────────────────────────────────────────────────────────
CACHE_FILENAME = "images_perceptual_hash_db.csv"
CACHE_FIELDS = ["path", "size", "mtime", "phash", "dhash"]
DEFAULT_THRESHOLD = 10
_TS_TOLERANCE = 2.0 # seconds; covers FAT32 / float round-trip noise
IMAGE_EXTENSIONS = {
".jpg", ".jpeg", ".png", ".gif", ".bmp",
".tiff", ".tif", ".webp",
".heic", ".heif",
}
VIDEO_EXTENSIONS = {
".mp4", ".mov", ".avi", ".mkv", ".wmv", ".webm",
".flv", ".3gp", ".m4v", ".mts", ".m2ts",
}
MEDIA_EXTENSIONS = IMAGE_EXTENSIONS | VIDEO_EXTENSIONS
# ── Exact-match DB constants ────────────────────────────────────────────────────
DB_FILENAME = "all_media_sha_hash_db.csv"
DB_FIELDS = ["path", "size", "ctime", "mtime", "checksum"]
# Sampling thresholds (must match kura.py so existing DB entries are reusable).
_SAMPLE_SIZE = 4 * 1024 * 1024 # 4 MiB per window
_FULL_HASH_THRESHOLD = 3 * _SAMPLE_SIZE # 12 MiB — full hash below this
# ── Video perceptual cache constants ──────────────────────────────────────────
VCACHE_FILENAME = "videos_perceptual_hash_db.csv"
VCACHE_FIELDS = ["path", "size", "mtime", "duration", "vhash"]
N_VIDEO_FRAMES = 8 # evenly-spaced frames sampled per video
DB_DIR = "__databases" # subdirectory within any scanned directory that holds all 3 DB files
# ── Helpers ────────────────────────────────────────────────────────────────────
def _valid_hex(s: str) -> bool:
"""Return True if s is a non-empty valid hexadecimal string."""
return bool(s and re.fullmatch(r'[0-9a-fA-F]+', s))
def path_without_drive(path: str) -> str:
"""Strip Windows drive letter or UNC share prefix from a path.
C:\\Users\\foo\\bar.jpg → \\Users\\foo\\bar.jpg
\\\\server\\share\\foo.jpg → \\foo.jpg
On non-Windows paths without a drive, returns the string unchanged.
"""
p = Path(path)
drive = p.drive
if drive:
return str(path)[len(drive):]
return str(path)
def _ensure_db_dir(directory: str) -> str:
"""Return the ``__databases`` subdirectory of *directory*, creating it if needed."""
d = os.path.join(directory, DB_DIR)
os.makedirs(d, exist_ok=True)
return d
# ── Cache I/O ──────────────────────────────────────────────────────────────────
def load_cache(cache_path: str) -> dict:
"""Return dict: abs_path -> {size, mtime, phash, dhash}."""
cache = {}
if not os.path.exists(cache_path):
return cache
try:
with open(cache_path, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
try:
phash = row.get("phash", "")
dhash = row.get("dhash", "")
if not _valid_hex(phash) or (dhash and not _valid_hex(dhash)):
continue # skip rows with missing or corrupt hashes
cache[path_without_drive(row["path"])] = {
"size": int(row["size"]),
"mtime": float(row["mtime"]),
"phash": phash,
"dhash": dhash,
}
except (ValueError, KeyError):
pass # skip individual corrupt rows; rest of cache is intact
except Exception as e:
print(f"Warning: could not read cache ({e}), starting fresh.", file=sys.stderr)
return cache
def save_cache(cache_path: str, cache: dict) -> None:
"""Rewrite the cache CSV from the in-memory dict (compacts any appended rows).
Writes to a temporary file in the same directory then atomically replaces
the target so a crash mid-write never leaves the cache truncated or empty.
"""
try:
cache_dir = os.path.dirname(cache_path) or "."
fd, tmp_path = tempfile.mkstemp(dir=cache_dir, suffix=".tmp")
except Exception as e:
print(f"Warning: could not save cache ({e}).", file=sys.stderr)
return
try:
with os.fdopen(fd, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=CACHE_FIELDS)
writer.writeheader()
for path, data in sorted(cache.items()):
# Keys are always drive-stripped (path_without_drive applied on insert).
writer.writerow({"path": path, **data})
os.replace(tmp_path, cache_path)
except Exception as e:
print(f"Warning: could not save cache ({e}).", file=sys.stderr)
try:
os.unlink(tmp_path)
except OSError:
pass
def open_cache_for_append(cache_path: str):
"""Open the cache file for incremental appending.
Writes the CSV header if the file does not yet exist.
Returns an open file handle; caller is responsible for closing it.
Each row written via this handle is immediately flushed so that an
interrupted run loses no already-computed hashes.
"""
f = open(cache_path, "a", newline="", encoding="utf-8")
if f.tell() == 0: # new or empty file — write header
csv.DictWriter(f, fieldnames=CACHE_FIELDS).writeheader()
f.flush()
return f
# ── Video perceptual cache I/O ─────────────────────────────────────────────────
def load_vcache(cache_path: str) -> dict:
"""Return dict: path_without_drive -> {size, mtime, duration, vhash}.
vhash is stored as a list of hex strings (one per sampled frame).
"""
cache = {}
if not os.path.exists(cache_path):
return cache
try:
with open(cache_path, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
try:
vhash_str = row.get("vhash", "")
if not vhash_str:
continue
parts = vhash_str.split(",")
if not parts or not all(_valid_hex(p) for p in parts):
continue
cache[path_without_drive(row["path"])] = {
"size": int(row["size"]),
"mtime": float(row["mtime"]),
"duration": float(row["duration"]),
"vhash": parts,
}
except (ValueError, KeyError):
pass
except Exception as e:
print(f"Warning: could not read video cache ({e}), starting fresh.",
file=sys.stderr)
return cache
def save_vcache(cache_path: str, cache: dict) -> None:
"""Atomically rewrite the video cache CSV from the in-memory dict."""
try:
cache_dir = os.path.dirname(cache_path) or "."
fd, tmp_path = tempfile.mkstemp(dir=cache_dir, suffix=".tmp")
except Exception as e:
print(f"Warning: could not save video cache ({e}).", file=sys.stderr)
return
try:
with os.fdopen(fd, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=VCACHE_FIELDS)
writer.writeheader()
for path, data in sorted(cache.items()):
writer.writerow({
"path": path_without_drive(path),
"size": data["size"],
"mtime": data["mtime"],
"duration": data["duration"],
"vhash": ",".join(data["vhash"]),
})
os.replace(tmp_path, cache_path)
except Exception as e:
print(f"Warning: could not save video cache ({e}).", file=sys.stderr)
try:
os.unlink(tmp_path)
except OSError:
pass
def _open_vcache_for_append(cache_path: str):
"""Open the video cache file for incremental appending.
Writes the CSV header if the file does not yet exist.
Returns an open file handle; caller is responsible for closing it.
"""
f = open(cache_path, "a", newline="", encoding="utf-8")
if f.tell() == 0:
csv.DictWriter(f, fieldnames=VCACHE_FIELDS).writeheader()
f.flush()
return f
# ── Exact-match DB I/O ─────────────────────────────────────────────────────────
def _load_db(db_path: str) -> dict:
"""Load all_media_sha_hash_db.csv; return dict keyed by path_without_drive."""
entries = {}
if not os.path.exists(db_path):
return entries
try:
with open(db_path, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
try:
row["size"] = int(row["size"])
row["ctime"] = float(row["ctime"])
row["mtime"] = float(row["mtime"])
except (TypeError, ValueError, KeyError):
continue
entries[row["path"]] = row
except Exception as e:
print(f"Warning: could not read DB ({e}), starting fresh.", file=sys.stderr)
return entries
def _save_db(db_path: str, entries: dict) -> None:
"""Atomically write all_media_sha_hash_db.csv from the in-memory dict."""
try:
db_dir = os.path.dirname(db_path) or "."
fd, tmp = tempfile.mkstemp(dir=db_dir, suffix=".tmp")
except Exception as e:
print(f"Warning: could not save DB ({e}).", file=sys.stderr)
return
try:
with os.fdopen(fd, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=DB_FIELDS)
writer.writeheader()
writer.writerows(entries.values())
os.replace(tmp, db_path)
except Exception as e:
print(f"Warning: could not save DB ({e}).", file=sys.stderr)
try:
os.unlink(tmp)
except OSError:
pass
def _file_checksum(path: str) -> str:
"""SHA-256 digest matching kura.py's file_checksum (sampled for large files).
Files up to 12 MiB are hashed in full. Larger files are sampled from three
4 MiB windows (first / middle / last) plus the file size so the algorithm
stays compatible with checksums already stored in all_media_sha_hash_db.csv.
"""
p = Path(path)
size = p.stat().st_size
h = hashlib.sha256()
# Mixing the file size into the digest first ensures two files whose sampled
# windows happen to contain identical bytes but differ in total length will
# produce different checksums.
h.update(size.to_bytes(8, "little"))
with open(path, "rb") as f:
if size <= _FULL_HASH_THRESHOLD:
# Use a reusable buffer + readinto to avoid allocating a new bytes
# object on every read; cuts GC pressure on large files.
buf = bytearray(1 << 20)
view = memoryview(buf)
while True:
n = f.readinto(view)
if not n:
break
h.update(view[:n])
else:
h.update(f.read(_SAMPLE_SIZE)) # first 4 MiB
f.seek(size // 2 - _SAMPLE_SIZE // 2)
h.update(f.read(_SAMPLE_SIZE)) # middle 4 MiB
f.seek(-_SAMPLE_SIZE, 2)
h.update(f.read(_SAMPLE_SIZE)) # last 4 MiB
return h.hexdigest()
# ── Hashing ────────────────────────────────────────────────────────────────────
def compute_hashes(path: str) -> tuple:
"""Return (phash_str, dhash_str). Opens the image once. Raises on error."""
img = Image.open(path)
img.load() # force full JPEG decompression before hashing
return str(imagehash.phash(img)), str(imagehash.dhash(img))
# ── Formatting / parsing ───────────────────────────────────────────────────────
def parse_size(s: str) -> int:
"""Parse a human-readable size string into bytes.
Accepts an optional suffix (case-insensitive): b, kb, mb, gb, tb.
No suffix means bytes. Examples: '500', '50kb', '2.5MB', '1GB'.
"""
s = s.strip()
lo = s.lower()
multipliers = [("tb", 1024**4), ("gb", 1024**3), ("mb", 1024**2), ("kb", 1024), ("b", 1)]
for suffix, mult in multipliers:
if lo.endswith(suffix):
return int(float(s[: -len(suffix)]) * mult)
return int(s) # bare number → bytes
def fmt_size(n: int) -> str:
for unit in ("B", "KB", "MB", "GB"):
if n < 1024:
return f"{n:6.1f} {unit}"
n /= 1024
return f"{n:6.1f} TB"
# ── Terminal helpers ────────────────────────────────────────────────────────────
def _fmt_path(path: str) -> str:
"""Return a file:// URI on Windows (clickable in terminal), plain path elsewhere."""
if sys.platform == "win32":
return Path(path).as_uri()
return path
def _terminal_width():
try:
return os.get_terminal_size().columns
except OSError:
return 80
def _progress_bar(i, n, label=""):
"""Overwrite the current line with a progress bar. No-op if not a TTY."""
if not sys.stdout.isatty() or n == 0:
return
cols = _terminal_width()
counter = f"{i}/{n}"
# Fixed overhead: " [" bar "] " counter " " = bar_area + len(counter) + 9
bar_area = min(40, max(10, cols - len(counter) - 9))
filled = round(i / n * bar_area)
bar = "#" * filled + "-" * (bar_area - filled)
head = f" [{bar}] {counter}"
avail = cols - len(head) - 3
tail = (" " + label[:avail]) if avail > 4 and label else ""
sys.stdout.write(("\r" + head + tail).ljust(cols - 1)[:cols - 1])
sys.stdout.flush()
def _clear_bar():
"""Blank the current progress-bar line so an error message can be printed."""
if not sys.stdout.isatty():
return
cols = _terminal_width()
sys.stdout.write("\r" + " " * (cols - 1) + "\r")
sys.stdout.flush()
# ── Core logic ─────────────────────────────────────────────────────────────────
def scan_files(directory: str, extensions=IMAGE_EXTENSIONS) -> list:
"""Return sorted list of absolute paths for matching files under directory.
``__duplicate_files_trash/`` and ``__databases/`` are excluded so previously
trashed files are never re-presented as duplicates, and DB temp files are
never mistaken for media files.
"""
result = []
_skip = {"__duplicate_files_trash", DB_DIR}
for root, dirs, files in os.walk(directory):
dirs[:] = [d for d in dirs if d not in _skip] # in-place edit prunes os.walk's descent
for fname in files:
if Path(fname).suffix.lower() in extensions:
result.append(os.path.join(root, fname))
return sorted(result)
def scan_exact_files(directory: str) -> list:
"""Return sorted list of all media files (images + videos) under directory.
Convenience wrapper around scan_files for exact/checksum mode.
"""
return scan_files(directory, MEDIA_EXTENSIONS)
def build_hashes(all_files: list, cache: dict, cache_out=None) -> tuple:
"""
Compute/load perceptual hashes (phash + dhash) for all files.
Returns (hashes dict, new_count, rehashed_count, error_count).
hashes maps path -> (phash_int, dhash_int, size_bytes).
Mutates cache in-place with any newly computed hashes.
cache_out: optional open file handle (from open_cache_for_append). When
provided, newly computed hashes are appended and flushed to disk every
200 updates (and once more at the end) so that an interrupted run loses
at most 200 hashes worth of work.
"""
writer = csv.DictWriter(cache_out, fieldnames=CACHE_FIELDS) if cache_out else None
hashes = {}
new_count = rehashed_count = errors = 0
n = len(all_files)
for i, path in enumerate(all_files, 1):
if i % 50 == 0 or i == n:
_progress_bar(i, n, os.path.basename(path))
try:
st = os.stat(path)
except OSError as e:
_clear_bar()
print(f" Warning: skipped {os.path.basename(path)}: {e}", flush=True)
errors += 1
continue
size, mtime = st.st_size, st.st_mtime
cache_key = path_without_drive(path)
cached = cache.get(cache_key)
metadata_ok = (cached and cached["size"] == size
and abs(cached["mtime"] - mtime) < _TS_TOLERANCE)
is_new = not cached
if metadata_ok:
# Cache hit — file unchanged (size and mtime within tolerance).
ph = int(cached["phash"], 16)
dh = int(cached["dhash"], 16)
else:
try:
phash_str, dhash_str = compute_hashes(path)
except Exception as e:
_clear_bar()
print(f" Warning: skipped {os.path.basename(path)}: {e}", flush=True)
errors += 1
continue
ph = int(phash_str, 16)
dh = int(dhash_str, 16)
cache[cache_key] = {"size": size, "mtime": mtime,
"phash": phash_str, "dhash": dhash_str}
if writer:
writer.writerow({"path": cache_key, "size": size, "mtime": mtime,
"phash": phash_str, "dhash": dhash_str})
if is_new:
new_count += 1
else:
rehashed_count += 1
if writer and (new_count + rehashed_count) % 200 == 0:
cache_out.flush() # periodic flush: limits lost work to ~200 hashes on interrupt
hashes[path] = (ph, dh, size)
if writer:
cache_out.flush() # flush any remainder at the end
if n > 0:
print() # end progress line
return hashes, new_count, rehashed_count, errors
def group_duplicates(hashes: dict, threshold: int) -> list:
"""
Return list of duplicate groups, each a list of (path, size_bytes).
Uses a BK-tree for O(n log n) near-duplicate detection rather than O(n²).
Within each group files are sorted largest-first (largest = likely original).
Groups are sorted most-files-first.
"""
if not hashes:
return []
def hamming(a, b):
# Items are (path, ph_int) tuples; XOR the integer pHashes and count
# the differing bits to get the Hamming distance between the two images.
return (a[1] ^ b[1]).bit_count()
items = [(path, ph) for path, (ph, _, _sz) in hashes.items()]
tree = pybktree.BKTree(hamming, items)
seen = set()
groups = []
n = len(items)
for i, (path, (ph, dh, _sz)) in enumerate(hashes.items(), 1):
if i % 50 == 0 or i == n:
_progress_bar(i, n)
if path in seen:
continue
matches = tree.find((path, ph), threshold) # includes self
if len(matches) < 2:
continue
# Secondary dhash filter: pHash captures frequency-domain (DCT) structure;
# dHash captures pixel-gradient direction changes. Requiring both hashes
# to be within threshold significantly reduces false positives, since a
# pair of unrelated images is unlikely to fool both independently.
# Candidates already assigned to an earlier group are excluded so that each
# image appears in exactly one group (the first pivot whose BK-tree search
# returned it).
group_paths = [m[1][0] for m in matches
if m[1][0] not in seen
and (hashes[m[1][0]][1] ^ dh).bit_count() <= threshold]
if len(group_paths) < 2:
continue
seen.update(group_paths)
group = sorted(
((p, hashes[p][2]) for p in group_paths),
key=lambda x: x[1],
reverse=True,
)
groups.append(group)
print() # end progress line
groups.sort(key=lambda g: (-len(g), -g[0][1]))
return groups
# ── Video perceptual hashing ───────────────────────────────────────────────────
def ffmpeg_available() -> bool:
"""Return True if ffmpeg is on PATH."""
return shutil.which("ffmpeg") is not None
def _get_video_duration(path: str) -> float:
"""Return video duration in seconds via ffprobe, falling back to ffmpeg."""
import subprocess
if shutil.which("ffprobe"):
r = subprocess.run(
["ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", path],
capture_output=True, text=True, timeout=30,
)
if r.returncode == 0:
try:
return float(r.stdout.strip())
except ValueError:
pass
# Fallback: parse "Duration: HH:MM:SS.ss" from ffmpeg -i stderr.
r = subprocess.run(
["ffmpeg", "-nostdin", "-i", path],
capture_output=True, text=True, timeout=30,
)
m = re.search(r"Duration:\s*(\d+):(\d+):([\d.]+)", r.stderr)
if m:
h, mi, s = int(m.group(1)), int(m.group(2)), float(m.group(3))
return h * 3600 + mi * 60 + s
raise RuntimeError(f"Could not determine duration of {os.path.basename(path)}")
def compute_video_hashes(path: str, n: int = N_VIDEO_FRAMES) -> tuple:
"""Return (duration_seconds, [phash_int, ...]) for a video file.
Opens the video n times in one ffmpeg call, each with a fast input-level
seek (-ss before -i) to a midpoint timestamp. trim=end_frame=1 stops
ffmpeg from reading past the first frame of each seek, so only ~1 GOP
worth of data is decoded per sample regardless of video length.
Output is raw 64×64 RGB — no PNG encode/decode overhead.
Raises RuntimeError if ffmpeg fails or the video cannot be decoded.
"""
import subprocess
duration = _get_video_duration(path)
if duration <= 0:
raise RuntimeError(
f"Invalid duration ({duration:.1f}s) for {os.path.basename(path)}"
)
FRAME_W, FRAME_H = 64, 64
timestamps = [duration * (2 * i + 1) / (2 * n) for i in range(n)]
# Placing -ss *before* -i tells ffmpeg to seek at the input level: it jumps
# to the nearest preceding keyframe (fast). Putting -ss *after* -i would
# force ffmpeg to decode every frame from the file start up to the target
# timestamp, which is prohibitively slow for large or high-bitrate videos.
args = ["ffmpeg", "-nostdin"]
for t in timestamps:
args += ["-ss", f"{t:.6f}", "-i", path]
# One frame per input, scaled; then concatenate into a single stream.
fc_parts = [
f"[{i}:v]trim=start_frame=0:end_frame=1,setpts=PTS-STARTPTS,"
f"scale={FRAME_W}:{FRAME_H}[v{i}]"
for i in range(n)
]
fc_concat = "".join(f"[v{i}]" for i in range(n)) + f"concat=n={n}:v=1[out]"
args += [
"-filter_complex", ";".join(fc_parts) + ";" + fc_concat,
"-map", "[out]",
"-f", "rawvideo", "-pix_fmt", "rgb24",
"pipe:1", "-loglevel", "error",
]
result = subprocess.run(args, capture_output=True, timeout=120)
if result.returncode != 0 or not result.stdout:
raise RuntimeError(
f"ffmpeg failed for {os.path.basename(path)}"
)
frame_size = FRAME_W * FRAME_H * 3 # bytes per raw RGB frame: 64×64×3 = 12 288
raw = result.stdout
n_got = len(raw) // frame_size
if n_got == 0:
raise RuntimeError(
f"ffmpeg produced no frames for {os.path.basename(path)}"
)
frame_hashes = []
for i in range(min(n, n_got)):
chunk = raw[i * frame_size : (i + 1) * frame_size]
img = Image.frombytes("RGB", (FRAME_W, FRAME_H), chunk)
frame_hashes.append(int(str(imagehash.phash(img)), 16))
return duration, frame_hashes
def build_video_hashes(files: list, cache: dict, cache_out=None) -> tuple:
"""Compute/load frame hashes for video files.
Returns (vhashes dict, new_count, rehashed_count, error_count).
vhashes maps path -> (duration, [phash_int, ...], size_bytes).
Mutates cache in-place with any newly computed hashes.
"""
writer = csv.DictWriter(cache_out, fieldnames=VCACHE_FIELDS) if cache_out else None
vhashes = {}
new_count = rehashed_count = errors = 0
n = len(files)
for i, path in enumerate(files, 1):
name = os.path.basename(path)
_progress_bar(i, n, name)
try:
st = os.stat(path)
except OSError as e:
_clear_bar()
print(f" Warning: skipped {name}: {e}", flush=True)
errors += 1
continue
size, mtime = st.st_size, st.st_mtime
cache_key = path_without_drive(path)
cached = cache.get(cache_key)
metadata_ok = (cached and cached["size"] == size
and abs(cached["mtime"] - mtime) < _TS_TOLERANCE)
is_new = not cached
if metadata_ok:
dur = cached["duration"]
frames = [int(h, 16) for h in cached["vhash"]]
else:
try:
dur, frames = compute_video_hashes(path)
except Exception as e:
_clear_bar()
print(f" Warning: skipped ({fmt_size(size).strip()}) {_fmt_path(path)}", flush=True)
errors += 1
continue
hex_frames = [format(h, "016x") for h in frames]
cache[cache_key] = {
"size": size, "mtime": mtime,
"duration": dur, "vhash": hex_frames,
}
if writer:
writer.writerow({
"path": cache_key, "size": size, "mtime": mtime,
"duration": dur, "vhash": ",".join(hex_frames),
})
# Flush after every video: each hash takes several seconds, so a
# per-entry flush (rather than the 200-entry batch used for images)
# keeps data-loss on interrupt to at most one video's worth of work.
cache_out.flush()
if is_new:
new_count += 1
else:
rehashed_count += 1
vhashes[path] = (dur, frames, size)
print() # end progress line
return vhashes, new_count, rehashed_count, errors
def _video_distance(frames_a: list, frames_b: list) -> float:
"""Mean per-frame pHash Hamming distance between two frame sequences."""
n = min(len(frames_a), len(frames_b))
if n == 0:
return float("inf")
return sum((frames_a[i] ^ frames_b[i]).bit_count() for i in range(n)) / n
def group_video_duplicates(vhashes: dict, threshold: int) -> list:
"""Group videos by perceptual similarity using mean frame Hamming distance.
Pre-filters candidate pairs by duration: videos must be within
max(10 s, 5% of the longer video) of each other. This targets re-encodes
and resolution variants; trimmed or offset clips will not match.
Returns groups in the same format as group_duplicates:
list of [(path, size_bytes), ...] largest-first, most-files-first.
"""
if not vhashes:
return []
# Sort by duration for the early-break inner loop.
paths = sorted(vhashes.keys(), key=lambda p: vhashes[p][0])
# Union-Find with path compression: groups transitively similar videos so that
# if A~B and B~C they end up in the same component even when A and C are never
# directly compared. A simple "add to list" approach would miss such chains.
parent = {p: p for p in paths}
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(x, y):
parent[find(x)] = find(y)
n = len(paths)
for i in range(n):
pa = paths[i]
dur_a, frames_a, _ = vhashes[pa]
for j in range(i + 1, n):
pb = paths[j]
dur_b, frames_b, _ = vhashes[pb]
# dur_b >= dur_a (sorted ascending).
# tol grows with dur_b, so once the gap exceeds it the break holds
# for all larger dur_b values (monotone).
tol = max(10.0, 0.05 * dur_b)
if dur_b - dur_a > tol:
break
if _video_distance(frames_a, frames_b) <= threshold:
union(pa, pb)
groups_map: dict = {}
for p in paths:
groups_map.setdefault(find(p), []).append(p)
groups = []
for members in groups_map.values():
if len(members) < 2:
continue
group = sorted(
[(p, vhashes[p][2]) for p in members],
key=lambda x: x[1],
reverse=True,
)
groups.append(group)
groups.sort(key=lambda g: (-len(g), -g[0][1]))
return groups
# ── Exact-match logic ──────────────────────────────────────────────────────────
def _collect_stale(files: list, db: dict) -> list:
"""Return paths from *files* needing checksum computation (new or stale).
Stale entries are removed from *db* in-place only when the file is confirmed
accessible and its metadata has changed. Transient OSErrors are ignored so
the cached entry survives until the next successful stat.
"""
to_compute = []
for path in files:
k = path_without_drive(path)
cached = db.get(k)
if cached:
try:
st = os.stat(path)
if (cached["size"] == st.st_size
and abs(cached["mtime"] - st.st_mtime) < _TS_TOLERANCE):
continue # cache hit
del db[k] # stale — metadata changed
except OSError:
pass
to_compute.append(path)
return to_compute
def build_exact_index(all_files: list, db_path: str) -> tuple:
"""Load/update all_media_sha_hash_db.csv; compute checksums for new or stale files.
Returns (db, new_count, gone_count, errors).
db is keyed by path_without_drive.
"""
db = _load_db(db_path)
live_keys = {path_without_drive(p) for p in all_files}
# Remove entries for files no longer on disk.
gone_count = 0
gone = [k for k in db if k not in live_keys]
for k in gone:
del db[k]
gone_count += 1
# Identify new files and stale entries (metadata changed).
to_compute = _collect_stale(all_files, db)
new_count = errors = 0
n = len(to_compute)
for i, path in enumerate(to_compute, 1):
if i % 50 == 0 or i == n:
_progress_bar(i, n, os.path.basename(path))
try:
st = os.stat(path)
checksum = _file_checksum(path)
except Exception as e:
_clear_bar()
print(f" Warning: skipped {os.path.basename(path)}: {e}", flush=True)
errors += 1
continue
k = path_without_drive(path)
db[k] = {
"path": k,
"size": st.st_size,
"ctime": st.st_ctime,
"mtime": st.st_mtime,
"checksum": checksum,
}
new_count += 1
if n > 0:
print() # end progress line
_save_db(db_path, db)
return db, new_count, gone_count, errors
def group_exact_duplicates(db: dict, abs_path_map: dict) -> list:
"""Group files in db by checksum into duplicate groups.
db: {path_without_drive -> entry}
abs_path_map: {path_without_drive -> abs_path}
Returns list of groups, each group = [(abs_path, size), ...] largest-first.
"""
by_checksum: dict = {}
for k, entry in db.items():
by_checksum.setdefault(entry["checksum"], []).append((k, entry["size"]))
groups = []
for items in by_checksum.values():
if len(items) < 2:
continue
group = sorted(
[(abs_path_map.get(k, k), size) for k, size in items],
key=lambda x: x[1],
reverse=True,
)
groups.append(group)
groups.sort(key=lambda g: (-len(g), -g[0][1]))
return groups
def _update_checksums_additive(files: list, db_path: str) -> tuple:
"""Load db_path, compute checksums for new/stale files in *files*, save.
Unlike build_exact_index, entries for files *not* in *files* are preserved
(so image entries in a shared all_media_sha_hash_db.csv are not removed when only videos
are being indexed). Returns (db, new_count, errors).
"""
db = _load_db(db_path)
to_compute = _collect_stale(files, db)
new_count = errors = 0
n = len(to_compute)
for i, path in enumerate(to_compute, 1):
if i % 50 == 0 or i == n:
_progress_bar(i, n, os.path.basename(path))
try:
st = os.stat(path)
checksum = _file_checksum(path)
except Exception as e:
_clear_bar()
print(f" Warning: skipped {os.path.basename(path)}: {e}", flush=True)
errors += 1
continue
k = path_without_drive(path)
db[k] = {"path": k, "size": st.st_size, "ctime": st.st_ctime,
"mtime": st.st_mtime, "checksum": checksum}
new_count += 1
if n > 0:
print()
_save_db(db_path, db)
return db, new_count, errors
# ── Output ─────────────────────────────────────────────────────────────────────
def _exact_group_keep(group: list, ignore: tuple, directory: str) -> tuple:
"""Return (keep_path, final_path) for an exact-mode duplicate group.
keep_path — the replica with the best-scored folder (the file left in place).
final_path — keep_path's directory combined with the best filename from any
replica. When a file in a well-named folder has a generic name,
it can adopt a more descriptive name from another replica without
moving to a different directory.
"""
files = [{"path": p, "name": os.path.basename(p), "dir": str(Path(p).parent)}
for p, _ in group]
keep_path = _pick_keeper(files, ignore, directory)
best_name = os.path.basename(keep_path)
best_ns = _name_score(best_name, ignore)
for f in files:
ns = _name_score(f["name"], ignore)
if ns > best_ns:
best_ns, best_name = ns, f["name"]
return keep_path, os.path.join(str(Path(keep_path).parent), best_name)
def _print_group_files(group: list, keep_path: str, final_path: str) -> None:
"""Print keep/remove lines for an exact-mode group."""
for path, _ in sorted(group, key=lambda x: x[0] == keep_path):
label = "keep " if path == keep_path else "remove"
print(f" {label} {path}")
if path == keep_path and os.path.normpath(final_path) != os.path.normpath(keep_path):
print(f" -> {final_path}")
def print_results(groups: list, directory: str,
exact: bool = False, ignore: tuple = ()) -> None:
if not groups:
print("\nNo duplicate groups found.")
return
total_files = sum(len(g) for g in groups)
# Bytes that could be freed if all but the largest copy were removed
wasted_bytes = sum(size for g in groups for _, size in g[1:])
print(f"\nFound {len(groups)} duplicate group(s) * "
f"{total_files} files * "