Commit
·
bb8f1a5
1
Parent(s):
472f99b
add custom handler
Browse files- handler.py +37 -0
- requirements.txt +9 -0
handler.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import io
|
2 |
+
from typing import Dict, List, Any
|
3 |
+
from transformers import LayoutLMv3ForSequenceClassification, LayoutLMv3FeatureExtractor, LayoutLMv3Tokenizer, LayoutLMv3Processor
|
4 |
+
import torch
|
5 |
+
from subprocess import run
|
6 |
+
from PIL import Image
|
7 |
+
|
8 |
+
# install tesseract-ocr and pytesseract
|
9 |
+
run("apt install -y tesseract-ocr", shell=True, check=True)
|
10 |
+
run("python -m pip install detectron2 -f https://dl.fbaipublicfiles.com/detectron2/wheels/cpu/torch1.10/index.html", shell=True, check=True)
|
11 |
+
|
12 |
+
# set device
|
13 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
14 |
+
|
15 |
+
|
16 |
+
class EndpointHandler:
|
17 |
+
def __init__(self, path=""):
|
18 |
+
# load model and processor from path
|
19 |
+
self.FEATURE_EXTRACTOR = LayoutLMv3FeatureExtractor()
|
20 |
+
self.TOKENIZER = LayoutLMv3Tokenizer.from_pretrained("microsoft/layoutlmv3-base")
|
21 |
+
self.PROCESSOR = LayoutLMv3Processor(self.FEATURE_EXTRACTOR, self.TOKENIZER)
|
22 |
+
self.MODEL = LayoutLMv3ForSequenceClassification.from_pretrained("OtraBoi/document_classifier_testing").to(device)
|
23 |
+
|
24 |
+
def __call__(self, data: bytes):
|
25 |
+
image = Image.open(io.BytesIO(data)).convert("RGB")
|
26 |
+
encoding = self.PROCESSOR(image, return_tensors="pt", padding="max_length", truncation=True)
|
27 |
+
|
28 |
+
for k,v in encoding.items():
|
29 |
+
encoding[k] = v.to(self.MODEL.device)
|
30 |
+
|
31 |
+
# run prediction
|
32 |
+
with torch.inference_mode():
|
33 |
+
outputs = self.MODEL(**encoding)
|
34 |
+
logits = outputs.logits
|
35 |
+
predicted_class_idx = logits.argmax(-1).item()
|
36 |
+
|
37 |
+
return self.MODEL.config.id2label[predicted_class_idx]
|
requirements.txt
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
-f https://download.pytorch.org/whl/torch_stable.html
|
2 |
+
Pillow==9.3.0
|
3 |
+
PyMuPDF==1.20.2
|
4 |
+
pytesseract==0.3.10
|
5 |
+
torch==1.10.2+cu113
|
6 |
+
torchvision==0.11.3+cu113
|
7 |
+
transformers==4.25.1
|
8 |
+
optimum[onnxruntime]
|
9 |
+
wandb
|