debu das commited on
Commit
1b3c267
1 Parent(s): 2750b20

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +500 -0
  2. packages.txt +6 -0
  3. requirements.txt +46 -0
app.py ADDED
@@ -0,0 +1,500 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ st.write("Implemented by MSFT team: https://github.com/microsoft/table-transformer")
29
+
30
+
31
+ def PIL_to_cv(pil_img):
32
+ return cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)
33
+
34
+ def cv_to_PIL(cv_img):
35
+ return Image.fromarray(cv2.cvtColor(cv_img, cv2.COLOR_BGR2RGB))
36
+
37
+
38
+ async def pytess(cell_pil_img):
39
+ 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()
40
+
41
+
42
+ # def super_res(pil_img):
43
+ # '''
44
+ # Useful for low-res docs
45
+ # '''
46
+ # requires opencv-contrib-python installed without the opencv-python
47
+ # sr = dnn_superres.DnnSuperResImpl_create()
48
+ # image = PIL_to_cv(pil_img)
49
+ # model_path = "/data/Salman/TRD/code/table-transformer/transformers/LapSRN_x2.pb"
50
+ # model_name = 'lapsrn'
51
+ # model_scale = 2
52
+ # sr.readModel(model_path)
53
+ # sr.setModel(model_name, model_scale)
54
+ # final_img = sr.upsample(image)
55
+ # final_img = cv_to_PIL(final_img)
56
+
57
+ # return final_img
58
+
59
+
60
+ def sharpen_image(pil_img):
61
+
62
+ img = PIL_to_cv(pil_img)
63
+ sharpen_kernel = np.array([[-1, -1, -1],
64
+ [-1, 9, -1],
65
+ [-1, -1, -1]])
66
+
67
+ sharpen = cv2.filter2D(img, -1, sharpen_kernel)
68
+ pil_img = cv_to_PIL(sharpen)
69
+ return pil_img
70
+
71
+
72
+ def uniquify(seq, suffs = count(1)):
73
+ """Make all the items unique by adding a suffix (1, 2, etc).
74
+ Credit: https://stackoverflow.com/questions/30650474/python-rename-duplicates-in-list-with-progressive-numbers-without-sorting-list
75
+ `seq` is mutable sequence of strings.
76
+ `suffs` is an optional alternative suffix iterable.
77
+ """
78
+ not_unique = [k for k,v in Counter(seq).items() if v>1]
79
+
80
+ suff_gens = dict(zip(not_unique, tee(suffs, len(not_unique))))
81
+ for idx,s in enumerate(seq):
82
+ try:
83
+ suffix = str(next(suff_gens[s]))
84
+ except KeyError:
85
+ continue
86
+ else:
87
+ seq[idx] += suffix
88
+
89
+ return seq
90
+
91
+ def binarizeBlur_image(pil_img):
92
+ image = PIL_to_cv(pil_img)
93
+ thresh = cv2.threshold(image, 150, 255, cv2.THRESH_BINARY_INV)[1]
94
+
95
+ result = cv2.GaussianBlur(thresh, (5,5), 0)
96
+ result = 255 - result
97
+ return cv_to_PIL(result)
98
+
99
+
100
+
101
+ def td_postprocess(pil_img):
102
+ '''
103
+ Removes gray background from tables
104
+ '''
105
+ img = PIL_to_cv(pil_img)
106
+
107
+ hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
108
+ mask = cv2.inRange(hsv, (0, 0, 100), (255, 5, 255)) # (0, 0, 100), (255, 5, 255)
109
+ nzmask = cv2.inRange(hsv, (0, 0, 5), (255, 255, 255)) # (0, 0, 5), (255, 255, 255))
110
+ nzmask = cv2.erode(nzmask, np.ones((3,3))) # (3,3)
111
+ mask = mask & nzmask
112
+
113
+ new_img = img.copy()
114
+ new_img[np.where(mask)] = 255
115
+
116
+
117
+ return cv_to_PIL(new_img)
118
+
119
+ # def super_res(pil_img):
120
+ # # requires opencv-contrib-python installed without the opencv-python
121
+ # sr = dnn_superres.DnnSuperResImpl_create()
122
+ # image = PIL_to_cv(pil_img)
123
+ # model_path = "./LapSRN_x8.pb"
124
+ # model_name = model_path.split('/')[1].split('_')[0].lower()
125
+ # model_scale = int(model_path.split('/')[1].split('_')[1].split('.')[0][1])
126
+
127
+ # sr.readModel(model_path)
128
+ # sr.setModel(model_name, model_scale)
129
+ # final_img = sr.upsample(image)
130
+ # final_img = cv_to_PIL(final_img)
131
+
132
+ # return final_img
133
+
134
+ def table_detector(image, THRESHOLD_PROBA):
135
+ '''
136
+ Table detection using DEtect-object TRansformer pre-trained on 1 million tables
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
+ c1.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
+ c2.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
+ Returns:
297
+
298
+ '''
299
+ cells_img = {}
300
+ header_idx = 0
301
+ row_idx = 0
302
+ previous_xmax_col = 0
303
+ new_cols = {}
304
+ new_master_row = {}
305
+ previous_ymin_row = 0
306
+ new_cols = cols
307
+ new_master_row = master_row
308
+ ## Below 2 for loops remove redundant bounding boxes ###
309
+ # for k_col, v_col in cols.items():
310
+ # xmin_col, _, xmax_col, _, col_img = v_col
311
+ # if (np.isclose(previous_xmax_col, xmax_col, atol=5)) or (xmin_col >= xmax_col):
312
+ # print('Found a column with double bbox')
313
+ # continue
314
+ # previous_xmax_col = xmax_col
315
+ # new_cols[k_col] = v_col
316
+
317
+ # for k_row, v_row in master_row.items():
318
+ # _, ymin_row, _, ymax_row, row_img = v_row
319
+ # if (np.isclose(previous_ymin_row, ymin_row, atol=5)) or (ymin_row >= ymax_row):
320
+ # print('Found a row with double bbox')
321
+ # continue
322
+ # previous_ymin_row = ymin_row
323
+ # new_master_row[k_row] = v_row
324
+ ######################################################
325
+ for k_row, v_row in new_master_row.items():
326
+
327
+ _, _, _, _, row_img = v_row
328
+ xmax, ymax = row_img.size
329
+ xa, ya, xb, yb = 0, 0, 0, ymax
330
+ row_img_list = []
331
+ # plt.imshow(row_img)
332
+ # st.pyplot()
333
+ for idx, kv in enumerate(new_cols.items()):
334
+ k_col, v_col = kv
335
+ xmin_col, _, xmax_col, _, col_img = v_col
336
+ xmin_col, xmax_col = xmin_col - padd_left - 10, xmax_col - padd_left
337
+ # plt.imshow(col_img)
338
+ # st.pyplot()
339
+ # xa + 3 : to remove borders on the left side of the cropped cell
340
+ # yb = 3: to remove row information from the above row of the cropped cell
341
+ # xb - 3: to remove borders on the right side of the cropped cell
342
+ xa = xmin_col
343
+ xb = xmax_col
344
+ if idx == 0:
345
+ xa = 0
346
+ if idx == len(new_cols)-1:
347
+ xb = xmax
348
+ xa, ya, xb, yb = xa, ya, xb, yb
349
+
350
+ row_img_cropped = row_img.crop((xa, ya, xb, yb))
351
+ row_img_list.append(row_img_cropped)
352
+
353
+ cells_img[k_row+'.'+str(row_idx)] = row_img_list
354
+ row_idx += 1
355
+
356
+ return cells_img, len(new_cols), len(new_master_row)-1
357
+
358
+ def clean_dataframe(self, df):
359
+ '''
360
+ Remove irrelevant symbols that appear with tesseractOCR
361
+ '''
362
+ # df.columns = [col.replace('|', '') for col in df.columns]
363
+
364
+ for col in df.columns:
365
+
366
+ df[col]=df[col].str.replace("'", '', regex=True)
367
+ df[col]=df[col].str.replace('"', '', regex=True)
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
+ return df
373
+
374
+ @st.cache
375
+ def convert_df(self, df):
376
+ return df.to_csv().encode('utf-8')
377
+
378
+
379
+ def create_dataframe(self, c3, cells_pytess_result:list, max_cols:int, max_rows:int):
380
+ '''Create dataframe using list of cell values of the table, also checks for valid header of dataframe
381
+ Args:
382
+ cells_pytess_result: list of strings, each element representing a cell in a table
383
+ max_cols, max_rows: number of columns and rows
384
+ Returns:
385
+ dataframe : final dataframe after all pre-processing
386
+ '''
387
+
388
+ headers = cells_pytess_result[:max_cols]
389
+ new_headers = uniquify(headers, (f' {x!s}' for x in string.ascii_lowercase))
390
+ counter = 0
391
+
392
+ cells_list = cells_pytess_result[max_cols:]
393
+ df = pd.DataFrame("", index=range(0, max_rows), columns=new_headers)
394
+
395
+ cell_idx = 0
396
+ for nrows in range(max_rows):
397
+ for ncols in range(max_cols):
398
+ df.iat[nrows, ncols] = str(cells_list[cell_idx])
399
+ cell_idx += 1
400
+
401
+ ## To check if there are duplicate headers if result of uniquify+col == col
402
+ ## This check removes headers when all headers are empty or if median of header word count is less than 6
403
+ for x, col in zip(string.ascii_lowercase, new_headers):
404
+ if f' {x!s}' == col:
405
+ counter += 1
406
+ header_char_count = [len(col) for col in new_headers]
407
+
408
+ # if (counter == len(new_headers)) or (statistics.median(header_char_count) < 6):
409
+ # st.write('woooot')
410
+ # df.columns = uniquify(df.iloc[0], (f' {x!s}' for x in string.ascii_lowercase))
411
+ # df = df.iloc[1:,:]
412
+
413
+ df = self.clean_dataframe(df)
414
+
415
+ c3.dataframe(df)
416
+ csv = self.convert_df(df)
417
+ c3.download_button("Download table", csv, "file.csv", "text/csv", key='download-csv')
418
+
419
+ return df
420
+
421
+
422
+
423
+
424
+
425
+
426
+ 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):
427
+ '''
428
+ Initiates process of generating pandas dataframes from raw pdf-page images
429
+ '''
430
+ image = Image.open(image_path).convert("RGB")
431
+ model, probas, bboxes_scaled = table_detector(image, THRESHOLD_PROBA=TD_THRESHOLD)
432
+
433
+ if bboxes_scaled.nelement() == 0:
434
+ print('No table found in the pdf-page image'+image_path.split('/')[-1])
435
+ return ''
436
+
437
+ # try:
438
+ # st.write('Document: '+image_path.split('/')[-1])
439
+ c1, c2, c3 = st.columns((1,1,1))
440
+
441
+ self.plot_results_detection(c1, model, image, probas, bboxes_scaled, delta_xmin, delta_ymin, delta_xmax, delta_ymax)
442
+ cropped_img_list = self.crop_tables(image, probas, bboxes_scaled, delta_xmin, delta_ymin, delta_xmax, delta_ymax)
443
+
444
+ for unpadded_table in cropped_img_list:
445
+
446
+ table = self.add_padding(unpadded_table, padd_top, padd_right, padd_bottom, padd_left)
447
+ # table = super_res(table)
448
+ # table = binarizeBlur_image(table)
449
+ # table = sharpen_image(table) # Test sharpen image next
450
+ # table = td_postprocess(table)
451
+
452
+ model, probas, bboxes_scaled = table_struct_recog(table, THRESHOLD_PROBA=TSR_THRESHOLD)
453
+ rows, cols = self.generate_structure(c2, model, table, probas, bboxes_scaled, expand_rowcol_bbox_top, expand_rowcol_bbox_bottom)
454
+ # st.write(len(rows), len(cols))
455
+ rows, cols = self.sort_table_featuresv2(rows, cols)
456
+ master_row, cols = self.individual_table_featuresv2(table, rows, cols)
457
+
458
+ cells_img, max_cols, max_rows = self.object_to_cellsv2(master_row, cols, expand_rowcol_bbox_top, expand_rowcol_bbox_bottom, padd_left)
459
+
460
+ sequential_cell_img_list = []
461
+ for k, img_list in cells_img.items():
462
+ for img in img_list:
463
+ # img = super_res(img)
464
+ # img = sharpen_image(img) # Test sharpen image next
465
+ # img = binarizeBlur_image(img)
466
+ # img = self.add_padding(img, 10,10,10,10)
467
+ # plt.imshow(img)
468
+ # c3.pyplot()
469
+ sequential_cell_img_list.append(pytess(img))
470
+
471
+ cells_pytess_result = await asyncio.gather(*sequential_cell_img_list)
472
+
473
+
474
+ self.create_dataframe(c3, cells_pytess_result, max_cols, max_rows)
475
+ st.write('Errors in OCR is due to either quality of the image or performance of the OCR')
476
+ # except:
477
+ # st.write('Either incorrectly identified table or no table, to debug remove try/except')
478
+ # break
479
+ # break
480
+
481
+
482
+
483
+
484
+ if __name__ == "__main__":
485
+
486
+ img_name = st.file_uploader("Upload an image with table(s)")
487
+
488
+ padd_top = st.slider('Padding top', 0, 200, 20)
489
+ padd_left = st.slider('Padding left', 0, 200, 20)
490
+ padd_right = st.slider('Padding right', 0, 200, 20)
491
+ padd_bottom = st.slider('Padding bottom', 0, 200, 20)
492
+
493
+
494
+ te = TableExtractionPipeline()
495
+ # for img in image_list:
496
+ if img_name is not None:
497
+ asyncio.run(te.start_process(img_name, TD_THRESHOLD=0.6, TSR_THRESHOLD=0.8, 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))
498
+
499
+
500
+
packages.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ffmpeg
2
+ libsm6
3
+ libxext6
4
+ libgl1
5
+ tesseract-ocr-eng
6
+ python3-opencv
requirements.txt ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Cython==0.29.14
2
+ dask==2021.3.1
3
+ datasets==1.18.3
4
+ Flask==2.0.1
5
+ GitPython==3.1.26
6
+ imutils==0.5.4
7
+ multiprocess==0.70.12.2
8
+ numba==0.54.1
9
+ numexpr==2.7.3
10
+ numpy==1.20.3
11
+ oauthlib==3.1.0
12
+ opencv-contrib-python==4.6.0.66
13
+ openpyxl==3.0.7
14
+ Pillow==9.0.1
15
+ plotly==4.14.3
16
+ ply==3.11
17
+ protobuf==3.14.0
18
+ psutil==5.8.0
19
+ pyarrow==7.0.0
20
+ pydantic==1.7.3
21
+ pydeck==0.7.1
22
+ PyDictionary==2.0.1
23
+ pydot==1.4.2
24
+ pymongo==4.0.2
25
+ Pympler==1.0.1
26
+ PyMuPDF==1.20.2
27
+ pyperclip==1.8.2
28
+ pyppeteer==0.2.5
29
+ pyquery==1.4.3
30
+ pyreadline3==3.3
31
+ pytesseract==0.3.10
32
+ pytz-deprecation-shim==0.1.0.post0
33
+ PyWavelets==1.1.1
34
+ PyYAML==5.4.1
35
+ scipy==1.4.1
36
+ seaborn==0.11.1
37
+ sklearn==0.0
38
+ streamlit==1.5.1
39
+ timm==0.6.7
40
+ tokenizers==0.12.1
41
+ toml==0.10.2
42
+ toolz==0.11.1
43
+ torch==1.10.0
44
+ torchvision==0.11.1
45
+ -e git+https://github.com/nielsrogge/transformers.git@d34f7e6ffbb911d39465173ef2b35ba147ef58a9#egg=transformers
46
+ urllib3==1.26.7