#!/usr/bin/env python3 """Move byte-identical project assets into /_ortak/ and leave relative symlinks. Usage: python3 dedupe_shared_assets.py [...] [--sub assets/fonts --sub assets/voices] [--do] Dry-run by default (prints PLAN lines). Each root is a folder of sibling projects (e.g. 'Video Projeleri', 'YouTube Lab/Uretim'). A file is consolidated only when the same path under /assets/ has the SAME md5 in >=2 projects; a path that has different contents in different projects is skipped (SKIP line). Originals go to the macOS Trash via /usr/bin/trash; every symlink is re-hashed after creation. One _ortak per root, never across roots: render servers often reject symlinks resolving outside their own tree. """ import os, sys, hashlib, subprocess, collections args = sys.argv[1:] do = '--do' in args subs = [args[i + 1] for i, a in enumerate(args) if a == '--sub'] or ['assets/fonts', 'assets/voices'] roots = [a for i, a in enumerate(args) if not a.startswith('--') and (i == 0 or args[i - 1] != '--sub')] def md5(p): h = hashlib.md5() with open(p, 'rb') as f: for c in iter(lambda: f.read(1 << 20), b''): h.update(c) return h.hexdigest() for R in map(os.path.expanduser, roots): groups = collections.defaultdict(list) for proj in sorted(os.listdir(R)): if proj.startswith(('_', '.')): continue for sub in subs: base = os.path.join(R, proj, sub) if not os.path.isdir(base): continue for dp, _, fn in os.walk(base): for f in fn: p = os.path.join(dp, f) if os.path.islink(p) or f == '.DS_Store': continue rel = os.path.relpath(p, os.path.join(R, proj, 'assets')) groups[(rel, md5(p))].append(p) per_rel = collections.Counter(k[0] for k in groups) saved = 0 for (rel, h), ps in sorted(groups.items()): if len(ps) < 2: continue if per_rel[rel] > 1: print('SKIP different content', rel) continue dst = os.path.join(R, '_ortak', rel) size = os.path.getsize(ps[0]) print('DO' if do else 'PLAN', rel, len(ps), 'copies', size // 1024, 'KB') if not do: continue if os.path.exists(dst): print(' destination exists, skipped') continue os.makedirs(os.path.dirname(dst), exist_ok=True) subprocess.run(['cp', '-p', ps[0], dst], check=True) assert md5(dst) == h for p in ps: subprocess.run(['/usr/bin/trash', p], check=True) os.symlink(os.path.relpath(dst, os.path.dirname(p)), p) assert md5(p) == h saved += size * (len(ps) - 1) print(R, 'saved MB', round(saved / 2**20, 1))