flickr.py 5.21 KB
Newer Older
1
2
import glob
import os
3
from collections import defaultdict
Philip Meier's avatar
Philip Meier committed
4
from html.parser import HTMLParser
Philip Meier's avatar
Philip Meier committed
5
from typing import Any, Callable, Dict, List, Optional, Tuple
6

7
8
from PIL import Image

9
from .vision import VisionDataset
10
11


Philip Meier's avatar
Philip Meier committed
12
class Flickr8kParser(HTMLParser):
13
14
    """Parser for extracting captions from the Flickr8k dataset web page."""

Philip Meier's avatar
Philip Meier committed
15
    def __init__(self, root: str) -> None:
16
        super().__init__()
17
18
19
20

        self.root = root

        # Data structure to store captions
Philip Meier's avatar
Philip Meier committed
21
        self.annotations: Dict[str, List[str]] = {}
22
23
24

        # State variables
        self.in_table = False
Philip Meier's avatar
Philip Meier committed
25
26
        self.current_tag: Optional[str] = None
        self.current_img: Optional[str] = None
27

Philip Meier's avatar
Philip Meier committed
28
    def handle_starttag(self, tag: str, attrs: List[Tuple[str, Optional[str]]]) -> None:
29
30
        self.current_tag = tag

31
        if tag == "table":
32
33
            self.in_table = True

Philip Meier's avatar
Philip Meier committed
34
    def handle_endtag(self, tag: str) -> None:
35
36
        self.current_tag = None

37
        if tag == "table":
38
39
            self.in_table = False

Philip Meier's avatar
Philip Meier committed
40
    def handle_data(self, data: str) -> None:
41
        if self.in_table:
42
            if data == "Image Not Found":
43
                self.current_img = None
44
45
46
            elif self.current_tag == "a":
                img_id = data.split("/")[-2]
                img_id = os.path.join(self.root, img_id + "_*.jpg")
47
48
49
                img_id = glob.glob(img_id)[0]
                self.current_img = img_id
                self.annotations[img_id] = []
50
            elif self.current_tag == "li" and self.current_img:
51
52
53
54
                img_id = self.current_img
                self.annotations[img_id].append(data.strip())


55
class Flickr8k(VisionDataset):
56
    """`Flickr8k Entities <http://hockenmaier.cs.illinois.edu/8k-pictures.html>`_ Dataset.
57
58
59
60
61

    Args:
        root (string): Root directory where images are downloaded to.
        ann_file (string): Path to annotation file.
        transform (callable, optional): A function/transform that takes in a PIL image
62
            and returns a transformed version. E.g, ``transforms.PILToTensor``
63
64
65
        target_transform (callable, optional): A function/transform that takes in the
            target and transforms it.
    """
66

Philip Meier's avatar
Philip Meier committed
67
    def __init__(
68
69
70
71
72
        self,
        root: str,
        ann_file: str,
        transform: Optional[Callable] = None,
        target_transform: Optional[Callable] = None,
Philip Meier's avatar
Philip Meier committed
73
    ) -> None:
74
        super().__init__(root, transform=transform, target_transform=target_transform)
75
        self.ann_file = os.path.expanduser(ann_file)
76
77
78
79
80
81
82
83
84

        # Read annotations and store in a dict
        parser = Flickr8kParser(self.root)
        with open(self.ann_file) as fh:
            parser.feed(fh.read())
        self.annotations = parser.annotations

        self.ids = list(sorted(self.annotations.keys()))

Philip Meier's avatar
Philip Meier committed
85
    def __getitem__(self, index: int) -> Tuple[Any, Any]:
86
87
88
89
90
91
92
93
94
95
        """
        Args:
            index (int): Index

        Returns:
            tuple: Tuple (image, target). target is a list of captions for the image.
        """
        img_id = self.ids[index]

        # Image
96
        img = Image.open(img_id).convert("RGB")
97
98
99
100
101
102
103
104
105
106
        if self.transform is not None:
            img = self.transform(img)

        # Captions
        target = self.annotations[img_id]
        if self.target_transform is not None:
            target = self.target_transform(target)

        return img, target

Philip Meier's avatar
Philip Meier committed
107
    def __len__(self) -> int:
108
109
110
        return len(self.ids)


111
class Flickr30k(VisionDataset):
112
    """`Flickr30k Entities <https://bryanplummer.com/Flickr30kEntities/>`_ Dataset.
113
114
115
116
117

    Args:
        root (string): Root directory where images are downloaded to.
        ann_file (string): Path to annotation file.
        transform (callable, optional): A function/transform that takes in a PIL image
118
            and returns a transformed version. E.g, ``transforms.PILToTensor``
119
120
121
        target_transform (callable, optional): A function/transform that takes in the
            target and transforms it.
    """
122

Philip Meier's avatar
Philip Meier committed
123
    def __init__(
124
125
126
127
128
        self,
        root: str,
        ann_file: str,
        transform: Optional[Callable] = None,
        target_transform: Optional[Callable] = None,
Philip Meier's avatar
Philip Meier committed
129
    ) -> None:
130
        super().__init__(root, transform=transform, target_transform=target_transform)
131
        self.ann_file = os.path.expanduser(ann_file)
132
133
134
135
136

        # Read annotations and store in a dict
        self.annotations = defaultdict(list)
        with open(self.ann_file) as fh:
            for line in fh:
137
                img_id, caption = line.strip().split("\t")
138
139
140
141
                self.annotations[img_id[:-2]].append(caption)

        self.ids = list(sorted(self.annotations.keys()))

Philip Meier's avatar
Philip Meier committed
142
    def __getitem__(self, index: int) -> Tuple[Any, Any]:
143
144
145
146
147
148
149
150
151
152
153
        """
        Args:
            index (int): Index

        Returns:
            tuple: Tuple (image, target). target is a list of captions for the image.
        """
        img_id = self.ids[index]

        # Image
        filename = os.path.join(self.root, img_id)
154
        img = Image.open(filename).convert("RGB")
155
156
157
158
159
160
161
162
163
164
        if self.transform is not None:
            img = self.transform(img)

        # Captions
        target = self.annotations[img_id]
        if self.target_transform is not None:
            target = self.target_transform(target)

        return img, target

Philip Meier's avatar
Philip Meier committed
165
    def __len__(self) -> int:
166
        return len(self.ids)