Spaces:
Runtime error
Runtime error
Ammar-alhaj-ali
commited on
Commit
•
63a9bd9
1
Parent(s):
1bbdd8e
Create new file
Browse files
app.py
ADDED
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
os.system('pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cpu')
|
3 |
+
os.system('pip install -q git+https://github.com/huggingface/transformers.git')
|
4 |
+
os.system('pip install pytesseract')
|
5 |
+
|
6 |
+
|
7 |
+
|
8 |
+
import gradio as gr
|
9 |
+
import numpy as np
|
10 |
+
from transformers import AutoModelForTokenClassification
|
11 |
+
from datasets.features import ClassLabel
|
12 |
+
from transformers import AutoProcessor
|
13 |
+
from datasets import Features, Sequence, ClassLabel, Value, Array2D, Array3D
|
14 |
+
import torch
|
15 |
+
from datasets import load_metric
|
16 |
+
from transformers import LayoutLMv3ForTokenClassification
|
17 |
+
from transformers.data.data_collator import default_data_collator
|
18 |
+
|
19 |
+
|
20 |
+
from transformers import AutoModelForTokenClassification
|
21 |
+
from datasets import load_dataset
|
22 |
+
from PIL import Image, ImageDraw, ImageFont
|
23 |
+
|
24 |
+
|
25 |
+
processor = AutoProcessor.from_pretrained("Ammar-alhaj-ali/LayoutLMv3-Fine-Tuning-Invoice", apply_ocr=True)
|
26 |
+
model = AutoModelForTokenClassification.from_pretrained("Ammar-alhaj-ali/LayoutLMv3-Fine-Tuning-Invoice")
|
27 |
+
|
28 |
+
|
29 |
+
|
30 |
+
# define id2label, label2color
|
31 |
+
labels = ['O', 'B-ABN', 'B-BILLER', 'B-BILLER_ADDRESS', 'B-BILLER_POST_CODE', 'B-DUE_DATE', 'B-GST', 'B-INVOICE_DATE', 'B-INVOICE_NUMBER', 'B-SUBTOTAL', 'B-TOTAL', 'I-BILLER_ADDRESS']
|
32 |
+
id2label = {v: k for v, k in enumerate(labels)}
|
33 |
+
label2color = {
|
34 |
+
"B-ABN": 'blue',
|
35 |
+
"B-BILLER": 'blue',
|
36 |
+
"B-BILLER_ADDRESS": 'green',
|
37 |
+
"B-BILLER_POST_CODE": 'orange',
|
38 |
+
"B-DUE_DATE": "blue",
|
39 |
+
"B-GST": 'green',
|
40 |
+
"B-INVOICE_DATE": 'violet',
|
41 |
+
"B-INVOICE_NUMBER": 'orange',
|
42 |
+
"B-SUBTOTAL": 'green',
|
43 |
+
"B-TOTAL": 'blue',
|
44 |
+
"I-BILLER_ADDRESS": 'blue',
|
45 |
+
"O": 'orange'
|
46 |
+
}
|
47 |
+
|
48 |
+
def unnormalize_box(bbox, width, height):
|
49 |
+
return [
|
50 |
+
width * (bbox[0] / 1000),
|
51 |
+
height * (bbox[1] / 1000),
|
52 |
+
width * (bbox[2] / 1000),
|
53 |
+
height * (bbox[3] / 1000),
|
54 |
+
]
|
55 |
+
|
56 |
+
|
57 |
+
def iob_to_label(label):
|
58 |
+
return label
|
59 |
+
|
60 |
+
|
61 |
+
|
62 |
+
def process_image(image):
|
63 |
+
|
64 |
+
print(type(image))
|
65 |
+
width, height = image.size
|
66 |
+
|
67 |
+
# encode
|
68 |
+
encoding = processor(image, truncation=True, return_offsets_mapping=True, return_tensors="pt")
|
69 |
+
offset_mapping = encoding.pop('offset_mapping')
|
70 |
+
|
71 |
+
# forward pass
|
72 |
+
outputs = model(**encoding)
|
73 |
+
|
74 |
+
# get predictions
|
75 |
+
predictions = outputs.logits.argmax(-1).squeeze().tolist()
|
76 |
+
token_boxes = encoding.bbox.squeeze().tolist()
|
77 |
+
|
78 |
+
# only keep non-subword predictions
|
79 |
+
is_subword = np.array(offset_mapping.squeeze().tolist())[:,0] != 0
|
80 |
+
true_predictions = [id2label[pred] for idx, pred in enumerate(predictions) if not is_subword[idx]]
|
81 |
+
true_boxes = [unnormalize_box(box, width, height) for idx, box in enumerate(token_boxes) if not is_subword[idx]]
|
82 |
+
|
83 |
+
# draw predictions over the image
|
84 |
+
draw = ImageDraw.Draw(image)
|
85 |
+
font = ImageFont.load_default()
|
86 |
+
for prediction, box in zip(true_predictions, true_boxes):
|
87 |
+
predicted_label = iob_to_label(prediction)
|
88 |
+
draw.rectangle(box, outline=label2color[predicted_label]) #label2color[predicted_label]
|
89 |
+
draw.text((box[0]+10, box[1]-10), text=predicted_label, fill=label2color[predicted_label], font=font) #label2color[predicted_label]
|
90 |
+
|
91 |
+
return image
|
92 |
+
|
93 |
+
|
94 |
+
title = "Extracting information from FUNSD using the LayoutLMv3 "
|
95 |
+
description = "I Fine tuned LayoutLMv3 on FUNSD (Form Understanding in. Noisy Scanned Documents) "
|
96 |
+
|
97 |
+
article="<b>References</b><br>[1] Y. Xu et al., “LayoutLMv3: Pre-training for Document AI with Unified Text and Image Masking.” 2022. <a href='https://arxiv.org/abs/2204.08387'>Paper Link</a><br>[2]"
|
98 |
+
|
99 |
+
examples =[['img1.png'],['img2.png'],['img3.png']]
|
100 |
+
|
101 |
+
css = """.output_image, .input_image {height: 600px !important}"""
|
102 |
+
|
103 |
+
iface = gr.Interface(fn=process_image,
|
104 |
+
inputs=gr.inputs.Image(type="pil"),
|
105 |
+
outputs=gr.outputs.Image(type="pil", label="annotated image"),
|
106 |
+
title=title,
|
107 |
+
description=description,
|
108 |
+
article=article,
|
109 |
+
examples=examples,
|
110 |
+
css=css,
|
111 |
+
analytics_enabled = True, enable_queue=True)
|
112 |
+
|
113 |
+
iface.launch(inline=False, share=False, debug=False)
|