"""Acquire current official 5 fps annotations without local account credentials.""" from pathlib import Path import concurrent.futures import hashlib import json import sys import time import urllib.request ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "code/vendor")) import gdown import ijson import requests.sessions # Public downloads only: do not consult a user's .netrc or stored cookies. requests.sessions.get_netrc_auth = lambda *args, **kwargs: None def acquire(item): dest = ROOT / item["local_path"] dest.parent.mkdir(parents=True, exist_ok=True) print("START", item["local_path"], flush=True) try: gdown.download( id=item["drive_id"], output=str(dest), quiet=True, use_cookies=False, resume=True, timeout=(30, 120), retries=5, ) except gdown.exceptions.FileURLRetrievalError: # The public direct endpoint can work when Drive's HTML link resolver fails. url = ("https://drive.usercontent.google.com/download?id=" + item["drive_id"] + "&export=download&confirm=t") request = urllib.request.Request(url, headers={"User-Agent": "dataset-download-audit"}) partial = dest.with_suffix(dest.suffix + ".direct_partial") with urllib.request.urlopen(request, timeout=120) as response, partial.open("wb") as stream: if response.status != 200: raise RuntimeError("Unexpected partial response from direct annotation URL") expected = response.headers.get("Content-Length") count = 0 for block in iter(lambda: response.read(4 * 1024 * 1024), b""): stream.write(block) count += len(block) if expected is not None and count != int(expected): raise RuntimeError("Annotation download has incorrect length") partial.replace(dest) sha = hashlib.sha256() with dest.open("rb") as stream: for block in iter(lambda: stream.read(8 * 1024 * 1024), b""): sha.update(block) record = dict(item, bytes=dest.stat().st_size, sha256=sha.hexdigest()) if dest.suffix == ".json": # Consume every token, so a truncated response cannot pass as complete. counts = {"images": 0, "annotations": 0, "captures": 0} with dest.open("rb") as stream: for prefix, event, value in ijson.parse(stream): if prefix == "images.item" and event == "start_map": counts["images"] += 1 elif prefix == "annotations.item" and event == "start_map": counts["annotations"] += 1 elif prefix == "" and event == "map_key" and value.isdigit(): counts["captures"] += 1 record["json_counts"] = counts print("OK", item["local_path"], record["bytes"], flush=True) return record def main(): items = json.loads((ROOT / "audit/annotations_manifest.json").read_text()) results, failures = [], [] with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool: pending = {pool.submit(acquire, item): item for item in items} for future in concurrent.futures.as_completed(pending): item = pending[future] try: results.append(future.result()) except Exception as exc: failures.append({"path": item["local_path"], "error": str(exc)}) print("FAILED", item["local_path"], type(exc).__name__, flush=True) report = {"complete": len(results) == len(items), "updated_unix": time.time(), "verified": sorted(results, key=lambda x: x["local_path"]), "failures": failures} temp = ROOT / "audit/annotations_verification.json.tmp" temp.write_text(json.dumps(report, indent=2) + "\n") temp.replace(ROOT / "audit/annotations_verification.json") if failures: raise SystemExit(1) if __name__ == "__main__": main()