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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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
import os
import logging
import datasets
import xml.etree.ElementTree as ET
from PIL import Image
from collections import defaultdict

_CITATION = """
PASCAL_VOC
"""

_DESCRIPTION = """
PASCAL_VOC
"""

_URLS = {
    "voc2007": "voc2007.tar.gz",
    "voc2012": "voc2012.tar.gz",
}

# fmt: off
CLASS_INFOS = [
    #  class name                id      train          color
    (  'aeroplane'             ,  0 ,        0 , ( 128,   0,   0) ),
    (  'bicycle'               ,  1 ,        1 , (   0, 128,   0) ),
    (  'bird'                  ,  2 ,        2 , ( 128, 128,   0) ),
    (  'boat'                  ,  3 ,        3 , (   0,   0, 128) ),
    (  'bottle'                ,  4 ,        4 , ( 128,   0, 128) ),
    (  'bus'                   ,  5 ,        5 , (   0, 128, 128) ),
    (  'car'                   ,  6 ,        6 , ( 128, 128, 128) ),
    (  'cat'                   ,  7 ,        7 , (  64,   0,   0) ),
    (  'chair'                 ,  8 ,        8 , ( 192,   0,   0) ),
    (  'cow'                   ,  9 ,        9 , (  64, 128,   0) ),
    (  'diningtable'           , 10 ,       10 , ( 192, 128,   0) ),
    (  'dog'                   , 11 ,       11 , (  64,   0, 128) ),
    (  'horse'                 , 12 ,       12 , ( 192,   0, 128) ),
    (  'motorbike'             , 13 ,       13 , (  64, 128, 128) ),
    (  'person'                , 14 ,       14 , ( 192, 128, 128) ),
    (  'pottedplant'           , 15 ,       15 , (   0,  64,   0) ),
    (  'sheep'                 , 16 ,       16 , ( 128,  64,   0) ),
    (  'sofa'                  , 17 ,       17 , (   0, 192,   0) ),
    (  'train'                 , 18 ,       18 , ( 128, 192,   0) ),
    (  'tvmonitor'             , 19 ,       19 , (   0,  64, 128) ),
    (  'background'            , 20 ,       20 , (   0,   0,   0) ),
    (  'borderingregion'       , 255,       21 , ( 224, 224, 192) ),
]

ACTION_INFOS = [
    #  class name                id
    (  'phoning'               ,  0 ),
    (  'playinginstrument'     ,  1 ),
    (  'reading'               ,  2 ),
    (  'ridingbike'            ,  3 ),
    (  'ridinghorse'           ,  4 ),
    (  'running'               ,  5 ),
    (  'takingphoto'           ,  6 ),
    (  'usingcomputer'         ,  7 ),
    (  'walking'               ,  8 ),
    (  'jumping'               ,  9 ),
    (  'other'                 , 10 ),
]

LAYOUT_INFOS = [
    #  class name                id
    (  'Frontal'               ,  0 ),
    (  'Left'                  ,  1 ),
    (  'Rear'                  ,  2 ),
    (  'Right'                 ,  3 ),
    (  'Unspecified'           ,  4 ),
]

# fmt: on

CLASS_NAMES = [CLASS_INFO[0] for CLASS_INFO in CLASS_INFOS]
ACTION_NAMES = [ACTION_INFO[0] for ACTION_INFO in ACTION_INFOS]
LAYOUT_NAMES = [LAYOUT_INFO[0] for LAYOUT_INFO in LAYOUT_INFOS]

CLASS_DICT = {CLASS_INFO[0]: CLASS_INFO[2] for CLASS_INFO in CLASS_INFOS}
ACTION_DICT = {ACTION_INFO[0]: ACTION_INFO[1] for ACTION_INFO in ACTION_INFOS}
LAYOUT_DICT = {LAYOUT_INFO[0]: LAYOUT_INFO[1] for LAYOUT_INFO in LAYOUT_INFOS}

# datasets.Features

action_features = datasets.Features(
    {
        "id": datasets.Value("int32"),
        "image": datasets.features.Image(),
        "height": datasets.Value("int32"),
        "width": datasets.Value("int32"),
        "classes": datasets.features.Sequence(datasets.Value("int32")),
        "objects": datasets.features.Sequence(
            {
                "bboxes": datasets.Sequence(datasets.Value("float32")),
                "classes": datasets.features.ClassLabel(names=ACTION_NAMES),
                "difficult": datasets.Value("int32"),
            }
        ),
    }
)

layout_features = datasets.Features(
    {
        "id": datasets.Value("int32"),
        "image": datasets.features.Image(),
        "height": datasets.Value("int32"),
        "width": datasets.Value("int32"),
        "classes": datasets.features.Sequence(datasets.Value("int32")),
        "objects": datasets.features.Sequence(
            {
                "bboxes": datasets.Sequence(datasets.Value("float32")),
                "classes": datasets.features.ClassLabel(names=LAYOUT_NAMES),
                "difficult": datasets.Value("int32"),
            }
        ),
    }
)

main_features = datasets.Features(
    {
        "id": datasets.Value("int32"),
        "image": datasets.features.Image(),
        "height": datasets.Value("int32"),
        "width": datasets.Value("int32"),
        "classes": datasets.features.Sequence(datasets.Value("int32")),
        "objects": datasets.features.Sequence(
            {
                "bboxes": datasets.Sequence(datasets.Value("float32")),
                "classes": datasets.features.ClassLabel(names=CLASS_NAMES),
                "difficult": datasets.Value("int32"),
            }
        ),
    }
)

segmentation_features = datasets.Features(
    {
        "id": datasets.Value("int32"),
        "image": datasets.features.Image(),
        "height": datasets.Value("int32"),
        "width": datasets.Value("int32"),
        "classes": datasets.features.Sequence(datasets.Value("int32")),
        "class_gt_image": datasets.features.Image(),
        "object_gt_image": datasets.features.Image(),
    }
)

_DATASET_FEATURES = {
    "action": action_features,
    "layout": layout_features,
    "main": main_features,
    "segmentation": segmentation_features,
}


def get_main_classes(data_folder):
    class_infos = defaultdict(set)
    class_folder = os.path.join(data_folder, "ImageSets", "Main")
    for f in os.listdir(class_folder):
        if not f.endswith(".txt") or len(f.split("_")) != 2:
            continue
        lines = open(os.path.join(class_folder, f), "r").read().split("\n")
        name = f.split("_")[0]
        for line in lines:
            spans = line.strip().split(" ")
            spans = list(filter(lambda x: x.strip() != "", spans))
            if len(spans) != 2 or int(spans[1]) != 1:
                continue
            class_infos[spans[0]].add(name)
    return class_infos


def get_annotation(data_folder):
    anno_infos = dict()
    anno_folder = os.path.join(data_folder, "Annotations")
    for f in os.listdir(anno_folder):
        if not f.endswith(".xml"):
            continue
        anno_file = os.path.join(anno_folder, f)
        anno_tree = ET.parse(anno_file)
        objects = []
        for obj in anno_tree.findall("./object"):
            info = {
                "class": obj.findall("./name")[0].text,
                "bbox": [
                    int(float(obj.findall("./bndbox/xmin")[0].text)),
                    int(float(obj.findall("./bndbox/ymin")[0].text)),
                    int(float(obj.findall("./bndbox/xmax")[0].text)),
                    int(float(obj.findall("./bndbox/ymax")[0].text)),
                ],
            }

            if obj.findall("./pose"):
                info["pose"] = obj.findall("./pose")[0].text
            if obj.findall("./truncated"):
                info["truncated"] = int(obj.findall("./truncated")[0].text)
            if obj.findall("./difficult"):
                info["difficult"] = int(obj.findall("./difficult")[0].text)
            else:
                info["difficult"] = 0
            if obj.findall("./occluded"):
                info["occluded"] = int(obj.findall("./occluded")[0].text)

            if obj.findall("./actions"):
                info["action"] = [
                    action.tag
                    for action in obj.findall("./actions/")
                    if int(action.text) == 1
                ][0]

            objects.append(info)
        anno_info = {
            "image": anno_tree.findall("./filename")[0].text,
            "height": int(anno_tree.findall("./size/height")[0].text),
            "width": int(anno_tree.findall("./size/width")[0].text),
            "segmented": int(anno_tree.findall("./segmented")[0].text),
            "objects": objects,
        }
        stem, suffix = os.path.splitext(f)
        anno_infos[stem] = anno_info

    return anno_infos


class PASCALConfig(datasets.BuilderConfig):
    def __init__(self, data_name, task_name, **kwargs):
        """

        Args:
          **kwargs: keyword arguments forwarded to super.
        """
        super().__init__(**kwargs)
        assert data_name in ["voc2007", "voc2012"] and task_name in [
            "action",
            "layout",
            "main",
            "segmentation",
        ]
        assert not (data_name == "voc2007" and task_name == "action")
        self.data_name = data_name
        self.task_name = task_name


class PASCALDataset(datasets.GeneratorBasedBuilder):

    BUILDER_CONFIGS = [
        PASCALConfig(
            name="voc2007_layout",
            version=datasets.Version("1.0.0", ""),
            description="voc2007 layout dataset",
            data_name="voc2007",
            task_name="layout",
        ),
        PASCALConfig(
            name="voc2007_main",
            version=datasets.Version("1.0.0", ""),
            description="voc2007 main dataset",
            data_name="voc2007",
            task_name="main",
        ),
        PASCALConfig(
            name="voc2007_segmentation",
            version=datasets.Version("1.0.0", ""),
            description="voc2007 segmentation dataset",
            data_name="voc2007",
            task_name="segmentation",
        ),
        PASCALConfig(
            name="voc2012_action",
            version=datasets.Version("1.0.0", ""),
            description="voc2012 action dataset",
            data_name="voc2012",
            task_name="action",
        ),
        PASCALConfig(
            name="voc2012_layout",
            version=datasets.Version("1.0.0", ""),
            description="voc2012 layout dataset",
            data_name="voc2012",
            task_name="layout",
        ),
        PASCALConfig(
            name="voc2012_main",
            version=datasets.Version("1.0.0", ""),
            description="voc2012 main dataset",
            data_name="voc2012",
            task_name="main",
        ),
        PASCALConfig(
            name="voc2012_segmentation",
            version=datasets.Version("1.0.0", ""),
            description="voc2012 segmentation dataset",
            data_name="voc2012",
            task_name="segmentation",
        ),
    ]

    def _info(self):
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=_DATASET_FEATURES[self.config.task_name],
            # No default supervised_keys (as we have to pass both question
            # and context as input).
            supervised_keys=None,
            homepage="https://fuliucansheng.github.io/",
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        downloaded_files = dl_manager.download_and_extract(_URLS[self.config.data_name])

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={"filepath": downloaded_files, "split": "train"},
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                gen_kwargs={"filepath": downloaded_files, "split": "val"},
            ),
            datasets.SplitGenerator(
                name=datasets.Split.TEST,
                gen_kwargs={"filepath": downloaded_files, "split": "test"},
            ),
        ]

    def _generate_examples(self, filepath, split):
        """This function returns the examples in the raw (text) form."""
        logging.info("generating examples from = %s, split = %s", filepath, split)
        data_folder = os.path.join(filepath, os.listdir(filepath)[0])
        anno_infos = get_annotation(data_folder)
        class_infos = get_main_classes(data_folder)
        data_file = os.path.join(
            data_folder, "ImageSets", self.config.task_name.capitalize(), f"{split}.txt"
        )
        with open(data_file, encoding="utf-8") as f:
            for id_, line in enumerate(f):
                line = line.strip()
                if line.count(" ") > 0:
                    line = line.split(" ")[0]
                anno_info = anno_infos.get(line)
                if anno_info is None:
                    continue

                image = os.path.join(data_folder, "JPEGImages", anno_info["image"])
                if not os.path.exists(image):
                    continue

                classes = (
                    [CLASS_DICT[c] for c in class_infos.get(line.strip())]
                    if line.strip() in class_infos
                    else []
                )

                example = {
                    "id": id_,
                    "image": Image.open(os.path.abspath(image)),
                    "height": anno_info["height"],
                    "width": anno_info["width"],
                    "classes": classes,
                }

                objects_info = anno_info["objects"]

                if self.config.task_name == "action":
                    example["objects"] = [
                        {
                            "bboxes": object_info["bbox"],
                            "classes": object_info["action"],
                            "difficult": object_info["difficult"],
                        }
                        for object_info in objects_info
                        if "action" in object_info
                    ]
                    if len(example["objects"]) == 0 and split != "test":
                        continue

                if self.config.task_name == "layout":
                    example["objects"] = [
                        {"bboxes": object_info["bbox"], "classes": object_info["pose"], "difficult": object_info["difficult"],}
                        for object_info in objects_info
                        if "pose" in object_info
                    ]
                    if len(example["objects"]) == 0 and split != "test":
                        continue

                if self.config.task_name == "main":
                    example["objects"] = [
                        {"bboxes": object_info["bbox"], "classes": object_info["class"], "difficult": object_info["difficult"],}
                        for object_info in objects_info
                        if "class" in object_info
                    ]
                    if len(example["objects"]) == 0 and split != "test":
                        continue

                if self.config.task_name == "segmentation":
                    example["class_gt_image"] = Image.open(os.path.abspath(
                        os.path.join(
                            data_folder,
                            "SegmentationClass",
                            anno_info["image"].replace(".jpg", ".png"),
                        )
                    ))
                    example["object_gt_image"] = Image.open(os.path.abspath(
                        os.path.join(
                            data_folder,
                            "SegmentationObject",
                            anno_info["image"].replace(".jpg", ".png"),
                        )
                    ))

                yield id_, example