File size: 9,835 Bytes
9939031
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import os
from typing import Dict, List, Tuple

# import csv
import datasets
import jsonlines as jl
import pandas as pd

from seacrowd.utils import schemas
from seacrowd.utils.configs import SEACrowdConfig
from seacrowd.utils.constants import Licenses, Tasks

_CITATION = """\
@inproceedings{thapliyal-etal-2022-crossmodal,
    title = "Crossmodal-3600: A Massively Multilingual Multimodal Evaluation Dataset",
    author = "Thapliyal, Ashish V.  and
      Pont Tuset, Jordi  and
      Chen, Xi  and
      Soricut, Radu",
    editor = "Goldberg, Yoav  and
      Kozareva, Zornitsa  and
      Zhang, Yue",
    booktitle = "Proceedings of the 2022 Conference on Empirical Methods in Natural Language Processing",
    month = dec,
    year = "2022",
    address = "Abu Dhabi, United Arab Emirates",
    publisher = "Association for Computational Linguistics",
    url = "https://aclanthology.org/2022.emnlp-main.45",
    doi = "10.18653/v1/2022.emnlp-main.45",
    pages = "715--729",
}
"""

_DATASETNAME = "coco_35l"

_DESCRIPTION = """\
    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.
    152520 image ids are not found in the coco 2014 training caption. Validation set is ok Using COCO 2014 train and validation set.
    """

_HOMEPAGE = "https://google.github.io/crossmodal-3600/"

_LICENSE = Licenses.CC_BY_4_0.value

_URLS = {
    "coco2017_train_images": "http://images.cocodataset.org/zips/train2017.zip",
    "coco2014_train_images": "http://images.cocodataset.org/zips/train2014.zip",
    "coco2014_val_images": "http://images.cocodataset.org/zips/val2014.zip",
    "coco2014_train_val_annots": "http://images.cocodataset.org/annotations/annotations_trainval2014.zip",
    "coco2017_train_val_annots": "http://images.cocodataset.org/annotations/annotations_trainval2017.zip",
    "trans_train": "https://storage.googleapis.com/crossmodal-3600/coco_mt_train.jsonl.gz",
    "trans_dev": "https://storage.googleapis.com/crossmodal-3600/coco_mt_dev.jsonl.gz",
}

_SUPPORTED_TASKS = [Tasks.IMAGE_CAPTIONING]

_SOURCE_VERSION = "1.0.0"

_SEACROWD_VERSION = "2024.06.20"

_LANGUAGES = {"fil": "fil", "ind": "id", "tha": "th", "vie": "vi"}

_LOCAL = False

class Coco35LDataset(datasets.GeneratorBasedBuilder):
    """
    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.
    """

    SOURCE_VERSION = datasets.Version(_SOURCE_VERSION)
    SEACROWD_VERSION = datasets.Version(_SEACROWD_VERSION)

    BUILDER_CONFIGS = [
        SEACrowdConfig(
            name=f"{_DATASETNAME}_{lang}_source",
            version=datasets.Version(_SOURCE_VERSION),
            description=f"{_DATASETNAME}_{lang} source schema",
            schema="source",
            subset_id=f"{_DATASETNAME}_{lang}",
        ) for lang in _LANGUAGES
    ] + [
        SEACrowdConfig(
            name=f"{_DATASETNAME}_{lang}_seacrowd_imtext",
            version=datasets.Version(_SEACROWD_VERSION),
            description=f"{_DATASETNAME}_{lang} SEACrowd schema",
            schema="seacrowd_imtext",
            subset_id=f"{_DATASETNAME}_{lang}",
        ) for lang in _LANGUAGES
    ]

    DEFAULT_CONFIG_NAME = f"{_DATASETNAME}_{sorted(_LANGUAGES)[0]}_source"

    def _info(self) -> datasets.DatasetInfo:
        if self.config.schema == "source":
            features = datasets.Features(
                {
                    "id": datasets.Value("string"),
                    "image_paths": datasets.Value("string"),
                    "src_lang": datasets.Value("string"),
                    "caption_tokenized": datasets.Value("string"),
                    "trg_lang": datasets.Value("string"),
                    "translation_tokenized": datasets.Value("string"),
                    "backtranslation_tokenized": datasets.Value("string"),
                }
            )
        elif self.config.schema == "seacrowd_imtext":
            features = schemas.image_text_features()

        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=features,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
        """Returns SplitGenerators."""
        trans_train_path = dl_manager.download_and_extract(_URLS["trans_train"])
        trans_val_path = dl_manager.download_and_extract(_URLS["trans_dev"])

        coco2014_train_val_annots_path = dl_manager.download_and_extract(_URLS["coco2014_train_val_annots"])
        coco2014_val_images_path = dl_manager.download_and_extract(_URLS["coco2014_val_images"])
        coco2014_train_images_path = dl_manager.download_and_extract(_URLS["coco2014_train_images"])

        trans_train_captions = {}
        trans_dev_captions = {}
        train_df = pd.DataFrame()
        val_df = pd.DataFrame()

        current_lang = _LANGUAGES[self.config.subset_id.split("_")[2]]

        # 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.
        # load the image informations from COCO 2014 dataset and put it into a dataframe
        with open(os.path.join(coco2014_train_val_annots_path, "annotations", "captions_val2014.json")) as json_captions:
            captions = json.load(json_captions)
            val_df = pd.DataFrame(captions["images"])

        with open(os.path.join(coco2014_train_val_annots_path, "annotations", "captions_train2014.json")) as json_captions:
            captions = json.load(json_captions)
            train_df = pd.DataFrame(captions["images"])

        # the translated caption has "image_id" which refers to the "image_id" in the COCO annotations.
        # however we can skip this and connect it to the images' "id"
        # the example of an "image_id" in the translated caption -> "123456_0" since an image can has many descriptions.
        # thus, the real image_id to map it into the COCO image dataset is the "123456"
        with jl.open(trans_train_path, mode="r") as j:
            total = 0
            not_found = 0
            missing_ids = []
            for line in j:
                if line["trg_lang"] == current_lang:
                    total += 1

                    trans_img_id = line["image_id"]
                    coco2014_img_id = line["image_id"].split("_")[0]

                    # unfortunately, not all image_id in the translated caption can be found in the original COCO 2014.
                    # hence, we need to handle such errors
                    try:
                        filename = train_df.query(f"id=={int(coco2014_img_id)}")["file_name"].values[0]
                        trans_train_captions[trans_img_id] = line
                        trans_train_captions[trans_img_id]["filename"] = os.path.join(coco2014_train_images_path, "train2014", filename)
                    except IndexError:
                        missing_ids.append(trans_img_id)
                        not_found += 1
                        pass

        # the validation set are strangely okay. with no missing image_id(s)
        with jl.open(trans_val_path, mode="r") as j:
            for line in j:
                if line["trg_lang"] == current_lang:
                    trans_img_id = line["image_id"]
                    trans_dev_captions[trans_img_id] = line
                    coco2014_img_id = int(trans_img_id.split("_")[0])
                    filename = val_df.query(f"id=={coco2014_img_id}")["file_name"].values[0]
                    trans_dev_captions[trans_img_id]["filename"] = os.path.join(coco2014_val_images_path, "val2014", filename)

        return [
            datasets.SplitGenerator(
                name=datasets.Split.TRAIN,
                gen_kwargs={
                    "filepath": {
                        "images": trans_train_captions,
                    },
                    "split": "train",
                },
            ),
            datasets.SplitGenerator(
                name=datasets.Split.VALIDATION,
                gen_kwargs={
                    "filepath": {
                        "images": trans_dev_captions,
                    },
                    "split": "dev",
                },
            ),
        ]

    def _generate_examples(self, filepath: dict, split: str) -> Tuple[int, Dict]:
        """Yields examples as (key, example) tuples."""
        counter = 0
        for trans_img_id, data in filepath["images"].items():
            if self.config.schema == "source":
                yield counter, {
                    "id": trans_img_id + "_" + str(counter),
                    "image_paths": data["filename"],
                    "src_lang": data["src_lang"],
                    "caption_tokenized": data["caption_tokenized"],
                    "trg_lang": data["trg_lang"],
                    "translation_tokenized": data["translation_tokenized"],
                    "backtranslation_tokenized": data["backtranslation_tokenized"],
                }

            elif self.config.schema == "seacrowd_imtext":
                yield counter, {
                    "id": trans_img_id + "_" + str(counter),
                    "image_paths": [data["filename"]],
                    "texts": data["translation_tokenized"],
                    "metadata": {
                        "context": None,
                        "labels": None,
                    },
                }

            else:
                raise ValueError(f"Invalid config: {self.config.name}")

            counter += 1