iakarshu commited on
Commit
15f37f2
1 Parent(s): 15dee1b

Upload dataset.py

Browse files

Added dataset file

Files changed (1) hide show
  1. dataset.py +302 -0
dataset.py ADDED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import os
3
+ import pickle
4
+ from functools import lru_cache
5
+ import pytesseract
6
+ import numpy as np
7
+ from PIL import Image
8
+ import torch
9
+ from torchvision.transforms import ToTensor
10
+
11
+ PAD_TOKEN_BOX = [0, 0, 0, 0]
12
+ GRID_SIZE = 1000
13
+
14
+
15
+ def normalize_box(box, width, height, size=1000):
16
+ """
17
+ Takes a bounding box and normalizes it to a thousand pixels. If you notice it is
18
+ just like calculating percentage except takes 1000 instead of 100.
19
+ """
20
+ return [
21
+ int(size * (box[0] / width)),
22
+ int(size * (box[1] / height)),
23
+ int(size * (box[2] / width)),
24
+ int(size * (box[3] / height)),
25
+ ]
26
+
27
+
28
+ @lru_cache(maxsize=10)
29
+ def resize_align_bbox(bbox, orig_w, orig_h, target_w, target_h):
30
+ x_scale = target_w / orig_w
31
+ y_scale = target_h / orig_h
32
+ orig_left, orig_top, orig_right, orig_bottom = bbox
33
+ x = int(np.round(orig_left * x_scale))
34
+ y = int(np.round(orig_top * y_scale))
35
+ xmax = int(np.round(orig_right * x_scale))
36
+ ymax = int(np.round(orig_bottom * y_scale))
37
+ return [x, y, xmax, ymax]
38
+
39
+
40
+ def get_topleft_bottomright_coordinates(df_row):
41
+ left, top, width, height = df_row["left"], df_row["top"], df_row["width"], df_row["height"]
42
+ return [left, top, left + width, top + height]
43
+
44
+
45
+ def apply_ocr(image_fp):
46
+ """
47
+ Returns words and its bounding boxes from an image
48
+ """
49
+ image = Image.open(image_fp)
50
+ width, height = image.size
51
+
52
+ ocr_df = pytesseract.image_to_data(image, output_type="data.frame")
53
+ ocr_df = ocr_df.dropna().reset_index(drop=True)
54
+ float_cols = ocr_df.select_dtypes("float").columns
55
+ ocr_df[float_cols] = ocr_df[float_cols].round(0).astype(int)
56
+ ocr_df = ocr_df.replace(r"^\s*$", np.nan, regex=True)
57
+ ocr_df = ocr_df.dropna().reset_index(drop=True)
58
+ words = list(ocr_df.text.apply(lambda x: str(x).strip()))
59
+ actual_bboxes = ocr_df.apply(get_topleft_bottomright_coordinates, axis=1).values.tolist()
60
+
61
+ # add as extra columns
62
+ assert len(words) == len(actual_bboxes)
63
+ return {"words": words, "bbox": actual_bboxes}
64
+
65
+ def get_tokens_with_boxes(unnormalized_word_boxes, pad_token_box, word_ids,max_seq_len = 512):
66
+
67
+ # assert len(unnormalized_word_boxes) == len(word_ids), this should not be applied, since word_ids may have higher
68
+ # length and the bbox corresponding to them may not exist
69
+
70
+ unnormalized_token_boxes = []
71
+
72
+ for i, word_idx in enumerate(word_ids):
73
+ if word_idx is None:
74
+ break
75
+ unnormalized_token_boxes.append(unnormalized_word_boxes[word_idx])
76
+
77
+ # all remaining are padding tokens so why add them in a loop one by one
78
+ num_pad_tokens = len(word_ids) - i - 1
79
+ if num_pad_tokens > 0:
80
+ unnormalized_token_boxes.extend([pad_token_box] * num_pad_tokens)
81
+
82
+
83
+ if len(unnormalized_token_boxes)<max_seq_len:
84
+ unnormalized_token_boxes.extend([pad_token_box] * (max_seq_len-len(unnormalized_token_boxes)))
85
+
86
+ return unnormalized_token_boxes
87
+
88
+
89
+ def get_centroid(actual_bbox):
90
+ centroid = []
91
+ for i in actual_bbox:
92
+ width = i[2] - i[0]
93
+ height = i[3] - i[1]
94
+ centroid.append([i[0] + width / 2, i[1] + height / 2])
95
+ return centroid
96
+
97
+
98
+ def get_pad_token_id_start_index(words, encoding, tokenizer):
99
+ # assert len(words) < len(encoding["input_ids"]) This condition, was creating errors on some sample images
100
+ for idx in range(len(encoding["input_ids"])):
101
+ if encoding["input_ids"][idx] == tokenizer.pad_token_id:
102
+ break
103
+ return idx
104
+
105
+
106
+ def get_relative_distance(bboxes, centroids, pad_tokens_start_idx):
107
+
108
+ a_rel_x = []
109
+ a_rel_y = []
110
+
111
+ for i in range(0, len(bboxes)-1):
112
+ if i >= pad_tokens_start_idx:
113
+ a_rel_x.append([0] * 8)
114
+ a_rel_y.append([0] * 8)
115
+ continue
116
+
117
+ curr = bboxes[i]
118
+ next = bboxes[i+1]
119
+
120
+ a_rel_x.append(
121
+ [
122
+ curr[0], # top left x
123
+ curr[2], # bottom right x
124
+ curr[2] - curr[0], # width
125
+ next[0] - curr[0], # diff top left x
126
+ next[0] - curr[0], # diff bottom left x
127
+ next[2] - curr[2], # diff top right x
128
+ next[2] - curr[2], # diff bottom right x
129
+ centroids[i+1][0] - centroids[i][0],
130
+ ]
131
+ )
132
+
133
+ a_rel_y.append(
134
+ [
135
+ curr[1], # top left y
136
+ curr[3], # bottom right y
137
+ curr[3] - curr[1], # height
138
+ next[1] - curr[1], # diff top left y
139
+ next[3] - curr[3], # diff bottom left y
140
+ next[1] - curr[1], # diff top right y
141
+ next[3] - curr[3], # diff bottom right y
142
+ centroids[i+1][1] - centroids[i][1],
143
+ ]
144
+ )
145
+
146
+ # For the last word
147
+
148
+ a_rel_x.append([0]*8)
149
+ a_rel_y.append([0]*8)
150
+
151
+
152
+ return a_rel_x, a_rel_y
153
+
154
+
155
+
156
+ def apply_mask(inputs, tokenizer):
157
+ inputs = torch.as_tensor(inputs)
158
+ rand = torch.rand(inputs.shape)
159
+ # where the random array is less than 0.15, we set true
160
+ mask_arr = (rand < 0.15) * (inputs != tokenizer.cls_token_id) * (inputs != tokenizer.pad_token_id)
161
+ # create selection from mask_arr
162
+ selection = torch.flatten(mask_arr.nonzero()).tolist()
163
+ # apply selection pad_tokens_start_idx to inputs.input_ids, adding MASK tokens
164
+ inputs[selection] = 103
165
+ return inputs
166
+
167
+
168
+ def read_image_and_extract_text(image):
169
+ original_image = Image.open(image).convert("RGB")
170
+ return apply_ocr(image)
171
+
172
+
173
+ def create_features(
174
+ image,
175
+ tokenizer,
176
+ add_batch_dim=False,
177
+ target_size=(500,384), # This was the resolution used by the authors
178
+ max_seq_length=512,
179
+ path_to_save=None,
180
+ save_to_disk=False,
181
+ apply_mask_for_mlm=False,
182
+ extras_for_debugging=False,
183
+ use_ocr = False,
184
+ bounding_box = None,
185
+ words = None
186
+ ):
187
+
188
+ # step 1: read original image and extract OCR entries
189
+ original_image = Image.open(image).convert("RGB")
190
+
191
+ if (use_ocr == False) and (bounding_box == None or words == None):
192
+ raise Exception('Please provide the bounding box and words or pass the argument "use_ocr" = True')
193
+
194
+ if use_ocr == True:
195
+ entries = apply_ocr(image)
196
+ bounding_box = entries["bbox"]
197
+ words = entries["words"]
198
+
199
+ CLS_TOKEN_BOX = [0, 0, *original_image.size] # Can be variable, but as per the paper, they have mentioned that it covers the whole image
200
+ # step 2: resize image
201
+ resized_image = original_image.resize(target_size)
202
+
203
+ # step 3: normalize image to a grid of 1000 x 1000 (to avoid the problem of differently sized images)
204
+ width, height = original_image.size
205
+ normalized_word_boxes = [
206
+ normalize_box(bbox, width, height, GRID_SIZE) for bbox in bounding_box
207
+ ]
208
+ assert len(words) == len(normalized_word_boxes), "Length of words != Length of normalized words"
209
+
210
+ # step 4: tokenize words and get their bounding boxes (one word may split into multiple tokens)
211
+ encoding = tokenizer(words,
212
+ padding="max_length",
213
+ max_length=max_seq_length,
214
+ is_split_into_words=True,
215
+ truncation=True,
216
+ add_special_tokens=False)
217
+
218
+ unnormalized_token_boxes = get_tokens_with_boxes(bounding_box,
219
+ PAD_TOKEN_BOX,
220
+ encoding.word_ids())
221
+
222
+ # step 5: add special tokens and truncate seq. to maximum length
223
+ unnormalized_token_boxes = [CLS_TOKEN_BOX] + unnormalized_token_boxes[:-1]
224
+ # add CLS token manually to avoid autom. addition of SEP too (as in the paper)
225
+ encoding["input_ids"] = [tokenizer.cls_token_id] + encoding["input_ids"][:-1]
226
+
227
+ # step 6: Add bounding boxes to the encoding dict
228
+ encoding["unnormalized_token_boxes"] = unnormalized_token_boxes
229
+
230
+ # step 7: apply mask for the sake of pre-training
231
+ if apply_mask_for_mlm:
232
+ encoding["mlm_labels"] = encoding["input_ids"]
233
+ encoding["input_ids"] = apply_mask(encoding["input_ids"], tokenizer)
234
+ assert len(encoding["mlm_labels"]) == max_seq_length, "Length of mlm_labels != Length of max_seq_length"
235
+
236
+ assert len(encoding["input_ids"]) == max_seq_length, "Length of input_ids != Length of max_seq_length"
237
+ assert len(encoding["attention_mask"]) == max_seq_length, "Length of attention mask != Length of max_seq_length"
238
+ assert len(encoding["token_type_ids"]) == max_seq_length, "Length of token type ids != Length of max_seq_length"
239
+
240
+ # step 8: normalize the image
241
+ encoding["resized_scaled_img"] = ToTensor()(resized_image)
242
+
243
+ # step 9: apply mask for the sake of pre-training
244
+ if apply_mask_for_mlm:
245
+ encoding["mlm_labels"] = encoding["input_ids"]
246
+ encoding["input_ids"] = apply_mask(encoding["input_ids"], tokenizer)
247
+
248
+ # step 10: rescale and align the bounding boxes to match the resized image size (typically 224x224)
249
+ resized_and_aligned_bboxes = []
250
+
251
+ for bbox in unnormalized_token_boxes:
252
+ # performing the normalization of the bounding box
253
+ resized_and_aligned_bboxes.append(resize_align_bbox(tuple(bbox), *original_image.size, *target_size))
254
+
255
+ encoding["resized_and_aligned_bounding_boxes"] = resized_and_aligned_bboxes
256
+
257
+ # step 11: add the relative distances in the normalized grid
258
+ bboxes_centroids = get_centroid(resized_and_aligned_bboxes)
259
+ pad_token_start_index = get_pad_token_id_start_index(words, encoding, tokenizer)
260
+ a_rel_x, a_rel_y = get_relative_distance(resized_and_aligned_bboxes, bboxes_centroids, pad_token_start_index)
261
+
262
+ # step 12: convert all to tensors
263
+ for k, v in encoding.items():
264
+ encoding[k] = torch.as_tensor(encoding[k])
265
+
266
+ encoding.update({
267
+ "x_features": torch.as_tensor(a_rel_x, dtype=torch.int32),
268
+ "y_features": torch.as_tensor(a_rel_y, dtype=torch.int32),
269
+ })
270
+
271
+ # step 13: add tokens for debugging
272
+ if extras_for_debugging:
273
+ input_ids = encoding["mlm_labels"] if apply_mask_for_mlm else encoding["input_ids"]
274
+ encoding["tokens_without_padding"] = tokenizer.convert_ids_to_tokens(input_ids)
275
+ encoding["words"] = words
276
+
277
+
278
+ # step 14: add extra dim for batch
279
+ if add_batch_dim:
280
+ encoding["x_features"].unsqueeze_(0)
281
+ encoding["y_features"].unsqueeze_(0)
282
+ encoding["input_ids"].unsqueeze_(0)
283
+ encoding["resized_scaled_img"].unsqueeze_(0)
284
+
285
+ # step 15: save to disk
286
+ if save_to_disk:
287
+ os.makedirs(path_to_save, exist_ok=True)
288
+ image_name = os.path.basename(image)
289
+ with open(f"{path_to_save}{image_name}.pickle", "wb") as f:
290
+ pickle.dump(encoding, f)
291
+
292
+ # step 16: keys to keep, resized_and_aligned_bounding_boxes have been added for the purpose to test if the bounding boxes are drawn correctly or not, it maybe removed
293
+
294
+ keys = ['resized_scaled_img', 'x_features','y_features','input_ids','resized_and_aligned_bounding_boxes']
295
+
296
+ if apply_mask_for_mlm:
297
+ keys.append('mlm_labels')
298
+
299
+ final_encoding = {k:encoding[k] for k in keys}
300
+
301
+ del encoding
302
+ return final_encoding