Datasets:

ArXiv:
License:
holylovenia commited on
Commit
9939031
·
verified ·
1 Parent(s): eeaaaf3

Upload coco_35l.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. coco_35l.py +230 -0
coco_35l.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from typing import Dict, List, Tuple
4
+
5
+ # import csv
6
+ import datasets
7
+ import jsonlines as jl
8
+ import pandas as pd
9
+
10
+ from seacrowd.utils import schemas
11
+ from seacrowd.utils.configs import SEACrowdConfig
12
+ from seacrowd.utils.constants import Licenses, Tasks
13
+
14
+ _CITATION = """\
15
+ @inproceedings{thapliyal-etal-2022-crossmodal,
16
+ title = "Crossmodal-3600: A Massively Multilingual Multimodal Evaluation Dataset",
17
+ author = "Thapliyal, Ashish V. and
18
+ Pont Tuset, Jordi and
19
+ Chen, Xi and
20
+ Soricut, Radu",
21
+ editor = "Goldberg, Yoav and
22
+ Kozareva, Zornitsa and
23
+ Zhang, Yue",
24
+ booktitle = "Proceedings of the 2022 Conference on Empirical Methods in Natural Language Processing",
25
+ month = dec,
26
+ year = "2022",
27
+ address = "Abu Dhabi, United Arab Emirates",
28
+ publisher = "Association for Computational Linguistics",
29
+ url = "https://aclanthology.org/2022.emnlp-main.45",
30
+ doi = "10.18653/v1/2022.emnlp-main.45",
31
+ pages = "715--729",
32
+ }
33
+ """
34
+
35
+ _DATASETNAME = "coco_35l"
36
+
37
+ _DESCRIPTION = """\
38
+ COCO-35L is a machine-generated image caption dataset, constructed by translating COCO Captions (Chen et al., 2015) to the other 34 languages using Google’s machine translation API.
39
+ 152520 image ids are not found in the coco 2014 training caption. Validation set is ok Using COCO 2014 train and validation set.
40
+ """
41
+
42
+ _HOMEPAGE = "https://google.github.io/crossmodal-3600/"
43
+
44
+ _LICENSE = Licenses.CC_BY_4_0.value
45
+
46
+ _URLS = {
47
+ "coco2017_train_images": "http://images.cocodataset.org/zips/train2017.zip",
48
+ "coco2014_train_images": "http://images.cocodataset.org/zips/train2014.zip",
49
+ "coco2014_val_images": "http://images.cocodataset.org/zips/val2014.zip",
50
+ "coco2014_train_val_annots": "http://images.cocodataset.org/annotations/annotations_trainval2014.zip",
51
+ "coco2017_train_val_annots": "http://images.cocodataset.org/annotations/annotations_trainval2017.zip",
52
+ "trans_train": "https://storage.googleapis.com/crossmodal-3600/coco_mt_train.jsonl.gz",
53
+ "trans_dev": "https://storage.googleapis.com/crossmodal-3600/coco_mt_dev.jsonl.gz",
54
+ }
55
+
56
+ _SUPPORTED_TASKS = [Tasks.IMAGE_CAPTIONING]
57
+
58
+ _SOURCE_VERSION = "1.0.0"
59
+
60
+ _SEACROWD_VERSION = "2024.06.20"
61
+
62
+ _LANGUAGES = {"fil": "fil", "ind": "id", "tha": "th", "vie": "vi"}
63
+
64
+ _LOCAL = False
65
+
66
+ class Coco35LDataset(datasets.GeneratorBasedBuilder):
67
+ """
68
+ COCO-35L is a machine-generated image caption dataset, constructed by translating COCO Captions (Chen et al., 2015) to the other 34 languages using Google’s machine translation API.
69
+ """
70
+
71
+ SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
72
+ SEACROWD_VERSION = datasets.Version(_SEACROWD_VERSION)
73
+
74
+ BUILDER_CONFIGS = [
75
+ SEACrowdConfig(
76
+ name=f"{_DATASETNAME}_{lang}_source",
77
+ version=datasets.Version(_SOURCE_VERSION),
78
+ description=f"{_DATASETNAME}_{lang} source schema",
79
+ schema="source",
80
+ subset_id=f"{_DATASETNAME}_{lang}",
81
+ ) for lang in _LANGUAGES
82
+ ] + [
83
+ SEACrowdConfig(
84
+ name=f"{_DATASETNAME}_{lang}_seacrowd_imtext",
85
+ version=datasets.Version(_SEACROWD_VERSION),
86
+ description=f"{_DATASETNAME}_{lang} SEACrowd schema",
87
+ schema="seacrowd_imtext",
88
+ subset_id=f"{_DATASETNAME}_{lang}",
89
+ ) for lang in _LANGUAGES
90
+ ]
91
+
92
+ DEFAULT_CONFIG_NAME = f"{_DATASETNAME}_{sorted(_LANGUAGES)[0]}_source"
93
+
94
+ def _info(self) -> datasets.DatasetInfo:
95
+ if self.config.schema == "source":
96
+ features = datasets.Features(
97
+ {
98
+ "id": datasets.Value("string"),
99
+ "image_paths": datasets.Value("string"),
100
+ "src_lang": datasets.Value("string"),
101
+ "caption_tokenized": datasets.Value("string"),
102
+ "trg_lang": datasets.Value("string"),
103
+ "translation_tokenized": datasets.Value("string"),
104
+ "backtranslation_tokenized": datasets.Value("string"),
105
+ }
106
+ )
107
+ elif self.config.schema == "seacrowd_imtext":
108
+ features = schemas.image_text_features()
109
+
110
+ return datasets.DatasetInfo(
111
+ description=_DESCRIPTION,
112
+ features=features,
113
+ homepage=_HOMEPAGE,
114
+ license=_LICENSE,
115
+ citation=_CITATION,
116
+ )
117
+
118
+ def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
119
+ """Returns SplitGenerators."""
120
+ trans_train_path = dl_manager.download_and_extract(_URLS["trans_train"])
121
+ trans_val_path = dl_manager.download_and_extract(_URLS["trans_dev"])
122
+
123
+ coco2014_train_val_annots_path = dl_manager.download_and_extract(_URLS["coco2014_train_val_annots"])
124
+ coco2014_val_images_path = dl_manager.download_and_extract(_URLS["coco2014_val_images"])
125
+ coco2014_train_images_path = dl_manager.download_and_extract(_URLS["coco2014_train_images"])
126
+
127
+ trans_train_captions = {}
128
+ trans_dev_captions = {}
129
+ train_df = pd.DataFrame()
130
+ val_df = pd.DataFrame()
131
+
132
+ current_lang = _LANGUAGES[self.config.subset_id.split("_")[2]]
133
+
134
+ # the COCO dataset structure has separated the captions and images information. The caption's "image_id" key will refer to the image's "id" key.
135
+ # load the image informations from COCO 2014 dataset and put it into a dataframe
136
+ with open(os.path.join(coco2014_train_val_annots_path, "annotations", "captions_val2014.json")) as json_captions:
137
+ captions = json.load(json_captions)
138
+ val_df = pd.DataFrame(captions["images"])
139
+
140
+ with open(os.path.join(coco2014_train_val_annots_path, "annotations", "captions_train2014.json")) as json_captions:
141
+ captions = json.load(json_captions)
142
+ train_df = pd.DataFrame(captions["images"])
143
+
144
+ # the translated caption has "image_id" which refers to the "image_id" in the COCO annotations.
145
+ # however we can skip this and connect it to the images' "id"
146
+ # the example of an "image_id" in the translated caption -> "123456_0" since an image can has many descriptions.
147
+ # thus, the real image_id to map it into the COCO image dataset is the "123456"
148
+ with jl.open(trans_train_path, mode="r") as j:
149
+ total = 0
150
+ not_found = 0
151
+ missing_ids = []
152
+ for line in j:
153
+ if line["trg_lang"] == current_lang:
154
+ total += 1
155
+
156
+ trans_img_id = line["image_id"]
157
+ coco2014_img_id = line["image_id"].split("_")[0]
158
+
159
+ # unfortunately, not all image_id in the translated caption can be found in the original COCO 2014.
160
+ # hence, we need to handle such errors
161
+ try:
162
+ filename = train_df.query(f"id=={int(coco2014_img_id)}")["file_name"].values[0]
163
+ trans_train_captions[trans_img_id] = line
164
+ trans_train_captions[trans_img_id]["filename"] = os.path.join(coco2014_train_images_path, "train2014", filename)
165
+ except IndexError:
166
+ missing_ids.append(trans_img_id)
167
+ not_found += 1
168
+ pass
169
+
170
+ # the validation set are strangely okay. with no missing image_id(s)
171
+ with jl.open(trans_val_path, mode="r") as j:
172
+ for line in j:
173
+ if line["trg_lang"] == current_lang:
174
+ trans_img_id = line["image_id"]
175
+ trans_dev_captions[trans_img_id] = line
176
+ coco2014_img_id = int(trans_img_id.split("_")[0])
177
+ filename = val_df.query(f"id=={coco2014_img_id}")["file_name"].values[0]
178
+ trans_dev_captions[trans_img_id]["filename"] = os.path.join(coco2014_val_images_path, "val2014", filename)
179
+
180
+ return [
181
+ datasets.SplitGenerator(
182
+ name=datasets.Split.TRAIN,
183
+ gen_kwargs={
184
+ "filepath": {
185
+ "images": trans_train_captions,
186
+ },
187
+ "split": "train",
188
+ },
189
+ ),
190
+ datasets.SplitGenerator(
191
+ name=datasets.Split.VALIDATION,
192
+ gen_kwargs={
193
+ "filepath": {
194
+ "images": trans_dev_captions,
195
+ },
196
+ "split": "dev",
197
+ },
198
+ ),
199
+ ]
200
+
201
+ def _generate_examples(self, filepath: dict, split: str) -> Tuple[int, Dict]:
202
+ """Yields examples as (key, example) tuples."""
203
+ counter = 0
204
+ for trans_img_id, data in filepath["images"].items():
205
+ if self.config.schema == "source":
206
+ yield counter, {
207
+ "id": trans_img_id + "_" + str(counter),
208
+ "image_paths": data["filename"],
209
+ "src_lang": data["src_lang"],
210
+ "caption_tokenized": data["caption_tokenized"],
211
+ "trg_lang": data["trg_lang"],
212
+ "translation_tokenized": data["translation_tokenized"],
213
+ "backtranslation_tokenized": data["backtranslation_tokenized"],
214
+ }
215
+
216
+ elif self.config.schema == "seacrowd_imtext":
217
+ yield counter, {
218
+ "id": trans_img_id + "_" + str(counter),
219
+ "image_paths": [data["filename"]],
220
+ "texts": data["translation_tokenized"],
221
+ "metadata": {
222
+ "context": None,
223
+ "labels": None,
224
+ },
225
+ }
226
+
227
+ else:
228
+ raise ValueError(f"Invalid config: {self.config.name}")
229
+
230
+ counter += 1