MMTA-v1.0 / processing /download.py
Lishenyi04's picture
Add six source-processing recipes and document local reconstruction
2e6f68f verified
Raw History Blame Contribute Delete
15.2 kB
#!/usr/bin/env python3
"""Download original datasets from official sources for local reconstruction.
Run with --dry-run to inspect a download plan. No restricted data are hosted
by MMTA. Account approval and source agreements must be completed upstream.
Downloads and private derivatives must remain outside this release tree.
"""
from __future__ import annotations
import argparse
import fnmatch
import hashlib
import json
import os
import shutil
import subprocess
import sys
import urllib.parse
import urllib.request
from pathlib import Path, PurePosixPath
RELEASE = Path(__file__).resolve().parents[1]
CUHK_PORTAL = "https://aiot-public-dataset-cuhk-x.cuhkaiot.com"
HF_REPOS = {
"covla": "turing-motors/CoVLA-Dataset",
"agibot": "agibot-world/AgiBotWorld2026",
"sp500": "Wenyan0110/Multimodal-Dataset-Image_Text_Table_TimeSeries-for-Financial-Time-Series-Forecasting",
"terra": "onedean/Terra",
}
PIXELREC = {
"covers": ("file", "17V70KN6UOAdphNEc0wXlocFwgmI7hVOo", "covers.archive"),
"interactions": ("folder", "1vR1lgQUZCy1cuhzPkM2q7AsdYRP43feQ", "interactions"),
"item-info": ("folder", "1rXBM-zi5sSdLHNshXWtGgVReWLuYNgDB", "item-info"),
"pixel200k": ("file", "1fu0tqCmmXkte5PAsyMo0DQrDS0zofTLH", "Pixel200K.archive"),
}
HOLOASSIST = {
"videos": "video_compress.tar", "eyes": "eyes.tar", "head": "head.tar", "imu": "imu.tar",
"annotations": "data-annotation-trainval-v1_1.json", "splits": "data-splits-v1_2.zip",
}
PHYSIONET = {"mimiciv": "3.1", "mimic-cxr-jpg": "2.1.0", "mimic-cxr": "2.1.0", "mimic-iv-note": "2.2"}
TERRA_PORTAL = "https://hkustgz-my.sharepoint.com/:f:/g/personal/wchen110_connect_hkust-gz_edu_cn/Ev1pUSErKghFkzmXb5j7svgBf2XwMn095VNz1kOOtjhTXA?e=lUCxZb"
def relative_path(raw: str) -> str:
path = PurePosixPath(raw)
if not raw or path.is_absolute() or any(x in {"..", "."} for x in path.parts) or "\\" in raw or ":" in raw or raw != path.as_posix():
raise ValueError(f"Expected a normalized relative file path: {raw}")
return raw
def download_url(url: str, target: Path, expected_sha256: str | None = None) -> None:
"""Stream a public URL to an atomic file and reject failed/HTML downloads."""
target.parent.mkdir(parents=True, exist_ok=True)
partial = target.with_name(target.name + ".partial")
request = urllib.request.Request(url, headers={"User-Agent": "MMTA-source-downloader/1.0"})
digest = hashlib.sha256()
received = 0
with urllib.request.urlopen(request, timeout=120) as response, partial.open("wb") as handle:
content_type = response.headers.get("Content-Type", "").lower()
expected_length = response.headers.get("Content-Length")
if "text/html" in content_type:
raise RuntimeError("The source returned a web/login page. Complete upstream access steps and obtain a file-download URL.")
first = True
while block := response.read(8 * 1024 * 1024):
if first and block.lstrip().lower().startswith((b"<!doctype html", b"<html")):
raise RuntimeError("The source returned HTML instead of a data file")
first = False
digest.update(block)
handle.write(block)
received += len(block)
if not partial.stat().st_size:
raise RuntimeError("The download was empty")
if expected_length and received != int(expected_length):
raise RuntimeError("The source download ended before all advertised bytes were received")
if expected_sha256 and digest.hexdigest() != expected_sha256:
raise RuntimeError("The downloaded file failed SHA-256 verification")
partial.replace(target)
print(json.dumps({"file": str(target), "bytes": target.stat().st_size, "sha256": digest.hexdigest()}))
def hf_download(args: argparse.Namespace) -> None:
repo = HF_REPOS[args.dataset]
patterns = args.include or (["*.tar.gz", "*.jsonl", "metadata*", "README.md"] if args.dataset == "covla" else ["*"])
if args.dataset == "agibot" and not args.include:
patterns = ["task_3641/*", "task_3777/*", "task3641/*", "task3777/*", "README.md"]
if args.dry_run:
print(json.dumps({"method": "huggingface_hub.snapshot_download", "repo_id": repo, "revision": args.revision,
"allow_patterns": patterns, "output": str(args.output), "token_environment": "HF_TOKEN"}, indent=2))
return
try:
from huggingface_hub import HfApi, snapshot_download
except ImportError as exc:
raise RuntimeError("Install huggingface-hub from processing/requirements.txt") from exc
token = os.environ.get("HF_TOKEN") or None
info = HfApi().dataset_info(repo_id=repo, revision=args.revision, token=token)
matched = [entry.rfilename for entry in info.siblings if any(fnmatch.fnmatch(entry.rfilename, pattern) for pattern in patterns)]
if not matched:
raise RuntimeError("No upstream files matched --include")
snapshot_download(repo_id=repo, repo_type="dataset", revision=info.sha, local_dir=args.output,
allow_patterns=patterns, token=token, max_workers=args.workers)
args.output.mkdir(parents=True, exist_ok=True)
(args.output / "download-provenance.json").write_text(json.dumps({"source": repo, "revision": info.sha, "files": matched}, indent=2) + "\n")
def pixelrec_download(args: argparse.Namespace) -> None:
components = args.component or ["pixel200k"]
for name in components:
if name not in PIXELREC:
raise ValueError(f"PixelRec components: {', '.join(PIXELREC)}")
kind, identifier, filename = PIXELREC[name]
url = f"https://drive.google.com/{'file/d' if kind == 'file' else 'drive/folders'}/{identifier}"
if args.dry_run:
print(json.dumps({"component": name, "url": url, "method": "gdown", "output": str(args.output / filename)}))
continue
try:
import gdown
except ImportError as exc:
raise RuntimeError("Install gdown from processing/requirements.txt") from exc
args.output.mkdir(parents=True, exist_ok=True)
if kind == "folder":
result = gdown.download_folder(url=url, output=str(args.output / filename), quiet=False, remaining_ok=True)
else:
result = gdown.download(id=identifier, output=str(args.output / filename), quiet=False, resume=True)
if not result:
raise RuntimeError(f"Official Google Drive download failed for {name}; use the upstream README to obtain access")
def mimic_download(args: argparse.Namespace) -> None:
if args.physionet_dataset not in PHYSIONET:
raise ValueError("Unknown PhysioNet dataset")
version = args.version or PHYSIONET[args.physionet_dataset]
if not version or any(character not in "0123456789." for character in version):
raise ValueError("Expected a numeric PhysioNet version")
base = f"https://physionet.org/files/{args.physionet_dataset}/{version}/"
paths = list(args.file or [])
if args.file_list:
paths.extend(line.strip() for line in args.file_list.read_text().splitlines() if line.strip() and not line.lstrip().startswith("#"))
if not paths:
raise ValueError("Use --file or --file-list to select personally authorized source files; whole medical datasets are not downloaded implicitly")
for raw in paths:
path = relative_path(raw)
url = base + urllib.parse.quote(path, safe="/")
command = ["wget", "--continue", "--no-verbose", "--user", args.username or "PHYSIONET_USERNAME", "--ask-password",
"--output-document", str(args.output / args.physionet_dataset / path), url]
if args.dry_run:
print(json.dumps({"command": command, "access": "PhysioNet credentialing, training and dataset DUA acceptance are required."}))
continue
if not args.username:
raise ValueError("Supply --username or PHYSIONET_USERNAME; the password is requested by wget and is never written to the command line")
if not shutil.which("wget"):
raise RuntimeError("Install wget to download credentialed PhysioNet files")
if not sys.stdin.isatty():
raise RuntimeError("Run in a terminal so wget can ask for your PhysioNet password")
target = args.output / args.physionet_dataset / path
target.parent.mkdir(parents=True, exist_ok=True)
subprocess.run(command, check=True)
if not target.stat().st_size:
raise RuntimeError("PhysioNet returned an empty file")
def cuhk_download(args: argparse.Namespace) -> None:
files = [relative_path(raw) for raw in args.file or []]
if args.list_directory is not None:
directory = args.list_directory.strip("/")
if directory:
directory = relative_path(directory)
url = CUHK_PORTAL + "/api/files/" + urllib.parse.quote(directory, safe="/") + ("/" if directory else "")
if args.dry_run:
print(json.dumps({"listing_url": url}))
else:
with urllib.request.urlopen(url, timeout=60) as response:
print(json.dumps(json.load(response), indent=2))
return
if not files:
raise ValueError("Select official portal files with --file; use --list-directory CUHK-S/HAR to inspect archive names. Complete the upstream DUA first.")
for raw in files:
url = CUHK_PORTAL + "/data/" + urllib.parse.quote(raw, safe="/")
if args.dry_run:
print(json.dumps({"url": url, "output": str(args.output / raw)}))
else:
download_url(url, args.output / raw)
def public_download(args: argparse.Namespace) -> None:
if args.dataset == "holo_assist":
for component in args.component or ["annotations", "splits"]:
if component not in HOLOASSIST:
raise ValueError(f"HoloAssist components: {', '.join(HOLOASSIST)}")
filename = HOLOASSIST[component]
base = "https://holoassist.github.io/label_files/" if component == "splits" else "https://hl2data.z5.web.core.windows.net/holoassist-data-release/"
if args.dry_run:
print(json.dumps({"url": base + filename, "output": str(args.output / filename)}))
else:
download_url(base + filename, args.output / filename)
elif args.dataset == "future_factories":
command = ["kaggle", "datasets", "download", "-d", "ramyharik/ff-2024-08-13-multi-modal-dataset-33", "-p", str(args.output)]
if args.dry_run:
print(json.dumps({"command": command, "version": 1, "note": "Configure your own Kaggle account; this source archive is about 104 GB."}))
else:
if not shutil.which("kaggle"):
raise RuntimeError("Install the Kaggle CLI and configure your own Kaggle credentials")
args.output.mkdir(parents=True, exist_ok=True)
subprocess.run(command, check=True)
elif args.dataset == "terra":
if not args.url or not args.filename:
print(json.dumps({"official_dataset_folder": TERRA_PORTAL, "next_step": "Use the official folder to obtain a direct file-download URL, then pass --url and --filename."}, indent=2))
if not args.dry_run:
raise ValueError("Terra's public SharePoint folder is not a file URL. --url and --filename are required for an actual download")
return
parsed = urllib.parse.urlsplit(args.url)
if parsed.scheme != "https" or not parsed.hostname or not (parsed.hostname.endswith(".sharepoint.com") or parsed.hostname.endswith(".1drv.com")):
raise ValueError("Use a direct HTTPS file link from Terra's official SharePoint source")
name = relative_path(args.filename)
if args.dry_run:
print(json.dumps({"method": "official SharePoint direct file", "filename": name, "output": str(args.output / name)}))
else:
download_url(args.url, args.output / name, args.sha256)
def main(dataset: str | None = None) -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dataset", choices=["mimic", "pixelrec", "covla", "cuhk_x_har", "agibot", "sp500", "terra", "future_factories", "holo_assist"], required=dataset is None, default=dataset)
parser.add_argument("--output", type=Path, required=True, help="Local source directory outside the public release.")
parser.add_argument("--dry-run", action="store_true", help="Print a plan without network access or file writes.")
parser.add_argument("--accept-terms", action="store_true", help="Confirm that your own upstream access and source agreement requirements have been completed.")
parser.add_argument("--component", action="append", help="Source component to download; repeat as needed.")
parser.add_argument("--include", action="append", help="Hugging Face filename pattern; repeat as needed.")
parser.add_argument("--revision", default="main", help="Hugging Face revision; the resolved commit is recorded locally.")
parser.add_argument("--workers", type=int, default=4)
parser.add_argument("--file", action="append", help="Source-relative PhysioNet or CUHK file path.")
parser.add_argument("--file-list", type=Path, help="Private file list for PhysioNet, one source-relative path per line.")
parser.add_argument("--physionet-dataset", choices=list(PHYSIONET), default="mimiciv")
parser.add_argument("--version", help="PhysioNet version (defaults match the original benchmark sources).")
parser.add_argument("--username", default=os.environ.get("PHYSIONET_USERNAME"))
parser.add_argument("--list-directory", help="List a CUHK official portal directory.")
parser.add_argument("--url", help="Direct Terra file URL from the official SharePoint folder.")
parser.add_argument("--terra-source", choices=["sharepoint", "huggingface"], default="sharepoint",
help="Terra source: current SharePoint folder or original Hugging Face files. The original repository has no satellite archive.")
parser.add_argument("--filename", help="Local Terra download filename.")
parser.add_argument("--sha256", help="Optional expected Terra file SHA-256.")
args = parser.parse_args()
args.output = args.output.expanduser().resolve()
if args.output.is_relative_to(RELEASE):
parser.error("Raw downloads must be stored outside the MMTA public release directory")
if not args.dry_run and not args.accept_terms:
parser.error("Complete upstream requirements, then pass --accept-terms; --dry-run needs no access")
try:
if args.dataset in HF_REPOS and (args.dataset != "terra" or args.terra_source == "huggingface"):
hf_download(args)
elif args.dataset == "mimic":
mimic_download(args)
elif args.dataset == "pixelrec":
pixelrec_download(args)
elif args.dataset == "cuhk_x_har":
cuhk_download(args)
else:
public_download(args)
except (ValueError, RuntimeError, OSError, subprocess.CalledProcessError) as exc:
raise SystemExit(str(exc)) from exc
if __name__ == "__main__":
main()