File size: 12,916 Bytes
3fbabfa
 
 
5b858ef
3fbabfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b858ef
 
3fbabfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7dd6183
 
 
 
 
 
 
 
3fbabfa
 
 
 
 
 
 
5b858ef
 
 
3fbabfa
 
 
 
 
 
 
 
5b858ef
 
 
3fbabfa
 
 
 
 
 
 
 
5b858ef
 
 
3fbabfa
 
 
 
 
 
 
 
 
5b858ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3fbabfa
 
 
5b858ef
3fbabfa
5b858ef
3fbabfa
 
 
5b858ef
3fbabfa
 
 
 
 
5b858ef
 
 
 
 
3fbabfa
 
5b858ef
 
3fbabfa
 
5b858ef
 
 
3fbabfa
 
 
5b858ef
 
 
 
 
 
 
 
 
 
3fbabfa
 
5b858ef
3fbabfa
 
 
 
5b858ef
 
3fbabfa
 
 
5b858ef
 
 
 
 
 
 
 
 
3fbabfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b858ef
 
 
 
 
 
 
 
 
 
 
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
import json
import os
import datasets
import torch


class COCOBuilderConfig(datasets.BuilderConfig):

    def __init__(self, name, splits, **kwargs):
        super().__init__(name, **kwargs)
        self.splits = splits


# Add BibTeX citation
# Find for instance the citation on arxiv or on the dataset repo/website
_CITATION = """\
@article{DBLP:journals/corr/LinMBHPRDZ14,
  author    = {Tsung{-}Yi Lin and
               Michael Maire and
               Serge J. Belongie and
               Lubomir D. Bourdev and
               Ross B. Girshick and
               James Hays and
               Pietro Perona and
               Deva Ramanan and
               Piotr Doll{'{a} }r and
               C. Lawrence Zitnick},
  title     = {Microsoft {COCO:} Common Objects in Context},
  journal   = {CoRR},
  volume    = {abs/1405.0312},
  year      = {2014},
  url       = {http://arxiv.org/abs/1405.0312},
  archivePrefix = {arXiv},
  eprint    = {1405.0312},
  timestamp = {Mon, 13 Aug 2018 16:48:13 +0200},
  biburl    = {https://dblp.org/rec/bib/journals/corr/LinMBHPRDZ14},
  bibsource = {dblp computer science bibliography, https://dblp.org}
}
"""

# Add description of the dataset here
# You can copy an official description
_DESCRIPTION = """\
COCO is a large-scale object detection, segmentation, and captioning dataset.
"""

# Add a link to an official homepage for the dataset here
_HOMEPAGE = "http://cocodataset.org/#home"

# Add the licence for the dataset here if you can find it
_LICENSE = ""

# Add link to the official dataset URLs here
# The HuggingFace dataset library don't host the datasets but only point to the original files
# This can be an arbitrary nested dict/list of URLs (see below in `_split_generators` method)

# This script is supposed to work with local (downloaded) COCO dataset.
_URLs = {}


# Name of the dataset usually match the script name with CamelCase instead of snake_case
class COCODataset(datasets.GeneratorBasedBuilder):
    """An example dataset script to work with the local (downloaded) COCO dataset"""

    VERSION = datasets.Version("0.0.0")

    BUILDER_CONFIG_CLASS = COCOBuilderConfig
    BUILDER_CONFIGS = [
        COCOBuilderConfig(name='2017', splits=['train', 'valid', 'test']),
    ]
    DEFAULT_CONFIG_NAME = "2017"

    def _info(self):
        # This method specifies the datasets.DatasetInfo object which contains informations and typings for the dataset

        feature_dict = {
            "image_id": datasets.Value("int64"),
            "caption_id": datasets.Value("int64"),
            "caption": datasets.Value("string"),
            "height": datasets.Value("int64"),
            "width": datasets.Value("int64"),
            "file_name": datasets.Value("string"),
            "coco_url": datasets.Value("string"),
            "image_path": datasets.Value("string"),
            "category_ids": datasets.Sequence(datasets.Value("int64")),
            "category_one_hot": datasets.Sequence(datasets.Value("int64")),
        }

        features = datasets.Features(feature_dict)

        return datasets.DatasetInfo(
            # This is the description that will appear on the datasets page.
            description=_DESCRIPTION,
            # This defines the different columns of the dataset and their types
            features=features,  # Here we define them above because they are different between the two configurations
            # If there's a common (input, target) tuple from the features,
            # specify them here. They'll be used if as_supervised=True in
            # builder.as_dataset.
            supervised_keys=None,
            # Homepage of the dataset for documentation
            homepage=_HOMEPAGE,
            # License for the dataset if available
            license=_LICENSE,
            # Citation for the dataset
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        """Returns SplitGenerators."""
        # This method is tasked with downloading/extracting the data and defining the splits depending on the configuration
        # If several configurations are possible (listed in BUILDER_CONFIGS), the configuration selected by the user is in self.config.name

        data_dir = self.config.data_dir
        if not data_dir:
            raise ValueError(
                "This script is supposed to work with local (downloaded) COCO dataset. The argument `data_dir` in `load_dataset()` is required."
            )

        _DL_URLS = {
            "train": os.path.join(data_dir, "train2017.zip"),
            "val": os.path.join(data_dir, "val2017.zip"),
            "test": os.path.join(data_dir, "test2017.zip"),
            "annotations_trainval": os.path.join(data_dir, "annotations_trainval2017.zip"),
            "image_info_test": os.path.join(data_dir, "image_info_test2017.zip"),
        }

        splits = []
        for split in self.config.splits:
            if split == 'train':
                dataset = datasets.SplitGenerator(
                    name=datasets.Split.TRAIN,
                    # These kwargs will be passed to _generate_examples
                    gen_kwargs={
                        "captions_json_path": os.path.join(data_dir, "annotations", "captions_train2017.json"),
                        "instances_json_path": os.path.join(data_dir, "annotations", "instances_train2017.json"),
                        "image_dir": os.path.join(data_dir, "train2017"),
                        "split": "train",
                    }
                )
            elif split in ['val', 'valid', 'validation', 'dev']:
                dataset = datasets.SplitGenerator(
                    name=datasets.Split.VALIDATION,
                    # These kwargs will be passed to _generate_examples
                    gen_kwargs={
                        "captions_json_path": os.path.join(data_dir, "annotations", "captions_val2017.json"),
                        "instances_json_path": os.path.join(data_dir, "annotations", "instances_val2017.json"),
                        "image_dir": os.path.join(data_dir, "val2017"),
                        "split": "valid",
                    },
                )
            elif split == 'test':
                dataset = datasets.SplitGenerator(
                    name=datasets.Split.TEST,
                    # These kwargs will be passed to _generate_examples
                    gen_kwargs={
                        "captions_json_path": os.path.join(data_dir, "annotations", "image_info_test2017.json"),
                        "instances_json_path": os.path.join(data_dir, "annotations", "image_info_test2017.json"), # "instances_test2017.json
                        "image_dir": os.path.join(data_dir, "test2017"),
                        "split": "test",
                    },
                )
            else:
                continue

            splits.append(dataset)

        return splits
    
    # instances.json
#     {
    #     "info": {
    #         "year": "2020",
    #         "version": "1",
    #         "description": "Exported from roboflow.ai",
    #         "contributor": "Roboflow",
    #         "url": "https://app.roboflow.ai/datasets/hard-hat-sample/1",
    #         "date_created": "2000-01-01T00:00:00+00:00"
    #     },
    #     "licenses": [
    #         {
    #             "id": 1,
    #             "url": "https://creativecommons.org/publicdomain/zero/1.0/",
    #             "name": "Public Domain"
    #         }
    #     ],
    #     "categories": [
    #         {
    #             "id": 0,
    #             "name": "Workers",
    #             "supercategory": "none"
    #         },
    #         {
    #             "id": 1,
    #             "name": "head",
    #             "supercategory": "Workers"
    #         },
    #         {
    #             "id": 2,
    #             "name": "helmet",
    #             "supercategory": "Workers"
    #         },
    #         {
    #             "id": 3,
    #             "name": "person",
    #             "supercategory": "Workers"
    #         }
    #     ],
    #     "images": [
    #         {
    #             "id": 0,
    #             "license": 1,
    #             "file_name": "0001.jpg",
    #             "height": 275,
    #             "width": 490,
    #             "date_captured": "2020-07-20T19:39:26+00:00"
    #         }
    #     ],
    #     "annotations": [
    #         {
    #             "id": 0,
    #             "image_id": 0,
    #             "category_id": 2,
    #             "bbox": [
    #                 45,
    #                 2,
    #                 85,
    #                 85
    #             ],
    #             "area": 7225,
    #             "segmentation": [],
    #             "iscrowd": 0
    #         },
    #         {
    #             "id": 1,
    #             "image_id": 0,
    #             "category_id": 2,
    #             "bbox": [
    #                 324,
    #                 29,
    #                 72,
    #                 81
    #             ],
    #             "area": 5832,
    #             "segmentation": [],
    #             "iscrowd": 0
    #         }
    #     ]
    # }

    def _generate_examples(
        # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
        self, captions_json_path, instances_json_path, image_dir, split
    ):
        """ Yields examples as (key, example, categories) tuples. """
        # This method handles input defined in _split_generators to yield (key, example) tuples from the dataset.
        # The `key` is here for legacy reason (tfds) and is not important in itself.

        _features = ["image_id", "caption_id", "caption", "height", "width", "file_name", "coco_url", "image_path", "id", "category_ids", "category_one_hot"]
        features = list(_features)

        if split in "valid":
            split = "val"

        with open(captions_json_path, 'r', encoding='UTF-8') as fp:
            captions_data = json.load(fp)

        with open(instances_json_path, 'r', encoding='UTF-8') as fp:
            instances_data = json.load(fp)

        # list of dict
        images = captions_data["images"]
        instances_annotations = instances_data["annotations"]
        entries = images

        self.classes = list(map(lambda x: {'id': x['id'], 'name': x['name']}, instances_data['categories']))
        self.num_classes = len(self.classes)

        # build a dict of image_id -> image info dict
        d = {image["id"]: image for image in images}

        # build a dict of image_id -> list of category_ids
        cat_ids_dict = {}

        for annotation in instances_annotations:
            image_id = annotation["image_id"]
            category_id = annotation["category_id"]
            if image_id not in cat_ids_dict:
                cat_ids_dict[image_id] = set([])
            cat_ids_dict[image_id].add(category_id)

        # list of dict
        if split in ["train", "val"]:
            annotations = captions_data["annotations"]       

            # build a dict of image_id ->
            for annotation in annotations:
                _id = annotation["id"]
                image_id = annotation["image_id"]
                image_info = d[image_id]
                annotation.update(image_info)
                annotation["id"] = _id

                # Add the category_ids to the annotation
                annotation["category_ids"] = cat_ids_dict[annotation["image_id"]] if annotation["image_id"] in cat_ids_dict else []
                
                annotation['category_one_hot'] = torch.zeros(len(self.classes))
                for category_id in annotation["category_ids"]:
                    # Get index of category_id in self.classes
                    index = next((index for (index, d) in enumerate(self.classes) if d["id"] == category_id), None)
                    annotation['category_one_hot'][index] = 1

            entries = annotations

        for id_, entry in enumerate(entries):

            entry = {k: v for k, v in entry.items() if k in features}

            if split == "test":
                entry["image_id"] = entry["id"]
                entry["id"] = -1
                entry["caption"] = -1

            entry["caption_id"] = entry.pop("id")
            entry["image_path"] = os.path.join(image_dir, entry["file_name"])

            entry = {k: entry[k] for k in _features if k in entry}

            yield str((entry["image_id"], entry["caption_id"])), entry

from datasets import load_dataset
if __name__ == "__main__":
    dataset = load_dataset(
            "coco_dataset_multi_label_script/coco_dataset_multi_label_script.py",
            "2017",
            keep_in_memory=False,
            splits=["valid"],
            data_dir="/workspace/pixt/clip-training/data/mscoco",
        )
    print(dataset["validation"][0])