florentgbelidji HF Staff commited on
Commit
20bd5b3
·
1 Parent(s): 1da1f10

Added handler for FUNSD example

Browse files
Files changed (1) hide show
  1. handler.py +46 -15
handler.py CHANGED
@@ -1,15 +1,25 @@
 
1
  from typing import Dict, List, Any
2
- from optimum.onnxruntime import ORTModelForSequenceClassification
 
3
  from transformers import pipeline, AutoTokenizer
4
 
5
 
6
  class EndpointHandler():
7
  def __init__(self, path=""):
8
- # load the optimized model
9
- model = ORTModelForSequenceClassification.from_pretrained(path)
10
- tokenizer = AutoTokenizer.from_pretrained(path)
11
- # create inference pipeline
12
- self.pipeline = pipeline("text-classification", model=model, tokenizer=tokenizer)
 
 
 
 
 
 
 
 
13
 
14
 
15
  def __call__(self, data: Any) -> List[List[Dict[str, float]]]:
@@ -22,13 +32,34 @@ class EndpointHandler():
22
  - "label": A string representing what the label/class is. There can be multiple labels.
23
  - "score": A score between 0 and 1 describing how confident the model is for this label/class.
24
  """
25
- inputs = data.pop("inputs", data)
26
- parameters = data.pop("parameters", None)
27
-
28
- # pass inputs with all kwargs in data
29
- if parameters is not None:
30
- prediction = self.pipeline(inputs, **parameters)
31
- else:
32
- prediction = self.pipeline(inputs)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  # postprocess the prediction
34
- return prediction
 
1
+ import numpy as np
2
  from typing import Dict, List, Any
3
+ from PIL import Image, ImageDraw, ImageFont
4
+ from transformers import LayoutLMv2Processor, LayoutLMv2ForTokenClassification
5
  from transformers import pipeline, AutoTokenizer
6
 
7
 
8
  class EndpointHandler():
9
  def __init__(self, path=""):
10
+ # load the processor and model
11
+
12
+ self.processor = LayoutLMv2Processor.from_pretrained("microsoft/layoutlmv2-base-uncased")
13
+ self.model = LayoutLMv2ForTokenClassification.from_pretrained("nielsr/layoutlmv2-finetuned-funsd")
14
+ self.id2label = {
15
+ 0: 'O',
16
+ 1: 'B-HEADER',
17
+ 2: 'I-HEADER',
18
+ 3: 'B-QUESTION',
19
+ 4: 'I-QUESTION',
20
+ 5: 'B-ANSWER',
21
+ 6: 'I-ANSWER'
22
+ }
23
 
24
 
25
  def __call__(self, data: Any) -> List[List[Dict[str, float]]]:
 
32
  - "label": A string representing what the label/class is. There can be multiple labels.
33
  - "score": A score between 0 and 1 describing how confident the model is for this label/class.
34
  """
35
+
36
+ def unnormalize_box(bbox, width, height):
37
+ return [
38
+ width * (bbox[0] / 1000),
39
+ height * (bbox[1] / 1000),
40
+ width * (bbox[2] / 1000),
41
+ height * (bbox[3] / 1000),
42
+ ]
43
+
44
+ image = data.pop("inputs", data)
45
+ # encode
46
+ encoding = self.processor(image, truncation=True, return_offsets_mapping=True, return_tensors="pt")
47
+ offset_mapping = encoding.pop('offset_mapping')
48
+
49
+ # forward pass
50
+ outputs = self.model(**encoding)
51
+
52
+ # get predictions
53
+ predictions = outputs.logits.argmax(-1).squeeze().tolist()
54
+ token_boxes = encoding.bbox.squeeze().tolist()
55
+
56
+ # only keep non-subword predictions
57
+ #is_subword = np.array(offset_mapping.squeeze().tolist())[:,0] != 0
58
+ width, height = image.size
59
+
60
+ true_predictions = [self.id2label[prediction] for prediction in predictions]
61
+ true_boxes = [unnormalize_box(box, width, height) for box in token_boxes]
62
+ is_subword = np.array(offset_mapping.squeeze().tolist())[:,0] != 0
63
+
64
  # postprocess the prediction
65
+ return {"labels": true_predictions, "boxes": true_boxes, "is_subword": is_subword}