Create handler.py
Browse files- handler.py +44 -0
handler.py
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import pipeline
|
2 |
+
import torch
|
3 |
+
from typing import Dict, Any
|
4 |
+
|
5 |
+
class EndpointHandler:
|
6 |
+
def __init__(self, path=""):
|
7 |
+
device = 0 if torch.cuda.is_available() else -1
|
8 |
+
torch_d_type = torch.float16 if torch.cuda.is_available() else torch.float32
|
9 |
+
|
10 |
+
self.classifier = pipeline(
|
11 |
+
task="text-classification",
|
12 |
+
model="abullard1/albert-v2-steam-review-constructiveness-classifier",
|
13 |
+
tokenizer="albert-base-v2",
|
14 |
+
device=device,
|
15 |
+
top_k=None,
|
16 |
+
truncation=True,
|
17 |
+
max_length=512,
|
18 |
+
torch_dtype=torch_d_type
|
19 |
+
)
|
20 |
+
|
21 |
+
def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
|
22 |
+
input_text = data.get("inputs", "")
|
23 |
+
|
24 |
+
results = self.classifier(input_text)
|
25 |
+
|
26 |
+
label_1, score_1 = results[0][0]["label"], results[0][0]["score"]
|
27 |
+
label_2, score_2 = results[0][1]["label"], results[0][1]["score"]
|
28 |
+
|
29 |
+
return {
|
30 |
+
"label_1": label_1,
|
31 |
+
"score_1": score_1,
|
32 |
+
"label_2": label_2,
|
33 |
+
"score_2": score_2,
|
34 |
+
"prediction_text": self.format_prediction_text(label_1, score_1, label_2, score_2)
|
35 |
+
}
|
36 |
+
|
37 |
+
def format_prediction_text(self, label_1, score_1, label_2, score_2) -> str:
|
38 |
+
def label_to_constructiveness(label):
|
39 |
+
return "Constructive" if label == "LABEL_1" else "Not Constructive"
|
40 |
+
|
41 |
+
if score_1 >= score_2:
|
42 |
+
return f"{label_to_constructiveness(label_1)} with a score of {score_1:.2f}. 👍🏻"
|
43 |
+
else:
|
44 |
+
return f"{label_to_constructiveness(label_2)} with a score of {score_2:.2f}. 👎🏻"
|