debu das commited on
Commit
f278fae
1 Parent(s): 01913fd

Create app.py

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