SalML commited on
Commit
71beb3c
·
1 Parent(s): f3d8605

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -495
app.py DELETED
@@ -1,495 +0,0 @@
1
- import streamlit as st
2
- from PIL import Image, ImageEnhance
3
- import statistics
4
- import os
5
- import string
6
- from collections import Counter
7
- from itertools import tee, count
8
- # import TDTSR
9
- import pytesseract
10
- from pytesseract import Output
11
- import json
12
- import pandas as pd
13
- import matplotlib.pyplot as plt
14
- import cv2
15
- import numpy as np
16
- # from transformers import TrOCRProcessor, VisionEncoderDecoderModel
17
- # from cv2 import dnn_superres
18
- from transformers import DetrFeatureExtractor
19
- from transformers import DetrForObjectDetection
20
- import torch
21
- import asyncio
22
- # pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
23
-
24
-
25
- st.set_option('deprecation.showPyplotGlobalUse', False)
26
- st.set_page_config(layout='wide')
27
- st.title("Table Detection and Table Structure Recognition")
28
-
29
-
30
- def PIL_to_cv(pil_img):
31
- return cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)
32
-
33
- def cv_to_PIL(cv_img):
34
- return Image.fromarray(cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB))
35
-
36
-
37
- async def pytess(cell_pil_img):
38
- return ' '.join(pytesseract.image_to_data(cell_pil_img, output_type=Output.DICT, config='-c tessedit_char_blacklist=œ˜â€œï¬â™Ã©œ¢!|”?«“¥ --psm 6 preserve_interword_spaces')['text']).strip()
39
-
40
-
41
- # def super_res(pil_img):
42
- # '''
43
- # Useful for low-res docs
44
- # '''
45
- # requires opencv-contrib-python installed without the opencv-python
46
- # sr = dnn_superres.DnnSuperResImpl_create()
47
- # image = PIL_to_cv(pil_img)
48
- # model_path = "/data/Salman/TRD/code/table-transformer/transformers/LapSRN_x2.pb"
49
- # model_name = 'lapsrn'
50
- # model_scale = 2
51
- # sr.readModel(model_path)
52
- # sr.setModel(model_name, model_scale)
53
- # final_img = sr.upsample(image)
54
- # final_img = cv_to_PIL(final_img)
55
-
56
- # return final_img
57
-
58
-
59
- def sharpen_image(pil_img):
60
-
61
- img = PIL_to_cv(pil_img)
62
- sharpen_kernel = np.array([[-1, -1, -1],
63
- [-1, 9, -1],
64
- [-1, -1, -1]])
65
-
66
- sharpen = cv2.filter2D(img, -1, sharpen_kernel)
67
- pil_img = cv_to_PIL(sharpen)
68
- return pil_img
69
-
70
-
71
- def uniquify(seq, suffs = count(1)):
72
- """Make all the items unique by adding a suffix (1, 2, etc).
73
- Credit: https://stackoverflow.com/questions/30650474/python-rename-duplicates-in-list-with-progressive-numbers-without-sorting-list
74
- `seq` is mutable sequence of strings.
75
- `suffs` is an optional alternative suffix iterable.
76
- """
77
- not_unique = [k for k,v in Counter(seq).items() if v>1]
78
-
79
- suff_gens = dict(zip(not_unique, tee(suffs, len(not_unique))))
80
- for idx,s in enumerate(seq):
81
- try:
82
- suffix = str(next(suff_gens[s]))
83
- except KeyError:
84
- continue
85
- else:
86
- seq[idx] += suffix
87
-
88
- return seq
89
-
90
- def binarizeBlur_image(pil_img):
91
- image = PIL_to_cv(pil_img)
92
- thresh = cv2.threshold(image, 150, 255, cv2.THRESH_BINARY_INV)[1]
93
-
94
- result = cv2.GaussianBlur(thresh, (5,5), 0)
95
- result = 255 - result
96
- return cv_to_PIL(result)
97
-
98
-
99
-
100
- def td_postprocess(pil_img):
101
- '''
102
- Removes gray background from tables
103
- '''
104
- img = PIL_to_cv(pil_img)
105
-
106
- hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
107
- mask = cv2.inRange(hsv, (0, 0, 100), (255, 5, 255)) # (0, 0, 100), (255, 5, 255)
108
- nzmask = cv2.inRange(hsv, (0, 0, 5), (255, 255, 255)) # (0, 0, 5), (255, 255, 255))
109
- nzmask = cv2.erode(nzmask, np.ones((3,3))) # (3,3)
110
- mask = mask & nzmask
111
-
112
- new_img = img.copy()
113
- new_img[np.where(mask)] = 255
114
-
115
-
116
- return cv_to_PIL(new_img)
117
-
118
- def super_res(pil_img):
119
- # requires opencv-contrib-python installed without the opencv-python
120
- sr = dnn_superres.DnnSuperResImpl_create()
121
- image = PIL_to_cv(pil_img)
122
- model_path = "./LapSRN_x8.pb"
123
- model_name = model_path.split('/')[1].split('_')[0].lower()
124
- model_scale = int(model_path.split('/')[1].split('_')[1].split('.')[0][1])
125
-
126
- sr.readModel(model_path)
127
- sr.setModel(model_name, model_scale)
128
- final_img = sr.upsample(image)
129
- final_img = cv_to_PIL(final_img)
130
-
131
- return final_img
132
-
133
- def table_detector(image, THRESHOLD_PROBA):
134
- '''
135
- Table detection using DEtect-object TRansformer pre-trained on 1 million tables
136
-
137
- '''
138
-
139
- feature_extractor = DetrFeatureExtractor(do_resize=True, size=800, max_size=800)
140
- encoding = feature_extractor(image, return_tensors="pt")
141
-
142
- model = DetrForObjectDetection.from_pretrained("SalML/DETR-table-detection")
143
-
144
- with torch.no_grad():
145
- outputs = model(**encoding)
146
-
147
- probas = outputs.logits.softmax(-1)[0, :, :-1]
148
- keep = probas.max(-1).values > THRESHOLD_PROBA
149
-
150
- target_sizes = torch.tensor(image.size[::-1]).unsqueeze(0)
151
- postprocessed_outputs = feature_extractor.post_process(outputs, target_sizes)
152
- bboxes_scaled = postprocessed_outputs[0]['boxes'][keep]
153
-
154
- return (model, probas[keep], bboxes_scaled)
155
-
156
-
157
- def table_struct_recog(image, THRESHOLD_PROBA):
158
- '''
159
- Table structure recognition using DEtect-object TRansformer pre-trained on 1 million tables
160
- '''
161
-
162
- feature_extractor = DetrFeatureExtractor(do_resize=True, size=1000, max_size=1000)
163
- encoding = feature_extractor(image, return_tensors="pt")
164
-
165
- model = DetrForObjectDetection.from_pretrained("SalML/DETR-table-structure-recognition")
166
- with torch.no_grad():
167
- outputs = model(**encoding)
168
-
169
- probas = outputs.logits.softmax(-1)[0, :, :-1]
170
- keep = probas.max(-1).values > THRESHOLD_PROBA
171
-
172
- target_sizes = torch.tensor(image.size[::-1]).unsqueeze(0)
173
- postprocessed_outputs = feature_extractor.post_process(outputs, target_sizes)
174
- bboxes_scaled = postprocessed_outputs[0]['boxes'][keep]
175
-
176
- return (model, probas[keep], bboxes_scaled)
177
-
178
-
179
-
180
-
181
-
182
- class TableExtractionPipeline():
183
-
184
- colors = ["red", "blue", "green", "yellow", "orange", "violet"]
185
-
186
- # colors = ["red", "blue", "green", "red", "red", "red"]
187
-
188
- def add_padding(self, pil_img, top, right, bottom, left, color=(255,255,255)):
189
- '''
190
- Image padding as part of TSR pre-processing to prevent missing table edges
191
- '''
192
- width, height = pil_img.size
193
- new_width = width + right + left
194
- new_height = height + top + bottom
195
- result = Image.new(pil_img.mode, (new_width, new_height), color)
196
- result.paste(pil_img, (left, top))
197
- return result
198
-
199
- def plot_results_detection(self, c1, model, pil_img, prob, boxes, delta_xmin, delta_ymin, delta_xmax, delta_ymax):
200
- '''
201
- crop_tables and plot_results_detection must have same co-ord shifts because 1 only plots the other one updates co-ordinates
202
- '''
203
- # st.write('img_obj')
204
- # st.write(pil_img)
205
- plt.imshow(pil_img)
206
- ax = plt.gca()
207
-
208
- for p, (xmin, ymin, xmax, ymax) in zip(prob, boxes.tolist()):
209
- cl = p.argmax()
210
- xmin, ymin, xmax, ymax = xmin-delta_xmin, ymin-delta_ymin, xmax+delta_xmax, ymax+delta_ymax
211
- ax.add_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin,fill=False, color='red', linewidth=3))
212
- text = f'{model.config.id2label[cl.item()]}: {p[cl]:0.2f}'
213
- ax.text(xmin-20, ymin-50, text, fontsize=10,bbox=dict(facecolor='yellow', alpha=0.5))
214
- plt.axis('off')
215
- st.pyplot()
216
-
217
-
218
- def crop_tables(self, pil_img, prob, boxes, delta_xmin, delta_ymin, delta_xmax, delta_ymax):
219
- '''
220
- crop_tables and plot_results_detection must have same co-ord shifts because 1 only plots the other one updates co-ordinates
221
- '''
222
- cropped_img_list = []
223
-
224
- for p, (xmin, ymin, xmax, ymax) in zip(prob, boxes.tolist()):
225
-
226
- xmin, ymin, xmax, ymax = xmin-delta_xmin, ymin-delta_ymin, xmax+delta_xmax, ymax+delta_ymax
227
- cropped_img = pil_img.crop((xmin, ymin, xmax, ymax))
228
- cropped_img_list.append(cropped_img)
229
-
230
-
231
- return cropped_img_list
232
-
233
- def generate_structure(self, c2, model, pil_img, prob, boxes, expand_rowcol_bbox_top, expand_rowcol_bbox_bottom):
234
- '''
235
- Co-ordinates are adjusted here by 3 'pixels'
236
- To plot table pillow image and the TSR bounding boxes on the table
237
- '''
238
- # st.write('img_obj')
239
- # st.write(pil_img)
240
- plt.figure(figsize=(32,20))
241
- plt.imshow(pil_img)
242
- ax = plt.gca()
243
- rows = {}
244
- cols = {}
245
- idx = 0
246
-
247
-
248
- for p, (xmin, ymin, xmax, ymax) in zip(prob, boxes.tolist()):
249
-
250
- xmin, ymin, xmax, ymax = xmin, ymin, xmax, ymax
251
- cl = p.argmax()
252
- class_text = model.config.id2label[cl.item()]
253
- text = f'{class_text}: {p[cl]:0.2f}'
254
- # or (class_text == 'table column')
255
- if (class_text == 'table row') or (class_text =='table projected row header') or (class_text == 'table column'):
256
- ax.add_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin,fill=False, color=self.colors[cl.item()], linewidth=2))
257
- ax.text(xmin-10, ymin-10, text, fontsize=5, bbox=dict(facecolor='yellow', alpha=0.5))
258
-
259
- if class_text == 'table row':
260
- rows['table row.'+str(idx)] = (xmin, ymin-expand_rowcol_bbox_top, xmax, ymax+expand_rowcol_bbox_bottom)
261
- if class_text == 'table column':
262
- cols['table column.'+str(idx)] = (xmin, ymin-expand_rowcol_bbox_top, xmax, ymax+expand_rowcol_bbox_bottom)
263
-
264
- idx += 1
265
-
266
-
267
- plt.axis('on')
268
- st.pyplot()
269
- return rows, cols
270
-
271
- def sort_table_featuresv2(self, rows:dict, cols:dict):
272
- # Sometimes the header and first row overlap, and we need the header bbox not to have first row's bbox inside the headers bbox
273
- rows_ = {table_feature : (xmin, ymin, xmax, ymax) for table_feature, (xmin, ymin, xmax, ymax) in sorted(rows.items(), key=lambda tup: tup[1][1])}
274
- cols_ = {table_feature : (xmin, ymin, xmax, ymax) for table_feature, (xmin, ymin, xmax, ymax) in sorted(cols.items(), key=lambda tup: tup[1][0])}
275
-
276
- return rows_, cols_
277
-
278
- def individual_table_featuresv2(self, pil_img, rows:dict, cols:dict):
279
-
280
- for k, v in rows.items():
281
- xmin, ymin, xmax, ymax = v
282
- cropped_img = pil_img.crop((xmin, ymin, xmax, ymax))
283
- rows[k] = xmin, ymin, xmax, ymax, cropped_img
284
-
285
- for k, v in cols.items():
286
- xmin, ymin, xmax, ymax = v
287
- cropped_img = pil_img.crop((xmin, ymin, xmax, ymax))
288
- cols[k] = xmin, ymin, xmax, ymax, cropped_img
289
-
290
- return rows, cols
291
-
292
-
293
- def object_to_cellsv2(self, master_row:dict, cols:dict, expand_rowcol_bbox_top, expand_rowcol_bbox_bottom, padd_left):
294
- '''Removes redundant bbox for rows&columns and divides each row into cells from columns
295
- Args:
296
-
297
- Returns:
298
-
299
-
300
- '''
301
- cells_img = {}
302
- header_idx = 0
303
- row_idx = 0
304
- previous_xmax_col = 0
305
- new_cols = {}
306
- new_master_row = {}
307
- previous_ymin_row = 0
308
- new_cols = cols
309
- new_master_row = master_row
310
- ## Below 2 for loops remove redundant bounding boxes ###
311
- for k_col, v_col in cols.items():
312
- xmin_col, _, xmax_col, _, col_img = v_col
313
- if (np.isclose(previous_xmax_col, xmax_col, atol=50)) or (xmin_col >= xmax_col):
314
- print('Found a column with double bbox')
315
- continue
316
- previous_xmax_col = xmax_col
317
- new_cols[k_col] = v_col
318
-
319
- for k_row, v_row in master_row.items():
320
- _, ymin_row, _, ymax_row, row_img = v_row
321
- if (np.isclose(previous_ymin_row, ymin_row, atol=50)) or (ymin_row >= ymax_row):
322
- print('Found a row with double bbox')
323
- continue
324
- previous_ymin_row = ymin_row
325
- new_master_row[k_row] = v_row
326
- ######################################################
327
- for k_row, v_row in new_master_row.items():
328
-
329
- _, _, _, _, row_img = v_row
330
- xmax, ymax = row_img.size
331
- xa, ya, xb, yb = 0, 0, 0, ymax
332
- row_img_list = []
333
- # plt.imshow(row_img)
334
- # st.pyplot()
335
- for idx, kv in enumerate(new_cols.items()):
336
- k_col, v_col = kv
337
- xmin_col, _, xmax_col, _, col_img = v_col
338
- xmin_col, xmax_col = xmin_col - padd_left - 10, xmax_col - padd_left
339
- # plt.imshow(col_img)
340
- # st.pyplot()
341
- # xa + 3 : to remove borders on the left side of the cropped cell
342
- # yb = 3: to remove row information from the above row of the cropped cell
343
- # xb - 3: to remove borders on the right side of the cropped cell
344
- xa = xmin_col
345
- xb = xmax_col
346
- if idx == 0:
347
- xa = 0
348
- if idx == len(new_cols)-1:
349
- xb = xmax
350
- xa, ya, xb, yb = xa, ya, xb, yb
351
-
352
- row_img_cropped = row_img.crop((xa, ya, xb, yb))
353
- row_img_list.append(row_img_cropped)
354
-
355
- cells_img[k_row+'.'+str(row_idx)] = row_img_list
356
- row_idx += 1
357
-
358
- return cells_img, len(new_cols), len(new_master_row)-1
359
-
360
- def clean_dataframe(self, df):
361
- '''
362
- Remove irrelevant symbols that appear with tesseractOCR
363
- '''
364
- # df.columns = [col.replace('|', '') for col in df.columns]
365
-
366
- for col in df.columns:
367
-
368
- df[col]=df[col].str.replace("'", '', regex=True)
369
- df[col]=df[col].str.replace('"', '', regex=True)
370
- df[col]=df[col].str.replace(']', '', regex=True)
371
- df[col]=df[col].str.replace('[', '', regex=True)
372
- df[col]=df[col].str.replace('{', '', regex=True)
373
- df[col]=df[col].str.replace('}', '', regex=True)
374
- return df
375
-
376
- @st.cache
377
- def convert_df(self, df):
378
- return df.to_csv().encode('utf-8')
379
-
380
-
381
- def create_dataframe(self, c3, cells_pytess_result:list, max_cols:int, max_rows:int):
382
- '''Create dataframe using list of cell values of the table, also checks for valid header of dataframe
383
- Args:
384
- cells_pytess_result: list of strings, each element representing a cell in a table
385
- max_cols, max_rows: number of columns and rows
386
- Returns:
387
- dataframe : final dataframe after all pre-processing
388
- '''
389
-
390
- headers = cells_pytess_result[:max_cols]
391
- new_headers = uniquify(headers, (f' {x!s}' for x in string.ascii_lowercase))
392
- counter = 0
393
-
394
- cells_list = cells_pytess_result[max_cols:]
395
- df = pd.DataFrame("", index=range(0, max_rows), columns=new_headers)
396
-
397
- cell_idx = 0
398
- for nrows in range(max_rows):
399
- for ncols in range(max_cols):
400
- df.iat[nrows, ncols] = str(cells_list[cell_idx])
401
- cell_idx += 1
402
-
403
- ## To check if there are duplicate headers if result of uniquify+col == col
404
- ## This check removes headers when all headers are empty or if median of header word count is less than 6
405
- for x, col in zip(string.ascii_lowercase, new_headers):
406
- if f' {x!s}' == col:
407
- counter += 1
408
- header_char_count = [len(col) for col in new_headers]
409
-
410
- if (counter == len(new_headers)) or (statistics.median(header_char_count) < 6):
411
- df.columns = uniquify(df.iloc[0], (f' {x!s}' for x in string.ascii_lowercase))
412
- df = df.iloc[1:,:]
413
-
414
- df = self.clean_dataframe(df)
415
-
416
- st.dataframe(df)
417
- csv = self.convert_df(df)
418
- st.download_button("Download table", csv, "file.csv", "text/csv", key='download-csv')
419
-
420
- return df
421
-
422
-
423
-
424
-
425
-
426
-
427
- async def start_process(self, image_path:str, TD_THRESHOLD, TSR_THRESHOLD, padd_top, padd_left, padd_bottom, padd_right, delta_xmin, delta_ymin, delta_xmax, delta_ymax, expand_rowcol_bbox_top, expand_rowcol_bbox_bottom):
428
- '''
429
- Initiates process of generating pandas dataframes from raw pdf-page images
430
-
431
- '''
432
- image = Image.open(image_path).convert("RGB")
433
- model, probas, bboxes_scaled = table_detector(image, THRESHOLD_PROBA=TD_THRESHOLD)
434
-
435
- if bboxes_scaled.nelement() == 0:
436
- print('No table found in the pdf-page image'+image_path.split('/')[-1])
437
- return ''
438
-
439
- # try:
440
- # st.write('Document: '+image_path.split('/')[-1])
441
- c1, c2, c3 = st.columns((1,1,1))
442
-
443
- self.plot_results_detection(c1, model, image, probas, bboxes_scaled, delta_xmin, delta_ymin, delta_xmax, delta_ymax)
444
- cropped_img_list = self.crop_tables(image, probas, bboxes_scaled, delta_xmin, delta_ymin, delta_xmax, delta_ymax)
445
-
446
- for unpadded_table in cropped_img_list:
447
-
448
- table = self.add_padding(unpadded_table, padd_top, padd_right, padd_bottom, padd_left)
449
- # table = super_res(table)
450
- # table = binarizeBlur_image(table)
451
- # table = sharpen_image(table) # Test sharpen image next
452
- # table = td_postprocess(table)
453
-
454
- model, probas, bboxes_scaled = table_struct_recog(table, THRESHOLD_PROBA=TSR_THRESHOLD)
455
- rows, cols = self.generate_structure(c2, model, table, probas, bboxes_scaled, expand_rowcol_bbox_top, expand_rowcol_bbox_bottom)
456
- # st.write(len(rows), len(cols))
457
- rows, cols = self.sort_table_featuresv2(rows, cols)
458
- master_row, cols = self.individual_table_featuresv2(table, rows, cols)
459
-
460
- cells_img, max_cols, max_rows = self.object_to_cellsv2(master_row, cols, expand_rowcol_bbox_top, expand_rowcol_bbox_bottom, padd_left)
461
-
462
- sequential_cell_img_list = []
463
- for k, img_list in cells_img.items():
464
- for img in img_list:
465
- # img = super_res(img)
466
- # img = sharpen_image(img) # Test sharpen image next
467
- # img = binarizeBlur_image(img)
468
-
469
- # plt.imshow(img)
470
- # c3.pyplot()
471
- sequential_cell_img_list.append(pytess(img))
472
-
473
- cells_pytess_result = await asyncio.gather(*sequential_cell_img_list)
474
-
475
-
476
- self.create_dataframe(c3, cells_pytess_result, max_cols, max_rows)
477
- # except:
478
- # st.write('Either incorrectly identified table or no table, to debug remove try/except')
479
- # break
480
- # break
481
-
482
-
483
-
484
-
485
- if __name__ == "__main__":
486
-
487
- img_name = st.file_uploader("Upload an image with table(s)")
488
-
489
- te = TableExtractionPipeline()
490
- # for img in image_list:
491
- if img_name is not None:
492
- asyncio.run(te.start_process(img_name, TD_THRESHOLD=0.6, TSR_THRESHOLD=0.8, padd_top=20, padd_left=20, padd_bottom=20, padd_right=20, delta_xmin=0, delta_ymin=0, delta_xmax=0, delta_ymax=0, expand_rowcol_bbox_top=0, expand_rowcol_bbox_bottom=0))
493
-
494
-
495
-