miteshkotak7 commited on
Commit
5a85bf7
·
verified ·
1 Parent(s): cefc335

Custom endpoint handler

Browse files

custom handler to revert label names from endpoint

Files changed (1) hide show
  1. handler.py +74 -0
handler.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, List, Any
2
+ from setfit import SetFitModel
3
+ import numpy as np
4
+
5
+
6
+ class EndpointHandler:
7
+ def __init__(self, path=""):
8
+ # load model
9
+ self.model = SetFitModel.from_pretrained(path)
10
+ def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
11
+ """
12
+ data args:
13
+ inputs (:obj: `str` | `PIL.Image` | `np.array`)
14
+ kwargs
15
+ Return:
16
+ A :obj:`list` | `dict`: will be serialized and returned
17
+ """
18
+
19
+ # get inputs
20
+ inputs = data.pop("inputs", data)
21
+ if isinstance(inputs, str):
22
+ inputs = [inputs]
23
+
24
+
25
+ exerciselabels = ['positive experience',
26
+ 'power posing',
27
+ 'worry vs rumination',
28
+ 'self-confidence',
29
+ 'negative emotions',
30
+ 'sleep',
31
+ 'loneliness',
32
+ 'imaginary friend',
33
+ 'perfectionism',
34
+ 'negative self-talk',
35
+ 'woop',
36
+ 'venting',
37
+ 'worry window',
38
+ 'act of kindness',
39
+ 'blowing balloons',
40
+ 'feeling on anger',
41
+ 'power of smile',
42
+ 'body scan',
43
+ 'stress enhancing thoughts',
44
+ 'anger ball of fire',
45
+ 'emotions',
46
+ 'lean against wall',
47
+ 'breathing',
48
+ 'crossed arms']
49
+
50
+ # run normal prediction
51
+ preds = self.model.predict(inputs)
52
+ scores = self.model.predict_proba(inputs)
53
+
54
+ label = [[el for el, p in zip(exerciselabels, ps) if p] for ps in preds]
55
+
56
+ # Modify the label array
57
+ modified_label = label[0]
58
+
59
+ # Extract the positives probabilities from each inner array
60
+ modified_proba = [[inner[0][1]] for item, inner in zip(scores, scores)]
61
+
62
+
63
+ score = [[el for el, p in zip(modified_proba, ps) if p] for ps in preds]
64
+
65
+ # Modify the score array
66
+ modified_score = score[0]
67
+
68
+
69
+ combined_dict = {key: value for key, value in zip(modified_label, modified_score)}
70
+
71
+ output_array = [combined_dict]
72
+
73
+ # for element in combined_array:
74
+ return output_array