File size: 6,100 Bytes
942378c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright 2020 The HuggingFace Datasets Authors.
#
# 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.
"""adVQA loading script."""


import csv
import json
import os
from pathlib import Path

import datasets


_CITATION = """\
@InProceedings{sheng2021human,
author = {Sheng, Sasha and Singh, Amanpreet and Goswami, Vedanuj and Magana, Jose Alberto Lopez and Galuba, Wojciech and Parikh, Devi and Kiela, Douwe},
title = {Human-Adversarial Visual Question Answering},
journal={arXiv preprint arXiv:2106.02280},
year = {2021},
} 
"""

_DESCRIPTION = """\
This is v1.0 of the ADVQA dataset.
"""

_HOMEPAGE = "https://adversarialvqa.org"

_LICENSE = "CC BY-NC 4.0" # In json file

_URLS = {
    "questions": {
        "val": "https://dl.fbaipublicfiles.com/advqa/v1_OpenEnded_mscoco_val2017_advqa_questions.json",
        "test-dev": "https://dl.fbaipublicfiles.com/advqa/v1_OpenEnded_mscoco_testdev2015_advqa_questions.json",
    },
    "annotations": {
        "val": "https://dl.fbaipublicfiles.com/advqa/v1_mscoco_val2017_advqa_annotations.json",
    },
    "images": {
        "val": "http://images.cocodataset.org/zips/val2014.zip",
        "test-dev": "http://images.cocodataset.org/zips/test2015.zip",
    },
}
_SUB_FOLDER_OR_FILE_NAME = {
    "questions": {
        "val": None,
        "test-dev": None,
    },
    "annotations": {
        "val": None,
    },
    "images": {
        "val": "val2014",
        "test-dev": "test2015",
    },
}


class VQAv2Dataset(datasets.GeneratorBasedBuilder):

    VERSION = datasets.Version("1.0.0")

    # BUILDER_CONFIGS = [
    #     datasets.BuilderConfig(name="v2", version=VERSION, description="TODO later"), coco version in-domain
    #     datasets.BuilderConfig(name="v1", version=VERSION, description="TODO later"), AVQA out-of-domain 
    # ]

    def _info(self):
        features = datasets.Features(
            {
                "answers": [
                    {
                        "answer": datasets.Value("string"),
                        "answer_id": datasets.Value("int64"),
                    }
                ],
                "image_id": datasets.Value("int64"),
                "answer_type": datasets.Value("string"),
                "question_id": datasets.Value("int64"),
                "question": datasets.Value("string"),
                "image": datasets.Image(),
            }
        )
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        # urls = _URLS[self.config.name] # TODO later
        data_dir = dl_manager.download_and_extract(_URLS)
        gen_kwargs = {}
        for split_name in ["val", "test-dev"]:
            gen_kwargs_per_split = {} 
            for dir_name in _URLS.keys():
                sub_folder_or_file_name = _SUB_FOLDER_OR_FILE_NAME.get(dir_name, None).get(split_name, None)
                if split_name in data_dir[dir_name] and sub_folder_or_file_name is not None:
                    path = Path(data_dir[dir_name][split_name]) / sub_folder_or_file_name
                elif split_name in data_dir[dir_name]:
                    path = Path(data_dir[dir_name][split_name])
                else:
                    path = None 
                gen_kwargs_per_split[f"{dir_name}_path"] = path
            gen_kwargs[split_name] = gen_kwargs_per_split

        return [
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                gen_kwargs=gen_kwargs["val"],
            ),
            datasets.SplitGenerator(
                name="testdev",
                gen_kwargs=gen_kwargs["test-dev"],
            ),
        ]

    def _generate_examples(self, questions_path, annotations_path, images_path):
        questions = json.load(open(questions_path, "r"))

        if annotations_path is not None:
            dataset = json.load(open(annotations_path, "r"))

            qa = {ann["question_id"]: [] for ann in dataset["annotations"]}
            for ann in dataset["annotations"]:
                qa[ann["question_id"]] = ann

            for question in questions["questions"]:
                annotation = qa[question["question_id"]]
                # some checks
                assert len(set(question.keys()) ^ set(["image_id", "question", "question_id"])) == 0
                assert (
                    len(
                        set(annotation.keys())
                        ^ set(
                            [
                                "answers",
                                "image_id",
                                "answer_type",
                                "question_id",
                            ]
                        )
                    )
                    == 0
                )
                record = question
                record.update(annotation)
                record["image"] = str(images_path / f"COCO_{images_path.name}_{record['image_id']:0>12}.jpg")
                yield question["question_id"], record
        else:
            # No annotations for the test split
            for question in questions["questions"]:
                question.update(
                    {
                        "answers": None,
                        "answer_type": None,
                    }
                )
                question["image"] = str(images_path / f"COCO_{images_path.name}_{question['image_id']:0>12}.jpg")
                yield question["question_id"], question