File size: 5,808 Bytes
bd366ff
 
 
 
 
 
 
 
 
 
 
 
 
00a0d1c
77f342e
 
6b11ed8
77f342e
 
 
 
1c43976
32f54f8
1c43976
 
32f54f8
 
77f342e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c43976
 
 
 
 
 
 
77f342e
1c43976
 
 
77f342e
 
1c43976
2a19855
77f342e
 
bd366ff
634e71b
 
 
 
 
 
 
 
 
77f342e
 
bd366ff
 
 
 
 
77f342e
 
c6a8eb4
5d1e206
124ef01
 
 
 
 
 
0858d75
 
 
 
 
 
124ef01
c6a8eb4
124ef01
 
 
 
 
 
77f342e
 
 
 
6b11ed8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c43976
 
 
 
 
 
 
6b11ed8
 
 
32f54f8
6b11ed8
 
 
 
 
 
 
 
 
77f342e
6b11ed8
bd366ff
f06f586
c6a8eb4
 
1c43976
 
8dacc50
 
 
 
6b11ed8
 
 
 
 
 
 
 
32f54f8
 
6b11ed8
 
 
 
 
 
 
1c43976
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
# Copyright 2022 Cristóbal Alcázar
#
# 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.
"""Rock Glacier dataset with images of the chilean andes."""

import os
import re

import datasets
from datasets.tasks import ImageClassification

datasets.logging.set_verbosity_debug()
logger = datasets.logging.get_logger(__name__)
#datasets.logging.set_verbosity_info()
#datasets.logging.set_verbosity_debug()


_HOMEPAGE = "https://github.com/alcazar90/rock-glacier-detection"


_CITATION = """\
@ONLINE {rock-glacier-dataset,
    author="CMM-Glaciares",
    title="Rock Glacier Dataset",
    month="October",
    year="2022",
    url="https://github.com/alcazar90/rock-glacier-detection"
}
"""

_DESCRIPTION = """\
TODO: Add a description...
"""


#_URLS = {
#	"train": "https://huggingface.co/datasets/alkzar90/rock-glacier-dataset/resolve/main/data/train.zip",
#	"validation": "https://huggingface.co/datasets/alkzar90/rock-glacier-dataset/resolve/main/data/validation.zip",
#	"train_mask": "https://huggingface.co/datasets/alkzar90/rock-glacier-dataset/resolve/main/data/glaciar_masks_trainset.zip",
#}


_URLS = {
	"train": "https://huggingface.co/datasets/alkzar90/rock-glacier-dataset/resolve/main/data/data_v01/train.zip",
	"validation": "https://huggingface.co/datasets/alkzar90/rock-glacier-dataset/resolve/main/data/data_v01/val.zip",
        "test": "https://huggingface.co/datasets/alkzar90/rock-glacier-dataset/resolve/main/data/data_v01/test.zip",
}


_NAMES = ["cordillera", "glaciar"]


class RockGlacierConfig(datasets.BuilderConfig):
   def __init__(self, name, **kwargs):
      super(RockGlacierConfig, self).__init__(
         version=datasets.Version("1.0.0"),
         name=name,
         description="Rock Glacier Dataset",
         **kwargs,
         )
         
         
class RockGlacierDataset(datasets.GeneratorBasedBuilder):
   """Rock Glacier images dataset."""
   
   BUILDER_CONFIGS = [
   		RockGlacierConfig("image-classification"),
   		RockGlacierConfig("image-segmentation"),
   ]

   def _info(self):
      if self.config.name == "image-classification":
         features = datasets.Features({
            "image": datasets.Image(),
            "labels": datasets.features.ClassLabel(names=_NAMES),
            })
         keys = ("image", "labels")
         
      if self.config.name == "image-segmentation":
         features = datasets.Features({
            "image": datasets.Image(),
            "labels": datasets.Image(),
            })
         keys = ("image", "labels")
         
         
      return datasets.DatasetInfo(
               description=_DESCRIPTION,
               features=features,
               supervised_keys=keys,
               homepage=_HOMEPAGE,
               citation=_CITATION,
               )
	

   def _split_generators(self, dl_manager):
       data_files = dl_manager.download_and_extract(_URLS)
       
       if self.config.name == "image-classification":
          return [
	          datasets.SplitGenerator(
	          name=datasets.Split.TRAIN,
	          gen_kwargs={
		          "files": dl_manager.iter_files([data_files["train"]]),
		          "split": "training",
	          },
	          ),
	          datasets.SplitGenerator(
	          name=datasets.Split.VALIDATION,
	          gen_kwargs={
		          "files": dl_manager.iter_files([data_files["validation"]]),
		          "split": "validation",
	          },
 	         ),
	          datasets.SplitGenerator(
	          name=datasets.Split.TEST,
	          gen_kwargs={
		          "files": dl_manager.iter_files([data_files["test"]]),
		          "split": "test",
	          },
 	         ),
           ]
           
       if self.config.name == "image-segmentation":
          train_data = dl_manager.iter_files([data_files["train"]]), dl_manager.iter_files([data_files["train_mask"]])
          return [
             datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                   "files": train_data,
                   "split": "training",
                },
             )]
                

   def _generate_examples(self, files, split):
   
      if self.config.name == "image-classification":
         for i, path in enumerate(files):
            file_name = os.path.basename(path)
            dir_name = os.path.basename(os.path.dirname(path))
            if dir_name != "masks" and file_name.endswith(".png"):
               yield i, {
                  "image": path,
                  "labels": os.path.basename(os.path.dirname(path)).lower(),
                  }
      
      if self.config.name == "image-segmentation":
         if split == "training":
            images, masks = files
            imageId2mask = {}
            # iterate trought masks
            for mask_path in masks:
               mask_id = re.search('\d+', mask_path).group(0)
               imageId2mask[mask_id] = mask_path
            logger.info(f"imageId2mask check paths: {imageId2mask}")     
            for i, path in enumerate(files):
               file_name = os.path.basename(path)
               if file_name.endswith(".png"):
                  yield i, {
                     "image": path,
                     "labels": imageId2mask[re.search('\d+', file_name).group(0)]
                  }