munzirmuneer commited on
Commit
fdad04a
·
verified ·
1 Parent(s): 7234735

Update handler.py

Browse files
Files changed (1) hide show
  1. 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
- # Load model and tokenizer
9
- model_name = "munzirmuneer/phishing_url_gemma_pytorch" # Replace with your specific model
10
- model_name2 = "google/gemma-2b"
11
- tokenizer = AutoTokenizer.from_pretrained(model_name2)
12
- model = AutoModelForSequenceClassification.from_pretrained(model_name)
13
- model = PeftModel.from_pretrained(model, model_name)
 
 
 
 
 
 
14
 
15
- def predict(input_text):
16
- # Tokenize input
17
- inputs = tokenizer(input_text, return_tensors="pt", truncation=True, padding=True)
18
-
19
- # Run inference
20
- with torch.no_grad():
21
- outputs = model(**inputs)
22
-
23
- # Get logits and probabilities
24
- logits = outputs.logits
25
- probs = F.softmax(logits, dim=-1)
26
-
27
- # Get the predicted class (highest probability)
28
- pred_class = torch.argmax(probs, dim=-1)
29
- return pred_class.item(), probs[0].tolist()
 
 
 
 
 
 
 
 
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
+ }