ivan-wald commited on
Commit
34b2cc2
β€’
1 Parent(s): 57e77f6

Upload 7 files

Browse files
Files changed (7) hide show
  1. README.md +6 -5
  2. app.py +94 -0
  3. packages.txt +1 -0
  4. requirements.txt +13 -0
  5. test0.jpeg +0 -0
  6. test1.jpeg +0 -0
  7. test2.jpeg +0 -0
README.md CHANGED
@@ -1,12 +1,13 @@
1
  ---
2
- title: Layoutlmv3 Finetuned Cord Dataset
3
- emoji: πŸ‘€
4
- colorFrom: gray
5
- colorTo: red
6
  sdk: gradio
7
  sdk_version: 5.5.0
8
  app_file: app.py
9
  pinned: false
 
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Receipt Extractor
3
+ emoji: πŸ“Š
4
+ colorFrom: pink
5
+ colorTo: purple
6
  sdk: gradio
7
  sdk_version: 5.5.0
8
  app_file: app.py
9
  pinned: false
10
+ license: apache-2.0
11
  ---
12
 
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces#reference
app.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.system('git clone https://github.com/facebookresearch/detectron2.git')
3
+ os.system('pip install -e detectron2')
4
+ os.system("git clone https://github.com/microsoft/unilm.git")
5
+ os.system("sed -i 's/from collections import Iterable/from collections.abc import Iterable/' unilm/dit/object_detection/ditod/table_evaluation/data_structure.py")
6
+ os.system("curl -LJ -o publaynet_dit-b_cascade.pth 'https://layoutlm.blob.core.windows.net/dit/dit-fts/publaynet_dit-b_cascade.pth?sv=2022-11-02&ss=b&srt=o&sp=r&se=2033-06-08T16:48:15Z&st=2023-06-08T08:48:15Z&spr=https&sig=a9VXrihTzbWyVfaIDlIT1Z0FoR1073VB0RLQUMuudD4%3D'")
7
+
8
+ import sys
9
+ sys.path.append("unilm")
10
+ sys.path.append("detectron2")
11
+
12
+ ## install PyTesseract
13
+ os.system('pip install -q pytesseract')
14
+
15
+ import gradio as gr
16
+ import numpy as np
17
+ from transformers import LayoutLMv3Processor, LayoutLMv3ForTokenClassification
18
+ from datasets import load_dataset
19
+ from PIL import Image, ImageDraw, ImageFont, ImageColor
20
+
21
+ processor = LayoutLMv3Processor.from_pretrained("microsoft/layoutlmv3-base")
22
+ model = LayoutLMv3ForTokenClassification.from_pretrained("nielsr/layoutlmv3-finetuned-cord")
23
+
24
+ dataset = load_dataset("ivan-wald/cord-layoutlmv3", split="test", trust_remote_code=True)
25
+ image = Image.open("./test0.jpeg")
26
+ labels = dataset.features['ner_tags'].feature.names
27
+ id2label = {v: k for v, k in enumerate(labels)}
28
+
29
+ #Need to get discrete colors for each labels
30
+ label_ints = np.random.randint(0, len(ImageColor.colormap.items()), 61)
31
+ label_color_pil = [k for k,_ in ImageColor.colormap.items()]
32
+ label_color = [label_color_pil[i] for i in label_ints]
33
+ label2color = {}
34
+ for k,v in id2label.items():
35
+ label2color[v[2:]]=label_color[k]
36
+
37
+ def unnormalize_box(bbox, width, height):
38
+ return [
39
+ width * (bbox[0] / 1000),
40
+ height * (bbox[1] / 1000),
41
+ width * (bbox[2] / 1000),
42
+ height * (bbox[3] / 1000),
43
+ ]
44
+
45
+ def iob_to_label(label):
46
+ label = label[2:]
47
+ if not label:
48
+ return 'other'
49
+ return label
50
+
51
+ def process_image(image):
52
+ width, height = image.size
53
+
54
+ # encode
55
+ encoding = processor(image, truncation=True, return_offsets_mapping=True, return_tensors="pt")
56
+ offset_mapping = encoding.pop('offset_mapping')
57
+
58
+ # forward pass
59
+ outputs = model(**encoding)
60
+
61
+ # get predictions
62
+ predictions = outputs.logits.argmax(-1).squeeze().tolist()
63
+ token_boxes = encoding.bbox.squeeze().tolist()
64
+
65
+ # only keep non-subword predictions
66
+ is_subword = np.array(offset_mapping.squeeze().tolist())[:,0] != 0
67
+ true_predictions = [id2label[pred] for idx, pred in enumerate(predictions) if not is_subword[idx]]
68
+ true_boxes = [unnormalize_box(box, width, height) for idx, box in enumerate(token_boxes) if not is_subword[idx]]
69
+
70
+ # draw predictions over the image
71
+ draw = ImageDraw.Draw(image)
72
+ font = ImageFont.load_default()
73
+ for prediction, box in zip(true_predictions, true_boxes):
74
+ predicted_label = iob_to_label(prediction) #.lower()
75
+ draw.rectangle(box, outline=label2color[predicted_label])
76
+ draw.text((box[0]+10, box[1]-10), text=predicted_label, fill=label2color[predicted_label], font=font)
77
+
78
+ return image
79
+
80
+
81
+ title = "LayoutLMv3 - CORD"
82
+ description = "description"
83
+ article = "article"
84
+ examples =[['test0.jpeg'],['test1.jpeg'],['test2.jpeg']]
85
+ css = ".output-image, .input-image, .image-preview {height: 600px !important}"
86
+
87
+ iface = gr.Interface(fn=process_image,
88
+ inputs=gr.Image(type="pil"),
89
+ outputs=gr.Image(type="pil", label="annotated image"),
90
+ title=title,
91
+ examples=examples,
92
+ css=css)
93
+
94
+ iface.launch(debug=True)
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ tesseract-ocr
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ Pillow
3
+ datasets
4
+ https://github.com/huggingface/transformers/archive/main.zip
5
+ pyyaml==5.1
6
+ torch==1.11.0
7
+ torchvision==0.12.0
8
+
9
+ numpy<2
10
+ scipy
11
+ shapely
12
+ timm
13
+ opencv-python
test0.jpeg ADDED
test1.jpeg ADDED
test2.jpeg ADDED