Update handler.py
Browse files- handler.py +34 -22
handler.py
CHANGED
@@ -1,29 +1,41 @@
|
|
1 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
2 |
import torch
|
3 |
-
from huggingface_hub import HfApi
|
4 |
import torch.nn.functional as F
|
5 |
from peft import PeftModel
|
6 |
|
7 |
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
tokenizer
|
12 |
-
|
13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
-
def
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
2 |
import torch
|
|
|
3 |
import torch.nn.functional as F
|
4 |
from peft import PeftModel
|
5 |
|
6 |
|
7 |
+
class EndpointHandler:
|
8 |
+
def __init__(self, model_dir):
|
9 |
+
"""
|
10 |
+
Initialize the model and tokenizer using the provided model directory.
|
11 |
+
"""
|
12 |
+
model_name = "munzirmuneer/phishing_url_gemma_pytorch" # Replace with your specific model
|
13 |
+
model_name2 = "google/gemma-2b"
|
14 |
+
|
15 |
+
# Load tokenizer and model
|
16 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_name2)
|
17 |
+
base_model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
18 |
+
self.model = PeftModel.from_pretrained(base_model, model_name)
|
19 |
|
20 |
+
def __call__(self, input_text):
|
21 |
+
"""
|
22 |
+
Perform inference on the input text and return predictions.
|
23 |
+
"""
|
24 |
+
# Tokenize input
|
25 |
+
inputs = self.tokenizer(input_text, return_tensors="pt", truncation=True, padding=True)
|
26 |
+
|
27 |
+
# Run inference
|
28 |
+
with torch.no_grad():
|
29 |
+
outputs = self.model(**inputs)
|
30 |
+
|
31 |
+
# Get logits and probabilities
|
32 |
+
logits = outputs.logits
|
33 |
+
probs = F.softmax(logits, dim=-1)
|
34 |
+
|
35 |
+
# Get the predicted class (highest probability)
|
36 |
+
pred_class = torch.argmax(probs, dim=-1)
|
37 |
+
|
38 |
+
return {
|
39 |
+
"predicted_class": pred_class.item(),
|
40 |
+
"probabilities": probs[0].tolist()
|
41 |
+
}
|