File size: 7,015 Bytes
2eccbda ca95bc9 4882dff 2eccbda 4882dff 2eccbda 658aa3c 2eccbda 658aa3c 2eccbda 658aa3c 2eccbda 4882dff ca95bc9 2eccbda 4882dff 2eccbda ca95bc9 2eccbda 4882dff 2eccbda 4882dff 2eccbda 4882dff 2eccbda 4882dff 2eccbda 4882dff 2eccbda 4882dff 2eccbda 4882dff 6559553 4882dff 2eccbda 4882dff 2eccbda 4882dff 2eccbda 4882dff 2eccbda 4882dff 2eccbda 4882dff 3e3f6c5 4882dff 3e3f6c5 4882dff 3e3f6c5 4882dff 3e3f6c5 4882dff |
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 |
import os
import json
import logging
import datasets
from pathlib import Path
logger = logging.getLogger(__name__)
_DESCRIPTION = """
A collection of T1-weighted .nii.gz structural MRI scans in a BIDS-like arrangement,
with JSON sidecar metadata indicating train/validation/test splits.
"""
_CITATION = """
@dataset{Radiata-Brain-Structure,
author = {Jesse Brown and Clayton Young},
title = {Brain-Structure: Processed Structural MRI Brain Scans Across the Lifespan},
year = {2025},
url = {https://huggingface.co/datasets/radiata-ai/brain-structure},
note = {Version 1.0},
publisher = {Hugging Face}
}
"""
_HOMEPAGE = "https://huggingface.co/datasets/radiata-ai/brain-structure"
_LICENSE = "ODC-By v1.0"
# The "resolve/main/data.zip" part ensures it grabs data.zip from your 'main' branch.
_DATA_URL = "https://huggingface.co/datasets/radiata-ai/brain-structure/resolve/main/data.zip"
class BrainStructureConfig(datasets.BuilderConfig):
"""Configuration for Brain-Structure dataset (if you need multiple, define them here)."""
def __init__(self, **kwargs):
super().__init__(**kwargs)
class BrainStructure(datasets.GeneratorBasedBuilder):
"""
A dataset loader for T1 .nii.gz files plus JSON sidecars stored in a single ZIP.
Usage:
ds_train = load_dataset("radiata-ai/brain-structure", split="train", trust_remote_code=True)
"""
VERSION = datasets.Version("1.0.0")
BUILDER_CONFIGS = [
BrainStructureConfig(
name="default",
version=VERSION,
description="Structural MRIs with sidecar metadata. Splits (train/val/test) indicated in the sidecars.",
)
]
DEFAULT_CONFIG_NAME = "default"
def _info(self):
return datasets.DatasetInfo(
description=_DESCRIPTION,
homepage=_HOMEPAGE,
license=_LICENSE,
citation=_CITATION,
features=datasets.Features(
{
"id": datasets.Value("string"),
"nii_filepath": datasets.Value("string"),
"metadata": {
"split": datasets.Value("string"),
"participant_id": datasets.Value("string"),
"session_id": datasets.Value("string"),
"study": datasets.Value("string"),
"age": datasets.Value("int32"),
"sex": datasets.Value("string"),
"clinical_diagnosis": datasets.Value("string"),
"scanner_manufacturer": datasets.Value("string"),
"scanner_model": datasets.Value("string"),
"field_strength": datasets.Value("string"),
"image_quality_rating": datasets.Value("float"),
"total_intracranial_volume": datasets.Value("float"),
"license": datasets.Value("string"),
"website": datasets.Value("string"),
"citation": datasets.Value("string"),
"t1_file_name": datasets.Value("string"),
"radiata_id": datasets.Value("int32"),
},
}
),
)
def _split_generators(self, dl_manager: datasets.DownloadManager):
"""
Downloads and extracts 'data.zip', then defines train/validation/test splits
by matching sidecars with 'split': 'train'/'validation'/'test'.
"""
# Download and extract your single ZIP containing all subfolders
extracted_dir = dl_manager.download_and_extract(_DATA_URL)
# The ZIP will typically unzip into a folder named "data" or similar. We'll just scan everything inside.
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={"data_dir": extracted_dir, "desired_split": "train"},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={"data_dir": extracted_dir, "desired_split": "validation"},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={"data_dir": extracted_dir, "desired_split": "test"},
),
]
def _generate_examples(self, data_dir, desired_split):
"""
Recursively find sidecar JSONs with 'split' matching desired_split.
For each, yield an example containing the .nii.gz path + metadata.
"""
id_ = 0
data_path = Path(data_dir)
for json_path in data_path.rglob("*_scandata.json"):
with open(json_path, "r") as f:
sidecar = json.load(f)
# Only yield if sidecar["split"] matches
if sidecar.get("split") == desired_split:
# Build a base prefix from the JSON filename (minus "_scandata")
# e.g. "msub-OASIS20133_ses-03"
base_prefix = json_path.stem.replace("_scandata", "")
# Search for a NIfTI that starts with that prefix and includes '_T1w'
nii_path = None
for potential_nii in json_path.parent.glob(f"{base_prefix}*_T1w*.nii.gz"):
nii_path = potential_nii
break
if not nii_path or not nii_path.is_file():
logger.warning(f"No .nii.gz found for {json_path}")
continue
yield id_, {
"id": str(id_),
"nii_filepath": str(nii_path),
"metadata": {
"split": sidecar.get("split", ""),
"participant_id": sidecar.get("participant_id", ""),
"session_id": sidecar.get("session_id", ""),
"study": sidecar.get("study", ""),
"age": sidecar.get("age", 0),
"sex": sidecar.get("sex", ""),
"clinical_diagnosis": sidecar.get("clinical_diagnosis", ""),
"scanner_manufacturer": sidecar.get("scanner_manufacturer", ""),
"scanner_model": sidecar.get("scanner_model", ""),
"field_strength": sidecar.get("field_strength", ""),
"image_quality_rating": float(sidecar.get("image_quality_rating", 0.0)),
"total_intracranial_volume": float(sidecar.get("total_intracranial_volume", 0.0)),
"license": sidecar.get("license", ""),
"website": sidecar.get("website", ""),
"citation": sidecar.get("citation", ""),
"t1_file_name": sidecar.get("t1_file_name", ""),
"radiata_id": sidecar.get("radiata_id", 0),
},
}
id_ += 1 |