import pandas as pd from pathlib import Path from typing import Dict, List, Any, Optional import time from loguru import logger from tqdm import tqdm from email_spam_classifier.modeling.predict import SpamPredictor from api.core.config import settings from api.core.exceptions import ModelLoadException, PredictionException class SpamClassifierService: """Service for spam classification with alert levels""" # Alert level thresholds based on spam probability - FIXED ALERT_THRESHOLDS = { 'LOW': 0.4, # 0.0 - 0.4: Low risk (less than 40% spam probability) 'MEDIUM': 0.6, # 0.4 - 0.6: Medium risk 'HIGH': 0.8, # 0.6 - 0.8: High risk 'SEVERE': 1.0 # 0.8 - 1.0: Severe risk (80%+ spam probability) } def __init__(self, model_path: Optional[Path] = None, batch_size: int = 100, cache_predictions: bool = True, cache_size: int = 1000): """ Initialize the spam classifier service Args: model_path: Optional custom path to the model file batch_size: Batch size for batch predictions cache_predictions: Whether to cache predictions cache_size: Size of prediction cache """ self.model_path = model_path or settings.MODEL_PATH self.batch_size = batch_size self.cache_predictions = cache_predictions self.cache_size = cache_size self.predictor = None self.is_initialized = False self.initialize_predictor() def initialize_predictor(self) -> None: """Initialize the SpamPredictor with advanced options""" try: logger.info(f"Initializing spam predictor with model at {self.model_path}") self.predictor = SpamPredictor( model_path=self.model_path, batch_size=self.batch_size, cache_predictions=self.cache_predictions, cache_size=self.cache_size ) self.is_initialized = True logger.success("Spam predictor initialized successfully") except Exception as e: logger.error(f"Failed to initialize spam predictor: {str(e)}") self.is_initialized = False raise ModelLoadException(f"Failed to load model: {str(e)}") def _get_alert_level(self, spam_probability: float) -> str: """ Determine alert level based on spam probability - FIXED LOGIC Args: spam_probability: Probability that message is spam (0.0 - 1.0) Returns: Alert level: LOW, MEDIUM, HIGH, or SEVERE """ if spam_probability < self.ALERT_THRESHOLDS['LOW']: # < 0.4 (40%) return 'LOW' elif spam_probability < self.ALERT_THRESHOLDS['MEDIUM']: # 0.4 - 0.6 (40-60%) return 'MEDIUM' elif spam_probability < self.ALERT_THRESHOLDS['HIGH']: # 0.6 - 0.8 (60-80%) return 'HIGH' else: # >= 0.8 (80%+) return 'SEVERE' def _enhance_prediction_result(self, result: Dict[str, Any]) -> Dict[str, Any]: """ Enhance prediction result with alert level and additional metadata Args: result: Basic prediction result from SpamPredictor Returns: Enhanced result with alert level and metadata """ spam_probability = result['spam_probability'] alert_level = self._get_alert_level(spam_probability) enhanced_result = { **result, 'alert_level': alert_level, 'confidence_score': max(spam_probability, 1 - spam_probability), 'risk_description': self._get_risk_description(alert_level), 'timestamp': time.time() } return enhanced_result def _get_risk_description(self, alert_level: str) -> str: """Get human-readable risk description for alert level - UPDATED""" descriptions = { 'LOW': 'Low risk - spam probability less than 40%, likely legitimate message', 'MEDIUM': 'Medium risk - spam probability 40-60%, requires review', 'HIGH': 'High risk - spam probability 60-80%, likely spam, recommend blocking', 'SEVERE': 'Severe risk - spam probability 80%+, almost certainly spam, block immediately' } return descriptions.get(alert_level, 'Unknown risk level') def check_model_health(self) -> Dict[str, Any]: """Check if the model is healthy with enhanced diagnostics""" status = { "is_ready": self.is_initialized and self.predictor is not None, "model_path": str(self.model_path), "loaded": self.predictor is not None, "batch_size": self.batch_size, "cache_enabled": self.cache_predictions } # If model is loaded, perform a test prediction if status["is_ready"]: try: # Test with both ham and spam-like messages test_ham = "This is a normal test message" test_spam = "URGENT! Click here to claim your prize NOW!" ham_result = self.predict_single(test_ham) spam_result = self.predict_single(test_spam) status["test_prediction"] = "successful" status["test_results"] = { "ham_test": { "classification": ham_result["classification"], "alert_level": ham_result["alert_level"] }, "spam_test": { "classification": spam_result["classification"], "alert_level": spam_result["alert_level"] } } status["last_checked"] = time.time() except Exception as e: status["is_ready"] = False status["test_prediction"] = f"failed: {str(e)}" return status def predict_single(self, text: str) -> Dict[str, Any]: """ Predict if a single message is spam or not with alert levels Args: text: Message text to classify Returns: Dictionary with enhanced prediction results including alert level """ if not self.is_initialized or self.predictor is None: self.initialize_predictor() try: # Use the enhanced SpamPredictor result = self.predictor.predict_single(text) # Enhance with alert level and metadata enhanced_result = self._enhance_prediction_result(result) return enhanced_result except Exception as e: logger.error(f"Prediction error: {str(e)}") raise PredictionException(f"Failed to make prediction: {str(e)}") def predict_batch(self, texts: List[str], parallel: bool = False, max_workers: int = 4) -> pd.DataFrame: """ Predict for a batch of texts with enhanced options Args: texts: List of message texts to classify parallel: Whether to use parallel processing max_workers: Number of workers for parallel processing Returns: DataFrame with enhanced prediction results including alert levels """ if not self.is_initialized or self.predictor is None: self.initialize_predictor() try: # Choose prediction method based on parameters if parallel and len(texts) > 50: # Use parallel for larger batches logger.info(f"Using parallel prediction with {max_workers} workers") results_df = self.predictor.predict_parallel(texts, max_workers=max_workers) else: logger.info(f"Using batch prediction with batch size {self.batch_size}") results_df = self.predictor.predict_batch(texts) # Add alert levels and enhanced metadata results_df['alert_level'] = results_df['spam_probability'].apply(self._get_alert_level) results_df['confidence_score'] = results_df['spam_probability'].apply( lambda x: max(x, 1 - x) ) results_df['risk_description'] = results_df['alert_level'].apply(self._get_risk_description) results_df['timestamp'] = time.time() return results_df except Exception as e: logger.error(f"Batch prediction error: {str(e)}") raise PredictionException(f"Failed to make batch prediction: {str(e)}") def get_batch_summary(self, results_df: pd.DataFrame) -> Dict[str, Any]: """ Generate summary statistics for batch predictions Args: results_df: DataFrame with prediction results Returns: Dictionary with summary statistics """ total = len(results_df) spam_count = results_df['is_spam'].sum() ham_count = total - spam_count # Alert level distribution alert_distribution = results_df['alert_level'].value_counts().to_dict() summary = { 'total': total, 'spam_count': spam_count, 'ham_count': ham_count, 'spam_percentage': f"{(spam_count/total*100):.1f}%" if total > 0 else "0%", 'alert_distribution': alert_distribution, 'high_risk_count': alert_distribution.get('HIGH', 0) + alert_distribution.get('SEVERE', 0), 'average_spam_probability': results_df['spam_probability'].mean(), 'timestamp': time.time() } return summary def log_prediction(self, text: str, result: Dict[str, Any]) -> None: """ Log a prediction with enhanced information Args: text: The predicted text result: Enhanced prediction result """ # Truncate text for logging truncated_text = text[:30] + "..." if len(text) > 30 else text classification = result["classification"] probability = result["spam_probability"] alert_level = result["alert_level"] logger.info( f"Prediction: '{truncated_text}' classified as {classification} " f"(probability: {probability:.4f}, alert: {alert_level})" ) def log_batch_processing(self, summary: Dict[str, Any]) -> None: """ Log batch processing summary with enhanced metrics Args: summary: Enhanced batch processing summary """ alert_dist = summary['alert_distribution'] logger.info( f"Batch processing complete: {summary['total']} messages processed, " f"{summary['spam_count']} spam ({summary['spam_percentage']}), " f"{summary['ham_count']} ham. " f"Alert levels - LOW: {alert_dist.get('LOW', 0)}, " f"MEDIUM: {alert_dist.get('MEDIUM', 0)}, " f"HIGH: {alert_dist.get('HIGH', 0)}, " f"SEVERE: {alert_dist.get('SEVERE', 0)}" ) def get_alert_statistics(self, results_df: pd.DataFrame) -> Dict[str, Any]: """ Get detailed statistics about alert levels Args: results_df: DataFrame with prediction results Returns: Dictionary with alert level statistics """ alert_stats = {} for level in ['LOW', 'MEDIUM', 'HIGH', 'SEVERE']: level_data = results_df[results_df['alert_level'] == level] alert_stats[level] = { 'count': len(level_data), 'percentage': f"{(len(level_data)/len(results_df)*100):.1f}%" if len(results_df) > 0 else "0%", 'avg_probability': level_data['spam_probability'].mean() if len(level_data) > 0 else 0.0, 'min_probability': level_data['spam_probability'].min() if len(level_data) > 0 else 0.0, 'max_probability': level_data['spam_probability'].max() if len(level_data) > 0 else 0.0 } return alert_stats