jinhybr commited on
Commit
1a33e6d
1 Parent(s): 9f448ef

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +130 -0
app.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 LayoutLMv3Processor, LayoutLMv3ForTokenClassification
25
+ from datasets import load_dataset
26
+ from PIL import Image, ImageDraw, ImageFont
27
+
28
+ processor = LayoutLMv3Processor.from_pretrained("jinhybr/LiLt-funsd-en")
29
+ model = LayoutLMv3ForTokenClassification.from_pretrained(
30
+ "jinhybr/LiLt-funsd-en"
31
+ )
32
+
33
+ # load image example
34
+ dataset = load_dataset("nielsr/funsd-layoutlmv3", split="test")
35
+ image = Image.open(dataset[0]["image_path"]).convert("RGB")
36
+ image = Image.open("./example_lm3.png")
37
+ image.save("document.png")
38
+
39
+ labels = dataset.features["ner_tags"].feature.names
40
+ id2label = {v: k for v, k in enumerate(labels)}
41
+ label2color = {
42
+ "question": "blue",
43
+ "answer": "green",
44
+ "header": "orange",
45
+ "other": "violet",
46
+ }
47
+
48
+
49
+ def unnormalize_box(bbox, width, height):
50
+ return [
51
+ width * (bbox[0] / 1000),
52
+ height * (bbox[1] / 1000),
53
+ width * (bbox[2] / 1000),
54
+ height * (bbox[3] / 1000),
55
+ ]
56
+
57
+
58
+ def iob_to_label(label):
59
+ label = label[2:]
60
+ if not label:
61
+ return "other"
62
+ return label
63
+
64
+
65
+ def process_image(image):
66
+ width, height = image.size
67
+
68
+ # encode
69
+ encoding = processor(
70
+ image, truncation=True, return_offsets_mapping=True, return_tensors="pt"
71
+ )
72
+ offset_mapping = encoding.pop("offset_mapping")
73
+
74
+ # forward pass
75
+ outputs = model(**encoding)
76
+
77
+ # get predictions
78
+ predictions = outputs.logits.argmax(-1).squeeze().tolist()
79
+ token_boxes = encoding.bbox.squeeze().tolist()
80
+
81
+ # only keep non-subword predictions
82
+ is_subword = np.array(offset_mapping.squeeze().tolist())[:, 0] != 0
83
+ true_predictions = [
84
+ id2label[pred] for idx, pred in enumerate(predictions) if not is_subword[idx]
85
+ ]
86
+ true_boxes = [
87
+ unnormalize_box(box, width, height)
88
+ for idx, box in enumerate(token_boxes)
89
+ if not is_subword[idx]
90
+ ]
91
+
92
+ # draw predictions over the image
93
+ draw = ImageDraw.Draw(image)
94
+ font = ImageFont.load_default()
95
+ for prediction, box in zip(true_predictions, true_boxes):
96
+ predicted_label = iob_to_label(prediction).lower()
97
+ draw.rectangle(box, outline=label2color[predicted_label])
98
+ draw.text(
99
+ (box[0] + 10, box[1] - 10),
100
+ text=predicted_label,
101
+ fill=label2color[predicted_label],
102
+ font=font,
103
+ )
104
+
105
+ return image
106
+
107
+
108
+ title = "OCR Document Parser : Information Extraction - Fine Tuned LiLT Language-independent Layout Transformer Model"
109
+ description = "Demo for LiLT Language-independent Layout Transformer, 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'."
110
+ article = "<p style='text-align: center'><a href=' https://arxiv.org/abs/2202.13669' target='_blank'> LiLT Language-independent Layout Transformer</a> | <a href='https://github.com/jpwang/lilt' target='_blank'>Github Repo</a></p>"
111
+ examples = [["document.png"]]
112
+
113
+ css = ".output-image, .input-image {height: 40rem !important; width: 100% !important;}"
114
+ # css = "@media screen and (max-width: 600px) { .output_image, .input_image {height:20rem !important; width: 100% !important;} }"
115
+ # css = ".output_image, .input_image {height: 600px !important}"
116
+
117
+ css = ".image-preview {height: auto !important;}"
118
+
119
+ iface = gr.Interface(
120
+ fn=process_image,
121
+ inputs=gr.inputs.Image(type="pil"),
122
+ outputs=gr.outputs.Image(type="pil", label="annotated image"),
123
+ title=title,
124
+ description=description,
125
+ article=article,
126
+ examples=examples,
127
+ css=css,
128
+ enable_queue=True,
129
+ )
130
+ iface.launch(debug=True)