Spaces:
Runtime error
Runtime error
Duplicate from sussahoo/table_extraction
Browse filesCo-authored-by: Susanta Sahoo <[email protected]>
- .gitattributes +34 -0
- README.md +13 -0
- app.py +480 -0
- image_0.png +0 -0
- packages.txt +2 -0
- requirements.txt +12 -0
.gitattributes
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Table Extraction
|
| 3 |
+
emoji: 💻
|
| 4 |
+
colorFrom: pink
|
| 5 |
+
colorTo: purple
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 3.13.0
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
duplicated_from: sussahoo/table_extraction
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
ADDED
|
@@ -0,0 +1,480 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 13 |
+
from transformers import DetrFeatureExtractor
|
| 14 |
+
from transformers import TableTransformerForObjectDetection
|
| 15 |
+
import torch
|
| 16 |
+
import gradio as gr
|
| 17 |
+
import pdf2image
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def plot_results_detection(
|
| 21 |
+
model, image, prob, bboxes_scaled, delta_xmin, delta_ymin, delta_xmax, delta_ymax
|
| 22 |
+
):
|
| 23 |
+
plt.imshow(image)
|
| 24 |
+
ax = plt.gca()
|
| 25 |
+
|
| 26 |
+
for p, (xmin, ymin, xmax, ymax) in zip(prob, bboxes_scaled.tolist()):
|
| 27 |
+
cl = p.argmax()
|
| 28 |
+
xmin, ymin, xmax, ymax = (
|
| 29 |
+
xmin - delta_xmin,
|
| 30 |
+
ymin - delta_ymin,
|
| 31 |
+
xmax + delta_xmax,
|
| 32 |
+
ymax + delta_ymax,
|
| 33 |
+
)
|
| 34 |
+
ax.add_patch(
|
| 35 |
+
plt.Rectangle(
|
| 36 |
+
(xmin, ymin),
|
| 37 |
+
xmax - xmin,
|
| 38 |
+
ymax - ymin,
|
| 39 |
+
fill=False,
|
| 40 |
+
color="red",
|
| 41 |
+
linewidth=3,
|
| 42 |
+
)
|
| 43 |
+
)
|
| 44 |
+
text = f"{model.config.id2label[cl.item()]}: {p[cl]:0.2f}"
|
| 45 |
+
ax.text(
|
| 46 |
+
xmin - 20,
|
| 47 |
+
ymin - 50,
|
| 48 |
+
text,
|
| 49 |
+
fontsize=10,
|
| 50 |
+
bbox=dict(facecolor="yellow", alpha=0.5),
|
| 51 |
+
)
|
| 52 |
+
plt.axis("off")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def crop_tables(pil_img, prob, boxes, delta_xmin, delta_ymin, delta_xmax, delta_ymax):
|
| 56 |
+
"""
|
| 57 |
+
crop_tables and plot_results_detection must have same co-ord shifts because 1 only plots the other one updates co-ordinates
|
| 58 |
+
"""
|
| 59 |
+
cropped_img_list = []
|
| 60 |
+
|
| 61 |
+
for p, (xmin, ymin, xmax, ymax) in zip(prob, boxes.tolist()):
|
| 62 |
+
|
| 63 |
+
xmin, ymin, xmax, ymax = (
|
| 64 |
+
xmin - delta_xmin,
|
| 65 |
+
ymin - delta_ymin,
|
| 66 |
+
xmax + delta_xmax,
|
| 67 |
+
ymax + delta_ymax,
|
| 68 |
+
)
|
| 69 |
+
cropped_img = pil_img.crop((xmin, ymin, xmax, ymax))
|
| 70 |
+
cropped_img_list.append(cropped_img)
|
| 71 |
+
return cropped_img_list
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def add_padding(pil_img, top, right, bottom, left, color=(255, 255, 255)):
|
| 75 |
+
"""
|
| 76 |
+
Image padding as part of TSR pre-processing to prevent missing table edges
|
| 77 |
+
"""
|
| 78 |
+
width, height = pil_img.size
|
| 79 |
+
new_width = width + right + left
|
| 80 |
+
new_height = height + top + bottom
|
| 81 |
+
result = Image.new(pil_img.mode, (new_width, new_height), color)
|
| 82 |
+
result.paste(pil_img, (left, top))
|
| 83 |
+
return result
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def table_detector(image, THRESHOLD_PROBA):
|
| 87 |
+
"""
|
| 88 |
+
Table detection using DEtect-object TRansformer pre-trained on 1 million tables
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
feature_extractor = DetrFeatureExtractor(do_resize=True, size=800, max_size=800)
|
| 92 |
+
encoding = feature_extractor(image, return_tensors="pt")
|
| 93 |
+
|
| 94 |
+
model = TableTransformerForObjectDetection.from_pretrained(
|
| 95 |
+
"microsoft/table-transformer-detection"
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
with torch.no_grad():
|
| 99 |
+
outputs = model(**encoding)
|
| 100 |
+
|
| 101 |
+
probas = outputs.logits.softmax(-1)[0, :, :-1]
|
| 102 |
+
keep = probas.max(-1).values > THRESHOLD_PROBA
|
| 103 |
+
|
| 104 |
+
target_sizes = torch.tensor(image.size[::-1]).unsqueeze(0)
|
| 105 |
+
postprocessed_outputs = feature_extractor.post_process(outputs, target_sizes)
|
| 106 |
+
bboxes_scaled = postprocessed_outputs[0]["boxes"][keep]
|
| 107 |
+
|
| 108 |
+
return (model, probas[keep], bboxes_scaled)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def table_struct_recog(image, THRESHOLD_PROBA):
|
| 112 |
+
"""
|
| 113 |
+
Table structure recognition using DEtect-object TRansformer pre-trained on 1 million tables
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
feature_extractor = DetrFeatureExtractor(do_resize=True, size=1000, max_size=1000)
|
| 117 |
+
encoding = feature_extractor(image, return_tensors="pt")
|
| 118 |
+
|
| 119 |
+
model = TableTransformerForObjectDetection.from_pretrained(
|
| 120 |
+
"microsoft/table-transformer-structure-recognition"
|
| 121 |
+
)
|
| 122 |
+
with torch.no_grad():
|
| 123 |
+
outputs = model(**encoding)
|
| 124 |
+
|
| 125 |
+
probas = outputs.logits.softmax(-1)[0, :, :-1]
|
| 126 |
+
keep = probas.max(-1).values > THRESHOLD_PROBA
|
| 127 |
+
|
| 128 |
+
target_sizes = torch.tensor(image.size[::-1]).unsqueeze(0)
|
| 129 |
+
postprocessed_outputs = feature_extractor.post_process(outputs, target_sizes)
|
| 130 |
+
bboxes_scaled = postprocessed_outputs[0]["boxes"][keep]
|
| 131 |
+
|
| 132 |
+
return (model, probas[keep], bboxes_scaled)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def generate_structure(
|
| 136 |
+
model, pil_img, prob, boxes, expand_rowcol_bbox_top, expand_rowcol_bbox_bottom
|
| 137 |
+
):
|
| 138 |
+
colors = ["red", "blue", "green", "yellow", "orange", "violet"]
|
| 139 |
+
"""
|
| 140 |
+
Co-ordinates are adjusted here by 3 'pixels'
|
| 141 |
+
To plot table pillow image and the TSR bounding boxes on the table
|
| 142 |
+
"""
|
| 143 |
+
# plt.figure(figsize=(32,20))
|
| 144 |
+
# plt.imshow(pil_img)
|
| 145 |
+
# ax = plt.gca()
|
| 146 |
+
rows = {}
|
| 147 |
+
cols = {}
|
| 148 |
+
idx = 0
|
| 149 |
+
for p, (xmin, ymin, xmax, ymax) in zip(prob, boxes.tolist()):
|
| 150 |
+
|
| 151 |
+
xmin, ymin, xmax, ymax = xmin, ymin, xmax, ymax
|
| 152 |
+
cl = p.argmax()
|
| 153 |
+
class_text = model.config.id2label[cl.item()]
|
| 154 |
+
text = f"{class_text}: {p[cl]:0.2f}"
|
| 155 |
+
# or (class_text == 'table column')
|
| 156 |
+
# if (class_text == 'table row') or (class_text =='table projected row header') or (class_text == 'table column'):
|
| 157 |
+
# ax.add_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin,fill=False, color=colors[0], linewidth=2))
|
| 158 |
+
# ax.text(xmin-10, ymin-10, text, fontsize=5, bbox=dict(facecolor='yellow', alpha=0.5))
|
| 159 |
+
|
| 160 |
+
if class_text == "table row":
|
| 161 |
+
rows["table row." + str(idx)] = (
|
| 162 |
+
xmin,
|
| 163 |
+
ymin - expand_rowcol_bbox_top,
|
| 164 |
+
xmax,
|
| 165 |
+
ymax + expand_rowcol_bbox_bottom,
|
| 166 |
+
)
|
| 167 |
+
if class_text == "table column":
|
| 168 |
+
cols["table column." + str(idx)] = (
|
| 169 |
+
xmin,
|
| 170 |
+
ymin - expand_rowcol_bbox_top,
|
| 171 |
+
xmax,
|
| 172 |
+
ymax + expand_rowcol_bbox_bottom,
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
idx += 1
|
| 176 |
+
|
| 177 |
+
# plt.axis('on')
|
| 178 |
+
return rows, cols
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def sort_table_featuresv2(rows: dict, cols: dict):
|
| 182 |
+
# Sometimes the header and first row overlap, and we need the header bbox not to have first row's bbox inside the headers bbox
|
| 183 |
+
rows_ = {
|
| 184 |
+
table_feature: (xmin, ymin, xmax, ymax)
|
| 185 |
+
for table_feature, (xmin, ymin, xmax, ymax) in sorted(
|
| 186 |
+
rows.items(), key=lambda tup: tup[1][1]
|
| 187 |
+
)
|
| 188 |
+
}
|
| 189 |
+
cols_ = {
|
| 190 |
+
table_feature: (xmin, ymin, xmax, ymax)
|
| 191 |
+
for table_feature, (xmin, ymin, xmax, ymax) in sorted(
|
| 192 |
+
cols.items(), key=lambda tup: tup[1][0]
|
| 193 |
+
)
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
return rows_, cols_
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def individual_table_featuresv2(pil_img, rows: dict, cols: dict):
|
| 200 |
+
|
| 201 |
+
for k, v in rows.items():
|
| 202 |
+
xmin, ymin, xmax, ymax = v
|
| 203 |
+
cropped_img = pil_img.crop((xmin, ymin, xmax, ymax))
|
| 204 |
+
rows[k] = xmin, ymin, xmax, ymax, cropped_img
|
| 205 |
+
|
| 206 |
+
for k, v in cols.items():
|
| 207 |
+
xmin, ymin, xmax, ymax = v
|
| 208 |
+
cropped_img = pil_img.crop((xmin, ymin, xmax, ymax))
|
| 209 |
+
cols[k] = xmin, ymin, xmax, ymax, cropped_img
|
| 210 |
+
|
| 211 |
+
return rows, cols
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def object_to_cellsv2(
|
| 215 |
+
master_row: dict,
|
| 216 |
+
cols: dict,
|
| 217 |
+
expand_rowcol_bbox_top,
|
| 218 |
+
expand_rowcol_bbox_bottom,
|
| 219 |
+
padd_left,
|
| 220 |
+
):
|
| 221 |
+
"""Removes redundant bbox for rows&columns and divides each row into cells from columns
|
| 222 |
+
Args:
|
| 223 |
+
Returns:
|
| 224 |
+
|
| 225 |
+
"""
|
| 226 |
+
cells_img = {}
|
| 227 |
+
header_idx = 0
|
| 228 |
+
row_idx = 0
|
| 229 |
+
previous_xmax_col = 0
|
| 230 |
+
new_cols = {}
|
| 231 |
+
new_master_row = {}
|
| 232 |
+
previous_ymin_row = 0
|
| 233 |
+
new_cols = cols
|
| 234 |
+
new_master_row = master_row
|
| 235 |
+
## Below 2 for loops remove redundant bounding boxes ###
|
| 236 |
+
# for k_col, v_col in cols.items():
|
| 237 |
+
# xmin_col, _, xmax_col, _, col_img = v_col
|
| 238 |
+
# if (np.isclose(previous_xmax_col, xmax_col, atol=5)) or (xmin_col >= xmax_col):
|
| 239 |
+
# print('Found a column with double bbox')
|
| 240 |
+
# continue
|
| 241 |
+
# previous_xmax_col = xmax_col
|
| 242 |
+
# new_cols[k_col] = v_col
|
| 243 |
+
|
| 244 |
+
# for k_row, v_row in master_row.items():
|
| 245 |
+
# _, ymin_row, _, ymax_row, row_img = v_row
|
| 246 |
+
# if (np.isclose(previous_ymin_row, ymin_row, atol=5)) or (ymin_row >= ymax_row):
|
| 247 |
+
# print('Found a row with double bbox')
|
| 248 |
+
# continue
|
| 249 |
+
# previous_ymin_row = ymin_row
|
| 250 |
+
# new_master_row[k_row] = v_row
|
| 251 |
+
######################################################
|
| 252 |
+
for k_row, v_row in new_master_row.items():
|
| 253 |
+
|
| 254 |
+
_, _, _, _, row_img = v_row
|
| 255 |
+
xmax, ymax = row_img.size
|
| 256 |
+
xa, ya, xb, yb = 0, 0, 0, ymax
|
| 257 |
+
row_img_list = []
|
| 258 |
+
# plt.imshow(row_img)
|
| 259 |
+
# st.pyplot()
|
| 260 |
+
for idx, kv in enumerate(new_cols.items()):
|
| 261 |
+
k_col, v_col = kv
|
| 262 |
+
xmin_col, _, xmax_col, _, col_img = v_col
|
| 263 |
+
xmin_col, xmax_col = xmin_col - padd_left - 10, xmax_col - padd_left
|
| 264 |
+
# plt.imshow(col_img)
|
| 265 |
+
# st.pyplot()
|
| 266 |
+
# xa + 3 : to remove borders on the left side of the cropped cell
|
| 267 |
+
# yb = 3: to remove row information from the above row of the cropped cell
|
| 268 |
+
# xb - 3: to remove borders on the right side of the cropped cell
|
| 269 |
+
xa = xmin_col
|
| 270 |
+
xb = xmax_col
|
| 271 |
+
if idx == 0:
|
| 272 |
+
xa = 0
|
| 273 |
+
if idx == len(new_cols) - 1:
|
| 274 |
+
xb = xmax
|
| 275 |
+
xa, ya, xb, yb = xa, ya, xb, yb
|
| 276 |
+
|
| 277 |
+
row_img_cropped = row_img.crop((xa, ya, xb, yb))
|
| 278 |
+
row_img_list.append(row_img_cropped)
|
| 279 |
+
|
| 280 |
+
cells_img[k_row + "." + str(row_idx)] = row_img_list
|
| 281 |
+
row_idx += 1
|
| 282 |
+
|
| 283 |
+
return cells_img, len(new_cols), len(new_master_row) - 1
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def pytess(cell_pil_img):
|
| 287 |
+
return " ".join(
|
| 288 |
+
pytesseract.image_to_data(
|
| 289 |
+
cell_pil_img,
|
| 290 |
+
output_type=Output.DICT,
|
| 291 |
+
config="-c tessedit_char_blacklist=œ˜â€œï¬â™Ã©œ¢!|”?«“¥ --psm 6 preserve_interword_spaces",
|
| 292 |
+
)["text"]
|
| 293 |
+
).strip()
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def uniquify(seq, suffs=count(1)):
|
| 297 |
+
"""Make all the items unique by adding a suffix (1, 2, etc).
|
| 298 |
+
Credit: https://stackoverflow.com/questions/30650474/python-rename-duplicates-in-list-with-progressive-numbers-without-sorting-list
|
| 299 |
+
`seq` is mutable sequence of strings.
|
| 300 |
+
`suffs` is an optional alternative suffix iterable.
|
| 301 |
+
"""
|
| 302 |
+
not_unique = [k for k, v in Counter(seq).items() if v > 1]
|
| 303 |
+
|
| 304 |
+
suff_gens = dict(zip(not_unique, tee(suffs, len(not_unique))))
|
| 305 |
+
for idx, s in enumerate(seq):
|
| 306 |
+
try:
|
| 307 |
+
suffix = str(next(suff_gens[s]))
|
| 308 |
+
except KeyError:
|
| 309 |
+
continue
|
| 310 |
+
else:
|
| 311 |
+
seq[idx] += suffix
|
| 312 |
+
|
| 313 |
+
return seq
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def clean_dataframe(df):
|
| 317 |
+
"""
|
| 318 |
+
Remove irrelevant symbols that appear with tesseractOCR
|
| 319 |
+
"""
|
| 320 |
+
# df.columns = [col.replace('|', '') for col in df.columns]
|
| 321 |
+
|
| 322 |
+
for col in df.columns:
|
| 323 |
+
|
| 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 |
+
df[col] = df[col].str.replace("|", "", regex=True)
|
| 331 |
+
return df
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def create_dataframe(cells_pytess_result: list, max_cols: int, max_rows: int, csv_path):
|
| 335 |
+
"""Create dataframe using list of cell values of the table, also checks for valid header of dataframe
|
| 336 |
+
Args:
|
| 337 |
+
cells_pytess_result: list of strings, each element representing a cell in a table
|
| 338 |
+
max_cols, max_rows: number of columns and rows
|
| 339 |
+
Returns:
|
| 340 |
+
dataframe : final dataframe after all pre-processing
|
| 341 |
+
"""
|
| 342 |
+
|
| 343 |
+
headers = cells_pytess_result[:max_cols]
|
| 344 |
+
new_headers = uniquify(headers, (f" {x!s}" for x in string.ascii_lowercase))
|
| 345 |
+
counter = 0
|
| 346 |
+
|
| 347 |
+
cells_list = cells_pytess_result[max_cols:]
|
| 348 |
+
df = pd.DataFrame("", index=range(0, max_rows), columns=new_headers)
|
| 349 |
+
|
| 350 |
+
cell_idx = 0
|
| 351 |
+
for nrows in range(max_rows):
|
| 352 |
+
for ncols in range(max_cols):
|
| 353 |
+
df.iat[nrows, ncols] = str(cells_list[cell_idx])
|
| 354 |
+
cell_idx += 1
|
| 355 |
+
|
| 356 |
+
## To check if there are duplicate headers if result of uniquify+col == col
|
| 357 |
+
## This check removes headers when all headers are empty or if median of header word count is less than 6
|
| 358 |
+
for x, col in zip(string.ascii_lowercase, new_headers):
|
| 359 |
+
if f" {x!s}" == col:
|
| 360 |
+
counter += 1
|
| 361 |
+
header_char_count = [len(col) for col in new_headers]
|
| 362 |
+
|
| 363 |
+
# if (counter == len(new_headers)) or (statistics.median(header_char_count) < 6):
|
| 364 |
+
# st.write('woooot')
|
| 365 |
+
# df.columns = uniquify(df.iloc[0], (f' {x!s}' for x in string.ascii_lowercase))
|
| 366 |
+
# df = df.iloc[1:,:]
|
| 367 |
+
|
| 368 |
+
df = clean_dataframe(df)
|
| 369 |
+
# df.to_csv(csv_path)
|
| 370 |
+
|
| 371 |
+
return df
|
| 372 |
+
|
| 373 |
+
def postprocess_dataframes(result_tables):
|
| 374 |
+
"""
|
| 375 |
+
Normalize column names
|
| 376 |
+
"""
|
| 377 |
+
# df.columns = [col.replace('|', '') for col in df.columns]
|
| 378 |
+
res = {}
|
| 379 |
+
for idx, table_df in enumerate(result_tables):
|
| 380 |
+
result_df = pd.DataFrame()
|
| 381 |
+
for col in table_df.columns:
|
| 382 |
+
if col.lower().startswith("item"):
|
| 383 |
+
result_df["name"] = table_df[col].copy()
|
| 384 |
+
if (
|
| 385 |
+
col.lower().startswith("total")
|
| 386 |
+
or col.lower().startswith("amount")
|
| 387 |
+
or col.lower().startswith("cost")
|
| 388 |
+
):
|
| 389 |
+
result_df["amount"] = table_df[col].copy()
|
| 390 |
+
print(result_df.columns)
|
| 391 |
+
if len(result_df.columns) == 0:
|
| 392 |
+
result_df["name"] = table_df.iloc[:, 0].copy()
|
| 393 |
+
result_df["amount"] = table_df.iloc[:, 1].copy()
|
| 394 |
+
|
| 395 |
+
result_df["cost_code"] = ""
|
| 396 |
+
res["Table1" + str(idx)] = result_df.to_json(orient="records")
|
| 397 |
+
return res
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def process_image(image):
|
| 401 |
+
# if pdf:
|
| 402 |
+
# path_to_pdf = pdf.name
|
| 403 |
+
# # convert PDF to PIL images (one image by page)
|
| 404 |
+
# first_page=True # we want here only the first page as image
|
| 405 |
+
# if first_page: last_page = 1
|
| 406 |
+
# else: last_page = None
|
| 407 |
+
# imgs = pdf2image.convert_from_path(path_to_pdf, last_page=last_page)
|
| 408 |
+
# image = imgs[0]
|
| 409 |
+
TD_THRESHOLD = 0.7
|
| 410 |
+
TSR_THRESHOLD = 0.8
|
| 411 |
+
padd_top = 100
|
| 412 |
+
padd_left = 100
|
| 413 |
+
padd_bottom = 100
|
| 414 |
+
padd_right = 20
|
| 415 |
+
delta_xmin = 0
|
| 416 |
+
delta_ymin = 0
|
| 417 |
+
delta_xmax = 0
|
| 418 |
+
delta_ymax = 0
|
| 419 |
+
expand_rowcol_bbox_top = 0
|
| 420 |
+
expand_rowcol_bbox_bottom = 0
|
| 421 |
+
|
| 422 |
+
image = image.convert("RGB")
|
| 423 |
+
model, probas, bboxes_scaled = table_detector(image, THRESHOLD_PROBA=TD_THRESHOLD)
|
| 424 |
+
# plot_results_detection(model, image, probas, bboxes_scaled, delta_xmin, delta_ymin, delta_xmax, delta_ymax)
|
| 425 |
+
cropped_img_list = crop_tables(
|
| 426 |
+
image, probas, bboxes_scaled, delta_xmin, delta_ymin, delta_xmax, delta_ymax
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
result = []
|
| 430 |
+
for idx, unpadded_table in enumerate(cropped_img_list):
|
| 431 |
+
table = add_padding(
|
| 432 |
+
unpadded_table, padd_top, padd_right, padd_bottom, padd_left
|
| 433 |
+
)
|
| 434 |
+
model, probas, bboxes_scaled = table_struct_recog(
|
| 435 |
+
table, THRESHOLD_PROBA=TSR_THRESHOLD
|
| 436 |
+
)
|
| 437 |
+
rows, cols = generate_structure(
|
| 438 |
+
model,
|
| 439 |
+
table,
|
| 440 |
+
probas,
|
| 441 |
+
bboxes_scaled,
|
| 442 |
+
expand_rowcol_bbox_top,
|
| 443 |
+
expand_rowcol_bbox_bottom,
|
| 444 |
+
)
|
| 445 |
+
rows, cols = sort_table_featuresv2(rows, cols)
|
| 446 |
+
master_row, cols = individual_table_featuresv2(table, rows, cols)
|
| 447 |
+
cells_img, max_cols, max_rows = object_to_cellsv2(
|
| 448 |
+
master_row,
|
| 449 |
+
cols,
|
| 450 |
+
expand_rowcol_bbox_top,
|
| 451 |
+
expand_rowcol_bbox_bottom,
|
| 452 |
+
padd_left,
|
| 453 |
+
)
|
| 454 |
+
sequential_cell_img_list = []
|
| 455 |
+
for k, img_list in cells_img.items():
|
| 456 |
+
for img in img_list:
|
| 457 |
+
sequential_cell_img_list.append(pytess(img))
|
| 458 |
+
|
| 459 |
+
csv_path = "/content/sample_data/table_" + str(idx)
|
| 460 |
+
df = create_dataframe(sequential_cell_img_list, max_cols, max_rows, csv_path)
|
| 461 |
+
result.append(df)
|
| 462 |
+
output = postprocess_dataframes(result)
|
| 463 |
+
return output
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
title = "Interactive demo OCR: microsoft - table-transformer-detection + tesseract"
|
| 467 |
+
description = "Demo for microsoft - table-transformer-detection + tesseract"
|
| 468 |
+
article = "<p style='text-align: center'></p>"
|
| 469 |
+
examples = [["image_0.png"]]
|
| 470 |
+
|
| 471 |
+
iface = gr.Interface(
|
| 472 |
+
fn=process_image,
|
| 473 |
+
inputs=gr.Image(type="pil"),
|
| 474 |
+
outputs="text",
|
| 475 |
+
title=title,
|
| 476 |
+
description=description,
|
| 477 |
+
article=article,
|
| 478 |
+
examples=examples,
|
| 479 |
+
)
|
| 480 |
+
iface.launch(debug=False)
|
image_0.png
ADDED
|
packages.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
tesseract-ocr
|
| 2 |
+
poppler-utils
|
requirements.txt
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
opencv-python
|
| 2 |
+
pytesseract
|
| 3 |
+
Pillow
|
| 4 |
+
gradio
|
| 5 |
+
timm
|
| 6 |
+
transformers
|
| 7 |
+
numpy
|
| 8 |
+
pandas
|
| 9 |
+
torch
|
| 10 |
+
craft_text_detector
|
| 11 |
+
transformers[sentencepiece]
|
| 12 |
+
pdf2image
|