jinhybr commited on
Commit
ec9238e
·
1 Parent(s): bbb00b4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -62
app.py CHANGED
@@ -1,76 +1,71 @@
1
  import os
2
- os.system('pip install pip --upgrade')
3
- os.system('pip install -q git+https://github.com/huggingface/transformers.git')
4
- os.system('pip install pyyaml==5.1')
5
  # workaround: install old version of pytorch since detectron2 hasn't released packages for pytorch 1.9 (issue: https://github.com/facebookresearch/detectron2/issues/3158)
6
- os.system('pip install torch==1.8.0+cu101 torchvision==0.9.0+cu101 -f https://download.pytorch.org/whl/torch_stable.html')
 
 
7
 
8
  # install detectron2 that matches pytorch 1.8
9
  # See https://detectron2.readthedocs.io/tutorials/install.html for instructions
10
- os.system('pip install -q detectron2 -f https://dl.fbaipublicfiles.com/detectron2/wheels/cu101/torch1.8/index.html')
 
 
11
 
12
  ## install PyTesseract
13
- os.system('pip install -q pytesseract')
14
 
15
  import gradio as gr
16
  import numpy as np
17
-
18
  from datasets import load_dataset
19
  from PIL import Image, ImageDraw, ImageFont
20
 
21
- from transformers import AutoModelForTokenClassification, AutoProcessor
22
-
23
-
24
- processor = AutoProcessor.from_pretrained("microsoft/layoutlmv3-base", apply_ocr=False)
25
-
26
-
27
- model = AutoModelForTokenClassification.from_pretrained("jinhybr/OCR-LayoutLMv3")
28
-
29
 
30
  # load image example
31
- dataset = load_dataset("nielsr/funsd-layoutlmv3", split="test")
32
- Image.open(dataset[0]["image_path"]).convert("RGB").save("example_lm3.png")
33
-
 
34
 
35
- # define id2label, label2color
36
- labels = dataset.features['ner_tags'].feature.names
37
  id2label = {v: k for v, k in enumerate(labels)}
38
- label2color = {'question':'blue', 'answer':'green', 'header':'orange', 'other':'violet'}
39
-
40
-
41
-
42
- #####
43
-
44
-
45
-
46
-
47
-
48
-
49
-
50
-
51
-
52
 
53
 
54
  def unnormalize_box(bbox, width, height):
55
- return [
56
- width * (bbox[0] / 1000),
57
- height * (bbox[1] / 1000),
58
- width * (bbox[2] / 1000),
59
- height * (bbox[3] / 1000),
60
- ]
 
61
 
62
  def iob_to_label(label):
63
  label = label[2:]
64
  if not label:
65
- return 'other'
66
  return label
67
 
 
68
  def process_image(image):
69
  width, height = image.size
70
 
71
  # encode
72
- encoding = processor(image, truncation=True, return_offsets_mapping=True, return_tensors="pt")
73
- offset_mapping = encoding.pop('offset_mapping')
 
 
74
 
75
  # forward pass
76
  outputs = model(**encoding)
@@ -80,9 +75,15 @@ def process_image(image):
80
  token_boxes = encoding.bbox.squeeze().tolist()
81
 
82
  # only keep non-subword predictions
83
- is_subword = np.array(offset_mapping.squeeze().tolist())[:,0] != 0
84
- true_predictions = [id2label[pred] for idx, pred in enumerate(predictions) if not is_subword[idx]]
85
- true_boxes = [unnormalize_box(box, width, height) for idx, box in enumerate(token_boxes) if not is_subword[idx]]
 
 
 
 
 
 
86
 
87
  # draw predictions over the image
88
  draw = ImageDraw.Draw(image)
@@ -90,29 +91,36 @@ def process_image(image):
90
  for prediction, box in zip(true_predictions, true_boxes):
91
  predicted_label = iob_to_label(prediction).lower()
92
  draw.rectangle(box, outline=label2color[predicted_label])
93
- draw.text((box[0]+10, box[1]-10), text=predicted_label, fill=label2color[predicted_label], font=font)
94
-
 
 
 
 
 
95
  return image
96
 
97
 
98
- title = "Interactive demo: OCR Document Parser"
99
- description = "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'."
100
- 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>"
101
- examples =[['example_lm3.png']]
102
 
103
  css = ".output-image, .input-image {height: 40rem !important; width: 100% !important;}"
104
- #css = "@media screen and (max-width: 600px) { .output_image, .input_image {height:20rem !important; width: 100% !important;} }"
105
  # css = ".output_image, .input_image {height: 600px !important}"
106
 
107
  css = ".image-preview {height: auto !important;}"
108
 
109
- iface = gr.Interface(fn=process_image,
110
- inputs=gr.inputs.Image(type="pil"),
111
- outputs=gr.outputs.Image(type="pil", label="annotated image"),
112
- title=title,
113
- description=description,
114
- article=article,
115
- examples=examples,
116
- css=css,
117
- enable_queue=True)
 
 
118
  iface.launch(debug=True)
 
1
  import os
2
+
3
+ os.system("pip install pyyaml==5.1")
 
4
  # workaround: install old version of pytorch since detectron2 hasn't released packages for pytorch 1.9 (issue: https://github.com/facebookresearch/detectron2/issues/3158)
5
+ os.system(
6
+ "pip install torch==1.8.0+cu101 torchvision==0.9.0+cu101 -f https://download.pytorch.org/whl/torch_stable.html"
7
+ )
8
 
9
  # install detectron2 that matches pytorch 1.8
10
  # See https://detectron2.readthedocs.io/tutorials/install.html for instructions
11
+ os.system(
12
+ "pip install -q detectron2 -f https://dl.fbaipublicfiles.com/detectron2/wheels/cu101/torch1.8/index.html"
13
+ )
14
 
15
  ## install PyTesseract
16
+ os.system("pip install -q pytesseract")
17
 
18
  import gradio as gr
19
  import numpy as np
20
+ from transformers import LayoutLMv3Processor, LayoutLMv3ForTokenClassification
21
  from datasets import load_dataset
22
  from PIL import Image, ImageDraw, ImageFont
23
 
24
+ processor = LayoutLMv3Processor.from_pretrained("microsoft/layoutlmv3-base")
25
+ model = LayoutLMv3ForTokenClassification.from_pretrained(
26
+ "jinhybr/OCR-LayoutLMv3"
27
+ )
 
 
 
 
28
 
29
  # load image example
30
+ dataset = load_dataset("nielsr/funsd", split="test")
31
+ image = Image.open(dataset[0]["image_path"]).convert("RGB")
32
+ image = Image.open("./example_lm3.png")
33
+ image.save("document.png")
34
 
35
+ labels = dataset.features["ner_tags"].feature.names
 
36
  id2label = {v: k for v, k in enumerate(labels)}
37
+ label2color = {
38
+ "question": "blue",
39
+ "answer": "green",
40
+ "header": "orange",
41
+ "other": "violet",
42
+ }
 
 
 
 
 
 
 
 
43
 
44
 
45
  def unnormalize_box(bbox, width, height):
46
+ return [
47
+ width * (bbox[0] / 1000),
48
+ height * (bbox[1] / 1000),
49
+ width * (bbox[2] / 1000),
50
+ height * (bbox[3] / 1000),
51
+ ]
52
+
53
 
54
  def iob_to_label(label):
55
  label = label[2:]
56
  if not label:
57
+ return "other"
58
  return label
59
 
60
+
61
  def process_image(image):
62
  width, height = image.size
63
 
64
  # encode
65
+ encoding = processor(
66
+ image, truncation=True, return_offsets_mapping=True, return_tensors="pt"
67
+ )
68
+ offset_mapping = encoding.pop("offset_mapping")
69
 
70
  # forward pass
71
  outputs = model(**encoding)
 
75
  token_boxes = encoding.bbox.squeeze().tolist()
76
 
77
  # only keep non-subword predictions
78
+ is_subword = np.array(offset_mapping.squeeze().tolist())[:, 0] != 0
79
+ true_predictions = [
80
+ id2label[pred] for idx, pred in enumerate(predictions) if not is_subword[idx]
81
+ ]
82
+ true_boxes = [
83
+ unnormalize_box(box, width, height)
84
+ for idx, box in enumerate(token_boxes)
85
+ if not is_subword[idx]
86
+ ]
87
 
88
  # draw predictions over the image
89
  draw = ImageDraw.Draw(image)
 
91
  for prediction, box in zip(true_predictions, true_boxes):
92
  predicted_label = iob_to_label(prediction).lower()
93
  draw.rectangle(box, outline=label2color[predicted_label])
94
+ draw.text(
95
+ (box[0] + 10, box[1] - 10),
96
+ text=predicted_label,
97
+ fill=label2color[predicted_label],
98
+ font=font,
99
+ )
100
+
101
  return image
102
 
103
 
104
+ title = "Interactive demo: LayoutLMv3"
105
+ description = "Demo for Microsoft's LayoutLMv3, 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'."
106
+ article = "<p style='text-align: center'><a href='https://arxiv.org/abs/2204.08387' target='_blank'>LayoutLMv3: Pre-training for Document AI with Unified Text and Image Masking</a> | <a href='https://github.com/microsoft/unilm' target='_blank'>Github Repo</a></p>"
107
+ examples = [["document.png"]]
108
 
109
  css = ".output-image, .input-image {height: 40rem !important; width: 100% !important;}"
110
+ # css = "@media screen and (max-width: 600px) { .output_image, .input_image {height:20rem !important; width: 100% !important;} }"
111
  # css = ".output_image, .input_image {height: 600px !important}"
112
 
113
  css = ".image-preview {height: auto !important;}"
114
 
115
+ iface = gr.Interface(
116
+ fn=process_image,
117
+ inputs=gr.inputs.Image(type="pil"),
118
+ outputs=gr.outputs.Image(type="pil", label="annotated image"),
119
+ title=title,
120
+ description=description,
121
+ article=article,
122
+ examples=examples,
123
+ css=css,
124
+ enable_queue=True,
125
+ )
126
  iface.launch(debug=True)