imflash217 commited on
Commit
04c7922
1 Parent(s): 6696a8f

Create new file

Browse files
Files changed (1) hide show
  1. app.py +96 -0
app.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # install detectron2 that matches pytorch 1.8
7
+ # See https://detectron2.readthedocs.io/tutorials/install.html for instructions
8
+ os.system('pip install -q detectron2 -f https://dl.fbaipublicfiles.com/detectron2/wheels/cu101/torch1.8/index.html')
9
+
10
+ ## install PyTesseract
11
+ os.system('pip install -q pytesseract')
12
+
13
+ import gradio as gr
14
+ import numpy as np
15
+ from transformers import LayoutLMv2Processor, LayoutLMv2ForTokenClassification
16
+ from datasets import load_dataset
17
+ from PIL import Image, ImageDraw, ImageFont
18
+
19
+ processor = LayoutLMv2Processor.from_pretrained("microsoft/layoutlmv2-base-uncased")
20
+ model = LayoutLMv2ForTokenClassification.from_pretrained("nielsr/layoutlmv2-finetuned-funsd")
21
+
22
+ # load image example
23
+ dataset = load_dataset("nielsr/funsd", split="test")
24
+ image = Image.open(dataset[0]["image_path"]).convert("RGB")
25
+ image = Image.open("./invoice.png")
26
+ image.save("document.png")
27
+ # define id2label, label2color
28
+ labels = dataset.features['ner_tags'].feature.names
29
+ id2label = {v: k for v, k in enumerate(labels)}
30
+ label2color = {'question':'blue', 'answer':'green', 'header':'orange', 'other':'violet'}
31
+
32
+ def unnormalize_box(bbox, width, height):
33
+ return [
34
+ width * (bbox[0] / 1000),
35
+ height * (bbox[1] / 1000),
36
+ width * (bbox[2] / 1000),
37
+ height * (bbox[3] / 1000),
38
+ ]
39
+
40
+ def iob_to_label(label):
41
+ label = label[2:]
42
+ if not label:
43
+ return 'other'
44
+ return label
45
+
46
+ def process_image(image):
47
+ width, height = image.size
48
+
49
+ # encode
50
+ encoding = processor(image, truncation=True, return_offsets_mapping=True, return_tensors="pt")
51
+ offset_mapping = encoding.pop('offset_mapping')
52
+
53
+ # forward pass
54
+ outputs = model(**encoding)
55
+
56
+ # get predictions
57
+ predictions = outputs.logits.argmax(-1).squeeze().tolist()
58
+ token_boxes = encoding.bbox.squeeze().tolist()
59
+
60
+ # only keep non-subword predictions
61
+ is_subword = np.array(offset_mapping.squeeze().tolist())[:,0] != 0
62
+ true_predictions = [id2label[pred] for idx, pred in enumerate(predictions) if not is_subword[idx]]
63
+ true_boxes = [unnormalize_box(box, width, height) for idx, box in enumerate(token_boxes) if not is_subword[idx]]
64
+
65
+ # draw predictions over the image
66
+ draw = ImageDraw.Draw(image)
67
+ font = ImageFont.load_default()
68
+ for prediction, box in zip(true_predictions, true_boxes):
69
+ predicted_label = iob_to_label(prediction).lower()
70
+ draw.rectangle(box, outline=label2color[predicted_label])
71
+ draw.text((box[0]+10, box[1]-10), text=predicted_label, fill=label2color[predicted_label], font=font)
72
+
73
+ return image
74
+
75
+
76
+ title = "Interactive demo: LayoutLMv2"
77
+ 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'."
78
+ 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>"
79
+ examples =[['document.png']]
80
+
81
+ css = ".output-image, .input-image {height: 40rem !important; width: 100% !important;}"
82
+ #css = "@media screen and (max-width: 600px) { .output_image, .input_image {height:20rem !important; width: 100% !important;} }"
83
+ # css = ".output_image, .input_image {height: 600px !important}"
84
+
85
+ css = ".image-preview {height: auto !important;}"
86
+
87
+ iface = gr.Interface(fn=process_image,
88
+ inputs=gr.inputs.Image(type="pil"),
89
+ outputs=gr.outputs.Image(type="pil", label="annotated image"),
90
+ title=title,
91
+ description=description,
92
+ article=article,
93
+ examples=examples,
94
+ css=css,
95
+ enable_queue=True)
96
+ iface.launch(debug=True)