jinhybr commited on
Commit
cecb26a
Β·
1 Parent(s): c804cbb

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +146 -0
app.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ os.system('pip install pip --upgrade')
4
+ os.system('pip install -q git+https://github.com/huggingface/transformers.git')
5
+
6
+
7
+ os.system("pip install pyyaml==5.1")
8
+ # workaround: install old version of pytorch since detectron2 hasn't released packages for pytorch 1.9 (issue: https://github.com/facebookresearch/detectron2/issues/3158)
9
+ os.system(
10
+ "pip install torch==1.8.0+cu101 torchvision==0.9.0+cu101 -f https://download.pytorch.org/whl/torch_stable.html"
11
+ )
12
+
13
+ # install detectron2 that matches pytorch 1.8
14
+ # See https://detectron2.readthedocs.io/tutorials/install.html for instructions
15
+ os.system(
16
+ "pip install -q detectron2 -f https://dl.fbaipublicfiles.com/detectron2/wheels/cu101/torch1.8/index.html"
17
+ )
18
+
19
+ ## install PyTesseract
20
+ os.system("pip install -q pytesseract")
21
+
22
+ import gradio as gr
23
+ import numpy as np
24
+ from transformers import AutoModelForTokenClassification
25
+ from datasets.features import ClassLabel
26
+ from transformers import AutoProcessor
27
+ from datasets import Features, Sequence, ClassLabel, Value, Array2D, Array3D
28
+ import torch
29
+ from datasets import load_metric
30
+ from transformers import LayoutLMv3ForTokenClassification
31
+ from transformers.data.data_collator import default_data_collator
32
+
33
+
34
+ from transformers import AutoModelForTokenClassification
35
+ from datasets import load_dataset
36
+ from PIL import Image, ImageDraw, ImageFont
37
+
38
+
39
+ processor = AutoProcessor.from_pretrained("jinhybr/OCR-LayoutLMv3-Invoice", apply_ocr=True)
40
+ model = AutoModelForTokenClassification.from_pretrained("jinhybr/OCR-LayoutLMv3-Invoice")
41
+
42
+
43
+
44
+ # load image example
45
+ dataset = load_dataset("jinhybr/WildReceipt", split="test")
46
+ Image.open(dataset[18]["image_path"]).convert("RGB").save("example1.png")
47
+ Image.open(dataset[19]["image_path"]).convert("RGB").save("example2.png")
48
+ Image.open(dataset[25]["image_path"]).convert("RGB").save("example3.png")
49
+ # define id2label, label2color
50
+ labels = dataset.features['ner_tags'].feature.names
51
+ id2label = {v: k for v, k in enumerate(labels)}
52
+ label2color = {
53
+ "Date_key": 'red',
54
+ "Date_value": 'green',
55
+ "Ignore": 'orange',
56
+ "Others": 'orange',
57
+ "Prod_item_key": 'red',
58
+ "Prod_item_value": 'green',
59
+ "Prod_price_key": 'red',
60
+ "Prod_price_value": 'green',
61
+ "Prod_quantity_key": 'red',
62
+ "Prod_quantity_value": 'green',
63
+ "Store_addr_key": 'red',
64
+ "Store_addr_value": 'green',
65
+ "Store_name_key": 'red',
66
+ "Store_name_value": 'green',
67
+ "Subtotal_key": 'red',
68
+ "Subtotal_value": 'green',
69
+ "Tax_key": 'red',
70
+ "Tax_value": 'green',
71
+ "Tel_key": 'red',
72
+ "Tel_value": 'green',
73
+ "Time_key": 'red',
74
+ "Time_value": 'green',
75
+ "Tips_key": 'red',
76
+ "Tips_value": 'green',
77
+ "Total_key": 'red',
78
+ "Total_value": 'blue'
79
+ }
80
+
81
+ def unnormalize_box(bbox, width, height):
82
+ return [
83
+ width * (bbox[0] / 1000),
84
+ height * (bbox[1] / 1000),
85
+ width * (bbox[2] / 1000),
86
+ height * (bbox[3] / 1000),
87
+ ]
88
+
89
+
90
+ def iob_to_label(label):
91
+ return label
92
+
93
+
94
+
95
+ def process_image(image):
96
+
97
+ print(type(image))
98
+ width, height = image.size
99
+
100
+ # encode
101
+ encoding = processor(image, truncation=True, return_offsets_mapping=True, return_tensors="pt")
102
+ offset_mapping = encoding.pop('offset_mapping')
103
+
104
+ # forward pass
105
+ outputs = model(**encoding)
106
+
107
+ # get predictions
108
+ predictions = outputs.logits.argmax(-1).squeeze().tolist()
109
+ token_boxes = encoding.bbox.squeeze().tolist()
110
+
111
+ # only keep non-subword predictions
112
+ is_subword = np.array(offset_mapping.squeeze().tolist())[:,0] != 0
113
+ true_predictions = [id2label[pred] for idx, pred in enumerate(predictions) if not is_subword[idx]]
114
+ true_boxes = [unnormalize_box(box, width, height) for idx, box in enumerate(token_boxes) if not is_subword[idx]]
115
+
116
+ # draw predictions over the image
117
+ draw = ImageDraw.Draw(image)
118
+ font = ImageFont.load_default()
119
+ for prediction, box in zip(true_predictions, true_boxes):
120
+ predicted_label = iob_to_label(prediction)
121
+ draw.rectangle(box, outline=label2color[predicted_label])
122
+ draw.text((box[0]+10, box[1]-10), text=predicted_label, fill=label2color[predicted_label], font=font)
123
+
124
+ return image
125
+
126
+
127
+ title = "OCR Document Paper - Invoice"
128
+ description = "Fine-tuned Microsoft's LayoutLMv3 on WildReceipt Dataset to parse Invoice OCR document. To use it, simply upload an image or use the example image below. Results will show up in a few seconds."
129
+
130
+ 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><br>[3] Hongbin Sun, Zhanghui Kuang, Xiaoyu Yue, Chenhao Lin, and Wayne Zhang. 2021. Spatial Dual-Modality Graph Reasoning for Key Information Extraction. arXiv. DOI:https://doi.org/10.48550/ARXIV.2103.14470 <a href='https://doi.org/10.48550/ARXIV.2103.14470'>Paper Link</a>"
131
+
132
+ examples =[['example1.png'],['example2.png'],['example3.png']]
133
+
134
+ css = """.output_image, .input_image {height: 600px !important}"""
135
+
136
+ iface = gr.Interface(fn=process_image,
137
+ inputs=gr.inputs.Image(type="pil"),
138
+ outputs=gr.outputs.Image(type="pil", label="annotated image"),
139
+ title=title,
140
+ description=description,
141
+ article=article,
142
+ examples=examples,
143
+ css=css,
144
+ analytics_enabled = True, enable_queue=True)
145
+
146
+ iface.launch(inline=False, share=True, debug=True)