-
Notifications
You must be signed in to change notification settings - Fork 26
/
loader.py
147 lines (122 loc) Β· 5.1 KB
/
loader.py
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
from random import randint, choice
from pathlib import Path
from typing import Tuple
from PIL import Image, UnidentifiedImageError
import torch
from torch.utils.data import Dataset
from torchvision.transforms import transforms
from transformers import AutoTokenizer
from preprocess import remove_style, remove_subj
class TextImageDataset(Dataset):
def __init__(
self,
text_folder: str,
image_folder: str,
text_len: int,
image_size: int,
truncate_captions: bool,
resize_ratio: float,
tokenizer: AutoTokenizer = None,
shuffle: bool = False,
) -> None:
"""
@param folder: Folder containing images and text files matched by their paths' respective "stem"
@param truncate_captions: Rather than throw an exception, captions which are too long will be truncated.
"""
super().__init__()
self.shuffle = shuffle
# path = Path(folder)
self.tokenizer = tokenizer
text_path = Path(text_folder)
text_files = [*text_path.glob("**/*[0-9].txt")]
image_folder = image_folder
image_path = Path(image_folder)
image_files = [
*image_path.glob("**/*[0-9].png"),
*image_path.glob("**/*[0-9].jpg"),
*image_path.glob("**/*[0-9].jpeg"),
]
text_files = {text_file.stem: text_file for text_file in text_files}
image_files = {image_file.stem: image_file for image_file in image_files}
keys = image_files.keys() & text_files.keys()
self.keys = list(keys)
self.text_files = {k: v for k, v in text_files.items() if k in keys}
self.image_files = {k: v for k, v in image_files.items() if k in keys}
self.text_len = text_len
self.truncate_captions = truncate_captions
self.resize_ratio = resize_ratio
self.tokenizer = tokenizer
self.image_transform = transforms.Compose(
[
transforms.Lambda(
lambda img: img.convert("RGB") if img.mode != "RGB" else img
),
transforms.Resize([image_size, image_size]),
transforms.ToTensor(),
]
)
def __len__(self) -> int:
return len(self.keys)
def __getitem__(self, ind: int) -> Tuple[torch.tensor, torch.tensor, torch.tensor]:
key = self.keys[ind]
text_file = self.text_files[key]
image_file = self.image_files[key]
descriptions = text_file.read_text(encoding="utf-8")
descriptions = remove_style(descriptions).split("\n")
descriptions = list(filter(lambda t: len(t) > 0, descriptions))
try:
description = choice(descriptions)
except IndexError as zero_captions_in_file_ex:
print(f"An exception occurred trying to load file {text_file}.")
print(f"Skipping index {ind}")
return self.skip_sample(ind)
# ADD PREPROCESSING FUNCTION HERE
encoded_dict = self.tokenizer(
description,
return_tensors="pt",
padding="max_length",
truncation=True,
max_length=self.text_len,
add_special_tokens=True,
return_token_type_ids=False, # for RoBERTa
)
# flattens nested 2D tensor into 1D tensor
flattened_dict = {i: v.squeeze() for i, v in encoded_dict.items()}
input_ids = flattened_dict["input_ids"]
attention_mask = flattened_dict["attention_mask"]
try:
image_tensor = self.image_transform(Image.open(image_file))
except (UnidentifiedImageError, OSError) as corrupt_image_exceptions:
print(f"An exception occurred trying to load file {image_file}.")
print(f"Skipping index {ind}")
return self.skip_sample(ind)
return input_ids, image_tensor, attention_mask
def random_sample(self):
return self.__getitem__(randint(0, self.__len__() - 1))
def sequential_sample(self, ind):
if ind >= self.__len__() - 1:
return self.__getitem__(0)
return self.__getitem__(ind + 1)
def skip_sample(self, ind):
if self.shuffle:
return self.random_sample()
return self.sequential_sample(ind=ind)
class ImgDatasetExample(Dataset):
"""only for baseline cropped images"""
def __init__(
self, image_folder: str, image_transform: transforms.Compose = None,
) -> None:
self.image_transform = image_transform
self.image_path = Path(image_folder)
self.image_files = [
*self.image_path.glob("**/*.png"),
*self.image_path.glob("**/*.jpg"),
*self.image_path.glob("**/*.jpeg"),
]
def __getitem__(self, index: int) -> torch.tensor:
image = Image.open(self.image_files[index])
if self.image_transform:
image = self.image_transform(image)
return torch.tensor(image)
def __len__(self) -> int:
return len(self.image_files)