"""Shared paths and helpers for set 5 (runs on the Colab VM). Everything durable goes to OUT_LOCAL first and is mirrored to Google Drive (OUT_DRIVE) after each model, so a disconnect loses at most the model in progress. Data and checkpoints stay on the VM's local disk (/content). """ from __future__ import annotations import hashlib import json import os import shutil import subprocess import time from pathlib import Path WORK = Path(os.environ.get("SET5_WORK", "/content/set5")) CKPT = WORK / "ckpt" DATA = WORK / "data" OUT_LOCAL = WORK / "out" DRIVE_ROOT = Path("/content/drive/MyDrive") OUT_DRIVE = DRIVE_ROOT / os.environ.get("SET5_DRIVE_DIR", "repa_probe") / "set5" for d in (WORK, CKPT, DATA, OUT_LOCAL): d.mkdir(parents=True, exist_ok=True) def log(*a): print(time.strftime("%H:%M:%S"), *a, flush=True) def sha256(path, chunk=1 << 24): h = hashlib.sha256() with open(path, "rb") as f: while b := f.read(chunk): h.update(b) return h.hexdigest() def write_json(path, obj): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(path.suffix + ".tmp") tmp.write_text(json.dumps(obj, indent=2, default=str)) os.replace(tmp, path) def drive_ok(): return DRIVE_ROOT.is_dir() def is_done(rel): """A unit of work is done when its marker exists locally or on Drive.""" return (OUT_LOCAL / rel).exists() or (drive_ok() and (OUT_DRIVE / rel).exists()) def mark_done(rel, info=None): write_json(OUT_LOCAL / rel, {"done": time.strftime("%Y-%m-%d %H:%M:%S"), **(info or {})}) sync_out() def sync_out(): """Mirror OUT_LOCAL to Drive (copy new or changed files; never delete on Drive).""" if not drive_ok(): log("[sync] Drive not mounted; results stay in", OUT_LOCAL) return False for src in OUT_LOCAL.rglob("*"): if src.is_dir() or src.suffix == ".tmp": continue dst = OUT_DRIVE / src.relative_to(OUT_LOCAL) if dst.exists() and dst.stat().st_size == src.stat().st_size and dst.stat().st_mtime >= src.stat().st_mtime: continue dst.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(src, dst) return True def disk_free_gb(path=None): return shutil.disk_usage(path or WORK).free / 1e9 def env_report(): smi = subprocess.run(["nvidia-smi"], capture_output=True, text=True).stdout df = subprocess.run(["df", "-h", str(WORK)], capture_output=True, text=True).stdout return smi, df