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