Datasets:

ArXiv:
License:
File size: 10,239 Bytes
52fe1d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
# Copyright 2022 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.
"""Script for reading 'You Actually Look Twice At it (YALTAi)' dataset."""


import contextlib
from typing import Dict
import requests
import datasets
from PIL import Image
from pathlib import Path
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element
from typing import Any, List
from pathlib import PosixPath

_CITATION = """\
    @dataset{clerice_thibault_2022_6827706,
  author       = {Clérice, Thibault},
  title        = {YALTAi: Tabular Dataset},
  month        = jul,
  year         = 2022,
  publisher    = {Zenodo},
  version      = {1.0.0},
  doi          = {10.5281/zenodo.6827706},
  url          = {https://doi.org/10.5281/zenodo.6827706}
}
"""

_DESCRIPTION = """Yalt AI Tabular Dataset"""

_HOMEPAGE = "https://doi.org/10.5281/zenodo.6984525"

_LICENSE = "Creative Commons Attribution Non Commercial Share Alike 2.0 Generic"

ZENODO_API_URL = "https://zenodo.org/api/records/6984525"

_CATEGORIES = [
    "zebra",
    "tree",
    "nude",
    "crucifixion",
    "scroll",
    "head",
    "swan",
    "shield",
    "lily",
    "mouse",
    "knight",
    "dragon",
    "horn",
    "dog",
    "palm",
    "tiara",
    "helmet",
    "sheep",
    "deer",
    "person",
    "sword",
    "rooster",
    "bear",
    "halo",
    "lion",
    "monkey",
    "prayer",
    "crown of thorns",
    "elephant",
    "zucchetto",
    "unicorn",
    "holy shroud",
    "cat",
    "apple",
    "banana",
    "chalice",
    "bird",
    "eagle",
    "pegasus",
    "crown",
    "camauro",
    "saturno",
    "arrow",
    "dove",
    "centaur",
    "horse",
    "hands",
    "skull",
    "orange",
    "monk",
    "trumpet",
    "key of heaven",
    "fish",
    "cow",
    "angel",
    "devil",
    "book",
    "stole",
    "butterfly",
    "serpent",
    "judith",
    "mitre",
    "banner",
    "donkey",
    "shepherd",
    "boat",
    "god the father",
    "crozier",
    "jug",
    "lance",
]

_POSES = [
    "stand",
    "sit",
    "partial",
    "Unspecified",
    "squats",
    "lie",
    "bend",
    "fall",
    "walk",
    "push",
    "pray",
    "undefined",
    "kneel",
    "unrecognize",
    "unknown",
    "other",
    "ride",
]


logger = datasets.utils.logging.get_logger(__name__)


def parse_annotation(annotations_object: Element) -> Dict[str, Any]:
    with contextlib.suppress(ValueError):
        name = annotations_object.find("name").text
        pose = annotations_object.find("pose").text
        diffult = int(annotations_object.find("difficult").text)
        bndbox = annotations_object.find("bndbox")
        xmin = float(bndbox.find("xmin").text)
        ymin = float(bndbox.find("ymin").text)
        xmax = float(bndbox.find("xmax").text)
        ymax = float(bndbox.find("ymax").text)
        return {
            "name": name,
            "pose": pose,
            "diffult": diffult,
            "xmin": xmin,
            "ymin": ymin,
            "xmax": xmax,
            "ymax": ymax,
        }


def create_annotations_dict(xmls: List[PosixPath]) -> Dict[str, Any]:
    annotations = {}
    for xml in xmls:
        tree = ET.parse(xml)
        root = tree.getroot()
        filename = root.find("filename").text
        source = root.find("source/database").text
        size = root.find("size")
        width = int(size.find("width").text)
        height = int(size.find("height").text)
        depth = int(size.find("depth").text)
        segmented = root.find("segmented")
        segmented = int(segmented.text) if segmented else None
        annotation_objects = root.findall("object")
        annotation_objects = [
            parse_annotation(annotation) for annotation in annotation_objects
        ]
        annotation_objects = [
            annotation for annotation in annotation_objects if annotation is not None
        ]
        annotations[filename] = {
            "source": source,
            "width": width,
            "height": height,
            "dept": depth,
            "segmented": segmented,
            "objects": annotation_objects,
        }
    return annotations


def get_coco_annotation_from_obj(
    image_id, label, xmin, ymin, xmax, ymax
):  # adapted from https://github.com/yukkyo/voc2coco/blob/abd05bbfa0740a04bb483862eccea2032bc80e24/voc2coco.py#L60
    category_id = label
    assert xmax > xmin and ymax > ymin, logger.warn(
        f"Box size error !: (xmin, ymin, xmax, ymax): {xmin, ymin, xmax, ymax}"
    )
    o_width = xmax - xmin
    o_height = ymax - ymin
    ann = {
        "image_id": image_id,
        "area": o_width * o_height,
        "iscrowd": 0,
        "bbox": [xmin, ymin, o_width, o_height],
        "category_id": category_id,
        # "ignore": 0,
        "segmentation": [],
    }
    return ann


common_features = features = datasets.Features(
    {
        # "image_id": datasets.Value("int64"),
        "image": datasets.Image(),
        "source": datasets.Value("string"),
        "width": datasets.Value("int16"),
        "height": datasets.Value("int16"),
        "dept": datasets.Value("int8"),
        "segmented": datasets.Value("int8"),
    }
)


class DeartDatasetConfig(datasets.BuilderConfig):
    """BuilderConfig for YaltAiTabularDataset."""

    def __init__(self, name, **kwargs):
        """BuilderConfig for YaltAiTabularDataset."""
        super(DeartDatasetConfig, self).__init__(
            version=datasets.Version("1.0.0"), name=name, description=None, **kwargs
        )


class DeartDataset(datasets.GeneratorBasedBuilder):
    """Object Detection for historic manuscripts"""

    BUILDER_CONFIGS = [
        DeartDatasetConfig("raw"),
        DeartDatasetConfig("coco"),
    ]

    def _info(self):
        if self.config.name == "coco":
            features = common_features
            features["image_id"] = datasets.Value("string")
            object_dict = {
                "category_id": datasets.ClassLabel(names=_CATEGORIES),
                "image_id": datasets.Value("string"),
                "area": datasets.Value("int64"),
                "bbox": datasets.Sequence(datasets.Value("float32"), length=4),
                "segmentation": [[datasets.Value("float32")]],
                "iscrowd": datasets.Value("bool"),
            }
            features["objects"] = [object_dict]
        if self.config.name == "raw":
            features = common_features

            object_dict = {
                "name": datasets.ClassLabel(names=_CATEGORIES),
                "pose": datasets.ClassLabel(names=_POSES),
                "diffult": datasets.Value("int32"),
                "xmin": datasets.Value("float64"),
                "ymin": datasets.Value("float64"),
                "xmax": datasets.Value("float64"),
                "ymax": datasets.Value("float64"),
            }
            features["objects"] = [object_dict]
        return datasets.DatasetInfo(
            features=features,
            supervised_keys=None,
            description=_DESCRIPTION,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        zenodo_record = requests.get(ZENODO_API_URL).json()
        urls = sorted(
            [
                file["links"]["self"]
                for file in zenodo_record["files"]
                if file["type"] == "zip"
            ]
        )
        annotation_data = urls.pop(0)
        annotation_data = dl_manager.download_and_extract(annotation_data)

        image_data = dl_manager.download_and_extract(urls)
        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "annotations_data": Path(annotation_data),
                    "image_data": image_data,
                },
            ),
        ]

    def _generate_examples(self, annotations_data, image_data):
        xmls = list(annotations_data.rglob("*.xml"))
        annotations_data = create_annotations_dict(xmls)
        count = 0
        for directory in image_data:
            for file in Path(directory).glob("*.jpg"):
                with Image.open(file) as image:
                    try:
                        if self.config.name == "raw":
                            example = annotations_data[file.name]
                            example["image"] = image
                            count += 1
                            yield count, example
                        if self.config.name == "coco":
                            updated_annotations = []
                            example = annotations_data[file.name]
                            annotations = example["objects"]
                            for annotation in annotations:
                                label = annotation["name"]
                                xmin, ymin = annotation["xmin"], annotation["ymin"]
                                xmax, ymax = annotation["xmax"], annotation["ymax"]
                                updated_annotations.append(
                                    get_coco_annotation_from_obj(
                                        count, label, xmin, ymin, xmax, ymax
                                    ),
                                )
                            example["image"] = image
                            example["objects"] = updated_annotations
                            example["image_id"] = str(count)
                            count += 1
                            yield count, example
                    except Exception:
                        logger.warn(file.name)
                        continue