diff --git a/tools/music-audit/trash-duplicates.py b/tools/music-audit/trash-duplicates.py new file mode 100644 index 0000000..4219966 --- /dev/null +++ b/tools/music-audit/trash-duplicates.py @@ -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())