"""Step 1: download the metadata, select the datasets that qualify, download their data and videos, and download the DINOv2 ViT-S/14 weights. Needs internet; on clusters whose compute nodes are offline, run it on a login node. Re-running resumes: files already present are skipped. python scripts/download.py --work $POPT_WORK python scripts/download.py --work $POPT_WORK --only kantine/so100_kapla_tower6,DorayakiLin/so100_stack_cube Writes /raw/ (a copy of the repository at the pinned revision, selected datasets only), /selection.json (kept datasets, dropped datasets with the reason) and /weights/dinov2_vits14_pretrain.pth. """ import argparse import hashlib import os import sys import time import urllib.request from huggingface_hub import HfApi, snapshot_download sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from popt.common import (DINO_SHA256, DINO_URL, REPO, REVISION, dataset_check, read_json, # noqa: E402 work_dirs, write_json) def retry(fn, what: str, tries: int = 30): """The Hub rate-limits large downloads; wait and resume instead of failing.""" for k in range(tries): try: return fn() except Exception as e: # noqa: BLE001 if k == tries - 1: raise wait = min(600, 30 * (k + 1)) print(f"[{what}] attempt {k + 1} failed ({type(e).__name__}: {str(e)[:200]}); retrying in {wait} s", flush=True) time.sleep(wait) def sha256(path: str) -> str: h = hashlib.sha256() with open(path, "rb") as f: for b in iter(lambda: f.read(1 << 22), b""): h.update(b) return h.hexdigest() def dataset_of(path: str) -> str | None: parts = path.split("/") for k, p in enumerate(parts): if p in ("meta", "data", "videos") and k >= 1: return "/".join(parts[:k]) return None def main(): p = argparse.ArgumentParser() p.add_argument("--work", default=os.environ.get("POPT_WORK"), required=os.environ.get("POPT_WORK") is None) p.add_argument("--revision", default=REVISION) p.add_argument("--target-fps", type=int, default=int(os.environ.get("TARGET_FPS", 10))) p.add_argument("--only", default="", help="comma-separated dataset ids (smoke tests)") p.add_argument("--workers", type=int, default=16, help="parallel file downloads") p.add_argument("--skip-weights", action="store_true") a = p.parse_args() D = work_dirs(a.work) for k in ("raw", "weights"): os.makedirs(D[k], exist_ok=True) token = os.environ.get("HF_TOKEN") # optional; raises the Hub's rate limits # 1. file list and metadata files = retry(lambda: HfApi().list_repo_files(REPO, repo_type="dataset", revision=a.revision, token=token), "list") dsets: dict[str, set] = {} for f in files: d = dataset_of(f) if d: dsets.setdefault(d, set()).add(f[len(d) + 1:].split("/")[0]) print(f"revision {a.revision}: {len(files)} files, {len(dsets)} datasets", flush=True) only = [s for s in a.only.split(",") if s] if only: missing = [s for s in only if s not in dsets] assert not missing, f"not in the repository: {missing}" dsets = {d: dsets[d] for d in only} meta_patterns = ["PROCESSING_SUMMARY.json"] + [f"{d}/meta/*" for d in dsets] retry(lambda: snapshot_download(REPO, repo_type="dataset", revision=a.revision, local_dir=D["raw"], allow_patterns=meta_patterns, max_workers=a.workers, token=token), "meta") # 2. dataset-level selection kept, dropped = [], {} for d in sorted(dsets): info_p = os.path.join(D["raw"], d, "meta", "info.json") reason = dataset_check(read_json(info_p) if os.path.exists(info_p) else None, a.target_fps) if reason is None and "videos" not in dsets[d]: reason = "no_videos" if reason is None and "data" not in dsets[d]: reason = "no_data" if reason is None: kept.append(d) else: dropped[d] = reason reasons = {} for r in dropped.values(): reasons[r] = reasons.get(r, 0) + 1 write_json(D["selection"], {"repo": REPO, "revision": a.revision, "target_fps": a.target_fps, "kept": kept, "dropped": dropped, "dropped_by_reason": reasons}) print(f"selection: {len(kept)} kept, {len(dropped)} dropped {reasons}", flush=True) # 3. data and videos of the kept datasets, except those already turned into a shard (step 2 with --delete-raw # removes their videos; downloading them again would undo that) todo = [d for d in kept if not os.path.exists(os.path.join(D["shards"], d.replace("/", "__"), "DONE"))] pats = [f"{d}/{sub}/*" for d in todo for sub in ("data", "videos")] if pats: retry(lambda: snapshot_download(REPO, repo_type="dataset", revision=a.revision, local_dir=D["raw"], allow_patterns=pats, max_workers=a.workers, token=token), "data") print(f"data and videos downloaded ({len(todo)} datasets; {len(kept) - len(todo)} already in shards/)", flush=True) # 4. DINOv2 ViT-S/14 weights (the trunk of every PoP cell) if not a.skip_weights: if not (os.path.exists(D["dino"]) and sha256(D["dino"]) == DINO_SHA256): retry(lambda: urllib.request.urlretrieve(DINO_URL, D["dino"] + ".part"), "dinov2") os.replace(D["dino"] + ".part", D["dino"]) got = sha256(D["dino"]) assert got == DINO_SHA256, f"DINOv2 weights sha256 {got} != {DINO_SHA256}" print(f"DINOv2 weights ok ({D['dino']})", flush=True) print("download done", flush=True) if __name__ == "__main__": main()