flickr.py 5.3 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
5
6
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
7

8
9
from PIL import Image

10
from .vision import VisionDataset
11
12


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

16
    def __init__(self, root: Union[str, Path]) -> None:
17
        super().__init__()
18
19
20
21

        self.root = root

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

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

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

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

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

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

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


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

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

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

        # 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
86
    def __getitem__(self, index: int) -> Tuple[Any, Any]:
87
88
89
90
91
92
93
94
95
96
        """
        Args:
            index (int): Index

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

        # Image
97
        img = Image.open(img_id).convert("RGB")
98
99
100
101
102
103
104
105
106
107
        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
108
    def __len__(self) -> int:
109
110
111
        return len(self.ids)


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

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

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

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

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

Philip Meier's avatar
Philip Meier committed
143
    def __getitem__(self, index: int) -> Tuple[Any, Any]:
144
145
146
147
148
149
150
151
152
153
154
        """
        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)
155
        img = Image.open(filename).convert("RGB")
156
157
158
159
160
161
162
163
164
165
        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
166
    def __len__(self) -> int:
167
        return len(self.ids)