Christian2903 commited on
Commit
399efb5
·
1 Parent(s): c9f16a3

Create handler.py

Browse files
Files changed (1) hide show
  1. handler.py +29 -0
handler.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
2
+ from transformers import DataCollatorWithPadding
3
+ from torch.nn.functional import softmax
4
+
5
+ import torch
6
+ from typing import Any, Dict, List
7
+
8
+
9
+ class EndpointHandler:
10
+ def __init__(self, path=""):
11
+ self.tokenizer = AutoTokenizer.from_pretrained(path)
12
+ self.model = AutoModelForSequenceClassification.from_pretrained(path)
13
+
14
+ def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
15
+ batch_of_strings = data["inputs"]
16
+
17
+ tokens = self.tokenizer(
18
+ batch_of_strings, padding=True, truncation=True, return_tensors="pt"
19
+ )
20
+
21
+ # Calculate the loss
22
+ with torch.no_grad():
23
+ outputs = self.model(**tokens)
24
+
25
+ probabilities = softmax(outputs.logits, dim=1)
26
+
27
+ return {
28
+ "predictions": [pred[0] for pred in probabilities.tolist()],
29
+ }