| """Upload preprocessed .pt cache to Hugging Face. |
| |
| 6,050 files Γ ~4 MB = ~24 GB. Uploads in batches of 60 files (~240 MB/batch). |
| Resumable: HF Hub skips files already uploaded (content-addressed). |
| """ |
| from __future__ import annotations |
| import time |
| from pathlib import Path |
| from huggingface_hub import HfApi, CommitOperationAdd |
|
|
| TOKEN = "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" |
| REPO_ID = "bilalahmad176176/BrainAge-Golden-Preprocessed" |
| CACHE_DIR = Path("/home/MRI-DataSet/_train/cache") |
| BATCH_SIZE = 60 |
|
|
|
|
| def upload_readme(api: HfApi): |
| readme = """--- |
| license: cc-by-nc-4.0 |
| task_categories: |
| - other |
| language: |
| - en |
| pretty_name: BrainAge Golden Preprocessed Cache |
| size_categories: |
| - 1K<n<10K |
| tags: |
| - neuroimaging |
| - mri |
| - brain-age |
| - pytorch |
| - preprocessed |
| - tensor-cache |
| --- |
| |
| # BrainAge Golden Preprocessed Cache |
| |
| **6,050 preprocessed brain MRI tensors** ready for training a brain-age |
| prediction model. Skip the 40+ hour preprocessing step and jump straight |
| to model training. |
| |
| ## What's inside |
| |
| Each `.pt` file (one per subject) contains: |
| |
| | Key | Type | Shape | Description | |
| |-----|------|-------|-------------| |
| | `volume` | float16 | (128, 144, 112) | Z-normed T1w brain in MNI space, trilinear-resized | |
| | `tab` | float32 | (86,) | 70 regional volumes (log1p/12) + 3 sex one-hot + 13 site one-hot | |
| | `age` | float32 | scalar | Chronological age in years | |
| | `meta` | dict | β | subject_id, site, sex, age, split | |
| |
| ## Stats |
| |
| | Metric | Value | |
| |--------|-------| |
| | Total subjects | 6,050 | |
| | Age range | 0 β 86 years | |
| | Source datasets | 12 (BCP, Calgary, ds002726, ds000248, PTBP, IXI, MPI-Leipzig, AOMIC, NKI-Rockland, ABIDE-I, ABIDE-II, ADHD-200) | |
| | Volume shape | 128 Γ 144 Γ 112 (D Γ H Γ W) | |
| | Tabular dim | 86 (70 regions + 3 sex + 13 site) | |
| | File size | ~4 MB each | |
| | Total size | ~24 GB | |
| |
| ## Preprocessing pipeline applied |
| |
| ``` |
| Raw T1w NIfTI |
| β HD-BET skull-strip (GPU) |
| β N4 bias correction (ANTs) |
| β Affine registration to MNI152 1mm |
| β Z-score intensity normalization |
| β Harvard-Oxford atlas segmentation (69 regions) |
| β Volume measurement + rescaling to native space |
| β Tensor packaging (.pt) |
| ``` |
| |
| ## Quick start |
| |
| ```python |
| from huggingface_hub import snapshot_download |
| import torch |
| |
| # Download (~24 GB) |
| snapshot_download( |
| "bilalahmad176176/BrainAge-Golden-Preprocessed", |
| repo_type="dataset", |
| local_dir="cache/" |
| ) |
| |
| # Load one subject |
| data = torch.load("cache/cache/IXI002.pt", weights_only=False) |
| print(data["volume"].shape) # (128, 144, 112) float16 |
| print(data["tab"].shape) # (86,) float32 |
| print(data["age"]) # e.g. 36.2 |
| print(data["meta"]) # {'subject_id': 'IXI002', 'site': 'DataSet-6_IXI', ...} |
| ``` |
| |
| ## Train a model |
| |
| ```bash |
| # Generate split |
| python -m pipeline_v2.data_split \\ |
| --manifests Golden-0-to-25/manifest.csv Golden-25plus/manifest.csv \\ |
| --out cache/split.csv |
| |
| # Train |
| python -m pipeline_v2.train \\ |
| --cache_dir cache/cache \\ |
| --split_csv cache/split.csv \\ |
| --out_ckpt brainage_sfcn.pt \\ |
| --epochs 60 --batch 4 |
| ``` |
| |
| ## Related |
| |
| - Raw dataset: [bilalahmad176176/BrainAge-Golden-Raw](https://huggingface.co/datasets/bilalahmad176176/BrainAge-Golden-Raw) |
| - 3D Viewer demo: [bilalahmad176176/BrainAge-3D-Viewer](https://huggingface.co/spaces/bilalahmad176176/BrainAge-3D-Viewer) |
| |
| ## Citation |
| |
| Please cite the original source studies listed in the raw dataset manifests. |
| """ |
| api.upload_file( |
| path_or_fileobj=readme.encode(), |
| path_in_repo="README.md", |
| repo_id=REPO_ID, |
| repo_type="dataset", |
| commit_message="Add dataset card", |
| ) |
| print("README.md uploaded.") |
|
|
|
|
| def main(): |
| api = HfApi(token=TOKEN) |
| print(f"User: {api.whoami()['name']}") |
| print(f"Repo: https://huggingface.co/datasets/{REPO_ID}") |
|
|
| upload_readme(api) |
|
|
| |
| extras = [ |
| ("/home/MRI-DataSet/Golden-0-to-25/manifest.csv", "manifests/Golden-0-to-25_manifest.csv"), |
| ("/home/MRI-DataSet/Golden-25plus/manifest.csv", "manifests/Golden-25plus_manifest.csv"), |
| ("/home/MRI-DataSet/_train/logs/preprocess_status.csv", "logs/preprocess_status.csv"), |
| ] |
| ops = [] |
| for local, repo_path in extras: |
| if Path(local).exists(): |
| ops.append(CommitOperationAdd(path_in_repo=repo_path, path_or_fileobj=local)) |
| if ops: |
| api.create_commit(repo_id=REPO_ID, repo_type="dataset", |
| operations=ops, commit_message="Add manifests and preprocessing logs") |
| print(f"Uploaded {len(ops)} metadata files.") |
|
|
| |
| pts = sorted(CACHE_DIR.glob("*.pt")) |
| total = len(pts) |
| print(f"\nUploading {total} .pt files (~24 GB)β¦\n") |
|
|
| for i in range(0, total, BATCH_SIZE): |
| batch = pts[i : i + BATCH_SIZE] |
| ops = [CommitOperationAdd( |
| path_in_repo=f"cache/{p.name}", |
| path_or_fileobj=str(p), |
| ) for p in batch] |
| n = min(i + BATCH_SIZE, total) |
| msg = f"Add cache/{pts[i].name}β¦{batch[-1].name} ({i+1}β{n} of {total})" |
| print(f" [{n}/{total}] committing β¦ ", end="", flush=True) |
| t0 = time.time() |
| try: |
| api.create_commit( |
| repo_id=REPO_ID, repo_type="dataset", |
| operations=ops, commit_message=msg, |
| ) |
| print(f"done ({time.time()-t0:.0f}s)") |
| except Exception as e: |
| print(f"ERROR: {e}") |
| time.sleep(5) |
| try: |
| api.create_commit( |
| repo_id=REPO_ID, repo_type="dataset", |
| operations=ops, commit_message=msg + " (retry)", |
| ) |
| print(" retry ok") |
| except Exception as e2: |
| print(f" retry failed: {e2}, skipping batch β rerun to resume") |
|
|
| print(f"\nDONE β https://huggingface.co/datasets/{REPO_ID}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|