File size: 4,442 Bytes
2ffa416
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe18ffc
2ffa416
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Collection of brain xray images for fine-grain classification."""

import datasets
import numpy as np
import pandas as pd
from pathlib import Path
import os

_CITATION = """\
@misc{kaggle-brain-tumor-classification,
  title={Kaggle: Brain Tumor Classification (MRI)},
  howpublished={\\url{https://www.kaggle.com/datasets/sartajbhuvaji/brain-tumor-classification-mri?resource=download}},
  note = {Accessed: 2022-06-30},
}
"""

_DESCRIPTION = """\
This dataset is intended as a test case for classification tasks (4 different kinds of brain xrays). The dataset consists of almost 1400 JPEG images grouped into two splits - training and validation. Each split contains 4 categories labeled as n0~n3, each corresponding to a cancer result of the mrt.


| Label | Xray Category         | Train Images | Validation Images |
| ----- | --------------------- | ------------ | ----------------- |
| n0    | glioma_tumor          | 826          | 100               |
| n1    | meningioma_tumor      | 822          | 115               |
| n2    | pituitary_tumor       | 827          | 74                |
| n3    | no_tumor              | 395          | 105               |


"""

_HOMEPAGE = "https://www.kaggle.com/datasets/sartajbhuvaji/brain-tumor-classification-mri?resource=download"

_LICENSE = "cc0-1.0"

_URLS = {
    "original": "https://ibm.ent.box.com/index.php?rm=box_download_shared_file&shared_name=5ich3fqgpnbmkdho2eoe7fe4uwrplcfi&file_id=f_978363130854"
}

LABELS = [
    "Glioma Tumor",
    "Meningioma Tumor",
    "Pituitary Tumor",
    "No Tumor"
]


class BrainTumorCollectionGenerator(datasets.GeneratorBasedBuilder):
    """Collection of brain xray images for fine-grain classification."""

    VERSION = datasets.Version("1.0.0")

    BUILDER_CONFIGS = [
        datasets.BuilderConfig(name="original", version=VERSION, description="Original JPEG files: images are 400x300 px or larger; ~550 MB"),
    ]

    DEFAULT_CONFIG_NAME = "original"

    def _info(self):
        features = datasets.Features(
            {
                "image": datasets.Image(),
                "label": datasets.ClassLabel(names=LABELS)
            }
        )
        supervised_keys = ("image", "label")
        
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            supervised_keys=supervised_keys,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        url = _URLS[self.config.name]
        data_dir = dl_manager.download_and_extract(url)
        print("Test"+data_dir)

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "filepath": os.path.join(data_dir, "xrays", "training", "training"),
                    "split": "train",
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={
                    "filepath": os.path.join(data_dir, "xrays", "validation", "validation"),
                    "split": "test",
                },
            ),
        ]

    def _generate_examples(self, filepath, split):
        paths = list(Path(filepath).glob("**/*.jpg"))
        data = []

        for path in paths:
            tumor_folder = str(path).split("/")[-2]
            index = int(tumor_folder[1])
            label = LABELS[index]
            data.append({"file": str(path), "label": label})

        df = pd.DataFrame(data)
        print(df)
        df.sort_values("file", inplace=True)

        for idx_, row in df.iterrows():
            yield idx_, {
                "image": row["file"],
                "label": row["label"]
            }