Spaces:
Sleeping
Sleeping
File size: 13,101 Bytes
9e472d3 2b92082 0355b55 6823e29 9e472d3 0355b55 9e472d3 711ac8e 0355b55 3a83600 0355b55 711ac8e 2b92082 711ac8e 0355b55 6823e29 0355b55 3a83600 0355b55 3a83600 0355b55 3a83600 0355b55 3a83600 0355b55 3a83600 0355b55 3a83600 0355b55 6823e29 3a83600 0355b55 711ac8e 5bdaec2 0355b55 711ac8e 0355b55 711ac8e 2b92082 9e472d3 0355b55 9e472d3 2b92082 9e472d3 0355b55 2b92082 9e472d3 2b92082 0355b55 711ac8e 9e472d3 0355b55 847316c 113b42d 2b92082 0355b55 847316c 6823e29 113b42d 6823e29 9e472d3 6823e29 9e472d3 711ac8e 5bdaec2 2b92082 3a83600 847316c 2b92082 6823e29 0355b55 6823e29 0355b55 2b92082 3a83600 0355b55 2b92082 847316c 3a83600 2b92082 6823e29 2b92082 0355b55 9b309b6 847316c 9b309b6 9e472d3 6823e29 0355b55 6823e29 2b92082 6823e29 2b92082 9e472d3 6823e29 9e472d3 3a83600 9e472d3 847316c 9e472d3 2b92082 847316c 7e1eb79 847316c 7e1eb79 847316c 2b92082 0355b55 847316c 0355b55 847316c 0355b55 847316c 2b92082 5bdaec2 0355b55 72eb3f5 3a83600 9b309b6 2b92082 0355b55 847316c 2b92082 72eb3f5 847316c 72eb3f5 6823e29 72eb3f5 6823e29 847316c 72eb3f5 5bdaec2 0355b55 6823e29 0355b55 6823e29 0355b55 72eb3f5 3a83600 72eb3f5 0355b55 2b92082 72eb3f5 6823e29 72eb3f5 2b92082 72eb3f5 3a83600 72eb3f5 0355b55 c4d989f 6823e29 c4d989f 2b92082 c4d989f 3a83600 c4d989f 6823e29 0355b55 c4d989f 9b309b6 2b92082 c4d989f 2b92082 c4d989f 9b309b6 c4d989f 2b92082 0355b55 2b92082 0355b55 2b92082 c4d989f 6823e29 c4d989f 2b92082 c4d989f 0355b55 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 |
import os
from typing import List, Optional, Dict
import re
import json
import torch
import nltk
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer, WordNetLemmatizer
from nltk.tokenize import word_tokenize
from textblob import TextBlob
# Download NLTK data
try:
nltk.data.find('tokenizers/punkt')
except LookupError:
nltk.download('punkt')
nltk.download('stopwords')
nltk.download('wordnet')
MODEL_ID = (
os.environ.get("MODEL_ID")
or os.environ.get("HF_MODEL_ID")
or "Perth0603/phishing-email-mobilebert"
)
app = FastAPI(title="Phishing Text Classifier with Preprocessing", version="1.0.0")
# ============================================================================
# TEXT PREPROCESSING CLASS
# ============================================================================
class TextPreprocessor:
"""NLP preprocessing for analysis and feature extraction"""
def __init__(self):
self.stemmer = PorterStemmer()
self.lemmatizer = WordNetLemmatizer()
self.stop_words = set(stopwords.words('english'))
def tokenize(self, text: str) -> List[str]:
"""Break text into tokens"""
return word_tokenize(text.lower())
def remove_stopwords(self, tokens: List[str]) -> List[str]:
"""Remove common stop words"""
return [token for token in tokens if token.isalnum() and token not in self.stop_words]
def stem(self, tokens: List[str]) -> List[str]:
"""Reduce tokens to stems"""
return [self.stemmer.stem(token) for token in tokens]
def lemmatize(self, tokens: List[str]) -> List[str]:
"""Reduce tokens to lemmas"""
return [self.lemmatizer.lemmatize(token) for token in tokens]
def sentiment_analysis(self, text: str) -> Dict:
"""Analyze sentiment and phishing indicators"""
blob = TextBlob(text)
polarity = blob.sentiment.polarity
subjectivity = blob.sentiment.subjectivity
phishing_indicators = {
"urgent_words": bool(re.search(r'\b(urgent|immediate|act now|verify|confirm|update|click|verify account)\b', text, re.IGNORECASE)),
"threat_words": bool(re.search(r'\b(suspend|limited|expire|locked|disabled|restricted)\b', text, re.IGNORECASE)),
"suspicious_urls": bool(re.search(r'http\S+|www\S+', text)),
"urgency_level": "HIGH" if re.search(r'\b(urgent|immediate|act now)\b', text, re.IGNORECASE) else "LOW"
}
return {
"polarity": round(polarity, 4),
"subjectivity": round(subjectivity, 4),
"sentiment": "positive" if polarity > 0.1 else "negative" if polarity < -0.1 else "neutral",
"is_persuasive": subjectivity > 0.5,
"phishing_indicators": phishing_indicators
}
def preprocess(self, text: str) -> Dict:
"""Preprocessing for analysis"""
tokens = self.tokenize(text)
tokens_no_stop = self.remove_stopwords(tokens)
stemmed = self.stem(tokens_no_stop)
lemmatized = self.lemmatize(tokens_no_stop)
sentiment = self.sentiment_analysis(text)
return {
"original_text": text,
"tokens": tokens,
"tokens_without_stopwords": tokens_no_stop,
"stemmed_tokens": stemmed,
"lemmatized_tokens": lemmatized,
"sentiment": sentiment,
"token_count": len(tokens_no_stop)
}
# ============================================================================
# PYDANTIC MODELS
# ============================================================================
class PredictPayload(BaseModel):
inputs: str
include_preprocessing: bool = True
class BatchPredictPayload(BaseModel):
inputs: List[str]
include_preprocessing: bool = True
class LabeledText(BaseModel):
text: str
label: Optional[str] = None
class EvalPayload(BaseModel):
samples: List[LabeledText]
# ============================================================================
# GLOBAL VARIABLES
# ============================================================================
_tokenizer = None
_model = None
_device = "cpu"
_preprocessor = None
_LABEL_MAPPING = None
# ============================================================================
# HELPER FUNCTIONS
# ============================================================================
def _get_label_mapping():
"""Get complete label mapping from model config"""
global _model
if _model is None:
return None
id2label = getattr(_model.config, "id2label", {}) or {}
num_labels = int(getattr(_model.config, "num_labels", 0) or 0)
print(f"[DEBUG] Raw id2label from config: {id2label}")
print(f"[DEBUG] num_labels: {num_labels}")
# Build complete mapping by index
complete_mapping = {}
for i in range(num_labels):
if str(i) in id2label:
complete_mapping[i] = id2label[str(i)]
elif i in id2label:
complete_mapping[i] = id2label[i]
else:
complete_mapping[i] = f"LABEL_{i}"
# If incomplete, use fallback
if len(complete_mapping) < num_labels:
print(f"[WARNING] Incomplete mapping! Using fallback.")
complete_mapping = {
0: "LEGIT",
1: "PHISH"
}
print(f"[DEBUG] Complete mapping applied: {complete_mapping}")
return complete_mapping
def _normalize_label(txt: str) -> str:
"""Normalize label text"""
t = (str(txt) if txt is not None else "").strip().upper()
if t in ("PHISHING", "PHISH", "SPAM", "1"):
return "PHISH"
if t in ("LEGIT", "LEGITIMATE", "SAFE", "HAM", "0"):
return "LEGIT"
return t
def _load_model():
"""Load model, tokenizer, and preprocessor"""
global _tokenizer, _model, _device, _preprocessor, _LABEL_MAPPING
if _tokenizer is None or _model is None:
_device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"\n{'='*60}")
print(f"Loading model on device: {_device}")
print(f"Model ID: {MODEL_ID}")
print(f"{'='*60}\n")
_tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
_model = AutoModelForSequenceClassification.from_pretrained(MODEL_ID)
_model.to(_device)
_model.eval()
_preprocessor = TextPreprocessor()
# Get label mapping
_LABEL_MAPPING = _get_label_mapping()
# Warm-up
with torch.no_grad():
_ = _model(
**_tokenizer(["warm up"], return_tensors="pt", padding=True, truncation=True, max_length=512)
.to(_device)
).logits
print(f"{'='*60}\n")
def _predict_texts(texts: List[str], include_preprocessing: bool = True) -> List[Dict]:
"""
Predict with correct label index mapping
CRITICAL: probs[i][j] where j is the CLASS INDEX, not probability value
"""
_load_model()
if not texts:
return []
# Get preprocessing info
preprocessing_info = None
if include_preprocessing:
preprocessing_info = [_preprocessor.preprocess(text) for text in texts]
# Tokenize
enc = _tokenizer(
texts,
return_tensors="pt",
padding=True,
truncation=True,
max_length=512,
)
enc = {k: v.to(_device) for k, v in enc.items()}
# Predict
with torch.no_grad():
logits = _model(**enc).logits
probs = torch.softmax(logits, dim=-1)
num_labels = probs.shape[-1]
print(f"\n[DEBUG] num_labels from probs shape: {num_labels}")
outputs: List[Dict] = []
for text_idx in range(probs.shape[0]):
p = probs[text_idx] # Get probabilities for this text: shape [num_labels]
# Create probability breakdown for ALL classes
prob_breakdown = {}
all_probs_list = []
for class_idx in range(num_labels):
class_prob = float(p[class_idx].item())
class_label = _LABEL_MAPPING.get(class_idx, f"CLASS_{class_idx}")
prob_breakdown[class_label] = round(class_prob, 4)
all_probs_list.append(class_prob)
print(f"[DEBUG] Class {class_idx} ({class_label}): {round(class_prob, 4)}")
# Get argmax index
predicted_idx = int(torch.argmax(p).item())
predicted_label_raw = _LABEL_MAPPING.get(predicted_idx, f"CLASS_{predicted_idx}")
predicted_label_norm = _normalize_label(predicted_label_raw)
predicted_prob = float(p[predicted_idx].item())
print(f"[DEBUG] ARGMAX: index={predicted_idx}, label={predicted_label_raw}, prob={round(predicted_prob, 4)}")
print(f"[DEBUG] Normalized label: {predicted_label_norm}")
output = {
"text": texts[text_idx][:100] + "..." if len(texts[text_idx]) > 100 else texts[text_idx],
"predicted_class_index": predicted_idx,
"label": predicted_label_norm,
"raw_label": predicted_label_raw,
"is_phish": predicted_label_norm == "PHISH",
"score": round(predicted_prob, 4),
"confidence": round(predicted_prob * 100, 2),
"probs_by_class": prob_breakdown,
"all_probs_raw": [round(p_val, 4) for p_val in all_probs_list],
}
if include_preprocessing and preprocessing_info:
output["preprocessing"] = preprocessing_info[text_idx]
outputs.append(output)
print(f"\n")
return outputs
# ============================================================================
# API ENDPOINTS
# ============================================================================
@app.get("/")
def root():
"""Root endpoint"""
_load_model()
return {
"status": "ok",
"model": MODEL_ID,
"device": _device,
"label_mapping": _LABEL_MAPPING,
}
@app.get("/debug/labels")
def debug_labels():
"""View complete model configuration"""
_load_model()
id2label_raw = getattr(_model.config, "id2label", {}) or {}
label2id_raw = getattr(_model.config, "label2id", {}) or {}
num_labels = int(getattr(_model.config, "num_labels", 0) or 0)
return {
"status": "ok",
"model_config_id2label": id2label_raw,
"model_config_label2id": label2id_raw,
"model_config_num_labels": num_labels,
"applied_mapping": _LABEL_MAPPING,
"device": _device,
"note": "applied_mapping is what gets used for predictions"
}
@app.post("/debug/preprocessing")
def debug_preprocessing(payload: PredictPayload):
"""Debug preprocessing"""
try:
_load_model()
preprocessing = _preprocessor.preprocess(payload.inputs)
return {
"status": "ok",
"preprocessing": preprocessing
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error: {e}")
@app.post("/predict")
def predict(payload: PredictPayload):
"""Single prediction"""
try:
res = _predict_texts([payload.inputs], include_preprocessing=payload.include_preprocessing)
return res[0]
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error: {e}")
@app.post("/predict-batch")
def predict_batch(payload: BatchPredictPayload):
"""Batch predictions"""
try:
return _predict_texts(payload.inputs, include_preprocessing=payload.include_preprocessing)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error: {e}")
@app.post("/evaluate")
def evaluate(payload: EvalPayload):
"""Evaluate on labeled samples"""
try:
texts = [s.text for s in payload.samples]
gts = [(_normalize_label(s.label) if s.label is not None else None) for s in payload.samples]
preds = _predict_texts(texts, include_preprocessing=False)
total = len(preds)
correct = 0
per_class: Dict[str, Dict[str, int]] = {}
for gt, pr in zip(gts, preds):
pred_label = pr["label"]
if gt is not None:
correct += int(gt == pred_label)
per_class.setdefault(gt, {"tp": 0, "count": 0})
per_class[gt]["count"] += 1
if gt == pred_label:
per_class[gt]["tp"] += 1
has_gts = any(gt is not None for gt in gts)
acc = (correct / sum(1 for gt in gts if gt is not None)) if has_gts else None
return {
"accuracy": round(acc, 4) if acc else None,
"total": total,
"correct": correct,
"predictions": preds,
"per_class": per_class,
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error: {e}")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) |