balabis commited on
Commit
0c1e949
1 Parent(s): 3d0ae8f

Create new file

Browse files
Files changed (1) hide show
  1. app.py +101 -0
app.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import gradio as gr
4
+ import numpy as np
5
+ from transformers import AutoModelForTokenClassification
6
+ from datasets.features import ClassLabel
7
+ from transformers import AutoProcessor
8
+ from datasets import Features, Sequence, ClassLabel, Value, Array2D, Array3D
9
+ import torch
10
+ from datasets import load_metric
11
+ from transformers import LayoutLMv3ForTokenClassification
12
+ from transformers.data.data_collator import default_data_collator
13
+
14
+
15
+ from transformers import AutoModelForTokenClassification
16
+ from datasets import load_dataset
17
+ from PIL import Image, ImageDraw, ImageFont
18
+
19
+
20
+ processor = AutoProcessor.from_pretrained("microsoft/layoutlmv3-base", apply_ocr=True)
21
+ model = AutoModelForTokenClassification.from_pretrained("layoutlmv3-finetuned-invoice")
22
+
23
+
24
+
25
+ # load image example
26
+ dataset = load_dataset("balabis/invoices", use_auth_token=True, split="test")
27
+ Image.open(dataset[2]["image_path"]).convert("RGB").save("example1.png")
28
+ Image.open(dataset[1]["image_path"]).convert("RGB").save("example2.png")
29
+ Image.open(dataset[0]["image_path"]).convert("RGB").save("example3.png")
30
+ # define id2label, label2color
31
+ labels = dataset.features['ner_tags'].feature.names
32
+ id2label = {v: k for v, k in enumerate(labels)}
33
+ label2color = {
34
+ "INVOICE_NUM": 'blue',
35
+ "INVOICE_DATE": 'blue',
36
+ "BUYER": 'green',
37
+ "SELLER": 'orange',
38
+ "TOTAL_SUM": "blue",
39
+ "TOTAL_VAT": 'green',
40
+ "PAY_UNTIL": 'violet'
41
+ }
42
+
43
+ def unnormalize_box(bbox, width, height):
44
+ return [
45
+ width * (bbox[0] / 1000),
46
+ height * (bbox[1] / 1000),
47
+ width * (bbox[2] / 1000),
48
+ height * (bbox[3] / 1000),
49
+ ]
50
+
51
+
52
+ def iob_to_label(label):
53
+ return label
54
+
55
+
56
+
57
+ def process_image(image):
58
+ width, height = image.size
59
+ # encode
60
+ encoding = processor(image, truncation=True, return_offsets_mapping=True, return_tensors="pt")
61
+ offset_mapping = encoding.pop('offset_mapping')
62
+ # forward pass
63
+ outputs = model(**encoding)
64
+
65
+ # get predictions
66
+ predictions = outputs.logits.argmax(-1).squeeze().tolist()
67
+ token_boxes = encoding.bbox.squeeze().tolist()
68
+ # only keep non-subword predictions
69
+ is_subword = np.array(offset_mapping.squeeze().tolist())[:,0] != 0
70
+ true_predictions = [id2label[pred] for idx, pred in enumerate(predictions) if not is_subword[idx]]
71
+ true_boxes = [unnormalize_box(box, width, height) for idx, box in enumerate(token_boxes) if not is_subword[idx]]
72
+ # draw predictions over the image
73
+ draw = ImageDraw.Draw(image)
74
+ font = ImageFont.load_default()
75
+ for prediction, box in zip(true_predictions, true_boxes):
76
+ predicted_label = iob_to_label(prediction)
77
+ draw.rectangle(box, outline=label2color[predicted_label])
78
+ draw.text((box[0]+10, box[1]-10), text=predicted_label, fill=label2color[predicted_label], font=font)
79
+ return image
80
+
81
+
82
+ title = "Invoice Information extraction using LayoutLMv3 model"
83
+ description = "Invoice Information Extraction - We use Microsoft's LayoutLMv3 trained on Invoice Dataset to predict the Biller Name, Biller Address, Biller post_code, Due_date, GST, Invoice_date, Invoice_number, Subtotal and Total. To use it, simply upload an image or use the example image below. Results will show up in a few seconds."
84
+
85
+ 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] <a href='https://github.com/NielsRogge/Transformers-Tutorials/tree/master/LayoutLMv3'>LayoutLMv3 training and inference</a>"
86
+
87
+ examples =[['example1.png'],['example2.png'],['example3.png']]
88
+
89
+ css = """.output_image, .input_image {height: 600px !important}"""
90
+
91
+ iface = gr.Interface(fn=process_image,
92
+ inputs=gr.inputs.Image(type="pil"),
93
+ outputs=gr.outputs.Image(type="pil", label="annotated image"),
94
+ title=title,
95
+ description=description,
96
+ article=article,
97
+ examples=examples,
98
+ css=css,
99
+ analytics_enabled = True, enable_queue=True)
100
+
101
+ iface.launch(inline=False, share=True, debug=True)