jinhybr commited on
Commit
04e6a7b
1 Parent(s): 5fa47bf

Create handler.py

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