File size: 39,818 Bytes
1d83a66
 
 
 
 
 
 
 
 
 
 
 
 
 
cbdd0ca
1d83a66
 
 
 
59af408
1d83a66
59af408
1d83a66
cbdd0ca
622d8d0
3e03859
 
1d83a66
 
 
59af408
1d83a66
 
622d8d0
1d83a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e03859
 
 
 
 
 
 
1d83a66
cbdd0ca
1d83a66
 
cbdd0ca
1d83a66
 
622d8d0
1d83a66
 
 
 
 
 
 
 
 
 
 
59af408
cbdd0ca
1d83a66
cbdd0ca
 
 
1d83a66
 
59af408
cbdd0ca
1d83a66
 
622d8d0
1d83a66
 
 
622d8d0
59af408
cbdd0ca
59af408
66052c6
 
59af408
622d8d0
1d83a66
 
59af408
1d83a66
59af408
cbdd0ca
622d8d0
 
 
 
59af408
 
 
 
 
622d8d0
 
 
cbdd0ca
59af408
622d8d0
 
1d83a66
 
 
 
 
cbdd0ca
 
 
 
 
 
 
 
 
 
 
 
1d83a66
cbdd0ca
 
 
1d83a66
 
 
 
 
 
cbdd0ca
1d83a66
 
cbdd0ca
 
 
 
8b87149
 
cbdd0ca
622d8d0
fe105ca
cbdd0ca
 
 
 
 
 
 
 
 
1d83a66
 
 
 
 
 
 
 
 
 
 
 
 
cbdd0ca
 
 
 
 
 
 
 
1d83a66
cbdd0ca
 
 
 
 
 
1d83a66
 
 
 
 
3e03859
 
1d83a66
 
 
 
 
 
 
 
 
cbdd0ca
1d83a66
 
 
 
 
 
 
 
 
 
 
 
cbdd0ca
 
1d83a66
 
 
cbdd0ca
 
 
 
 
 
 
e4b750b
 
0199675
cbdd0ca
 
 
 
 
 
 
 
 
 
 
 
 
1d83a66
 
 
cbdd0ca
1d83a66
 
 
 
cbdd0ca
 
1d83a66
 
622d8d0
 
 
 
 
 
 
 
 
 
 
3e03859
 
622d8d0
 
 
 
1d83a66
 
 
 
 
 
 
 
 
 
 
cbdd0ca
 
 
 
 
 
 
 
1d83a66
cbdd0ca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802b20
1d83a66
 
 
 
 
 
622d8d0
1d83a66
8c55fa4
1d83a66
702ea76
622d8d0
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
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
# 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.
import itertools
import json
import re
import sqlite3
from abc import abstractmethod
from functools import partial
from hashlib import md5
from multiprocessing import Pool
from pathlib import Path
from typing import Any, Dict, List, Optional, Iterator
import pyarrow as pa

from datetime import datetime
from urllib.parse import unquote_plus

import datasets
from datasets import load_dataset, Dataset
from langdetect import detect

# TODO: @thomasw21
_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, writer_batch_size: int):
        self.source = source
        self.split = split
        self.writer_batch_size = writer_batch_size

    @abstractmethod
    def _generate_batches(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,
        num_proc: int,
        datasets_batch_size: int = 1000,
    ):
        super(DatasetsLoader, self).__init__(
            source=dataset_name, split=split, writer_batch_size=datasets_batch_size
        )
        self.dataset_name = dataset_name
        self.config_name = config_name
        self.num_proc = num_proc
        self.datasets_batch_size = datasets_batch_size

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

    def _generate_batch_table(self, batch_start: int, dset: Dataset) -> pa.Table:
        dataset_size = len(dset)
        batch_end = min(batch_start + self.datasets_batch_size, dataset_size)
        batch = dset[batch_start:batch_end]
        output_batch = self.cast_to_pmd_features(batch)
        return pa.table(_FEATURES.encode_batch(output_batch))

    def _generate_batches(self):
        dataset = load_dataset(self.dataset_name, self.config_name, split=self.split)
        dataset_size = len(dataset)

        # load batches and yield individual rows
        if self.num_proc == 1:
            for batch_start in range(0, dataset_size, self.datasets_batch_size):
                batch_casted_pmd_features = self._generate_batch_table(
                    dset=dataset, batch_start=batch_start
                )
                yield batch_casted_pmd_features

        # Parallel version
        else:
            assert self.num_proc > 1
            with Pool(self.num_proc) as pool:
                # TODO @thomasw21 figure out if we care about imap / imap_unordered
                batch_iterator = pool.imap(
                    partial(self._generate_batch_table, dset=dataset),
                    range(0, dataset_size, self.datasets_batch_size),
                )
                for batch_casted_pmd_features in batch_iterator:
                    yield batch_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,
        num_proc: int,
        chunk_size: int,
        writer_batch_size: int = 10_000,
    ):
        super(BaseLoaderWithDLManager, self).__init__(
            source=source, split=split, writer_batch_size=writer_batch_size
        )
        self.gen_kwargs = self.generate_gen_kwargs(dl_manager)
        # Used for multiprocessing
        self.chunk_size = chunk_size
        self.num_proc = num_proc

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

    @abstractmethod
    def _build_rows_iterator(self, chunk_size: int, **kwargs) -> Iterator[List[Any]]:
        raise NotImplementedError()

    @abstractmethod
    def _generate_examples(self, examples: List[Any], **kwargs) -> Dict[str, List[Any]]:
        raise NotImplementedError

    def _generate_tables(self, examples: List[Any], **kwargs) -> pa.Table:
        return pa.table(_FEATURES.encode_batch(self._generate_examples(examples, **kwargs)))

    def _generate_batches(self):
        rows_iterator = self._build_rows_iterator(chunk_size=self.chunk_size, **self.gen_kwargs)

        with Pool(self.num_proc) as pool:
            tables_iterator = pool.imap(
                partial(self._generate_tables, **self.gen_kwargs),
                rows_iterator,
                chunksize=1,
            )
            for table in tables_iterator:
                yield table


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,
        num_proc: int,
        chunk_size: int,
        writer_batch_size: int,
    ):
        super(COCOloader, self).__init__(
            dl_manager=dl_manager,
            source="coco",
            split=split,
            num_proc=num_proc,
            chunk_size=chunk_size,
            writer_batch_size=writer_batch_size,
        )

    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 _build_rows_iterator(self, chunk_size: int, annotation_file: str, base_image_path: Path) -> Iterator[List[Any]]:
        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]

            # yield chunks
            buffer = []
            for image_metadata in annotations["images"]:
                image_id = image_metadata["id"]
                for annotation in annotations_per_image_id[image_id]:
                    buffer.append({
                        "annotation": annotation,
                        "image_metadata": image_metadata
                    })
                    if len(buffer) == chunk_size:
                        yield buffer
                        buffer = []
	    # Getting the last batch
	    if len(buffer) > 0:
		    yield buffer

    def _generate_examples(self, examples: List[Any], annotation_file: str, base_image_path: Path) -> Dict[str, List[Any]]:
        return {
            "image_url": [None for _ in examples],
            "image": [str((base_image_path / f"{example['image_metadata']['id']:012}.jpg").absolute()) for example in examples],
            "texts": [example["annotation"]["caption"] for example in examples],
            "source": [self.source for _ in examples],
            "meta": [json.dumps(
                example,
                default=json_serializer,
                indent=2,
            ) for example in examples],
        }


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

    def cast_to_pmd_features(self, batch: Dict[str, List[Any]]) -> Dict[str, List[Any]]:
        metas = {k: v for k, v in batch.items() if k not in ["image_url", "caption"]}
        batch_size = len(next(iter(batch.values())))
        return {
            "image_url": batch["image_url"],
            "image": [None] * batch_size,
            "texts": [[caption] for caption in batch["caption"]],
            "source": [self.source] * batch_size,
            "meta": [
                json.dumps(
                    {key: value[batch_id] for key, value in metas.items()},
                    default=json_serializer,
                    indent=2,
                )
                for batch_id in range(batch_size)
            ],
        }


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,
        num_proc: int,
        chunk_size: int,
        writer_batch_size: int,
    ):
        super(LocalizedNarrativesOpenImagesLoader, self).__init__(
            dl_manager=dl_manager,
            source="localized_narratives__coco",
            split=split,
            num_proc=num_proc,
            chunk_size=chunk_size,
            writer_batch_size=writer_batch_size,
        )

    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 _build_rows_iterator(self, chunk_size: int, annotation_file: str, split: str) -> Iterator[List[Any]]:
        with open(annotation_file, "r", encoding="utf-8") as fi:
            chunk = tuple(itertools.islice(fi, chunk_size))

            if not chunk:
                return

            yield chunk

    def _generate_examples(self, examples: List[Any], annotation_file: str, split: str) -> Dict[str, List[Any]]:
        annotations = [json.loads(line) for line in examples]

        # sanity check
        for annotation in annotations:
            assert "image_url" not in annotation

        return {
            "image_url": [f"https://s3.amazonaws.com/open-images-dataset/{split}/{annotation['image_id']}.jpg" for annotation in annotations],
            "image": [None for _ in annotations],
            "texts": [[annotation["caption"]] for annotation in annotations],
            "source": [self.source for _ in annotations],
            "meta": [json.dumps(
                annotation,
                default=json_serializer,
                indent=2,
            ) for annotation in annotations],
        }


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,
        num_proc: int,
        chunk_size: int,
        writer_batch_size: int,
    ):
        super(LocalizedNarrativesCOCOLoader, self).__init__(
            dl_manager=dl_manager,
            source="localized_narratives__coco",
            split=split,
            num_proc=num_proc,
            chunk_size=chunk_size,
            writer_batch_size=writer_batch_size,
        )

    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 _build_rows_iterator(self, chunk_size: int, annotation_file: str, base_image_path: Path) -> Iterator[List[Any]]:
        with open(annotation_file, "r", encoding="utf-8") as fi:
            chunk = tuple(itertools.islice(fi, chunk_size))

            if not chunk:
                return

            yield chunk

    def _generate_examples(self, examples: List[Any], annotation_file: str, base_image_path: Path) -> Dict[str, List[Any]]:
        annotations = [json.loads(line) for line in examples]

        return {
            "image_url": [None for _ in examples],
            "image": [str((base_image_path / f"{annotation['image_id'].zfill(12)}.jpg").absolute()) for annotation in annotations],
            "texts": [[annotation["caption"]] for annotation in annotations],
            "source": [self.source for _ in annotations],
            "meta": [json.dumps(
                annotation,
                default=json_serializer,
                indent=2,
            ) for annotation in annotations],
        }

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,
        num_proc: int,
        chunk_size: int,
        writer_batch_size: int,
    ):
        super(LocalizedNarrativesFlickr30kLoader, self).__init__(
            dl_manager=dl_manager,
            source="localized_narratives__flickr30k",
            split=split,
            num_proc=num_proc,
            chunk_size=chunk_size,
            writer_batch_size=writer_batch_size,
        )

    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 _build_rows_iterator(self, chunk_size: int, annotation_file: str, base_image_path: Path) -> Iterator[List[Any]]:
        with open(annotation_file, "r", encoding="utf-8") as fi:
            chunk = tuple(itertools.islice(fi, chunk_size))

            if not chunk:
                return

            yield chunk

    def _generate_examples(self, examples: List[Any], annotation_file: str, base_image_path: Path) -> Dict[
        str, List[Any]]:
        annotations = [json.loads(line) for line in examples]

        return {
            "image_url": [None for _ in examples],
            "image": [str((base_image_path / f"{annotation['image_id']}.jpg").absolute()) for annotation in
                      annotations],
            "texts": [[annotation["caption"]] for annotation in annotations],
            "source": [self.source for _ in annotations],
            "meta": [json.dumps(
                annotation,
                default=json_serializer,
                indent=2,
            ) for annotation in annotations],
        }


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,
        num_proc: int,
        chunk_size: int,
        writer_batch_size: int,
    ):
        super(LocalizedNarrativesADE20kLoader, self).__init__(
            dl_manager=dl_manager,
            source="localized_narratives__ADE20k",
            split=split,
            num_proc=num_proc,
            chunk_size=chunk_size,
            writer_batch_size=writer_batch_size,
        )

    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 _build_rows_iterator(self, annotation_file: str, base_image_path: Path, chunk_size: int) -> Iterator[List[Any]]:
        with open(annotation_file, "r", encoding="utf-8") as fi:
            chunk = tuple(itertools.islice(fi, chunk_size))

            if not chunk:
                return

            yield chunk

    def _generate_examples(self, examples: List[Any], annotation_file: str, base_image_path: Path) -> Dict[str, Any]:
        annotations = [json.loads(line) for line in examples]
        return {
            "image_url": [None for _ in examples],
            "image": [str((base_image_path / f"{annotation['image_id']}.jpg").absolute()) for annotation in annotations],
            "texts": [annotation["caption"] for annotation in annotations],
            "source": [self.source for _ in examples],
            "meta": [json.dumps(
                annotation,
                default=json_serializer,
                indent=2,
            ) for annotation in annotations],
        }


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

    def cast_to_pmd_features(self, batch: Dict[str, List[Any]]) -> Dict[str, List[Any]]:
        metas = {k: v for k, v in batch.items() if k not in ["image", "regions"]}
        input_batch_size = len(next(iter(batch.values())))
        serialized_metas = [
            json.dumps(
                {key: value[batch_id] for key, value in metas.items()},
                default=json_serializer,
                indent=2,
            )
            for batch_id in range(input_batch_size)
        ]
        output_list_rows = [
            {
                "image": image.crop(
                    (
                        region["x"],
                        region["y"],
                        region["x"] + region["width"],
                        region["y"] + region["height"],
                    )
                ),
                "image_url": None,
                "texts": [region["phrase"]],
                "source": self.source,
                "meta": serialized_meta,
            }
            for image, regions, serialized_meta in zip(
                batch["image"], batch["regions"], serialized_metas
            )
            for region in regions
        ]
        return {
            column_name: [row[column_name] for row in output_list_rows]
            for column_name in ["image_url", "image", "texts", "source", "meta"]
        }


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

    def cast_to_pmd_features(self, batch: Dict[str, List[Any]]) -> Dict[str, List[Any]]:
        metas = {k: v for k, v in batch.items() if k not in ["image_url"]}
        batch_size = len(next(iter(batch.values())))
        return {
            "image_url": batch["image_url"],
            "image": [None] * batch_size,
            "texts": [
                texts
                # TODO @thomasw21 figure out which one we should choose
                for texts in zip(
                    batch["caption_reference_description"],
                    batch["context_section_description"],
                    batch["caption_attribution_description"],
                )
            ],
            "source": [self.source] * batch_size,
            "meta": [
                json.dumps(
                    {key: value[batch_id] for key, value in metas.items()},
                    default=json_serializer,
                    indent=2,
                )
                for batch_id in range(batch_size)
            ],
        }


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

    def cast_to_pmd_features(self, batch: Dict[str, List[Any]]) -> Dict[str, List[Any]]:
        metas = {k: v for k, v in batch.items() if k not in ["image_url", "caption"]}
        batch_size = len(next(iter(batch.values())))
        return {
            "image_url": batch["image_url"],
            "image": [None] * batch_size,
            "texts": [[caption] for caption in batch["caption"]],
            "source": [self.source] * batch_size,
            "meta": [
                json.dumps(
                    {key: value[batch_id] for key, value in metas.items()},
                    default=json_serializer,
                    indent=2,
                )
                for batch_id in range(batch_size)
            ],
        }


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

    def cast_to_pmd_features(self, batch: Dict[str, List[Any]]) -> Dict[str, List[Any]]:
        metas = {k: v for k, v in batch.items() if k not in ["image_url", "caption"]}
        batch_size = len(next(iter(batch.values())))
        return {
            "image_url": batch["image_url"],
            "image": [None] * batch_size,
            "texts": [[caption] for caption in batch["caption"]],
            "source": [self.source] * batch_size,
            "meta": [
                json.dumps(
                    {key: value[batch_id] for key, value in metas.items()},
                    default=json_serializer,
                    indent=2,
                )
                for batch_id in range(batch_size)
            ],
        }


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

    def cast_to_pmd_features(self, batch: Dict[str, List[Any]]) -> Dict[str, List[Any]]:
        metas = {
            k: v for k, v in batch.items() if k not in ["image_url", "raw_caption"]
        }
        batch_size = len(next(iter(batch.values())))
        return {
            "image_url": batch["image_url"],
            "image": [None] * batch_size,
            "texts": [[caption] for caption in batch["raw_caption"]],
            "source": [self.source] * batch_size,
            "meta": [
                json.dumps(
                    {key: value[batch_id] for key, value in metas.items()},
                    default=json_serializer,
                    indent=2,
                )
                for batch_id in range(batch_size)
            ],
        }


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,
        split: str,
        num_proc: int,
        chunk_size: int,
        writer_batch_size: int,
    ):
        super(YFCC100MLoader, self).__init__(
            dl_manager=dl_manager,
            source="yfcc100m",
            split=split,
            num_proc=num_proc,
            chunk_size=chunk_size,
            writer_batch_size=writer_batch_size,
        )
        self.chunk_size = chunk_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"""
        cleaned_text = unquote_plus(text)
        cleaned_text = self.LINE_BREAK_REGEX.sub(" ", cleaned_text)
        cleaned_text = self.REMOVE_HTML_TAGS_REGEX.sub("", cleaned_text)
        return cleaned_text

    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 _build_rows_iterator(self, sql_file: str, chunk_size: int) -> Iterator[List[Any]]:
        # 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.chunk_size)

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

                yield records

            cursor.close()

    def _generate_examples(self, examples: List[Any], sql_file: str) -> Dict[str, Any]:
        buffer = {}
        # Format data
        for example in examples:
            annotation = {
                column_name: value
                for value, column_name in zip(example, 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])

            # add data to buffer
            temp_object = {
                # 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,
                )],
            }
            if len(buffer) == 0:
                buffer = temp_object
            else:
                for column_name in buffer.keys():
                    buffer[column_name] += temp_object[column_name]
        return buffer


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

    def __init__(
        self,
        num_proc: Optional[int] = None,
        datasets_batch_size: int = 1000,
        sqlite3_batch_size: int = 10_000,
        chunk_size: int = 10_000,
        writer_batch_size: int = 10_000,
        **kwargs,
    ):
        if num_proc is None:
            # We disable multiprocessing.
            num_proc = 1
        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

        # Some datasets should be loaded via multiprocessing.
        self.num_proc = num_proc
        self.chunk_size = chunk_size

        # Batch writing
        self.writer_batch_size = writer_batch_size


class PMD(datasets.ArrowBasedBuilder):
    """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,
                            num_proc=self.config.num_proc,
                            chunk_size=self.config.chunk_size,
                            writer_batch_size=self.config.writer_batch_size,
                        ),
                        SBULoader(
                            split=split_name,
                            datasets_batch_size=self.config.datasets_batch_size,
                            num_proc=self.config.num_proc,
                        ),
                        LocalizedNarrativesOpenImagesLoader(
                            dl_manager=dl_manager,
                            split=split_name,
                            num_proc=self.config.num_proc,
                            chunk_size=self.config.chunk_size,
                            writer_batch_size=self.config.writer_batch_size,
                        ),
                        LocalizedNarrativesCOCOLoader(
                            dl_manager=dl_manager,
                            split=split_name,
                            num_proc=self.config.num_proc,
                            chunk_size=self.config.chunk_size,
                            writer_batch_size=self.config.writer_batch_size,
                        ),
                        LocalizedNarrativesFlickr30kLoader(
                            dl_manager=dl_manager,
                            split=split_name,
                            num_proc=self.config.num_proc,
                            chunk_size=self.config.chunk_size,
                            writer_batch_size=self.config.writer_batch_size,
                        ),
                        LocalizedNarrativesADE20kLoader(
                            dl_manager=dl_manager,
                            split=split_name,
                            num_proc=self.config.num_proc,
                            chunk_size=self.config.chunk_size,
                            writer_batch_size=self.config.writer_batch_size,
                        ),
                        ConceptualCaptions(
                            split=split_name,
                            num_proc=self.config.num_proc,
                            datasets_batch_size=self.config.datasets_batch_size,
                        ),
                        VisualGenomeLoader(
                            split=split_name,
                            num_proc=self.config.num_proc,
                            datasets_batch_size=self.config.datasets_batch_size,
                        ),
                        WITLoader(
                            split=split_name,
                            num_proc=self.config.num_proc,
                            datasets_batch_size=self.config.datasets_batch_size,
                        ),
                        Conceptual12MLoader(
                            split=split_name,
                            num_proc=self.config.num_proc,
                            datasets_batch_size=self.config.datasets_batch_size,
                        ),
                        RedCapsLoader(
                            split=split_name,
                            num_proc=self.config.num_proc,
                            datasets_batch_size=self.config.datasets_batch_size,
                        ),
                        YFCC100MLoader(
                            dl_manager=dl_manager,
                            split=split_name,
                            num_proc=self.config.num_proc,
                            chunk_size=self.config.sqlite3_batch_size,
                            writer_batch_size=self.config.writer_batch_size,
                        ),
                    ]
                },
            )
            for split_name in [datasets.Split.TRAIN]
        ]

    def _generate_tables(self, loaders: List[BaseLoader]):
        idx = 0
        print("start")
        for loader in loaders:
            print(loader.__class__.__name__)
            for elt in loader._generate_batches():
                yield idx, elt
                idx += 1