File size: 30,964 Bytes
1d83a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e03859
 
1d83a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e03859
 
 
 
 
 
 
1d83a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e03859
 
1d83a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e03859
 
 
 
 
 
1d83a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e03859
 
 
 
 
1d83a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e03859
 
 
 
 
1d83a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e03859
 
 
 
 
1d83a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e03859
 
 
 
 
1d83a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e03859
 
 
 
 
1d83a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e03859
 
 
 
 
1d83a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e03859
 
 
 
 
1d83a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e03859
 
 
 
 
1d83a66
 
 
 
 
 
 
 
 
 
 
 
 
 
09b5b06
1d83a66
 
 
 
 
 
3e03859
 
 
 
 
1d83a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e03859
 
 
 
 
1d83a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e03859
 
 
 
 
1d83a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09b5b06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d83a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
# coding=utf-8
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor.
#
# 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.
"""Wikipedia-based Image Text (WIT) Dataset is a large multimodal multilingual dataset"""
import json
import re
import sqlite3
from abc import abstractmethod
from hashlib import md5
from pathlib import Path
from typing import Any, Dict, List, Optional

from datetime import datetime
from urllib.parse import unquote_plus

# TODO: @thomasw21
import datasets
from datasets import load_dataset
from langdetect import detect

_CITATION = """"""

# TODO: @thomasw21
_DESCRIPTION = """"""

# TODO: @thomasw21
_HOMEPAGE = ""

# TODO: @thomasw21
_LICENSE = ""

_FEATURES = datasets.Features(
    {
        # Some images provide an url others provide an Image. Both are exclusive.
        "image_url": datasets.Value("string"),
        "image": datasets.Image(),
        # An image can have multiple text associated with the same value. For example COCO.
        "texts": [datasets.Value("string")],
        # Define where the sample comes from, this is necessary when we start to use aggregated versions like PMD.
        "source": datasets.Value("string"),
        # We commit any kind of additional information in json format in `meta`
        "meta": datasets.Value("string"),
    }
)


def json_serializer(o):
    if isinstance(o, datetime):
        return str(o)

    raise TypeError(f"Object of type {o.__class__.__name__} is not JSON serializable")


class BaseLoader:
    def __init__(
        self,
        source: str,
        split: str,
    ):
        self.source = source
        self.split = split

    @abstractmethod
    def _generate_examples(self):
        raise NotImplementedError()


class DatasetsLoader(BaseLoader):
    """Helper as some datasets are already implemented"""

    def __init__(
        self,
        dataset_name: str,
        config_name: Optional[str],
        split: str,
        batch_size: int = 1000,
    ):
        super(DatasetsLoader, self).__init__(source=dataset_name, split=split)
        self.dataset_name = dataset_name
        self.config_name = config_name
        self.batch_size = batch_size

    @abstractmethod
    def cast_to_pmd_features(self, row: Dict) -> List[Dict[str, Any]]:
        """Return list of caster rows. Casted row are either PMD features"""
        raise NotImplementedError()

    def convert_batch_to_list_of_rows(self, batch: Dict) -> List[Dict[str, Any]]:
        # batch_size can be different to self.batch_size, ie due to last batch
        batch_size = len(next(iter(batch.values())))
        column_names = list(batch.keys())
        return [
            {column_name: batch[column_name][i] for column_name in column_names}
            for i in range(batch_size)
        ]

    def _generate_examples(self):
        dataset = load_dataset(self.dataset_name, self.config_name, split=self.split)
        dataset_size = len(dataset)
        # load batches and yield individual rows
        for batch_start in range(0, dataset_size, self.batch_size):
            batch_end = min(batch_start + self.batch_size, dataset_size)
            batch = dataset[batch_start:batch_end]
            rows = self.convert_batch_to_list_of_rows(batch)
            for row in rows:
                rows_casted_pmd_features = self.cast_to_pmd_features(row)
                for row_casted_pmd_features in rows_casted_pmd_features:
                    yield row_casted_pmd_features


class BaseLoaderWithDLManager(BaseLoader):
    """We use dl_manager to generate `gen_kwargs` needed in order to generate examples."""

    def __init__(self, dl_manager, source: str, split: str):
        super(BaseLoaderWithDLManager, self).__init__(source=source, split=split)
        self.gen_kwargs = self.generate_gen_kwargs(dl_manager)

    @abstractmethod
    def generate_gen_kwargs(self, dl_manager):
        raise NotImplementedError()

    @abstractmethod
    def _generate_examples_with_kwargs(self, **kwargs):
        raise NotImplementedError()

    def _generate_examples(self):
        for elt in self._generate_examples_with_kwargs(**self.gen_kwargs):
            yield elt


class COCOloader(BaseLoaderWithDLManager):
    # TODO @thomasw21 rely on offical coco integration as soon as it's ready.
    _ANNOTATION_URL = (
        "http://images.cocodataset.org/annotations/annotations_trainval2017.zip"
    )
    _IMAGES_URLS = {
        "train": "http://images.cocodataset.org/zips/train2017.zip",
        "validation": "http://images.cocodataset.org/zips/val2017.zip",
    }
    _SPLIT_MAP = {"train": "train2017", "validation": "val207"}

    def __init__(self, dl_manager, split: str):
        super(COCOloader, self).__init__(
            dl_manager=dl_manager, source="coco", split=split
        )

    def generate_gen_kwargs(self, dl_manager):
        annotation_file = (
            Path(dl_manager.download_and_extract(self._ANNOTATION_URL))
            / "annotations"
            / f"captions_{self._SPLIT_MAP[self.split]}.json"
        )
        image_folder = Path(
            dl_manager.download_and_extract(self._IMAGES_URLS[self.split])
        )
        return {
            "annotation_file": annotation_file,
            "base_image_path": image_folder / self._SPLIT_MAP[self.split],
        }

    def _generate_examples_with_kwargs(
        self, annotation_file: str, base_image_path: Path
    ):
        with open(annotation_file, "r", encoding="utf-8") as fi:
            annotations = json.load(fi)

            # We're going to index all the annotations according to `image_id`
            annotations_per_image_id = {}
            for annotation in annotations["annotations"]:
                image_id = annotation["image_id"]
                if image_id in annotations_per_image_id:
                    annotations_per_image_id[image_id].append(annotation)
                else:
                    annotations_per_image_id[image_id] = [annotation]

            for image_metadata in annotations["images"]:
                image_id = image_metadata["id"]
                image_path = base_image_path / f"{image_id:012}.jpg"
                for annotation in annotations_per_image_id[image_id]:
                    yield {
                        "image_url": None,
                        "image": str(image_path.absolute()),
                        "texts": [annotation["caption"]],
                        "source": self.source,
                        "meta": json.dumps(
                            {
                                "image_metadata": image_metadata,
                                "annotation": annotation,
                            },
                            default=json_serializer,
                            indent=2,
                        ),
                    }


class SBULoader(DatasetsLoader):
    def __init__(self, split: str, batch_size: int = 1000):
        super(SBULoader, self).__init__(
            dataset_name="sbu_captions",
            config_name=None,
            split=split,
            batch_size=batch_size,
        )

    def cast_to_pmd_features(self, row: Dict) -> List[Dict[str, Any]]:
        meta = {k: v for k, v in row.items() if k not in ["image_url", "caption"]}
        return [
            {
                "image_url": row["image_url"],
                "image": None,
                "texts": [row["caption"]],
                "source": self.source,
                "meta": json.dumps(
                    meta,
                    default=json_serializer,
                    indent=2,
                ),
            }
        ]


class LocalizedNarrativesOpenImagesLoader(BaseLoaderWithDLManager):
    _ANNOTATION_URLs = {
        "train": "https://storage.googleapis.com/localized-narratives/annotations/open_images_train_v6_captions.jsonl",
        "validation": (
            "https://storage.googleapis.com/localized-narratives/annotations/open_images_validation_captions.jsonl"
        ),
        "test": "https://storage.googleapis.com/localized-narratives/annotations/open_images_test_captions.jsonl",
    }

    def __init__(self, dl_manager, split: str):
        super(LocalizedNarrativesOpenImagesLoader, self).__init__(
            dl_manager=dl_manager, source="localized_narratives__coco", split=split
        )

    def generate_gen_kwargs(self, dl_manager):
        annotation_file = dl_manager.download(self._ANNOTATION_URLs[self.split])
        return {"annotation_file": annotation_file, "split": self.split}

    def _generate_examples_with_kwargs(self, annotation_file: str, split: str):
        with open(annotation_file, "r", encoding="utf-8") as fi:
            for line in fi:
                annotation = json.loads(line)
                assert "image_url" not in annotation
                yield {
                    "image_url": f"https://s3.amazonaws.com/open-images-dataset/{split}/{annotation['image_id']}.jpg",
                    "image": None,
                    "texts": [annotation["caption"]],
                    "source": self.source,
                    "meta": json.dumps(
                        annotation,
                        default=json_serializer,
                        indent=2,
                    ),
                }


class LocalizedNarrativesCOCOLoader(BaseLoaderWithDLManager):
    # TODO @thomasw21 rely on offical coco integration as soon as it's ready.
    _ANNOTATION_URLs = {
        "train": "https://storage.googleapis.com/localized-narratives/annotations/coco_train_captions.jsonl",
        "validation": "https://storage.googleapis.com/localized-narratives/annotations/coco_val_captions.jsonl",
    }
    _IMAGES_URLS = {
        "train": "http://images.cocodataset.org/zips/train2017.zip",
        "validation": "http://images.cocodataset.org/zips/val2017.zip",
    }
    _SPLIT_MAP = {"train": "train2017", "validation": "val207"}

    def __init__(self, dl_manager, split: str):
        super(LocalizedNarrativesCOCOLoader, self).__init__(
            dl_manager=dl_manager, source="localized_narratives__coco", split=split
        )

    def generate_gen_kwargs(self, dl_manager):
        annotation_file = dl_manager.download(self._ANNOTATION_URLs[self.split])
        image_folder = Path(
            dl_manager.download_and_extract(self._IMAGES_URLS[self.split])
        )
        return {
            "annotation_file": annotation_file,
            "base_image_path": image_folder / self._SPLIT_MAP[self.split],
        }

    def _generate_examples_with_kwargs(
        self, annotation_file: str, base_image_path: Path
    ):
        with open(annotation_file, "r", encoding="utf-8") as fi:
            for line in fi:
                annotation = json.loads(line)
                assert "image_url" not in annotation
                image_path = base_image_path / f"{annotation['image_id'].zfill(12)}.jpg"
                yield {
                    "image_url": None,
                    "image": str(image_path.absolute()),
                    "texts": [annotation["caption"]],
                    "source": self.source,
                    "meta": json.dumps(
                        annotation,
                        default=json_serializer,
                        indent=2,
                    ),
                }


class LocalizedNarrativesFlickr30kLoader(BaseLoaderWithDLManager):
    _LOCAL_IMAGE_FOLDER_NAME = "flickr30k-images"
    _ANNOTATION_URLs = {
        "train": "https://storage.googleapis.com/localized-narratives/annotations/flickr30k_train_captions.jsonl",
        "validation": "https://storage.googleapis.com/localized-narratives/annotations/flickr30k_val_captions.jsonl",
        "test": "https://storage.googleapis.com/localized-narratives/annotations/flickr30k_test_captions.jsonl",
    }

    def __init__(self, dl_manager, split: str):
        super(LocalizedNarrativesFlickr30kLoader, self).__init__(
            dl_manager=dl_manager, source="localized_narratives__flickr30k", split=split
        )

    def generate_gen_kwargs(self, dl_manager):
        if dl_manager.manual_dir is None:
            raise FileNotFoundError(
                f"Please set manual dir via `datasets.load_dataset('pmd', data_dir={{PATH}})` where `{{PATH}}/flickr30k` includes `{self._LOCAL_IMAGE_FOLDER_NAME}`.\n. Manual download instructions: {self.manual_download_instruction}"
            )

        manual_dir = Path(dl_manager.manual_dir) / "flickr30k"
        if not manual_dir.exists():
            raise FileNotFoundError(
                f"Please set manual dir via `datasets.load_dataset('pmd', data_dir={{PATH}})` where `{{PATH}}/flickr30k` includes `{self._LOCAL_IMAGE_FOLDER_NAME}`.\n. Manual download instructions: {self.manual_download_instruction}"
            )

        annotation_file = dl_manager.download(self._ANNOTATION_URLs[self.split])

        return {"annotation_file": annotation_file, "base_image_path": manual_dir}

    @property
    def manual_download_instruction(self):
        return """\
            You need to go to http://shannon.cs.illinois.edu/DenotationGraph/data/index.html,
            and manually download the dataset ("Flickr 30k images."). Once it is completed,
            a file named `flickr30k-images.tar.gz` will appear in your Downloads folder
            or whichever folder your browser chooses to save files to. You then have
            to unzip the file and move `flickr30k-images` under <path/to/folder>/flickr30k.
            The <path/to/folder> can e.g. be "~/manual_data".
            dataset can then be loaded using the following command `datasets.load_dataset("pmd", data_dir="<path/to/folder>")`.
            """

    def _generate_examples_with_kwargs(
        self, annotation_file: str, base_image_path: Path
    ):
        with open(annotation_file, "r", encoding="utf-8") as fi:
            for line in fi:
                annotation = json.loads(line)
                assert "image" not in annotation
                image_path = base_image_path / f"{annotation['image_id']}.jpg"
                yield {
                    "image_url": None,
                    "image": str(image_path.absolute()),
                    "texts": [annotation["caption"]],
                    "source": self.source,
                    "meta": json.dumps(
                        annotation,
                        default=json_serializer,
                        indent=2,
                    ),
                }


class LocalizedNarrativesADE20kLoader(BaseLoaderWithDLManager):
    _ANNOTATION_URLs = {
        "train": "https://storage.googleapis.com/localized-narratives/annotations/ade20k_train_captions.jsonl",
        "validation": "https://storage.googleapis.com/localized-narratives/annotations/ade20k_validation_captions.jsonl",
    }
    _IMAGES_URL = (
        "http://data.csail.mit.edu/places/ADEchallenge/ADEChallengeData2016.zip"
    )
    _SPLIT_MAP = {"train": "training", "validation": "validation"}

    def __init__(self, dl_manager, split: str):
        super(LocalizedNarrativesADE20kLoader, self).__init__(
            dl_manager=dl_manager, source="localized_narratives__ADE20k", split=split
        )

    def generate_gen_kwargs(self, dl_manager):
        annotation_file = dl_manager.download(self._ANNOTATION_URLs[self.split])
        image_base_dir = (
            Path(dl_manager.download_and_extract(self._IMAGES_URL))
            / "ADEChallengeData2016"
            / "images"
        )

        return {
            "annotation_file": annotation_file,
            "base_image_path": image_base_dir / self._SPLIT_MAP[self.split],
        }

    def _generate_examples_with_kwargs(
        self, annotation_file: str, base_image_path: Path
    ):
        with open(annotation_file, "r", encoding="utf-8") as fi:
            for line in fi:
                annotation = json.loads(line)
                assert "image" not in annotation
                image_path = base_image_path / f"{annotation['image_id']}.jpg"
                yield {
                    "image_url": None,
                    "image": str(image_path.absolute()),
                    "texts": [annotation["caption"]],
                    "source": self.source,
                    "meta": json.dumps(
                        annotation,
                        default=json_serializer,
                        indent=2,
                    ),
                }


class VisualGenomeLoader(DatasetsLoader):
    def __init__(self, split: str, batch_size: int = 1000):
        super(VisualGenomeLoader, self).__init__(
            dataset_name="visual_genome",
            config_name="region_descriptions_v1.2.0",
            split=split,
            batch_size=batch_size,
        )

    def cast_to_pmd_features(self, row: Dict) -> List[Dict[str, Any]]:
        meta = {k: v for k, v in row.items() if k not in ["image", "regions"]}
        rows = [
            {
                "image_url": None,
                # TODO @thomasw21 I believe this is slow as hell
                "image": row["image"].crop(
                    (
                        region["x"],
                        region["y"],
                        region["x"] + region["width"],
                        region["y"] + region["height"],
                    )
                ),
                "texts": [region["phrase"]],
                "source": self.source,
                "meta": json.dumps(
                    meta,
                    default=json_serializer,
                    indent=2,
                ),
            }
            for region in row["regions"]
        ]
        return rows


class WITLoader(DatasetsLoader):
    def __init__(self, split: str, batch_size: int = 1000):
        super(WITLoader, self).__init__(
            dataset_name="google/wit",
            config_name=None,
            split=split,
            batch_size=batch_size,
        )

    def cast_to_pmd_features(self, row: Dict) -> List[Dict[str, Any]]:
        meta = {k: v for k, v in row.items() if k not in ["image_url"]}
        return [
            {
                "image_url": row["image_url"],
                "image": None,
                "texts": [
                    row[caption_name]
                    # TODO @thomasw21 figure out which one we should choose
                    for caption_name in [
                        "caption_reference_description",
                        "context_section_description",
                        "caption_attribution_description",
                    ]
                ],
                "source": self.source,
                "meta": json.dumps(
                    meta,
                    default=json_serializer,
                    indent=2,
                ),
            }
        ]


class ConceptualCaptions(DatasetsLoader):
    def __init__(self, split: str, batch_size: int = 1000):
        super(ConceptualCaptions, self).__init__(
            dataset_name="conceptual_captions",
            config_name="unlabeled",
            split=split,
            batch_size=batch_size,
        )

    def cast_to_pmd_features(self, row: Dict) -> List[Dict[str, Any]]:
        meta = {k: v for k, v in row.items() if k not in ["image_url", "caption"]}
        return [
            {
                "image_url": row["image_url"],
                "image": None,
                "texts": [row["caption"]],
                "source": self.source,
                "meta": json.dumps(
                    meta,
                    default=json_serializer,
                    indent=2,
                ),
            }
        ]


class Conceptual12MLoader(DatasetsLoader):
    def __init__(self, split: str, batch_size: int = 1000):
        super(Conceptual12MLoader, self).__init__(
            dataset_name="conceptual_12m",
            config_name=None,
            split=split,
            batch_size=batch_size,
        )

    def cast_to_pmd_features(self, row):
        meta = {k: v for k, v in row.items() if k not in ["image_url", "caption"]}
        return [
            {
                "image_url": row["image_url"],
                "image": None,
                "texts": [row["caption"]],
                "source": self.source,
                "meta": json.dumps(
                    meta,
                    default=json_serializer,
                    indent=2,
                ),
            }
        ]


class RedCapsLoader(DatasetsLoader):
    def __init__(self, split: str, batch_size: int = 1000):
        super(RedCapsLoader, self).__init__(
            dataset_name="red_caps",
            config_name="all",
            split=split,
            batch_size=batch_size,
        )

    def cast_to_pmd_features(self, row: Dict) -> List[Dict[str, Any]]:
        meta = {k: v for k, v in row.items() if k not in ["image_url", "raw_caption"]}
        return [
            {
                "image_url": row["image_url"],
                "image": None,
                # TODO @thomasw21
                "texts": [row["raw_caption"]],
                "source": self.source,
                "meta": json.dumps(
                    meta,
                    default=json_serializer,
                    indent=2,
                ),
            }
        ]


class YFCC100MLoader(BaseLoaderWithDLManager):
    _ANNOTATION_URL = "https://multimedia-commons.s3-us-west-2.amazonaws.com/tools/etc/yfcc100m_dataset.sql"
    # Columns we're interested in
    _COLUMNS = [
        "photoid",
        "uid",
        "title",
        "description",
        "usertags",
        "downloadurl",
        "licensename",
        "licenseurl",
        "marker",
    ]
    # Text columns that are url encoded
    _TEXT_COLUMNS = ["title", "description", "usertags"]

    WHITE_SPACE_REGEX = re.compile(r"\s+")

    # Original YFCC100M filtering regexes
    LINE_BREAK_REGEX = re.compile(r"[\n\r]")
    REMOVE_HTML_TAGS_REGEX = re.compile(r"<.*?>")
    # TODO @thomasw21 improve that regex
    DATE_HOUR_REGEX = re.compile(r"[0-9](:|\.|-|/)[0-9][0-9](:|\.|-|/)[0-9][0-9]")
    WEIRD_CHARACTERS_REGEX = re.compile(r"[_©]")
    SECOND_WORD_REGEX = re.compile(r" [a-zA-Z]+")

    def __init__(self, dl_manager, batch_size: int, split: str):
        super(YFCC100MLoader, self).__init__(
            dl_manager=dl_manager, source="yfcc100m", split=split
        )
        self.batch_size = batch_size

    # Code from https://gitlab.com/jfolz/yfcc100m/-/blob/master/yfcc100m/convert_metadata.py
    BYTE_MAP = {"%02x" % v: "%x" % v for v in range(256)}

    @classmethod
    def yfcc_local_path(cls, url, __bm=BYTE_MAP):
        h = md5(url.encode("utf-8")).hexdigest()
        hash_ = "".join(__bm[h[x : x + 2]] for x in range(0, 32, 2))
        return f"data/images/{hash_[0:3]}/{hash_[3:6]}/{hash_}.jpg"

    @classmethod
    def generate_image_url(cls, downloadurl: str):
        """Takes original image url, and download verion store in `multimedia-commons`"""
        # compute yfcc hash
        local_path = cls.yfcc_local_path(downloadurl)
        return f"https://multimedia-commons.s3-us-west-2.amazonaws.com/{local_path}"

    def generate_gen_kwargs(self, dl_manager):
        sql_file = dl_manager.download(self._ANNOTATION_URL)
        return {"sql_file": sql_file}

    def filter_text(self, text: str) -> bool:
        # # If less than two words return False
        # # TODO @thomasw21 we probably don't need to split all the way til the end ...
        # if len([substring for substring in self.WHITE_SPACE_REGEX.split(text) if substring != ""]) < 2:
        #     return False

        if self.WEIRD_CHARACTERS_REGEX.search(text) is not None:
            return False

        if self.SECOND_WORD_REGEX.search(text) is None:
            return False

        if self.DATE_HOUR_REGEX.search(text) is not None:
            return False

        # filter only english
        try:
            if detect(text) != "en":
                return False
        except Exception:
            return False

        return True

    def clean_text(self, text: str) -> str:
        """Inspired from original code"""
        text = self.LINE_BREAK_REGEX.sub(" ", text)
        cleantext = self.REMOVE_HTML_TAGS_REGEX.sub("", text)
        return cleantext

    def get_associated_text(self, annotation: Dict[str, Any]) -> Optional[str]:
        """
        Given an annotation, return text associated to the image
        We return None when the annotation should be filtered out
        """
        ordered_text_columns_consideration = ["description", "title"]
        record_text = None
        for column_name in ordered_text_columns_consideration:
            text_candidate = annotation[column_name]
            if column_name == "description" and not (5 < len(text_candidate) < 256):
                continue
            cleaned_text_candidate = self.clean_text(text_candidate)
            if self.filter_text(cleaned_text_candidate):
                record_text = cleaned_text_candidate
                break
        return record_text

    def _generate_examples_with_kwargs(self, sql_file: str):
        # query records command
        sql_command = f"select {', '.join(self._COLUMNS)} from yfcc100m_dataset"

        # Create a connection and get a cursor
        with sqlite3.connect(sql_file) as connection:
            cursor = connection.cursor()

            # Execute the query
            cursor.execute(sql_command)
            # Get data in batches
            while True:
                # Read the data
                records = cursor.fetchmany(self.batch_size)

                # If we are at the end
                if len(records) == 0:
                    break

                # Format data
                for record in records:
                    annotation = {
                        column_name: value
                        for value, column_name in zip(record, self._COLUMNS)
                    }

                    # TODO @thomasw21 if it's not an image we don't care for now
                    if annotation["marker"] != 0:
                        continue

                    # We compute text candidate and skip the row if None work.
                    text = self.get_associated_text(annotation)
                    if text is None:
                        continue

                    for text_column in self._TEXT_COLUMNS:
                        annotation[text_column] = unquote_plus(annotation[text_column])

                    yield {
                        # Add image_url that we download from s3 bucket instead of official download url
                        "image_url": self.generate_image_url(annotation["downloadurl"]),
                        "image": None,
                        "texts": [text],
                        "source": self.source,
                        "meta": json.dumps(
                            annotation,
                            default=json_serializer,
                            indent=2,
                        ),
                    }
            cursor.close()


class PMDConfig(datasets.BuilderConfig):
    """BuilderConfig for PMD."""

    def __init__(
        self,
        datasets_batch_size: int = 1000,
        sqlite3_batch_size: int = 10_000,
        **kwargs,
    ):
        super(PMDConfig, self).__init__(**kwargs)
        # determines how much we can load
        self.datasets_batch_size = datasets_batch_size
        self.sqlite3_batch_size = sqlite3_batch_size


class PMD(datasets.GeneratorBasedBuilder):
    """Builder for Open Images subset of PMD."""

    BUILDER_CONFIG_CLASS = PMDConfig

    def _info(self):
        return datasets.DatasetInfo(
            description=_DESCRIPTION,
            features=_FEATURES,
            homepage=_HOMEPAGE,
            license=_LICENSE,
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        return [
            datasets.SplitGenerator(
                name=split_name,
                gen_kwargs={
                    "loaders": [
                        # COCOloader(dl_manager=dl_manager, split=split_name),
                        # SBULoader(
                        #     split=split_name,
                        #     batch_size=self.config.datasets_batch_size,
                        # ),
                        # LocalizedNarrativesOpenImagesLoader(
                        #     dl_manager=dl_manager, split=split_name
                        # ),
                        # LocalizedNarrativesCOCOLoader(
                        #     dl_manager=dl_manager, split=split_name
                        # ),
                        # LocalizedNarrativesFlickr30kLoader(
                        #     dl_manager=dl_manager, split=split_name
                        # ),
                        # LocalizedNarrativesADE20kLoader(
                        #     dl_manager=dl_manager, split=split_name
                        # ),
                        # ConceptualCaptions(
                        #     split=split_name,
                        #     batch_size=self.config.datasets_batch_size,
                        # ),
                        # VisualGenomeLoader(
                        #     split=split_name,
                        #     batch_size=self.config.datasets_batch_size,
                        # ),
                        # WITLoader(
                        #     split=split_name,
                        #     batch_size=self.config.datasets_batch_size,
                        # ),
                        Conceptual12MLoader(
                            split=split_name,
                            batch_size=self.config.datasets_batch_size,
                        ),
                        RedCapsLoader(
                            split=split_name,
                            batch_size=self.config.datasets_batch_size,
                        ),
                        YFCC100MLoader(
                            dl_manager=dl_manager,
                            split=split_name,
                            batch_size=self.config.sqlite3_batch_size,
                        ),
                    ]
                },
            )
            for split_name in [datasets.Split.TRAIN]
        ]

    def _generate_examples(self, loaders: List[BaseLoader]):
        idx = 0
        for loader in loaders:
            for elt in loader._generate_examples():
                yield idx, elt
                idx += 1