Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
@@ -1,11 +1,12 @@
|
|
1 |
from PIL import Image, ImageEnhance, ImageOps
|
2 |
import string
|
3 |
-
from collections import Counter
|
4 |
from itertools import tee, count
|
5 |
import pytesseract
|
6 |
from pytesseract import Output
|
7 |
import json
|
8 |
import pandas as pd
|
|
|
9 |
# import matplotlib.pyplot as plt
|
10 |
import cv2
|
11 |
import numpy as np
|
@@ -14,35 +15,65 @@ from transformers import TableTransformerForObjectDetection
|
|
14 |
import torch
|
15 |
import gradio as gr
|
16 |
|
17 |
-
def plot_results_detection(model, image, prob, bboxes_scaled, delta_xmin, delta_ymin, delta_xmax, delta_ymax):
|
18 |
-
plt.imshow(image)
|
19 |
-
ax = plt.gca()
|
20 |
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
|
29 |
def crop_tables(pil_img, prob, boxes, delta_xmin, delta_ymin, delta_xmax, delta_ymax):
|
30 |
-
|
31 |
-
crop_tables and plot_results_detection must have same co-ord shifts because 1 only plots the other one updates co-ordinates
|
32 |
-
|
33 |
cropped_img_list = []
|
34 |
|
35 |
for p, (xmin, ymin, xmax, ymax) in zip(prob, boxes.tolist()):
|
36 |
|
37 |
-
xmin, ymin, xmax, ymax =
|
|
|
|
|
|
|
|
|
|
|
38 |
cropped_img = pil_img.crop((xmin, ymin, xmax, ymax))
|
39 |
cropped_img_list.append(cropped_img)
|
40 |
return cropped_img_list
|
41 |
|
42 |
-
|
43 |
-
|
|
|
44 |
Image padding as part of TSR pre-processing to prevent missing table edges
|
45 |
-
|
46 |
width, height = pil_img.size
|
47 |
new_width = width + right + left
|
48 |
new_height = height + top + bottom
|
@@ -50,15 +81,18 @@ def add_padding(pil_img, top, right, bottom, left, color=(255,255,255)):
|
|
50 |
result.paste(pil_img, (left, top))
|
51 |
return result
|
52 |
|
|
|
53 |
def table_detector(image, THRESHOLD_PROBA):
|
54 |
-
|
55 |
Table detection using DEtect-object TRansformer pre-trained on 1 million tables
|
56 |
-
|
57 |
|
58 |
feature_extractor = DetrFeatureExtractor(do_resize=True, size=800, max_size=800)
|
59 |
encoding = feature_extractor(image, return_tensors="pt")
|
60 |
|
61 |
-
model = TableTransformerForObjectDetection.from_pretrained(
|
|
|
|
|
62 |
|
63 |
with torch.no_grad():
|
64 |
outputs = model(**encoding)
|
@@ -68,20 +102,22 @@ def table_detector(image, THRESHOLD_PROBA):
|
|
68 |
|
69 |
target_sizes = torch.tensor(image.size[::-1]).unsqueeze(0)
|
70 |
postprocessed_outputs = feature_extractor.post_process(outputs, target_sizes)
|
71 |
-
bboxes_scaled = postprocessed_outputs[0][
|
72 |
|
73 |
return (model, probas[keep], bboxes_scaled)
|
74 |
|
75 |
|
76 |
def table_struct_recog(image, THRESHOLD_PROBA):
|
77 |
-
|
78 |
Table structure recognition using DEtect-object TRansformer pre-trained on 1 million tables
|
79 |
-
|
80 |
|
81 |
feature_extractor = DetrFeatureExtractor(do_resize=True, size=1000, max_size=1000)
|
82 |
encoding = feature_extractor(image, return_tensors="pt")
|
83 |
|
84 |
-
model = TableTransformerForObjectDetection.from_pretrained(
|
|
|
|
|
85 |
with torch.no_grad():
|
86 |
outputs = model(**encoding)
|
87 |
|
@@ -90,16 +126,19 @@ def table_struct_recog(image, THRESHOLD_PROBA):
|
|
90 |
|
91 |
target_sizes = torch.tensor(image.size[::-1]).unsqueeze(0)
|
92 |
postprocessed_outputs = feature_extractor.post_process(outputs, target_sizes)
|
93 |
-
bboxes_scaled = postprocessed_outputs[0][
|
94 |
|
95 |
return (model, probas[keep], bboxes_scaled)
|
96 |
|
97 |
-
|
|
|
|
|
|
|
98 |
colors = ["red", "blue", "green", "yellow", "orange", "violet"]
|
99 |
-
|
100 |
Co-ordinates are adjusted here by 3 'pixels'
|
101 |
To plot table pillow image and the TSR bounding boxes on the table
|
102 |
-
|
103 |
# plt.figure(figsize=(32,20))
|
104 |
# plt.imshow(pil_img)
|
105 |
# ax = plt.gca()
|
@@ -108,33 +147,55 @@ def generate_structure(model, pil_img, prob, boxes, expand_rowcol_bbox_top, expa
|
|
108 |
idx = 0
|
109 |
for p, (xmin, ymin, xmax, ymax) in zip(prob, boxes.tolist()):
|
110 |
|
111 |
-
xmin, ymin, xmax, ymax = xmin, ymin, xmax, ymax
|
112 |
cl = p.argmax()
|
113 |
class_text = model.config.id2label[cl.item()]
|
114 |
-
text = f
|
115 |
# or (class_text == 'table column')
|
116 |
# if (class_text == 'table row') or (class_text =='table projected row header') or (class_text == 'table column'):
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
if class_text ==
|
121 |
-
rows[
|
122 |
-
|
123 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
124 |
|
125 |
idx += 1
|
126 |
|
127 |
# plt.axis('on')
|
128 |
return rows, cols
|
129 |
|
130 |
-
|
|
|
131 |
# Sometimes the header and first row overlap, and we need the header bbox not to have first row's bbox inside the headers bbox
|
132 |
-
rows_ = {
|
133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
134 |
|
135 |
return rows_, cols_
|
136 |
|
137 |
-
|
|
|
138 |
|
139 |
for k, v in rows.items():
|
140 |
xmin, ymin, xmax, ymax = v
|
@@ -148,12 +209,19 @@ def individual_table_featuresv2(pil_img, rows:dict, cols:dict):
|
|
148 |
|
149 |
return rows, cols
|
150 |
|
151 |
-
|
152 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
153 |
Args:
|
154 |
Returns:
|
155 |
-
|
156 |
-
|
157 |
cells_img = {}
|
158 |
header_idx = 0
|
159 |
row_idx = 0
|
@@ -181,7 +249,7 @@ def object_to_cellsv2(master_row:dict, cols:dict, expand_rowcol_bbox_top, expand
|
|
181 |
# new_master_row[k_row] = v_row
|
182 |
######################################################
|
183 |
for k_row, v_row in new_master_row.items():
|
184 |
-
|
185 |
_, _, _, _, row_img = v_row
|
186 |
xmax, ymax = row_img.size
|
187 |
xa, ya, xb, yb = 0, 0, 0, ymax
|
@@ -201,31 +269,39 @@ def object_to_cellsv2(master_row:dict, cols:dict, expand_rowcol_bbox_top, expand
|
|
201 |
xb = xmax_col
|
202 |
if idx == 0:
|
203 |
xa = 0
|
204 |
-
if idx == len(new_cols)-1:
|
205 |
xb = xmax
|
206 |
xa, ya, xb, yb = xa, ya, xb, yb
|
207 |
|
208 |
row_img_cropped = row_img.crop((xa, ya, xb, yb))
|
209 |
row_img_list.append(row_img_cropped)
|
210 |
|
211 |
-
cells_img[k_row+
|
212 |
row_idx += 1
|
213 |
|
214 |
-
return cells_img, len(new_cols), len(new_master_row)-1
|
|
|
215 |
|
216 |
def pytess(cell_pil_img):
|
217 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
218 |
|
219 |
-
|
|
|
220 |
"""Make all the items unique by adding a suffix (1, 2, etc).
|
221 |
Credit: https://stackoverflow.com/questions/30650474/python-rename-duplicates-in-list-with-progressive-numbers-without-sorting-list
|
222 |
`seq` is mutable sequence of strings.
|
223 |
`suffs` is an optional alternative suffix iterable.
|
224 |
"""
|
225 |
-
not_unique = [k for k,v in Counter(seq).items() if v>1]
|
226 |
|
227 |
-
suff_gens = dict(zip(not_unique, tee(suffs, len(not_unique))))
|
228 |
-
for idx,s in enumerate(seq):
|
229 |
try:
|
230 |
suffix = str(next(suff_gens[s]))
|
231 |
except KeyError:
|
@@ -235,34 +311,36 @@ def uniquify(seq, suffs = count(1)):
|
|
235 |
|
236 |
return seq
|
237 |
|
|
|
238 |
def clean_dataframe(df):
|
239 |
-
|
240 |
Remove irrelevant symbols that appear with tesseractOCR
|
241 |
-
|
242 |
# df.columns = [col.replace('|', '') for col in df.columns]
|
243 |
|
244 |
for col in df.columns:
|
245 |
|
246 |
-
df[col]=df[col].str.replace("'",
|
247 |
-
df[col]=df[col].str.replace('"',
|
248 |
-
df[col]=df[col].str.replace(
|
249 |
-
df[col]=df[col].str.replace(
|
250 |
-
df[col]=df[col].str.replace(
|
251 |
-
df[col]=df[col].str.replace(
|
252 |
-
df[col]=df[col].str.replace(
|
253 |
return df
|
254 |
|
255 |
-
|
256 |
-
|
|
|
257 |
Args:
|
258 |
cells_pytess_result: list of strings, each element representing a cell in a table
|
259 |
max_cols, max_rows: number of columns and rows
|
260 |
Returns:
|
261 |
-
dataframe : final dataframe after all pre-processing
|
262 |
-
|
263 |
|
264 |
headers = cells_pytess_result[:max_cols]
|
265 |
-
new_headers = uniquify(headers, (f
|
266 |
counter = 0
|
267 |
|
268 |
cells_list = cells_pytess_result[max_cols:]
|
@@ -274,10 +352,10 @@ def create_dataframe(cells_pytess_result:list, max_cols:int, max_rows:int,csv_pa
|
|
274 |
df.iat[nrows, ncols] = str(cells_list[cell_idx])
|
275 |
cell_idx += 1
|
276 |
|
277 |
-
## To check if there are duplicate headers if result of uniquify+col == col
|
278 |
## This check removes headers when all headers are empty or if median of header word count is less than 6
|
279 |
for x, col in zip(string.ascii_lowercase, new_headers):
|
280 |
-
if f
|
281 |
counter += 1
|
282 |
header_char_count = [len(col) for col in new_headers]
|
283 |
|
@@ -291,42 +369,93 @@ def create_dataframe(cells_pytess_result:list, max_cols:int, max_rows:int,csv_pa
|
|
291 |
|
292 |
return df
|
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 |
title = "Interactive demo OCR: microsoft - table-transformer-detection + tesseract"
|
321 |
description = "Demo for microsoft - table-transformer-detection + tesseract"
|
322 |
article = "<p style='text-align: center'></p>"
|
323 |
-
examples =[["image_0.png"]]
|
324 |
-
|
325 |
-
iface = gr.Interface(
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
332 |
iface.launch(debug=True)
|
|
|
|
1 |
from PIL import Image, ImageEnhance, ImageOps
|
2 |
import string
|
3 |
+
from collections import Counter
|
4 |
from itertools import tee, count
|
5 |
import pytesseract
|
6 |
from pytesseract import Output
|
7 |
import json
|
8 |
import pandas as pd
|
9 |
+
|
10 |
# import matplotlib.pyplot as plt
|
11 |
import cv2
|
12 |
import numpy as np
|
|
|
15 |
import torch
|
16 |
import gradio as gr
|
17 |
|
|
|
|
|
|
|
18 |
|
19 |
+
def plot_results_detection(
|
20 |
+
model, image, prob, bboxes_scaled, delta_xmin, delta_ymin, delta_xmax, delta_ymax
|
21 |
+
):
|
22 |
+
plt.imshow(image)
|
23 |
+
ax = plt.gca()
|
24 |
+
|
25 |
+
for p, (xmin, ymin, xmax, ymax) in zip(prob, bboxes_scaled.tolist()):
|
26 |
+
cl = p.argmax()
|
27 |
+
xmin, ymin, xmax, ymax = (
|
28 |
+
xmin - delta_xmin,
|
29 |
+
ymin - delta_ymin,
|
30 |
+
xmax + delta_xmax,
|
31 |
+
ymax + delta_ymax,
|
32 |
+
)
|
33 |
+
ax.add_patch(
|
34 |
+
plt.Rectangle(
|
35 |
+
(xmin, ymin),
|
36 |
+
xmax - xmin,
|
37 |
+
ymax - ymin,
|
38 |
+
fill=False,
|
39 |
+
color="red",
|
40 |
+
linewidth=3,
|
41 |
+
)
|
42 |
+
)
|
43 |
+
text = f"{model.config.id2label[cl.item()]}: {p[cl]:0.2f}"
|
44 |
+
ax.text(
|
45 |
+
xmin - 20,
|
46 |
+
ymin - 50,
|
47 |
+
text,
|
48 |
+
fontsize=10,
|
49 |
+
bbox=dict(facecolor="yellow", alpha=0.5),
|
50 |
+
)
|
51 |
+
plt.axis("off")
|
52 |
+
|
53 |
|
54 |
def crop_tables(pil_img, prob, boxes, delta_xmin, delta_ymin, delta_xmax, delta_ymax):
|
55 |
+
"""
|
56 |
+
crop_tables and plot_results_detection must have same co-ord shifts because 1 only plots the other one updates co-ordinates
|
57 |
+
"""
|
58 |
cropped_img_list = []
|
59 |
|
60 |
for p, (xmin, ymin, xmax, ymax) in zip(prob, boxes.tolist()):
|
61 |
|
62 |
+
xmin, ymin, xmax, ymax = (
|
63 |
+
xmin - delta_xmin,
|
64 |
+
ymin - delta_ymin,
|
65 |
+
xmax + delta_xmax,
|
66 |
+
ymax + delta_ymax,
|
67 |
+
)
|
68 |
cropped_img = pil_img.crop((xmin, ymin, xmax, ymax))
|
69 |
cropped_img_list.append(cropped_img)
|
70 |
return cropped_img_list
|
71 |
|
72 |
+
|
73 |
+
def add_padding(pil_img, top, right, bottom, left, color=(255, 255, 255)):
|
74 |
+
"""
|
75 |
Image padding as part of TSR pre-processing to prevent missing table edges
|
76 |
+
"""
|
77 |
width, height = pil_img.size
|
78 |
new_width = width + right + left
|
79 |
new_height = height + top + bottom
|
|
|
81 |
result.paste(pil_img, (left, top))
|
82 |
return result
|
83 |
|
84 |
+
|
85 |
def table_detector(image, THRESHOLD_PROBA):
|
86 |
+
"""
|
87 |
Table detection using DEtect-object TRansformer pre-trained on 1 million tables
|
88 |
+
"""
|
89 |
|
90 |
feature_extractor = DetrFeatureExtractor(do_resize=True, size=800, max_size=800)
|
91 |
encoding = feature_extractor(image, return_tensors="pt")
|
92 |
|
93 |
+
model = TableTransformerForObjectDetection.from_pretrained(
|
94 |
+
"microsoft/table-transformer-detection"
|
95 |
+
)
|
96 |
|
97 |
with torch.no_grad():
|
98 |
outputs = model(**encoding)
|
|
|
102 |
|
103 |
target_sizes = torch.tensor(image.size[::-1]).unsqueeze(0)
|
104 |
postprocessed_outputs = feature_extractor.post_process(outputs, target_sizes)
|
105 |
+
bboxes_scaled = postprocessed_outputs[0]["boxes"][keep]
|
106 |
|
107 |
return (model, probas[keep], bboxes_scaled)
|
108 |
|
109 |
|
110 |
def table_struct_recog(image, THRESHOLD_PROBA):
|
111 |
+
"""
|
112 |
Table structure recognition using DEtect-object TRansformer pre-trained on 1 million tables
|
113 |
+
"""
|
114 |
|
115 |
feature_extractor = DetrFeatureExtractor(do_resize=True, size=1000, max_size=1000)
|
116 |
encoding = feature_extractor(image, return_tensors="pt")
|
117 |
|
118 |
+
model = TableTransformerForObjectDetection.from_pretrained(
|
119 |
+
"microsoft/table-transformer-structure-recognition"
|
120 |
+
)
|
121 |
with torch.no_grad():
|
122 |
outputs = model(**encoding)
|
123 |
|
|
|
126 |
|
127 |
target_sizes = torch.tensor(image.size[::-1]).unsqueeze(0)
|
128 |
postprocessed_outputs = feature_extractor.post_process(outputs, target_sizes)
|
129 |
+
bboxes_scaled = postprocessed_outputs[0]["boxes"][keep]
|
130 |
|
131 |
return (model, probas[keep], bboxes_scaled)
|
132 |
|
133 |
+
|
134 |
+
def generate_structure(
|
135 |
+
model, pil_img, prob, boxes, expand_rowcol_bbox_top, expand_rowcol_bbox_bottom
|
136 |
+
):
|
137 |
colors = ["red", "blue", "green", "yellow", "orange", "violet"]
|
138 |
+
"""
|
139 |
Co-ordinates are adjusted here by 3 'pixels'
|
140 |
To plot table pillow image and the TSR bounding boxes on the table
|
141 |
+
"""
|
142 |
# plt.figure(figsize=(32,20))
|
143 |
# plt.imshow(pil_img)
|
144 |
# ax = plt.gca()
|
|
|
147 |
idx = 0
|
148 |
for p, (xmin, ymin, xmax, ymax) in zip(prob, boxes.tolist()):
|
149 |
|
150 |
+
xmin, ymin, xmax, ymax = xmin, ymin, xmax, ymax
|
151 |
cl = p.argmax()
|
152 |
class_text = model.config.id2label[cl.item()]
|
153 |
+
text = f"{class_text}: {p[cl]:0.2f}"
|
154 |
# or (class_text == 'table column')
|
155 |
# if (class_text == 'table row') or (class_text =='table projected row header') or (class_text == 'table column'):
|
156 |
+
# ax.add_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin,fill=False, color=colors[0], linewidth=2))
|
157 |
+
# ax.text(xmin-10, ymin-10, text, fontsize=5, bbox=dict(facecolor='yellow', alpha=0.5))
|
158 |
+
|
159 |
+
if class_text == "table row":
|
160 |
+
rows["table row." + str(idx)] = (
|
161 |
+
xmin,
|
162 |
+
ymin - expand_rowcol_bbox_top,
|
163 |
+
xmax,
|
164 |
+
ymax + expand_rowcol_bbox_bottom,
|
165 |
+
)
|
166 |
+
if class_text == "table column":
|
167 |
+
cols["table column." + str(idx)] = (
|
168 |
+
xmin,
|
169 |
+
ymin - expand_rowcol_bbox_top,
|
170 |
+
xmax,
|
171 |
+
ymax + expand_rowcol_bbox_bottom,
|
172 |
+
)
|
173 |
|
174 |
idx += 1
|
175 |
|
176 |
# plt.axis('on')
|
177 |
return rows, cols
|
178 |
|
179 |
+
|
180 |
+
def sort_table_featuresv2(rows: dict, cols: dict):
|
181 |
# Sometimes the header and first row overlap, and we need the header bbox not to have first row's bbox inside the headers bbox
|
182 |
+
rows_ = {
|
183 |
+
table_feature: (xmin, ymin, xmax, ymax)
|
184 |
+
for table_feature, (xmin, ymin, xmax, ymax) in sorted(
|
185 |
+
rows.items(), key=lambda tup: tup[1][1]
|
186 |
+
)
|
187 |
+
}
|
188 |
+
cols_ = {
|
189 |
+
table_feature: (xmin, ymin, xmax, ymax)
|
190 |
+
for table_feature, (xmin, ymin, xmax, ymax) in sorted(
|
191 |
+
cols.items(), key=lambda tup: tup[1][0]
|
192 |
+
)
|
193 |
+
}
|
194 |
|
195 |
return rows_, cols_
|
196 |
|
197 |
+
|
198 |
+
def individual_table_featuresv2(pil_img, rows: dict, cols: dict):
|
199 |
|
200 |
for k, v in rows.items():
|
201 |
xmin, ymin, xmax, ymax = v
|
|
|
209 |
|
210 |
return rows, cols
|
211 |
|
212 |
+
|
213 |
+
def object_to_cellsv2(
|
214 |
+
master_row: dict,
|
215 |
+
cols: dict,
|
216 |
+
expand_rowcol_bbox_top,
|
217 |
+
expand_rowcol_bbox_bottom,
|
218 |
+
padd_left,
|
219 |
+
):
|
220 |
+
"""Removes redundant bbox for rows&columns and divides each row into cells from columns
|
221 |
Args:
|
222 |
Returns:
|
223 |
+
|
224 |
+
"""
|
225 |
cells_img = {}
|
226 |
header_idx = 0
|
227 |
row_idx = 0
|
|
|
249 |
# new_master_row[k_row] = v_row
|
250 |
######################################################
|
251 |
for k_row, v_row in new_master_row.items():
|
252 |
+
|
253 |
_, _, _, _, row_img = v_row
|
254 |
xmax, ymax = row_img.size
|
255 |
xa, ya, xb, yb = 0, 0, 0, ymax
|
|
|
269 |
xb = xmax_col
|
270 |
if idx == 0:
|
271 |
xa = 0
|
272 |
+
if idx == len(new_cols) - 1:
|
273 |
xb = xmax
|
274 |
xa, ya, xb, yb = xa, ya, xb, yb
|
275 |
|
276 |
row_img_cropped = row_img.crop((xa, ya, xb, yb))
|
277 |
row_img_list.append(row_img_cropped)
|
278 |
|
279 |
+
cells_img[k_row + "." + str(row_idx)] = row_img_list
|
280 |
row_idx += 1
|
281 |
|
282 |
+
return cells_img, len(new_cols), len(new_master_row) - 1
|
283 |
+
|
284 |
|
285 |
def pytess(cell_pil_img):
|
286 |
+
return " ".join(
|
287 |
+
pytesseract.image_to_data(
|
288 |
+
cell_pil_img,
|
289 |
+
output_type=Output.DICT,
|
290 |
+
config="-c tessedit_char_blacklist=œ˜â€œï¬â™Ã©œ¢!|”?«“¥ --psm 6 preserve_interword_spaces",
|
291 |
+
)["text"]
|
292 |
+
).strip()
|
293 |
|
294 |
+
|
295 |
+
def uniquify(seq, suffs=count(1)):
|
296 |
"""Make all the items unique by adding a suffix (1, 2, etc).
|
297 |
Credit: https://stackoverflow.com/questions/30650474/python-rename-duplicates-in-list-with-progressive-numbers-without-sorting-list
|
298 |
`seq` is mutable sequence of strings.
|
299 |
`suffs` is an optional alternative suffix iterable.
|
300 |
"""
|
301 |
+
not_unique = [k for k, v in Counter(seq).items() if v > 1]
|
302 |
|
303 |
+
suff_gens = dict(zip(not_unique, tee(suffs, len(not_unique))))
|
304 |
+
for idx, s in enumerate(seq):
|
305 |
try:
|
306 |
suffix = str(next(suff_gens[s]))
|
307 |
except KeyError:
|
|
|
311 |
|
312 |
return seq
|
313 |
|
314 |
+
|
315 |
def clean_dataframe(df):
|
316 |
+
"""
|
317 |
Remove irrelevant symbols that appear with tesseractOCR
|
318 |
+
"""
|
319 |
# df.columns = [col.replace('|', '') for col in df.columns]
|
320 |
|
321 |
for col in df.columns:
|
322 |
|
323 |
+
df[col] = df[col].str.replace("'", "", regex=True)
|
324 |
+
df[col] = df[col].str.replace('"', "", regex=True)
|
325 |
+
df[col] = df[col].str.replace("]", "", regex=True)
|
326 |
+
df[col] = df[col].str.replace("[", "", regex=True)
|
327 |
+
df[col] = df[col].str.replace("{", "", regex=True)
|
328 |
+
df[col] = df[col].str.replace("}", "", regex=True)
|
329 |
+
df[col] = df[col].str.replace("|", "", regex=True)
|
330 |
return df
|
331 |
|
332 |
+
|
333 |
+
def create_dataframe(cells_pytess_result: list, max_cols: int, max_rows: int, csv_path):
|
334 |
+
"""Create dataframe using list of cell values of the table, also checks for valid header of dataframe
|
335 |
Args:
|
336 |
cells_pytess_result: list of strings, each element representing a cell in a table
|
337 |
max_cols, max_rows: number of columns and rows
|
338 |
Returns:
|
339 |
+
dataframe : final dataframe after all pre-processing
|
340 |
+
"""
|
341 |
|
342 |
headers = cells_pytess_result[:max_cols]
|
343 |
+
new_headers = uniquify(headers, (f" {x!s}" for x in string.ascii_lowercase))
|
344 |
counter = 0
|
345 |
|
346 |
cells_list = cells_pytess_result[max_cols:]
|
|
|
352 |
df.iat[nrows, ncols] = str(cells_list[cell_idx])
|
353 |
cell_idx += 1
|
354 |
|
355 |
+
## To check if there are duplicate headers if result of uniquify+col == col
|
356 |
## This check removes headers when all headers are empty or if median of header word count is less than 6
|
357 |
for x, col in zip(string.ascii_lowercase, new_headers):
|
358 |
+
if f" {x!s}" == col:
|
359 |
counter += 1
|
360 |
header_char_count = [len(col) for col in new_headers]
|
361 |
|
|
|
369 |
|
370 |
return df
|
371 |
|
372 |
+
|
373 |
+
def process_image(
|
374 |
+
image,
|
375 |
+
td_threshold,
|
376 |
+
tsr_threshold,
|
377 |
+
padd_top,
|
378 |
+
padd_left,
|
379 |
+
padd_bottom,
|
380 |
+
padd_right,
|
381 |
+
delta_xmin,
|
382 |
+
delta_ymin,
|
383 |
+
delta_xmax,
|
384 |
+
delta_ymax,
|
385 |
+
expand_rowcol_bbox_top,
|
386 |
+
expand_rowcol_bbox_bottom,
|
387 |
+
):
|
388 |
+
image = image.convert("RGB")
|
389 |
+
model, probas, bboxes_scaled = table_detector(image, THRESHOLD_PROBA=td_threshold)
|
390 |
+
# plot_results_detection(model, image, probas, bboxes_scaled, delta_xmin, delta_ymin, delta_xmax, delta_ymax)
|
391 |
+
cropped_img_list = crop_tables(
|
392 |
+
image, probas, bboxes_scaled, delta_xmin, delta_ymin, delta_xmax, delta_ymax
|
393 |
+
)
|
394 |
+
|
395 |
+
result = []
|
396 |
+
for idx, unpadded_table in enumerate(cropped_img_list):
|
397 |
+
table = add_padding(
|
398 |
+
unpadded_table, padd_top, padd_right, padd_bottom, padd_left
|
399 |
+
)
|
400 |
+
model, probas, bboxes_scaled = table_struct_recog(
|
401 |
+
table, THRESHOLD_PROBA=tsr_threshold
|
402 |
+
)
|
403 |
+
rows, cols = generate_structure(
|
404 |
+
model,
|
405 |
+
table,
|
406 |
+
probas,
|
407 |
+
bboxes_scaled,
|
408 |
+
expand_rowcol_bbox_top,
|
409 |
+
expand_rowcol_bbox_bottom,
|
410 |
+
)
|
411 |
+
rows, cols = sort_table_featuresv2(rows, cols)
|
412 |
+
master_row, cols = individual_table_featuresv2(table, rows, cols)
|
413 |
+
cells_img, max_cols, max_rows = object_to_cellsv2(
|
414 |
+
master_row,
|
415 |
+
cols,
|
416 |
+
expand_rowcol_bbox_top,
|
417 |
+
expand_rowcol_bbox_bottom,
|
418 |
+
padd_left,
|
419 |
+
)
|
420 |
+
sequential_cell_img_list = []
|
421 |
+
for k, img_list in cells_img.items():
|
422 |
+
for img in img_list:
|
423 |
+
sequential_cell_img_list.append(pytess(img))
|
424 |
+
|
425 |
+
csv_path = "/content/sample_data/table_" + str(idx)
|
426 |
+
df = create_dataframe(sequential_cell_img_list, max_cols, max_rows, csv_path)
|
427 |
+
result.append(df)
|
428 |
+
res = result[0].to_json()
|
429 |
+
return res
|
430 |
|
431 |
|
432 |
title = "Interactive demo OCR: microsoft - table-transformer-detection + tesseract"
|
433 |
description = "Demo for microsoft - table-transformer-detection + tesseract"
|
434 |
article = "<p style='text-align: center'></p>"
|
435 |
+
examples = [["image_0.png"]]
|
436 |
+
|
437 |
+
iface = gr.Interface(
|
438 |
+
fn=process_image,
|
439 |
+
inputs=[
|
440 |
+
gr.Image(type="pil"),
|
441 |
+
gr.Slider(0, 1, 0.9),
|
442 |
+
gr.Slider(0, 1, 0.8),
|
443 |
+
gr.Slider(0, 200, 100),
|
444 |
+
gr.Slider(0, 200, 100),
|
445 |
+
gr.Slider(0, 200, 100),
|
446 |
+
gr.Slider(0, 200, 100),
|
447 |
+
gr.Number(0),
|
448 |
+
gr.Number(0),
|
449 |
+
gr.Number(0),
|
450 |
+
gr.Number(0),
|
451 |
+
gr.Number(0),
|
452 |
+
gr.Number(0),
|
453 |
+
],
|
454 |
+
outputs="text",
|
455 |
+
title=title,
|
456 |
+
description=description,
|
457 |
+
article=article,
|
458 |
+
examples=examples,
|
459 |
+
)
|
460 |
iface.launch(debug=True)
|
461 |
+
|