echarlaix HF staff commited on
Commit
1b5b6d6
1 Parent(s): 3d13a02

Add gqa dataset script

Browse files
Files changed (1) hide show
  1. gqa-lxmert.py +142 -0
gqa-lxmert.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """The GQA dataset preprocessed for LXMERT."""
16
+
17
+ import base64
18
+ import csv
19
+ import json
20
+ import os
21
+ import sys
22
+
23
+ import datasets
24
+ import numpy as np
25
+
26
+
27
+ csv.field_size_limit(sys.maxsize)
28
+
29
+
30
+ _CITATION = """\
31
+ @inproceedings{hudson2019gqa,
32
+ title={Gqa: A new dataset for real-world visual reasoning and compositional question answering},
33
+ author={Hudson, Drew A and Manning, Christopher D},
34
+ booktitle={Proceedings of the IEEE/CVF conference on computer vision and pattern recognition},
35
+ pages={6700--6709},
36
+ year={2019}
37
+ }
38
+ """
39
+
40
+ _DESCRIPTION = """\
41
+ GQA is a new dataset for real-world visual reasoning and compositional question answering,
42
+ seeking to address key shortcomings of previous visual question answering (VQA) datasets.
43
+ """
44
+
45
+ _URLS = {
46
+ "train": "https://nlp.cs.unc.edu/data/lxmert_data/gqa/train.json",
47
+ "dev": "https://nlp.cs.unc.edu/data/lxmert_data/gqa/valid.json",
48
+ "feat": "https://nlp.cs.unc.edu/data/lxmert_data/vg_gqa_imgfeat/vg_gqa_obj36.zip",
49
+ "ans2label": "https://raw.githubusercontent.com/airsplay/lxmert/master/data/gqa/trainval_ans2label.json",
50
+ }
51
+
52
+ _FEAT_PATH = "vg_gqa_imgfeat/vg_gqa_obj36.tsv"
53
+
54
+ FIELDNAMES = [
55
+ "img_id", "img_h", "img_w", "objects_id", "objects_conf", "attrs_id", "attrs_conf", "num_boxes", "boxes", "features"
56
+ ]
57
+
58
+ _SHAPE_FEATURES = (36, 2048)
59
+ _SHAPE_BOXES = (36, 4)
60
+
61
+
62
+ class GqaLxmert(datasets.GeneratorBasedBuilder):
63
+ """The GQA dataset preprocessed for LXMERT, with the objects features detected by a Faster RCNN replacing the
64
+ raw images."""
65
+
66
+ BUILDER_CONFIGS = [
67
+ datasets.BuilderConfig(name="gqa", version=datasets.Version("1.0.0"), description="GQA dataset."),
68
+ ]
69
+
70
+ def _info(self):
71
+ features = datasets.Features(
72
+ {
73
+ "question": datasets.Value("string"),
74
+ "question_id": datasets.Value("int32"),
75
+ "image_id": datasets.Value("string"),
76
+ "features": datasets.Array2D(_SHAPE_FEATURES, dtype="float32"),
77
+ "boxes": datasets.Array2D(_SHAPE_BOXES, dtype="float32"),
78
+ "label": datasets.Value("int32"),
79
+ }
80
+ )
81
+ return datasets.DatasetInfo(
82
+ description=_DESCRIPTION,
83
+ features=features,
84
+ supervised_keys=None,
85
+ citation=_CITATION,
86
+ )
87
+
88
+ def _split_generators(self, dl_manager):
89
+ """Returns SplitGenerators."""
90
+ dl_dir = dl_manager.download_and_extract(_URLS)
91
+ self.ans2label = json.load(open(dl_dir["ans2label"]))
92
+ self.id2features = self._load_features(os.path.join(dl_dir["feat"], _FEAT_PATH))
93
+
94
+ return [
95
+ datasets.SplitGenerator(
96
+ name=datasets.Split.TRAIN,
97
+ gen_kwargs={"filepath": dl_dir["train"]},
98
+ ),
99
+ datasets.SplitGenerator(
100
+ name=datasets.Split.VALIDATION,
101
+ gen_kwargs={"filepath": dl_dir["dev"]},
102
+ ),
103
+ ]
104
+
105
+ def _load_features(self, filepath):
106
+ """Returns a dictionary mapping an image id to the corresponding image's objects features."""
107
+ id2features = {}
108
+ with open(filepath) as f:
109
+ reader = csv.DictReader(f, FIELDNAMES, delimiter="\t")
110
+ for i, item in enumerate(reader):
111
+ features = {}
112
+ for key in ["img_h", "img_w", "num_boxes"]:
113
+ features[key] = int(item[key])
114
+ num_boxes = features["num_boxes"]
115
+ decode_config = [
116
+ ("objects_id", (num_boxes,), np.int64),
117
+ ("objects_conf", (num_boxes,), np.float32),
118
+ ("attrs_id", (num_boxes,), np.int64),
119
+ ("attrs_conf", (num_boxes,), np.float32),
120
+ ("boxes", (num_boxes, 4), np.float32),
121
+ ("features", (num_boxes, -1), np.float32),
122
+ ]
123
+ for key, shape, dtype in decode_config:
124
+ features[key] = np.frombuffer(base64.b64decode(item[key]), dtype=dtype).reshape(shape)
125
+ id2features[item["img_id"]] = features
126
+ return id2features
127
+
128
+ def _generate_examples(self, filepath):
129
+ """ Yields examples as (key, example) tuples."""
130
+ with open(filepath, encoding="utf-8") as f:
131
+ gqa = json.load(f)
132
+ for id_, d in enumerate(gqa):
133
+ img_features = self.id2features[d["img_id"]]
134
+ label = self.ans2label[next(iter(d["label"]))]
135
+ yield id_, {
136
+ "question": d["sent"],
137
+ "question_id": d["question_id"],
138
+ "image_id": d["img_id"],
139
+ "features": img_features["features"],
140
+ "boxes": img_features["boxes"],
141
+ "label": label,
142
+ }