File size: 7,659 Bytes
2eccbda
 
 
ca95bc9
2eccbda
 
 
 
 
ca95bc9
 
2eccbda
 
 
 
 
 
 
ca95bc9
2eccbda
 
 
 
 
 
 
 
ca95bc9
2eccbda
 
 
ca95bc9
2eccbda
 
 
 
ca95bc9
2eccbda
 
ca95bc9
 
2eccbda
 
 
 
 
 
 
 
 
 
ca95bc9
 
2eccbda
 
 
 
ca95bc9
2eccbda
 
 
 
 
 
ca95bc9
2eccbda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca95bc9
 
 
2eccbda
ca95bc9
 
 
 
 
2eccbda
 
 
 
ca95bc9
2eccbda
 
 
ca95bc9
2eccbda
 
 
ca95bc9
2eccbda
 
 
 
 
ca95bc9
 
2eccbda
 
 
 
 
 
 
 
 
ca95bc9
2eccbda
ca95bc9
 
2eccbda
 
ca95bc9
2eccbda
 
 
 
 
ca95bc9
2eccbda
 
 
 
 
 
 
 
 
 
ca95bc9
2eccbda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
import logging
import datasets

logger = logging.getLogger(__name__)

_DESCRIPTION = """
This dataset contains T1-weighted .nii.gz structural MRI scans in a BIDS-like arrangement.
Each scan has an associated JSON sidecar with metadata, including a 'split' field indicating
whether it's train, validation, or test.
"""

_CITATION = """
@dataset{Radiata-Brain-Structure,
  author    = {Jesse Brown and Clayton Young},
  title     = {Brain-Structure: A Collection of Processed Structural MRI Scans},
  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"


class BrainStructureConfig(datasets.BuilderConfig):
    """
    Configuration class for the Brain-Structure dataset.
    You can define multiple configurations if needed (e.g., different subsets).
    """
    def __init__(self, **kwargs):
        super().__init__(**kwargs)


class BrainStructure(datasets.GeneratorBasedBuilder):
    """
    A dataset loader for T1 .nii.gz files plus JSON sidecars indicating splits
    (train, validation, test). Usage example:

        ds = load_dataset(
            "radiata-ai/brain-structure",
            name="all",
            split="train",
            trust_remote_code=True
        )
    """

    VERSION = datasets.Version("1.0.0")

    # If you do NOT need multiple configs, you can define just one here:
    BUILDER_CONFIGS = [
        BrainStructureConfig(
            name="all",
            version=VERSION,
            description="All structural MRI data in a BIDS-like arrangement, labeled with train/val/test splits."
        ),
    ]
    DEFAULT_CONFIG_NAME = "all"

    def _info(self):
        """
        Returns DatasetInfo, including feature types and other meta information.
        """
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            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"),

                        # Additional fields from the JSON sidecar
                        "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"),
                    },
                }
            ),
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager: datasets.DownloadManager):
        """
        Creates SplitGenerators for train, validation, and test.
        No remote download is performed here. Instead, we reference
        the local directory containing this script.
        """
        # Typically, we use dl_manager.download_and_extract(...) for remote data,
        # but here we assume the data is already in the same repo as this script.

        # Path to the folder containing this script (and presumably the data).
        data_dir = os.path.abspath(os.path.dirname(__file__))

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={"data_dir": data_dir, "desired_split": "train"}
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                gen_kwargs={"data_dir": data_dir, "desired_split": "validation"}
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={"data_dir": data_dir, "desired_split": "test"}
            ),
        ]

    def _generate_examples(self, data_dir, desired_split):
        """
        Recursively walks data_dir, locates JSON sidecar files, and yields
        examples that match the specified 'desired_split'.
        """
        id_ = 0
        for root, dirs, files in os.walk(data_dir):
            for fname in files:
                if fname.endswith("_scandata.json"):
                    sidecar_path = os.path.join(root, fname)
                    with open(sidecar_path, "r") as f:
                        sidecar = json.load(f)

                    # Only yield if 'split' matches the requested split
                    if sidecar.get("split") == desired_split:
                        # Locate corresponding NIfTI .nii.gz
                        nii_prefix = fname.replace("_scandata.json", "_T1w")
                        nii_filepath = None
                        for potential_file in files:
                            if (potential_file.startswith(nii_prefix) 
                                and potential_file.endswith(".nii.gz")):
                                nii_filepath = os.path.join(root, potential_file)
                                break

                        if not nii_filepath:
                            logger.warning(f"No .nii.gz found for {sidecar_path}")
                            continue

                        yield id_, {
                            "id": str(id_),
                            "nii_filepath": nii_filepath,
                            "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