Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
model = LayoutLMv2ForTokenClassification.from_pretrained("Mishtert/Invoice_extraction_categorization")
|
22 |
+
|
23 |
+
# load image example
|
24 |
+
#dataset = load_dataset("nielsr/funsd", split="test")
|
25 |
+
dataset = load_dataset("Mishtert/niefunsd", split="test")
|
26 |
+
image = Image.open(dataset[0]["image_path"]).convert("RGB")
|
27 |
+
image = Image.open("./invoice.png")
|
28 |
+
image.save("document.png")
|
29 |
+
# define id2label, label2color
|
30 |
+
labels = dataset.features['ner_tags'].feature.names
|
31 |
+
id2label = {v: k for v, k in enumerate(labels)}
|
32 |
+
label2color = {'question':'blue', 'answer':'green', 'header':'orange', 'other':'violet'}
|
33 |
+
|
34 |
+
def unnormalize_box(bbox, width, height):
|
35 |
+
return [
|
36 |
+
width * (bbox[0] / 1000),
|
37 |
+
height * (bbox[1] / 1000),
|
38 |
+
width * (bbox[2] / 1000),
|
39 |
+
height * (bbox[3] / 1000),
|
40 |
+
]
|
41 |
+
|
42 |
+
def iob_to_label(label):
|
43 |
+
label = label[2:]
|
44 |
+
if not label:
|
45 |
+
return 'other'
|
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 = "Interactive demo: Invoice Extraction & Categorization"
|
79 |
+
description = "Text extracted and annotated QUESTION/ANSWER/HEADER/OTHER.
|
80 |
+
|
81 |
+
examples =[['document.png']]
|
82 |
+
|
83 |
+
css = ".output-image, .input-image {height: 40rem !important; width: 100% !important;}"
|
84 |
+
#css = "@media screen and (max-width: 600px) { .output_image, .input_image {height:20rem !important; width: 100% !important;} }"
|
85 |
+
# css = ".output_image, .input_image {height: 600px !important}"
|
86 |
+
|
87 |
+
css = ".image-preview {height: auto !important;}"
|
88 |
+
|
89 |
+
iface = gr.Interface(fn=process_image,
|
90 |
+
inputs=gr.inputs.Image(type="pil"),
|
91 |
+
outputs=gr.outputs.Image(type="pil", label="annotated image"),
|
92 |
+
title=title,
|
93 |
+
description=description,
|
94 |
+
article=article,
|
95 |
+
examples=examples,
|
96 |
+
css=css,
|
97 |
+
enable_queue=True)
|
98 |
+
iface.launch(debug=True)
|