gnn_wm2 / download_0420_validation.py
EndeavourDD's picture
Upload folder using huggingface_hub (part 18)
4245ec7 verified
Raw History Blame Contribute Delete
6.43 kB
#!/usr/bin/env python3
"""Download the 6 GNN Hanoi 0420 balanced validation episodes.
Strategy (disk-safe): the HF folder holds ONE 91.8GB outer zip whose members are
6 *stored* inner episode zips. We range-extract one inner zip at a time (never
storing the full 92GB outer), unzip it into the session dir, then delete the
inner zip. Resumable: completed episodes are skipped.
"""
from __future__ import annotations
import json
import os
import shutil
import sys
import time
import zipfile
from pathlib import Path
os.environ.setdefault("HF_HUB_DISABLE_XET", "1")
os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1")
from huggingface_hub import hf_hub_url
from remotezip import RemoteZip
TOKEN = os.environ.get("HF_TOKEN")
REPO = "ChangChrisLiu/GNN_Disassembly_WorldModel"
OUTER = "validation/hanoi_0420_balanced/GNN_Hanoi_0420_balanced_validation_package.zip"
INNER_PREFIX = "GNN_Hanoi_0420_balanced_validation_package/data/"
SESSION_DIR = Path("/workspace/gnn_data/hanoi/session_hanoi_0420_132840")
STAGING = Path("/workspace/gnn_data/_dl_staging_0420")
STATUS = Path("/workspace/download_0420_status.json")
# smallest -> largest, so the pipeline is validated cheaply first
EPISODES = ["episode_14", "episode_12", "episode_00", "episode_15", "episode_07", "episode_10"]
# expected rgb frame counts from episodes.csv (completion check)
EXPECTED_FRAMES = {
"episode_00": 2598, "episode_07": 3013, "episode_10": 5218,
"episode_12": 1761, "episode_14": 1357, "episode_15": 2649,
}
MIN_FREE_GB = 15.0 # abort before filling the disk
def log(msg: str) -> None:
print(f"[{time.strftime('%Y-%m-%dT%H:%M:%S')}] {msg}", flush=True)
def free_gb() -> float:
st = shutil.disk_usage("/workspace")
return st.free / 1e9
def write_status(d: dict) -> None:
STATUS.write_text(json.dumps(d, indent=2), encoding="utf-8")
def url_with_headers():
url = hf_hub_url(repo_id=REPO, repo_type="dataset", filename=OUTER)
headers = {"Authorization": f"Bearer {TOKEN}"} if TOKEN else {}
return url, headers
def episode_complete(ep: str) -> bool:
rgb = SESSION_DIR / ep / "side" / "rgb"
if not rgb.is_dir():
return False
n = len(list(rgb.glob("frame_*.png")))
exp = EXPECTED_FRAMES.get(ep, 0)
return n >= exp > 0
def unzip_inner(inner_zip: Path, ep: str) -> None:
"""Unzip inner episode zip into SESSION_DIR/<ep>/ (strip any top-level prefix)."""
dest = SESSION_DIR / ep
dest.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(inner_zip) as z:
names = [n for n in z.namelist() if not n.endswith("/")]
# detect common top-level dir
tops = {n.split("/", 1)[0] for n in names}
strip = None
if len(tops) == 1:
only = next(iter(tops))
# strip if everything lives under a single folder (e.g. "episode_14/")
if all(n.startswith(only + "/") for n in names):
strip = only + "/"
total = len(names)
for i, n in enumerate(names, 1):
rel = n[len(strip):] if strip and n.startswith(strip) else n
if not rel:
continue
target = dest / rel
target.parent.mkdir(parents=True, exist_ok=True)
with z.open(n) as src, open(target, "wb") as out:
shutil.copyfileobj(src, out, length=8 * 1024 * 1024)
if i % 2000 == 0 or i == total:
log(f" {ep}: unzipped {i}/{total} files (free={free_gb():.1f}GB)")
def fetch_episode(ep: str, idx: int, status: dict) -> None:
member = f"{INNER_PREFIX}{ep}.zip"
STAGING.mkdir(parents=True, exist_ok=True)
inner_zip = STAGING / f"{ep}.zip"
if episode_complete(ep):
log(f"[{idx}/6] {ep}: already complete, skip")
status[ep] = "complete"; write_status(status); return
if free_gb() < MIN_FREE_GB:
raise RuntimeError(f"Aborting: free space {free_gb():.1f}GB < {MIN_FREE_GB}GB")
url, headers = url_with_headers()
# range-extract the inner zip (retry on transient failure)
status[ep] = "downloading"; write_status(status)
log(f"[{idx}/6] {ep}: range-extracting inner zip ... (free={free_gb():.1f}GB)")
t0 = time.time()
last_err = None
for attempt in range(1, 6):
try:
with RemoteZip(url, headers=headers) as rz:
info = rz.getinfo(member)
size_gb = info.file_size / 1e9
log(f" {ep}: inner zip = {size_gb:.2f}GB (attempt {attempt})")
# extract member into STAGING (writes STAGING/<INNER_PREFIX><ep>.zip)
rz.extract(member, path=str(STAGING))
extracted = STAGING / member
extracted.replace(inner_zip)
break
except Exception as e: # noqa: BLE001
last_err = e
log(f" {ep}: download attempt {attempt} failed: {e!r}; retrying in 10s")
time.sleep(10)
else:
raise RuntimeError(f"{ep}: all download attempts failed: {last_err!r}")
dl_gb = inner_zip.stat().st_size / 1e9
log(f"[{idx}/6] {ep}: downloaded {dl_gb:.2f}GB in {(time.time()-t0)/60:.1f} min (free={free_gb():.1f}GB)")
status[ep] = "unzipping"; write_status(status)
log(f"[{idx}/6] {ep}: unzipping into {SESSION_DIR/ep} ...")
unzip_inner(inner_zip, ep)
inner_zip.unlink(missing_ok=True)
# clean empty staging subdirs from extract()
shutil.rmtree(STAGING / "GNN_Hanoi_0420_balanced_validation_package", ignore_errors=True)
ok = episode_complete(ep)
status[ep] = "complete" if ok else "incomplete"
write_status(status)
log(f"[{idx}/6] {ep}: DONE (complete={ok}) (free={free_gb():.1f}GB)")
def main() -> None:
SESSION_DIR.mkdir(parents=True, exist_ok=True)
status = {}
if STATUS.exists():
try:
status = json.loads(STATUS.read_text())
except Exception: # noqa: BLE001
status = {}
log(f"start: target={SESSION_DIR} free={free_gb():.1f}GB token={'set' if TOKEN else 'NONE'}")
for i, ep in enumerate(EPISODES, 1):
fetch_episode(ep, i, status)
shutil.rmtree(STAGING, ignore_errors=True)
log("ALL EPISODES DONE")
for ep in EPISODES:
rgb = SESSION_DIR / ep / "side" / "rgb"
n = len(list(rgb.glob("frame_*.png"))) if rgb.is_dir() else 0
log(f" {ep}: {n} rgb frames status={status.get(ep)}")
if __name__ == "__main__":
main()