M4Raw_brain / code /download_case.py
mylyu's picture
Add files using upload-large-folder tool
0c48aa5 verified
Raw History Blame Contribute Delete
2.78 kB
#!/usr/bin/env python3
"""Download one M4Raw Brain examination from Hugging Face."""
from __future__ import annotations
import argparse
import csv
from pathlib import Path
from huggingface_hub import hf_hub_download
REPO_ID = "mylyu/M4Raw_brain"
MANIFESTS = {
"T1": "metadata/T1_manifest.tsv",
"T2": "metadata/T2_manifest.tsv",
"FLAIR": "metadata/FLAIR_manifest.tsv",
"GRE": "metadata/GRE_manifest.tsv",
}
REP_FIELDS = tuple(f"h5_rep{index:02d}" for index in range(1, 7))
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("scan_id")
parser.add_argument("--sequence", choices=tuple(MANIFESTS), required=True)
parser.add_argument("--output", type=Path, default=Path("M4Raw_case"))
parser.add_argument("--repo-id", default=REPO_ID)
parser.add_argument("--revision", default="v1.6.0")
parser.add_argument(
"--include-gre",
action="store_true",
help="Also download GRE for an original-cohort T1/T2/FLAIR examination.",
)
return parser.parse_args()
def download(repo_id: str, revision: str, filename: str, output: Path) -> Path:
return Path(
hf_hub_download(
repo_id=repo_id,
repo_type="dataset",
revision=revision,
filename=filename,
local_dir=output,
)
)
def manifest_row(path: Path, scan_id: str) -> dict[str, str]:
with path.open(newline="", encoding="utf-8") as handle:
rows = [
row
for row in csv.DictReader(handle, delimiter="\t")
if row["scan_id"] == scan_id
]
if len(rows) != 1:
raise RuntimeError(
f"Expected one manifest row for {scan_id}, found {len(rows)}"
)
return rows[0]
def paths_for_sequence(args: argparse.Namespace, sequence: str) -> list[str]:
manifest_name = MANIFESTS[sequence]
local_manifest = download(args.repo_id, args.revision, manifest_name, args.output)
row = manifest_row(local_manifest, args.scan_id)
return [manifest_name, *(row[field] for field in REP_FIELDS if row.get(field))]
def main() -> None:
args = parse_args()
if args.include_gre and args.sequence == "GRE":
raise SystemExit("--include-gre is unnecessary with --sequence GRE")
args.output.mkdir(parents=True, exist_ok=True)
paths = paths_for_sequence(args, args.sequence)
if args.include_gre:
paths.extend(paths_for_sequence(args, "GRE"))
unique_paths = list(dict.fromkeys(paths))
for filename in unique_paths:
print(download(args.repo_id, args.revision, filename, args.output))
print(f"Downloaded {len(unique_paths)} files for {args.scan_id}")
if __name__ == "__main__":
main()