Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import numpy as np
|
3 |
+
from PIL import Image
|
4 |
+
import torch
|
5 |
+
import pandas as pd
|
6 |
+
from transformers import AutoImageProcessor, AutoModelForObjectDetection, AutoProcessor, Pix2StructForConditionalGeneration
|
7 |
+
import torch
|
8 |
+
from io import StringIO
|
9 |
+
|
10 |
+
device="cpu"
|
11 |
+
|
12 |
+
MAX_PATCHES = 1024
|
13 |
+
MAX_NEW_TOKENS = 1024
|
14 |
+
TABLE_THRESHOLD = 0.9
|
15 |
+
TABLE_PADDING = 5
|
16 |
+
|
17 |
+
# Detection related
|
18 |
+
table_detr_processor = AutoImageProcessor.from_pretrained("microsoft/table-transformer-detection")
|
19 |
+
table_detr_model = AutoModelForObjectDetection.from_pretrained("microsoft/table-transformer-detection", revision="no_timm")
|
20 |
+
table_detr_model.to(device)
|
21 |
+
table_detr_model.eval()
|
22 |
+
|
23 |
+
no_table_found = Image.open("app_assets/no_table_found.png")
|
24 |
+
|
25 |
+
# Recognition related
|
26 |
+
table_recog_processor = AutoProcessor.from_pretrained("KennethTM/pix2struct-base-table2html")
|
27 |
+
table_recog_model = Pix2StructForConditionalGeneration.from_pretrained("KennethTM/pix2struct-base-table2html")
|
28 |
+
table_recog_model.to(device)
|
29 |
+
table_recog_model.eval()
|
30 |
+
|
31 |
+
def table_detection(image, threshold=TABLE_THRESHOLD):
|
32 |
+
|
33 |
+
inputs = table_detr_processor(images=image, return_tensors="pt")
|
34 |
+
inputs = {k: v.to(device) for k, v in inputs.items()}
|
35 |
+
|
36 |
+
with torch.inference_mode():
|
37 |
+
|
38 |
+
outputs = table_detr_model(**inputs)
|
39 |
+
|
40 |
+
target_sizes = torch.tensor([image.size[::-1]])
|
41 |
+
results = table_detr_processor.post_process_object_detection(outputs, threshold=threshold, target_sizes=target_sizes)
|
42 |
+
table_boxes = [i for i in results[0]["boxes"]]
|
43 |
+
|
44 |
+
tables = []
|
45 |
+
if len(table_boxes) == 0:
|
46 |
+
tables.append(no_table_found)
|
47 |
+
else:
|
48 |
+
padding = TABLE_PADDING
|
49 |
+
for box in table_boxes:
|
50 |
+
box = [int(i) for i in box]
|
51 |
+
box[0] = max(0, box[0]-padding)
|
52 |
+
box[1] = max(0, box[1]-padding)
|
53 |
+
box[2] = min(image.width, box[2]+padding)
|
54 |
+
box[3] = min(image.height, box[3]+padding)
|
55 |
+
tables.append(image.crop(box))
|
56 |
+
|
57 |
+
return tables
|
58 |
+
|
59 |
+
def table_recognition(image, max_new_tokens = MAX_NEW_TOKENS):
|
60 |
+
|
61 |
+
encoding = table_recog_processor(image, return_tensors="pt", max_patches=MAX_PATCHES)
|
62 |
+
|
63 |
+
with torch.inference_mode():
|
64 |
+
flattened_patches = encoding.pop("flattened_patches").to(device)
|
65 |
+
attention_mask = encoding.pop("attention_mask").to(device)
|
66 |
+
predictions = table_recog_model.generate(flattened_patches=flattened_patches, attention_mask=attention_mask, max_new_tokens=max_new_tokens)
|
67 |
+
|
68 |
+
predictions_decoded = table_recog_processor.tokenizer.batch_decode(predictions, skip_special_tokens=True)
|
69 |
+
table_html = predictions_decoded[0]
|
70 |
+
|
71 |
+
return table_html
|
72 |
+
|
73 |
+
def table_recognition_outputs(image):
|
74 |
+
# Table to HTML
|
75 |
+
table_html = table_recognition(image)
|
76 |
+
|
77 |
+
# Write HTML to files
|
78 |
+
with open("table.html", "w") as file:
|
79 |
+
file.write(table_html)
|
80 |
+
|
81 |
+
df = pd.read_html(StringIO(table_html))[0]
|
82 |
+
df.to_csv("table.csv", index=False)
|
83 |
+
|
84 |
+
return [table_html,
|
85 |
+
gr.DownloadButton("Download HTML", value="table.html", visible=True),
|
86 |
+
gr.DownloadButton("Download CSV", value="table.csv", visible=True)]
|
87 |
+
|
88 |
+
demo_detection = [
|
89 |
+
"app_assets/example_one_table.jpg",
|
90 |
+
"app_assets/example_two_tables.jpg",
|
91 |
+
]
|
92 |
+
|
93 |
+
demo_recognition = [
|
94 |
+
"app_assets/example_recog_1.jpg",
|
95 |
+
"app_assets/example_recog_2.jpg",
|
96 |
+
]
|
97 |
+
|
98 |
+
with gr.Blocks() as demo:
|
99 |
+
|
100 |
+
with gr.Tab("Recognition"):
|
101 |
+
gr.Markdown("# Table recognition")
|
102 |
+
gr.Markdown("This model ([KennethTM/pix2struct-base-table2html](https://huggingface.co/KennethTM/pix2struct-base-table2html)) converts an image of a table to HTML format and is finetuned from [Pix2Struct base model](https://huggingface.co/google/pix2struct-base).")
|
103 |
+
gr.Markdown("The model expects an image containing only a table. If the table is embedded in a document, first use the detection model in the 'Detection' tab.")
|
104 |
+
gr.Markdown("*note that recognition model inference is slow on cpu, please be patient*")
|
105 |
+
with gr.Row():
|
106 |
+
with gr.Column():
|
107 |
+
input_table = gr.Image(type="pil", label="Table", show_label=True, scale=1)
|
108 |
+
|
109 |
+
with gr.Column():
|
110 |
+
output_html = gr.HTML(label="Table (HTML format)", show_label=False)
|
111 |
+
|
112 |
+
with gr.Row():
|
113 |
+
download_html = gr.DownloadButton(visible=False)
|
114 |
+
download_csv = gr.DownloadButton(visible=False)
|
115 |
+
|
116 |
+
with gr.Row():
|
117 |
+
examples = gr.Examples(demo_recognition, input_table, cache_examples=False, label="Example tables ([MMTab](https://huggingface.co/datasets/SpursgoZmy/MMTab))")
|
118 |
+
|
119 |
+
input_table.change(fn=table_recognition_outputs, inputs=input_table, outputs=[output_html, download_html, download_csv])
|
120 |
+
|
121 |
+
with gr.Tab("Detection"):
|
122 |
+
gr.Markdown("# Table detection")
|
123 |
+
gr.Markdown("This model detect tables in a document image with [Microsoft's Table Transformer model](https://huggingface.co/microsoft/table-transformer-detection).")
|
124 |
+
gr.Markdown("Use the detection to find tables, download the results and use as input for table recognition in the 'Recognition' tab.")
|
125 |
+
with gr.Row():
|
126 |
+
with gr.Column():
|
127 |
+
input_image = gr.Image(type="pil", label="Document", show_label=True, scale=1)
|
128 |
+
|
129 |
+
with gr.Column():
|
130 |
+
output_gallery = gr.Gallery(type="pil", label="Tables", show_label=True, scale=1, format="png")
|
131 |
+
|
132 |
+
with gr.Row():
|
133 |
+
examples = gr.Examples(demo_detection, input_image, cache_examples=False, label="Example documents ([PubTabNet](https://huggingface.co/datasets/apoidea/pubtabnet-html))")
|
134 |
+
|
135 |
+
input_image.change(fn=table_detection, inputs=input_image, outputs=output_gallery)
|
136 |
+
|
137 |
+
demo.launch()
|