"""Sort images in a Drive folder into aspect-ratio subfolders (16x9, 4x3, 3x2, 1x1, 5x4, 21x9, 2x1, Diğer). Usage: python3 drive_sort_by_ratio.py FOLDER_ID [TOKEN_PATH] - Needs the drive service (setup.py --services ...,drive) and the user's approval: it moves files inside their Drive. - Orientation-agnostic: ratio = long/short side, so 9:16 lands in 16x9. - 2% tolerance to the nearest standard ratio, else 'Diğer' (printed with size). - Exact duplicates (same md5Checksum anywhere in the folder tree): the earliest upload stays, later ones are MOVED to 'Kopyalar'. Nothing is ever deleted. - Idempotent: only processes images still in the root folder, so re-run it while/after the user is uploading. Prints per-folder totals for verification. """ import os, sys, collections from pathlib import Path from google.oauth2.credentials import Credentials from googleapiclient.discovery import build sys.path.insert(0, str(Path(__file__).resolve().parent)) from _hermes_home import get_hermes_home ROOT = sys.argv[1] TOKEN = sys.argv[2] if len(sys.argv) > 2 else os.path.expanduser( os.environ.get('GOOGLE_TOKEN_PATH', str(get_hermes_home() / 'google_token.json'))) TOL = 0.02 RATIOS = [("16x9", 16/9), ("4x3", 4/3), ("3x2", 3/2), ("1x1", 1.0), ("5x4", 5/4), ("21x9", 21/9), ("2x1", 2.0)] FOLDER_MIME = 'application/vnd.google-apps.folder' s = build('drive', 'v3', credentials=Credentials.from_authorized_user_file(TOKEN)) def ls(q, fields="files(id,name,mimeType,md5Checksum,createdTime,parents,imageMediaMetadata(width,height))"): out, t = [], None while True: r = s.files().list(q=q, fields="nextPageToken," + fields, pageSize=1000, pageToken=t).execute() out += r['files']; t = r.get('nextPageToken') if not t: return out _cache = {} def folder(name): if name not in _cache: ex = ls(f"'{ROOT}' in parents and trashed=false and mimeType='{FOLDER_MIME}' and name='{name}'", "files(id)") _cache[name] = ex[0]['id'] if ex else s.files().create( body={'name': name, 'mimeType': FOLDER_MIME, 'parents': [ROOT]}, fields='id').execute()['id'] return _cache[name] def move(f, dest): s.files().update(fileId=f['id'], addParents=folder(dest), removeParents=ROOT, fields='id').execute() def bucket(w, h): r = max(w, h) / min(w, h) name, val = min(RATIOS, key=lambda x: abs(r - x[1]) / x[1]) return name if abs(r - val) / val <= TOL else "Diğer" subs = ls(f"'{ROOT}' in parents and trashed=false and mimeType='{FOLDER_MIME}'", "files(id,name)") parents_q = " or ".join([f"'{ROOT}' in parents"] + [f"'{x['id']}' in parents" for x in subs]) imgs = ls(f"trashed=false and mimeType contains 'image/' and ({parents_q})") first = {} for f in sorted(imgs, key=lambda f: f['createdTime']): first.setdefault(f.get('md5Checksum'), f['id']) log, other = collections.Counter(), [] for f in [f for f in imgs if ROOT in f.get('parents', [])]: if first.get(f.get('md5Checksum')) != f['id']: move(f, "Kopyalar"); log["Kopyalar"] += 1; continue m = f.get('imageMediaMetadata') or {} if not m.get('width'): log["no-size (left in root)"] += 1; continue # still uploading/processing b = bucket(m['width'], m['height']); move(f, b); log[b] += 1 if b == "Diğer": other.append(f"{f['name']} {m['width']}x{m['height']}") print("moved this run:", dict(log)) if other: print("Diğer:", other) tot = collections.Counter({fo['name']: len(ls(f"'{fo['id']}' in parents and trashed=false", "files(id)")) for fo in ls(f"'{ROOT}' in parents and trashed=false and mimeType='{FOLDER_MIME}'", "files(id,name)")}) tot["(root, unprocessed)"] = len(ls(f"'{ROOT}' in parents and trashed=false and mimeType contains 'image/'", "files(id)")) uniq = sum(v for k, v in tot.items() if k not in ("Kopyalar", "(root, unprocessed)")) print("TOTALS:", dict(tot), "| unique sorted:", uniq)