Ammar-alhaj-ali commited on
Commit
86e26e9
1 Parent(s): b50e977

Create new file

Browse files
Files changed (1) hide show
  1. app.py +99 -0
app.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.system('pip install pyyaml==5.1')
3
+ # workaround: install old version of pytorch since detectron2 hasn't released packages for pytorch 1.9 (issue: https://github.com/facebookresearch/detectron2/issues/3158)
4
+ #os.system('pip install torch==1.8.0+cu101 torchvision==0.9.0+cu101 -f https://download.pytorch.org/whl/torch_stable.html')
5
+
6
+
7
+
8
+ ## install PyTesseract
9
+ os.system('pip install -q pytesseract')
10
+
11
+ import gradio as gr
12
+ import numpy as np
13
+ from transformers import LayoutLMv3ForTokenClassification
14
+ from datasets import load_dataset
15
+ from PIL import Image, ImageDraw, ImageFont
16
+
17
+
18
+
19
+
20
+
21
+
22
+ processor = LayoutLMv2Processor.from_pretrained("Ammar-alhaj-ali/LayoutLMv3-Fine-Tuning-FUNSD")
23
+ model = LayoutLMv2ForTokenClassification.from_pretrained("Ammar-alhaj-ali/LayoutLMv3-Fine-Tuning-FUNSD")
24
+
25
+ # load image example
26
+ dataset = load_dataset("nielsr/funsd", split="test")
27
+ image = Image.open(dataset[0]["image_path"]).convert("RGB")
28
+ image = Image.open("./invoice.png")
29
+ image.save("document.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 = {'question':'blue', 'answer':'green', 'header':'orange', 'other':'violet'}
34
+
35
+ def unnormalize_box(bbox, width, height):
36
+ return [
37
+ width * (bbox[0] / 1000),
38
+ height * (bbox[1] / 1000),
39
+ width * (bbox[2] / 1000),
40
+ height * (bbox[3] / 1000),
41
+ ]
42
+
43
+ def iob_to_label(label):
44
+ label = label[2:]
45
+ if not label:
46
+ return 'other'
47
+ return label
48
+
49
+ def process_image(image):
50
+ width, height = image.size
51
+
52
+ # encode
53
+ encoding = processor(image, truncation=True, return_offsets_mapping=True, return_tensors="pt")
54
+ offset_mapping = encoding.pop('offset_mapping')
55
+
56
+ # forward pass
57
+ outputs = model(**encoding)
58
+
59
+ # get predictions
60
+ predictions = outputs.logits.argmax(-1).squeeze().tolist()
61
+ token_boxes = encoding.bbox.squeeze().tolist()
62
+
63
+ # only keep non-subword predictions
64
+ is_subword = np.array(offset_mapping.squeeze().tolist())[:,0] != 0
65
+ true_predictions = [id2label[pred] for idx, pred in enumerate(predictions) if not is_subword[idx]]
66
+ true_boxes = [unnormalize_box(box, width, height) for idx, box in enumerate(token_boxes) if not is_subword[idx]]
67
+
68
+ # draw predictions over the image
69
+ draw = ImageDraw.Draw(image)
70
+ font = ImageFont.load_default()
71
+ for prediction, box in zip(true_predictions, true_boxes):
72
+ predicted_label = iob_to_label(prediction).lower()
73
+ draw.rectangle(box, outline=label2color[predicted_label])
74
+ draw.text((box[0]+10, box[1]-10), text=predicted_label, fill=label2color[predicted_label], font=font)
75
+
76
+ return image
77
+
78
+
79
+ title = "Interactive demo: LayoutLMv3"
80
+ description = "Demo for Microsoft's LayoutLMv2, a Transformer for state-of-the-art document image understanding tasks. This particular model is fine-tuned on FUNSD, a dataset of manually annotated forms. It annotates the words appearing in the image as QUESTION/ANSWER/HEADER/OTHER. To use it, simply upload an image or use the example image below and click 'Submit'. Results will show up in a few seconds. If you want to make the output bigger, right-click on it and select 'Open image in new tab'."
81
+ article = "<p style='text-align: center'><a href='https://arxiv.org/abs/2012.14740' target='_blank'>LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding</a> | <a href='https://github.com/microsoft/unilm' target='_blank'>Github Repo</a></p>"
82
+ examples =[['document.png']]
83
+
84
+ css = ".output-image, .input-image {height: 40rem !important; width: 100% !important;}"
85
+ #css = "@media screen and (max-width: 600px) { .output_image, .input_image {height:20rem !important; width: 100% !important;} }"
86
+ # css = ".output_image, .input_image {height: 600px !important}"
87
+
88
+ css = ".image-preview {height: auto !important;}"
89
+
90
+ iface = gr.Interface(fn=process_image,
91
+ inputs=gr.inputs.Image(type="pil"),
92
+ outputs=gr.outputs.Image(type="pil", label="annotated image"),
93
+ title=title,
94
+ description=description,
95
+ article=article,
96
+ examples=examples,
97
+ css=css,
98
+ enable_queue=True)
99
+ iface.launch(debug=True)