gregojoh commited on
Commit
9690de1
1 Parent(s): 0250447
Files changed (2) hide show
  1. app.py +122 -0
  2. requirements.txt +6 -0
app.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import pandas as pd
3
+ import plotly.express as px
4
+ import streamlit as st
5
+
6
+ import torch
7
+ import torch.nn.functional as F
8
+ from easyocr import Reader
9
+ from PIL import Image
10
+ from torch.utils.data import Dataset, DataLoader
11
+
12
+ from transformers import (
13
+ LayoutLMv3FeatureExtractor,
14
+ LayoutLMv3TokenizerFast,
15
+ LayoutLMv3Processor,
16
+ LayoutLMv3ForSequenceClassification
17
+ )
18
+
19
+ DEVICE = "cuda:0" if torch.cuda.is_available() else "cpu"
20
+ MICROSOFT_MODEL_NAME = "microsoft/layoutlmv3-base"
21
+ MODEL_NAME = "curiousily/layoutlmv3-financial-document-classification"
22
+
23
+ def creat_bounding_box(bbox_data, width_scale: float, height_scale: float):
24
+ xs = []
25
+ ys = []
26
+ for x, y in bbox_data:
27
+ xs.append(x)
28
+ ys.append(y)
29
+
30
+ left = int(min(xs) * width_scale)
31
+ top = int(min(ys) * height_scale)
32
+ right = int(max(xs) * width_scale)
33
+ bottom = int(max(ys) * height_scale)
34
+
35
+ return [left, top, right, bottom]
36
+
37
+ @st.experimental_singleton
38
+ def create_ocr_reader():
39
+ return Reader(["en"])
40
+
41
+ @st.experimental_singleton
42
+ def create_processor():
43
+ feature_extractor = LayoutLMv3FeatureExtractor(apply_ocr=False)
44
+ tokenizer = LayoutLMv3TokenizerFast.from_pretrained(MICROSOFT_MODEL_NAME)
45
+ return LayoutLMv3Processor(feature_extractor, tokenizer)
46
+
47
+ @st.experimental_singleton
48
+ def create_model():
49
+ model = LayoutLMv3ForSequenceClassification.from_pretrained(MODEL_NAME)
50
+ return model.eval().to(DEVICE)
51
+
52
+ def predict(
53
+ image: Image,
54
+ reader: Reader,
55
+ processor: LayoutLMv3Processor,
56
+ model: LayoutLMv3ForSequenceClassification
57
+ ):
58
+
59
+ ocr_result = reader.readtext(image)
60
+
61
+ width, height = image.size
62
+ width_scale = 1000 / width
63
+ height_scale = 1000 / height
64
+
65
+ words = []
66
+ boxes = []
67
+
68
+ for bbox, word, confidence in ocr_result:
69
+ words.append(word)
70
+ boxes.append(creat_bounding_box(bbox, width_scale, height_scale))
71
+
72
+ encoding = processor(
73
+ image,
74
+ words,
75
+ boxes=boxes,
76
+ max_length=512,
77
+ padding="max_length",
78
+ truncation=True,
79
+ return_tensors="pt"
80
+ )
81
+
82
+ with torch.inference_mode():
83
+ output = model(
84
+ input_ids=encoding["input_ids"].to(DEVICE),
85
+ attention_mask=encoding["attention_mask"].to(DEVICE),
86
+ bbox=encoding["bbox"].to(DEVICE),
87
+ pixel_values=encoding["pixel_values"].to(DEVICE),
88
+ )
89
+
90
+ logits = output.logits
91
+ predicted_class = logits.argmax()
92
+ probabilities = F.softmax(logits, dim=-1).flatten().tolist()
93
+
94
+ return predicted_class.detach().item(), probabilities
95
+
96
+
97
+ reader = create_ocr_reader()
98
+ processor = create_processor()
99
+ model = create_model()
100
+
101
+ uploaded_file = st.file_uploader("Upload Document Image", ["jpg", "png"])
102
+ if uploaded_file is not None:
103
+ bytes_data = io.BytesIO(uploaded_file.getvalue())
104
+ image = Image.open(bytes_data)
105
+ st.image(image, "Your Document")
106
+
107
+ predicted_class, probabilities = predict(image, reader, processor, model)
108
+ predicted_label = model.config.id2label[predicted_class]
109
+
110
+ st.markdown(f"Predicted document type: **{predicted_label}**")
111
+
112
+ df_predictions = pd.DataFrame(
113
+ {"Document": list(model.config.id2label.values()), "Confidence": probabilities}
114
+ )
115
+
116
+ fig = px.bar(df_predictions, x="Document", y="Confidence")
117
+ st.plotly_chart(fig, use_container_width=True)
118
+
119
+
120
+
121
+
122
+
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ easyocr==1.6.2
2
+ pandas==1.5.3
3
+ Pillow==9.4.0
4
+ plotly-express==0.4.1
5
+ torch==1.13.1
6
+ transformers==4.25.1