menimeni123
commited on
Commit
•
c48a85b
1
Parent(s):
180d0f0
latest
Browse files- handler.py +23 -23
handler.py
CHANGED
@@ -1,30 +1,30 @@
|
|
1 |
-
from transformers import
|
2 |
import torch
|
3 |
-
import joblib
|
4 |
|
5 |
-
class
|
6 |
-
def __init__(self,
|
7 |
-
|
8 |
-
self.
|
|
|
9 |
|
10 |
-
def
|
11 |
-
return
|
12 |
|
13 |
-
def
|
14 |
-
|
15 |
-
|
16 |
-
|
|
|
17 |
with torch.no_grad():
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
predicted_label = self.label_mapping[predicted_class]
|
25 |
-
confidence = torch.softmax(logits, dim=1)[0][predicted_class].item()
|
26 |
|
27 |
-
return {
|
28 |
-
|
29 |
-
|
30 |
-
|
|
|
1 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
2 |
import torch
|
|
|
3 |
|
4 |
+
class EndpointHandler:
|
5 |
+
def __init__(self, model_dir):
|
6 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_dir)
|
7 |
+
self.model = AutoModelForSequenceClassification.from_pretrained(model_dir)
|
8 |
+
self.label_mapping = {0: "SAFE", 1: "JAILBREAK", 2: "INJECTION", 3: "PHISHING"}
|
9 |
|
10 |
+
def __call__(self, inputs):
|
11 |
+
return self.predict(inputs)
|
12 |
|
13 |
+
def predict(self, inputs):
|
14 |
+
# Tokenize the input
|
15 |
+
encoded_input = self.tokenizer(inputs, return_tensors='pt', truncation=True, padding=True)
|
16 |
+
|
17 |
+
# Make prediction
|
18 |
with torch.no_grad():
|
19 |
+
output = self.model(**encoded_input)
|
20 |
+
|
21 |
+
# Get the predicted class
|
22 |
+
predicted_class = torch.argmax(output.logits, dim=1).item()
|
23 |
+
|
24 |
+
# Map the predicted class to its label
|
25 |
predicted_label = self.label_mapping[predicted_class]
|
|
|
26 |
|
27 |
+
return {"label": predicted_label, "score": output.logits.softmax(dim=1).max().item()}
|
28 |
+
|
29 |
+
def get_pipeline():
|
30 |
+
return EndpointHandler
|