music-audit: move duplicates to a reversible trash with a manifest
trash-duplicates.py acts on the AcoustID duplicate report: for each group it keeps the nominated file and moves the extra copies into a dated folder, preserving their path relative to the library root so any batch can be restored in place. Two guards matter: a group is skipped entirely if its keeper no longer exists (a recording must never lose its last copy), and every move is recorded in a JSON manifest. First run: 999 files, 11.91 GiB, 14 groups skipped (sources already gone), 0 failures; keepers verified present afterwards and free space went 13G -> 27G.
This commit is contained in:
1 parent
72ac6b0cc6
commit
7a27c78476
1 file changed
+95
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Move duplicate files to a dated trash folder. Reversible, never deletes.
|
||||
|
||||
Built around two safety rules:
|
||||
|
||||
* the nominated keeper must still exist, otherwise the group is skipped
|
||||
entirely — a recording must never end up with zero copies;
|
||||
* every moved file keeps its path relative to the library root, so restoring
|
||||
is a copy back into place.
|
||||
|
||||
A JSON manifest records what moved where and why.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOTS = ["/mnt/MediaDisk/Music/MyLibrary", "/mnt/MediaOverflow/arr/library/Music"]
|
||||
|
||||
|
||||
def relpath(path: str):
|
||||
for root in ROOTS:
|
||||
if path.startswith(root.rstrip("/") + "/"):
|
||||
return os.path.relpath(path, root)
|
||||
return None
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--report", default="/var/lib/beets/duplicates.json")
|
||||
ap.add_argument("--trash", default="/mnt/MediaDisk/Music-Trash")
|
||||
ap.add_argument("--only-min-copies", type=int, default=0,
|
||||
help="only act on groups with at least this many removable copies")
|
||||
ap.add_argument("--move", action="store_true")
|
||||
args = ap.parse_args()
|
||||
|
||||
stamp = time.strftime("%Y%m%dT%H%M%S")
|
||||
report = json.load(open(args.report))
|
||||
|
||||
moved, skipped, failed = [], [], []
|
||||
for group in report["exact"]:
|
||||
if args.only_min_copies and len(group["remove"]) < args.only_min_copies:
|
||||
continue
|
||||
keep = group["keep"]
|
||||
if not os.path.exists(keep):
|
||||
skipped.append({"group": group.get("title"), "reason": "keeper missing", "keep": keep})
|
||||
continue
|
||||
for src in group["remove"]:
|
||||
if src == keep or not os.path.exists(src):
|
||||
skipped.append({"group": group.get("title"), "reason": "source missing", "path": src})
|
||||
continue
|
||||
rel = relpath(src)
|
||||
if rel is None:
|
||||
skipped.append({"group": group.get("title"), "reason": "outside known roots", "path": src})
|
||||
continue
|
||||
dest = os.path.join(args.trash, stamp, rel)
|
||||
entry = {"path": src, "moved_to": dest, "keeper": keep,
|
||||
"title": group.get("title"), "artist": group.get("artist"),
|
||||
"recording_id": group.get("recording_id"),
|
||||
"size": os.path.getsize(src)}
|
||||
if args.move:
|
||||
try:
|
||||
os.makedirs(os.path.dirname(dest), exist_ok=True)
|
||||
shutil.move(src, dest)
|
||||
moved.append(entry)
|
||||
except OSError as e:
|
||||
entry["error"] = str(e)[:120]
|
||||
failed.append(entry)
|
||||
else:
|
||||
moved.append(entry)
|
||||
|
||||
total = sum(e["size"] for e in moved)
|
||||
verb = "moved" if args.move else "would move"
|
||||
print("%s %d files (%.2f GiB); skipped %d; failed %d"
|
||||
% (verb, len(moved), total / 2**30, len(skipped), len(failed)))
|
||||
for e in moved[:5]:
|
||||
print(" %-64s -> trash" % e["path"].split("/", 4)[-1][:64])
|
||||
for e in failed[:3]:
|
||||
print(" FAILED %s (%s)" % (e["path"][-50:], e.get("error")))
|
||||
|
||||
manifest = "/var/lib/beets/duplicate-trash-%s.json" % stamp
|
||||
if args.move:
|
||||
with open(manifest, "w") as f:
|
||||
json.dump({"stamp": stamp, "trash_dir": os.path.join(args.trash, stamp),
|
||||
"roots": ROOTS, "moved": moved, "skipped": skipped, "failed": failed}, f, indent=1)
|
||||
print("manifest: %s" % manifest)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user