menimeni123 commited on
Commit
c48a85b
1 Parent(s): 180d0f0
Files changed (1) hide show
  1. handler.py +23 -23
handler.py CHANGED
@@ -1,30 +1,30 @@
1
- from transformers import Pipeline
2
  import torch
3
- import joblib
4
 
5
- class CustomPipeline(Pipeline):
6
- def __init__(self, model, tokenizer, device=-1, **kwargs):
7
- super().__init__(model=model, tokenizer=tokenizer, device=device, **kwargs)
8
- self.label_mapping = joblib.load("label_mapping.joblib")
 
9
 
10
- def _sanitize_parameters(self, **kwargs):
11
- return {}, {}, {}
12
 
13
- def preprocess(self, inputs):
14
- return self.tokenizer(inputs, return_tensors="pt", truncation=True, padding=True, max_length=512)
15
-
16
- def _forward(self, model_inputs):
 
17
  with torch.no_grad():
18
- outputs = self.model(**model_inputs)
19
- return outputs
20
-
21
- def postprocess(self, model_outputs):
22
- logits = model_outputs.logits
23
- predicted_class = torch.argmax(logits, dim=1).item()
24
  predicted_label = self.label_mapping[predicted_class]
25
- confidence = torch.softmax(logits, dim=1)[0][predicted_class].item()
26
 
27
- return {
28
- "label": predicted_label,
29
- "score": confidence
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