#!/usr/bin/env python3 """Trash render/build leftovers without ever losing a unique final video. Usage: python3 trash_render_leftovers.py targets.json [--apply] Dry-run by default: nothing is moved unless --apply is given. targets.json: [["", "", "full|partial"], ...] full : everything under target goes, except videos with no identical copy (same size AND same SHA256) elsewhere in the project root. partial : only frame dirs (>=50 images in one dir) and videos that have an identical copy elsewhere. KEEP names (exact basenames) are never moved: add them with --keep a.mp4,b.mp4. Skips a target if `lsof +D` shows any holder. Writes .log.json with GB moved and the list of kept videos per target. Uses /usr/bin/trash only. """ import hashlib, json, os, subprocess, sys VID = {".mp4", ".mov", ".webm", ".mkv"} IMG = {".jpg", ".jpeg", ".png", ".webp"} args = sys.argv[1:] dry = "--apply" not in args keep = set() if "--keep" in args: keep = set(args[args.index("--keep") + 1].split(",")) cfg = [a for a in args if a.endswith(".json")][0] HEDEF = json.load(open(cfg)) def ext(p): return os.path.splitext(p)[1].lower() def sha256(p): h = hashlib.sha256() with open(p, "rb") as fh: for chunk in iter(lambda: fh.read(1 << 20), b""): h.update(chunk) return h.hexdigest() def copy_sizes(root, target): """Map size -> list of video paths outside target (hash computed lazily).""" s = {} for d, dn, fn in os.walk(root): if d == target or d.startswith(target + "/"): dn[:] = [] continue for f in fn: if ext(f) in VID: p = os.path.join(d, f) try: s.setdefault(os.path.getsize(p), []).append(p) except OSError: pass return s _hash_cache = {} def has_identical_copy(path, sizes): size = os.path.getsize(path) if size not in sizes: return False try: h = _hash_cache.setdefault(path, sha256(path)) for other in sizes[size]: if _hash_cache.setdefault(other, sha256(other)) == h: return True except OSError: return False return False def plan(path, mode, sizes, kept): try: ents = list(os.scandir(path)) except OSError: return False, [] nimg = sum(1 for e in ents if e.is_file() and ext(e.name) in IMG) allok, out = True, [] for e in ents: if e.is_symlink(): allok = False continue if e.is_dir(): ok, sub = plan(e.path, mode, sizes, kept) if ok: out.append(e.path) else: allok = False out += sub continue x = ext(e.name) if x in VID: ok = e.name not in keep and has_identical_copy(e.path, sizes) elif e.name == ".DS_Store": ok = True elif mode == "full": ok = True else: ok = x in IMG and nimg >= 50 if ok: out.append(e.path) else: allok = False kept.append(e.path) return allok, out def kb(p): r = subprocess.run(["du", "-sk", p], capture_output=True, text=True) try: return int(r.stdout.split()[0]) except Exception: return 0 log = [] for root, rel, mode in HEDEF: t = os.path.join(root, rel) if not os.path.isdir(t): log.append({"target": t, "status": "missing"}) continue holders = subprocess.run(["lsof", "+D", t], capture_output=True, text=True).stdout.splitlines()[1:] if holders: log.append({"target": t, "status": "IN_USE", "lsof": holders[:3]}) continue kept = [] ok, lst = plan(t, mode, copy_sizes(root, t), kept) if ok: lst = [t] size = sum(kb(p) for p in lst) if not dry: for i in range(0, len(lst), 200): subprocess.run(["/usr/bin/trash"] + lst[i:i + 200], check=True) log.append({"target": t, "mode": mode, "gb": round(size / 1048576, 2), "items": len(lst), "kept_videos": [p.replace(root + "/", "") for p in kept if ext(p) in VID]}) json.dump(log, open(cfg.replace(".json", ".log.json"), "w"), ensure_ascii=False, indent=1) for k in log: print(json.dumps(k, ensure_ascii=False)) print("DRY_RUN (use --apply to move to Trash)" if dry else "TRASHED", "TOTAL_GB", round(sum(k.get("gb", 0) for k in log), 2))