echarlaix HF staff commited on
Commit
cb2942e
1 Parent(s): 26d4fbf

Commit file to HF hub

Browse files
Files changed (1) hide show
  1. gqa-lxmert.py +144 -0
gqa-lxmert.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "train_feat": "https://nlp.cs.unc.edu/data/lxmert_data/vg_gqa_imgfeat/vg_gqa_obj36.zip",
48
+ "dev": "https://nlp.cs.unc.edu/data/lxmert_data/gqa/valid.json",
49
+ "dev_feat": "https://nlp.cs.unc.edu/data/lxmert_data/vg_gqa_imgfeat/gqa_testdev_obj36.zip",
50
+ "ans2label": "https://raw.githubusercontent.com/airsplay/lxmert/master/data/gqa/trainval_ans2label.json",
51
+ }
52
+
53
+ _TRAIN_IMG_PATH = "vg_gqa_obj36.tsv"
54
+ _DEV_IMG_PATH = "vg_gqa_imgfeat/gqa_testdev_obj36.tsv"
55
+
56
+ FIELDNAMES = [
57
+ "img_id", "img_h", "img_w", "objects_id", "objects_conf", "attrs_id", "attrs_conf", "num_boxes", "boxes", "features"
58
+ ]
59
+
60
+ SHAPE_FEATURES = (36, 2048)
61
+ SHAPE_BOXES = (36, 4)
62
+
63
+
64
+ class GqaLxmert(datasets.GeneratorBasedBuilder):
65
+ """The GQA dataset preprocessed for LXMERT, with the objects features detected by a Faster RCNN replacing the
66
+ raw images."""
67
+
68
+ BUILDER_CONFIGS = [
69
+ datasets.BuilderConfig(name="gqa", version=datasets.Version("1.0.0"), description="GQA dataset."),
70
+ ]
71
+
72
+ def _info(self):
73
+ features = datasets.Features(
74
+ {
75
+ "question": datasets.Value("string"),
76
+ "question_id": datasets.Value("int32"),
77
+ "image_id": datasets.Value("string"),
78
+ "features": datasets.Array2D(SHAPE_FEATURES, dtype="float32"),
79
+ "boxes": datasets.Array2D(SHAPE_BOXES, dtype="float32"),
80
+ "label": datasets.Value("int32"),
81
+ }
82
+ )
83
+ return datasets.DatasetInfo(
84
+ description=_DESCRIPTION,
85
+ features=features,
86
+ supervised_keys=None,
87
+ citation=_CITATION,
88
+ )
89
+
90
+ def _split_generators(self, dl_manager):
91
+ """Returns SplitGenerators."""
92
+ dl_dir = dl_manager.download_and_extract(_URLS)
93
+ self.ans2label = json.load(open(dl_dir["ans2label"]))
94
+
95
+ return [
96
+ datasets.SplitGenerator(
97
+ name=datasets.Split.TRAIN,
98
+ gen_kwargs={"filepath": dl_dir["train"], "imgfeat": os.path.join(dl_dir["train_feat"], _TRAIN_IMG_PATH)},
99
+ ),
100
+ datasets.SplitGenerator(
101
+ name=datasets.Split.VALIDATION,
102
+ gen_kwargs={"filepath": dl_dir["dev"], "imgfeat": os.path.join(dl_dir["dev_feat"], _DEV_IMG_PATH)},
103
+ ),
104
+ ]
105
+
106
+ def _load_features(self, filepath):
107
+ """Returns a dictionary mapping an image id to the corresponding image's objects features."""
108
+ id2features = {}
109
+ with open(filepath) as f:
110
+ reader = csv.DictReader(f, FIELDNAMES, delimiter="\t")
111
+ for i, item in enumerate(reader):
112
+ features = {}
113
+ for key in ["img_h", "img_w", "num_boxes"]:
114
+ features[key] = int(item[key])
115
+ num_boxes = features["num_boxes"]
116
+ decode_config = [
117
+ ("objects_id", (num_boxes,), np.int64),
118
+ ("objects_conf", (num_boxes,), np.float32),
119
+ ("attrs_id", (num_boxes,), np.int64),
120
+ ("attrs_conf", (num_boxes,), np.float32),
121
+ ("boxes", (num_boxes, 4), np.float32),
122
+ ("features", (num_boxes, -1), np.float32),
123
+ ]
124
+ for key, shape, dtype in decode_config:
125
+ features[key] = np.frombuffer(base64.b64decode(item[key]), dtype=dtype).reshape(shape)
126
+ id2features[item["img_id"]] = features
127
+ return id2features
128
+
129
+ def _generate_examples(self, filepath, imgfeat):
130
+ """ Yields examples as (key, example) tuples."""
131
+ id2features = self._load_features(imgfeat)
132
+ with open(filepath, encoding="utf-8") as f:
133
+ gqa = json.load(f)
134
+ for id_, d in enumerate(gqa):
135
+ img_features = id2features[d["img_id"]]
136
+ label = self.ans2label[next(iter(d["label"]))]
137
+ yield id_, {
138
+ "question": d["sent"],
139
+ "question_id": d["question_id"],
140
+ "image_id": d["img_id"],
141
+ "features": img_features["features"],
142
+ "boxes": img_features["boxes"],
143
+ "label": label,
144
+ }