File size: 3,539 Bytes
4343508 |
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 |
import datasets
import re
from pathlib import Path
class Flickr8kDataset(datasets.GeneratorBasedBuilder):
VERSION = datasets.Version("0.0.0")
BUILDER_CONFIGS = [
datasets.BuilderConfig(
name="flickr8k_dataset",
version=VERSION,
),
]
def _info(self):
feature_dict = {
"image_id": datasets.Value("string"),
"image_path": datasets.Value("string"),
"captions": datasets.Sequence(datasets.Value("string")),
}
return datasets.DatasetInfo(
description="Flickr8k dataset",
features=datasets.Features(feature_dict),
)
def _split_generators(self, dl_manager):
data_dir = self.config.data_dir
if not data_dir:
raise ValueError("'data_dir' argument is required.")
archive_path = dl_manager.extract(
{
"images": Path(data_dir).joinpath("Flickr8k_Dataset.zip"),
"texts": Path(data_dir).joinpath("Flickr8k_text.zip"),
}
)
splits = [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"image_ids": Path(archive_path["texts"]).joinpath(
"Flickr_8k.trainImages.txt"
),
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"image_ids": Path(archive_path["texts"]).joinpath(
"Flickr_8k.testImages.txt"
),
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
"image_ids": Path(archive_path["texts"]).joinpath(
"Flickr_8k.devImages.txt"
),
},
),
]
for split in splits:
split.gen_kwargs.update(
{
"image_dir": Path(archive_path["images"]).joinpath(
"Flicker8k_Dataset"
),
"captions_txt": Path(archive_path["texts"]).joinpath(
"Flickr8k.token.txt"
),
}
)
return splits
def _generate_examples(
self,
image_ids,
image_dir,
captions_txt,
):
def get_image_ids_as_list(fpath):
ids = []
with open(fpath, "r") as f:
for image in f.read().split("\n"):
if image != "":
ids.append(image.split(".")[0])
return ids
def get_captions_by_id(captions_txt, id):
captions = []
with open(captions_txt, "r") as f:
for line in f.read().split("\n"):
if line != "":
m = re.match(id + r".jpg#\d+(.*)", line)
if m != None:
captions.append(m.group(1)[1:])
return captions
ids = get_image_ids_as_list(image_ids)
for id in ids:
img_path = image_dir.joinpath(id + ".jpg")
captions = get_captions_by_id(captions_txt, id)
example = {
"image_id": id,
"image_path": str(img_path),
"captions": captions,
}
yield id, example
|