Theivaprakasham commited on
Commit
47601f9
1 Parent(s): 8e158ac
Files changed (4) hide show
  1. README.md +1 -1
  2. app.py +97 -0
  3. packages.txt +6 -0
  4. requirements.txt +4 -0
README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: Layoutlmv2_invoice
3
  emoji: ⚡
4
  colorFrom: blue
5
  colorTo: purple
 
1
  ---
2
+ title: Invoice Information Extractor
3
  emoji: ⚡
4
  colorFrom: blue
5
  colorTo: purple
app.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ os.system('pip install torch==1.8.0+cpu torchvision==0.9.0+cpu -f https://download.pytorch.org/whl/torch_stable.html')
4
+ os.system('pip install -q detectron2 -f https://dl.fbaipublicfiles.com/detectron2/wheels/cpu/torch1.8/index.html')
5
+
6
+
7
+ import gradio as gr
8
+ import numpy as np
9
+ from transformers import LayoutLMv2Processor, LayoutLMv2ForTokenClassification
10
+ from datasets import load_dataset
11
+ from PIL import Image, ImageDraw, ImageFont
12
+
13
+ processor = LayoutLMv2Processor.from_pretrained("microsoft/layoutlmv2-base-uncased")
14
+ model = LayoutLMv2ForTokenClassification.from_pretrained("Theivaprakasham/layoutlmv2-finetuned-sroie_mod")
15
+
16
+ # load image example
17
+ dataset = load_dataset("darentang/generated", split="test")
18
+ Image.open(dataset[50]["image_path"]).convert("RGB").save("example1.png")
19
+ Image.open(dataset[14]["image_path"]).convert("RGB").save("example2.png")
20
+ Image.open(dataset[20]["image_path"]).convert("RGB").save("example3.png")
21
+ # define id2label, label2color
22
+ labels = dataset.features['ner_tags'].feature.names
23
+ id2label = {v: k for v, k in enumerate(labels)}
24
+ label2color = {'b-abn': "blue",
25
+ 'b-biller': "blue",
26
+ 'b-biller_address': "black",
27
+ 'b-biller_post_code': "green",
28
+ 'b-due_date': "orange",
29
+ 'b-gst': 'red',
30
+ 'b-invoice_date': 'red',
31
+ 'b-invoice_number': 'violet',
32
+ 'b-subtotal': 'green',
33
+ 'b-total': 'green',
34
+ 'i-biller_address': 'blue',
35
+ 'o': 'violet'}
36
+
37
+ def unnormalize_box(bbox, width, height):
38
+ return [
39
+ width * (bbox[0] / 1000),
40
+ height * (bbox[1] / 1000),
41
+ width * (bbox[2] / 1000),
42
+ height * (bbox[3] / 1000),
43
+ ]
44
+
45
+ def iob_to_label(label):
46
+ return label
47
+
48
+ def process_image(image):
49
+ width, height = image.size
50
+
51
+ # encode
52
+ encoding = processor(image, truncation=True, return_offsets_mapping=True, return_tensors="pt")
53
+ offset_mapping = encoding.pop('offset_mapping')
54
+
55
+ # forward pass
56
+ outputs = model(**encoding)
57
+
58
+ # get predictions
59
+ predictions = outputs.logits.argmax(-1).squeeze().tolist()
60
+ token_boxes = encoding.bbox.squeeze().tolist()
61
+
62
+ # only keep non-subword predictions
63
+ is_subword = np.array(offset_mapping.squeeze().tolist())[:,0] != 0
64
+ true_predictions = [id2label[pred] for idx, pred in enumerate(predictions) if not is_subword[idx]]
65
+ true_boxes = [unnormalize_box(box, width, height) for idx, box in enumerate(token_boxes) if not is_subword[idx]]
66
+
67
+ # draw predictions over the image
68
+ draw = ImageDraw.Draw(image)
69
+ font = ImageFont.load_default()
70
+ for prediction, box in zip(true_predictions, true_boxes):
71
+ predicted_label = iob_to_label(prediction).lower()
72
+ draw.rectangle(box, outline=label2color[predicted_label])
73
+ draw.text((box[0]+10, box[1]-10), text=predicted_label, fill=label2color[predicted_label], font=font)
74
+
75
+ return image
76
+
77
+
78
+ title = "Invoice Information extraction using LayoutLMv2 model"
79
+ description = "Invoice Information Extraction - We use Microsoft's LayoutLMv2 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."
80
+
81
+ article="<b>References</b><br>[1] Y. Xu et al., “LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding.” 2022. <a href='https://arxiv.org/abs/2012.14740'>Paper Link</a><br>[2] <a href='https://github.com/NielsRogge/Transformers-Tutorials/tree/master/LayoutLMv2/FUNSD'>LayoutLMv2 training and inference</a>"
82
+
83
+ examples =[['example1.png'],['example2.png'],['example3.png']]
84
+
85
+
86
+ css = """.output_image, .input_image {height: 600px !important}"""
87
+
88
+ iface = gr.Interface(fn=process_image,
89
+ inputs=gr.inputs.Image(type="pil"),
90
+ outputs=gr.outputs.Image(type="pil", label="annotated image"),
91
+ title=title,
92
+ description=description,
93
+ article=article,
94
+ examples=examples,
95
+ css=css,
96
+ analytics_enabled = True, enable_queue=True)
97
+ iface.launch(inline=False, share=True, debug=False)
packages.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ffmpeg
2
+ libsm6
3
+ libxext6 -y
4
+ libgl1
5
+ -y libgl1-mesa-glx
6
+ tesseract-ocr
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ git+https://github.com/huggingface/transformers.git
2
+ pyyaml==5.1
3
+ pytesseract==0.3.9
4
+ git+https://github.com/huggingface/datasets#egg=datasets