Msp Raja commited on
Commit
3dab771
β€’
1 Parent(s): 6670c2d

initial commit

Browse files
Files changed (6) hide show
  1. .DS_Store +0 -0
  2. README.md +27 -7
  3. app.py +96 -0
  4. invoice.png +0 -0
  5. packages.txt +0 -0
  6. requirements.txt +6 -0
.DS_Store ADDED
Binary file (6.15 kB). View file
 
README.md CHANGED
@@ -1,13 +1,33 @@
1
  ---
2
- title: Funsd Layoutlm V2 Pretrained
3
- emoji: πŸ“š
4
- colorFrom: indigo
5
- colorTo: indigo
6
  sdk: gradio
7
- sdk_version: 3.0.24
8
  app_file: app.py
9
  pinned: false
10
- license: afl-3.0
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: LayoutLMv 2 FUNSD
3
+ emoji: 🐨
4
+ colorFrom: purple
5
+ colorTo: green
6
  sdk: gradio
 
7
  app_file: app.py
8
  pinned: false
 
9
  ---
10
 
11
+ # Configuration
12
+
13
+ `title`: _string_
14
+ Display title for the Space
15
+
16
+ `emoji`: _string_
17
+ Space emoji (emoji-only character allowed)
18
+
19
+ `colorFrom`: _string_
20
+ Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
21
+
22
+ `colorTo`: _string_
23
+ Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
24
+
25
+ `sdk`: _string_
26
+ Can be either `gradio` or `streamlit`
27
+
28
+ `app_file`: _string_
29
+ Path to your main application file (which contains either `gradio` or `streamlit` Python code).
30
+ Path is relative to the root of the repository.
31
+
32
+ `pinned`: _boolean_
33
+ Whether the Space stays on top of your list.
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)
invoice.png ADDED
packages.txt ADDED
File without changes
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio
2
+ Pillow
3
+ numpy
4
+ datasets
5
+ torch
6
+ transformers