File size: 5,969 Bytes
17ee694 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | """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)
# Also upload the manifests + status logs for reproducibility
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.")
# Upload .pt files in batches
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()
|