jinhybr commited on
Commit
09d37f1
1 Parent(s): 90fa1cc

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +62 -0
handler.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any
2
+ from transformers import LayoutLMForTokenClassification, LayoutLMv2Processor
3
+ import torch
4
+ from subprocess import run
5
+
6
+ # install tesseract-ocr and pytesseract
7
+ run("apt install -y tesseract-ocr", shell=True, check=True)
8
+ run("pip install pytesseract", shell=True, check=True)
9
+
10
+ # helper function to unnormalize bboxes for drawing onto the image
11
+ def unnormalize_box(bbox, width, height):
12
+ return [
13
+ width * (bbox[0] / 1000),
14
+ height * (bbox[1] / 1000),
15
+ width * (bbox[2] / 1000),
16
+ height * (bbox[3] / 1000),
17
+ ]
18
+
19
+ # set device
20
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
21
+
22
+ class EndpointHandler:
23
+ def __init__(self, path=""):
24
+ # load model and processor from path
25
+ self.model = LayoutLMForTokenClassification.from_pretrained(path).to(device)
26
+ self.processor = LayoutLMv2Processor.from_pretrained(path)
27
+
28
+ def __call__(self, data: Dict[str, bytes]) -> Dict[str, List[Any]]:
29
+ """
30
+ Args:
31
+ data (:obj:):
32
+ includes the deserialized image file as PIL.Image
33
+ """
34
+ # process input
35
+ image = data.pop("inputs", data)
36
+
37
+ # process image
38
+ encoding = self.processor(image, return_tensors="pt")
39
+
40
+ # run prediction
41
+ with torch.inference_mode():
42
+ outputs = self.model(
43
+ input_ids=encoding.input_ids.to(device),
44
+ bbox=encoding.bbox.to(device),
45
+ attention_mask=encoding.attention_mask.to(device),
46
+ token_type_ids=encoding.token_type_ids.to(device),
47
+ )
48
+ predictions = outputs.logits.softmax(-1)
49
+
50
+ # post process output
51
+ result = []
52
+ for item, inp_ids, bbox in zip(
53
+ predictions.squeeze(0).cpu(), encoding.input_ids.squeeze(0).cpu(), encoding.bbox.squeeze(0).cpu()
54
+ ):
55
+ label = self.model.config.id2label[int(item.argmax().cpu())]
56
+ if label == "O":
57
+ continue
58
+ score = item.max().item()
59
+ text = self.processor.tokenizer.decode(inp_ids)
60
+ bbox = unnormalize_box(bbox.tolist(), image.width, image.height)
61
+ result.append({"label": label, "score": score, "text": text, "bbox": bbox})
62
+ return {"predictions": result}