import re import time import torch from dataclasses import dataclass, field from datetime import datetime from transformers import BertTokenizerFast, BertForSequenceClassification LABELS = {0: "Legitimate", 1: "Phishing"} DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") @dataclass class DetectionResult: label: str label_id: int confidence: float latency_ms: float prediction_timestamp: str = field( default_factory=lambda: datetime.now().strftime("%Y-%m-%d %H:%M:%S") ) log_id: int = None def to_dict(self): return { "label": self.label, "label_id": self.label_id, "confidence": self.confidence, "latency_ms": self.latency_ms, "prediction_timestamp": self.prediction_timestamp, "log_id": self.log_id, } class DetectionModel: MAX_LEN = 128 def __init__(self, model_path: str): self.model_path = model_path self._tokenizer = None self._model = None def _load(self): if self._model is None: # model_path can be a local directory or a HuggingFace Hub model ID (e.g. "YingEng1031/phishdetect-bert") self._tokenizer = BertTokenizerFast.from_pretrained(self.model_path) self._model = BertForSequenceClassification.from_pretrained(self.model_path) self._model.to(DEVICE) self._model.eval() def clean_for_bert(self, text: str) -> str: # Matches training exactly: lowercase, no HTML/URLs/non-ASCII — punctuation and stop words kept if not text or not isinstance(text, str): return "" text = text.lower() text = re.sub(r'<[^>]+>', ' ', text) text = re.sub(r'http\S+|www\.\S+', ' ', text) text = re.sub(r'[^\x20-\x7E]', ' ', text) text = re.sub(r'\s+', ' ', text).strip() return text def predict(self, text: str) -> DetectionResult: self._load() cleaned = self.clean_for_bert(text) encoding = self._tokenizer( cleaned, max_length=self.MAX_LEN, padding="max_length", truncation=True, return_tensors="pt" ) input_ids = encoding["input_ids"].to(DEVICE) attention_mask = encoding["attention_mask"].to(DEVICE) token_type_ids = encoding["token_type_ids"].to(DEVICE) t0 = time.time() with torch.no_grad(): outputs = self._model( input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids ) latency_ms = (time.time() - t0) * 1000 logits = outputs.logits probs = torch.softmax(logits, dim=1).squeeze() label_id = torch.argmax(probs).item() confidence = probs[label_id].item() return DetectionResult( label=LABELS[label_id], label_id=label_id, confidence=round(confidence * 100, 1), latency_ms=round(latency_ms, 3) )