-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathconvert_.py
More file actions
339 lines (278 loc) · 6.99 KB
/
convert_.py
File metadata and controls
339 lines (278 loc) · 6.99 KB
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import logging
from typing import (
List,
Dict,
Tuple
)
from sklearn.manifold import TSNE
import re
import pytesseract
import numpy as np
from pytesseract import Output
import cv2
import argparse
__author__ = "Sambit Sekhar"
arg = argparse.ArgumentParser()
arg.add_argument("-f", "--image_file", required=True, help=".jpg/.png file from which we will process")
arg.add_argument("-w", "--write_box", required=True, default=True, help="visualize bounding box")
arg.add_argument("-b", "--write_box_path", required=True, help="path where will save bounding box image")
arg.add_argument("-g", "--glove_path", required=True, help="filepath to load glove")
arg.add_argument("-d", "--draw_bertgrid", required=True, default=True, help="true/false to draw bertgrid representation")
arg.add_argument("-k", "--path_draw_bertgrid", required=True, help="path draw blank and bertgrid")
def write_boundingbox_image(
img_path: str,
only_text_box: List,
path_to_save: str
) -> None:
"""
:param img_path:
:param only_text_box:
:param path_to_save:
:return:
"""
img = cv2.imread(img_path)
for text, pt1, pt2 in only_text_box:
print(text)
cv2.rectangle(img, pt1, pt2, (0, 255, 0), cv2.FILLED)
cv2.imwrite(path_to_save, img)
def text_boundingbox(
img_path: str,
max_height: int = 500,
max_width: int = 500
) -> List:
"""
Get bounding box
:param img_path:
:param max_height:
:param max_width:
:return:
"""
text_bb = []
image = cv2.imread(img_path)
detected = pytesseract.image_to_data(
image, output_type=Output.DICT
)
n_boxes = len(detected['level'])
for i in range(n_boxes):
(x, y, w, h) = (
detected['left'][i],
detected['top'][i],
detected['width'][i],
detected['height'][i]
)
text = detected['text'][i]
if w < max_width and h < max_height:
text_bb.append((text, (x, y), (x + w, y + h)))
only_text_box = [
box
for box in text_bb
if box[0].strip() != ''
]
return only_text_box
def load_glove_model(
glove_file: str
) -> Dict:
"""
:param glove_file:
:return:
"""
f = open(glove_file, 'r')
model = {}
for line in f:
splitline = line.split()
word = splitline[0]
embedding = np.array(
[
float(val)
for val in splitline[1:]
]
)
model[word] = embedding
return model
def preprocess_text(
text
) -> str:
"""
:param text:
:return:
"""
text = re.sub('[^a-zA-Zа-яА-Я1-9]+', ' ', text)
text = re.sub(' +', ' ', text)
return text.strip().lower()
def words_with_embeddings(
keys: List,
word_emb: Dict
) -> Tuple[List, List]:
"""
:param keys:
:param word_emb:
:return:
"""
embeddings = []
words = []
for word in keys:
embedding_vector = word_emb.get(word[0])
if embedding_vector is not None:
words.append(word)
embeddings.append(word_emb[word[0]])
else:
emb = np.zeros(shape=(300,))
words.append(word)
embeddings.append(emb)
return words, embeddings
def convert_to_3d(
embeddings: List
) -> List:
"""
:param embeddings:
:return:
"""
embedding_clusters = np.array(embeddings)
tsne_model_en_3d = TSNE(
perplexity=15,
n_components=3,
init='pca',
n_iter=3500,
random_state=32
)
embeddings_en_3d = tsne_model_en_3d.fit_transform(embedding_clusters)
return embeddings_en_3d.tolist()
def clamp(
n,
minn=0,
maxn=255
) -> int:
"""
:param n:
:param minn:
:param maxn:
:return:
"""
if n < minn:
return minn
elif n > maxn:
return maxn
else:
return n
def get_color_list(
embeddings_list: List
) -> List:
"""
:param embeddings_list:
:return:
"""
colors = [
(
clamp(round(abs(vec[0]))),
clamp(round(abs(vec[1]))),
clamp(round(abs(vec[2])))
)
for vec in embeddings_list
]
return colors
def draw_black_img(
img_height: int,
img_width: int,
blank_path: str
) -> None:
"""
:param img_height:
:param img_width:
:param blank_path:
:return:
"""
blank_image = np.zeros((img_height, img_width, 3), np.uint8)
cv2.imwrite(blank_path, blank_image)
def draw_bertgrid(
blank_path: str,
words: List,
colors: List,
write_img_path: str
) -> None:
"""
:param blank_path:
:param words:
:param colors:
:param write_img_path:
:return:
"""
img = cv2.imread(blank_path)
for bb, color in zip(words, colors):
cv2.rectangle(img, bb[1], bb[2], color, cv2.FILLED)
cv2.imwrite(write_img_path, img)
def main():
args = arg.parse_args()
file_path = args.image_file
write_image = args.write_box
box_image_write = args.write_box_path
glove_path = args.glove_path
dw_bertgrid = args.draw_bertgrid
bertgrid_path = args.path_draw_bertgrid
text_bounding_boxes = text_boundingbox(file_path)
print("length of bounding box ....")
print(len(text_bounding_boxes))
img = cv2.imread(file_path)
# for text, pt1, pt2 in text_bounding_boxes:
# print(text, pt1, pt2)
# cv2.rectangle(img, pt1, pt2, (0, 255, 0), cv2.FILLED)
#
# cv2.imwrite(box_image_write, img)
if write_image:
write_boundingbox_image(
file_path,
text_bounding_boxes,
box_image_write
)
print('loading glove ... ')
word_emb = load_glove_model(glove_path)
keys = [
(preprocess_text(text), pt1, pt2)
for text, pt1, pt2 in text_bounding_boxes
]
print("length of keys ... ")
print(len(keys))
words, embeddings = words_with_embeddings(
keys,
word_emb
)
print("get embeddings .... ")
embeddings_3d_list = convert_to_3d(
embeddings
)
print("converted into 3d ... ")
colors_list = get_color_list(embeddings_3d_list)
print("colors 3d .... ")
print((len(colors_list)))
print(img.shape)
height, width = img.shape[:2]
if dw_bertgrid:
draw_black_img(
height,
width,
bertgrid_path
)
print("writting bertgrid ... ")
draw_bertgrid(
bertgrid_path,
words,
colors_list,
bertgrid_path
)
# def draw_black_img(
# img_height: int,
# img_width: int,
# blank_path: str
# ) -> None:
#
# draw_bertgrid(
#
# )
#
# def draw_bertgrid(
# blank_path: str,
# words: List,
# colors: List,
# write_img_path: str
# ) -> None:
if __name__ == '__main__':
main()