File size: 7,727 Bytes
34b2632 | 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 | """
Logging & Monitoring Module
Author: AI Generated
Created: 2025-11-24
Purpose: Track pipeline performance, errors, and model drift
"""
import logging
from datetime import datetime
from typing import Dict, Any, Optional
import json
from pathlib import Path
import numpy as np
from database import db
# Configure logging
LOG_DIR = Path("logs")
LOG_DIR.mkdir(exist_ok=True)
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(LOG_DIR / 'pipeline.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
class PipelineMonitor:
"""
Monitor AI pipeline performance and log metrics.
"""
def __init__(self):
self.metrics_collection = "PipelineMetrics"
def log_segmentation_run(self, metrics: Dict[str, Any]):
"""
Log segmentation pipeline metrics.
Metrics should include:
- n_users: Number of users processed
- n_segments: Number of segments created
- inertia: K-means inertia
- execution_time: Time in seconds
- outliers_removed: Count
"""
logger.info(f"Segmentation Run: {metrics}")
# Save to MongoDB for trend analysis
doc = {
"pipeline": "segmentation",
"timestamp": datetime.utcnow(),
"metrics": metrics
}
db.get_collection(self.metrics_collection).insert_one(doc)
def log_sentiment_run(self, metrics: Dict[str, Any]):
"""
Log sentiment analysis metrics.
Metrics should include:
- n_comments: Number of comments analyzed
- sentiment_distribution: {Positive: X, Negative: Y, Neutral: Z}
- avg_confidence: Average confidence score
- execution_time: Time in seconds
"""
logger.info(f"Sentiment Analysis Run: {metrics}")
doc = {
"pipeline": "sentiment",
"timestamp": datetime.utcnow(),
"metrics": metrics
}
db.get_collection(self.metrics_collection).insert_one(doc)
def log_genai_run(self, task: str, metrics: Dict[str, Any]):
"""
Log Generative AI metrics.
Metrics should include:
- n_generated: Number of items generated
- avg_generation_time: Average time per item
- total_time: Total execution time
"""
logger.info(f"GenAI Run ({task}): {metrics}")
doc = {
"pipeline": "genai",
"task": task,
"timestamp": datetime.utcnow(),
"metrics": metrics
}
db.get_collection(self.metrics_collection).insert_one(doc)
def log_error(self, pipeline: str, error: Exception, context: Dict = None):
"""
Log pipeline errors.
"""
logger.error(f"Error in {pipeline}: {str(error)}", exc_info=True)
doc = {
"pipeline": pipeline,
"timestamp": datetime.utcnow(),
"error": str(error),
"error_type": type(error).__name__,
"context": context or {}
}
db.get_collection("PipelineErrors").insert_one(doc)
def detect_drift_segmentation(self, current_centroids: np.ndarray) -> Dict:
"""
Detect drift in K-means clustering.
Compare current centroids with previous run.
"""
# Fetch last run's centroids
last_metric = db.get_collection(self.metrics_collection).find_one(
{"pipeline": "segmentation"},
sort=[("timestamp", -1)]
)
if not last_metric or "centroids" not in last_metric["metrics"]:
logger.info("No previous centroids found for drift detection")
return {"drift_detected": False, "reason": "no_baseline"}
# Calculate drift as Euclidean distance between centroids
prev_centroids = np.array(last_metric["metrics"]["centroids"])
if prev_centroids.shape != current_centroids.shape:
return {"drift_detected": True, "reason": "shape_mismatch"}
# Calculate average distance
distances = np.linalg.norm(current_centroids - prev_centroids, axis=1)
avg_drift = float(np.mean(distances))
max_drift = float(np.max(distances))
# Threshold: if average drift > 0.5 std, flag as drift
drift_detected = avg_drift > 0.5
result = {
"drift_detected": drift_detected,
"avg_drift": avg_drift,
"max_drift": max_drift,
"threshold": 0.5
}
if drift_detected:
logger.warning(f"⚠️ Cluster drift detected: avg={avg_drift:.3f}, max={max_drift:.3f}")
return result
def detect_drift_sentiment(self, current_distribution: Dict[str, int]) -> Dict:
"""
Detect drift in sentiment distribution.
"""
# Fetch last run's distribution
last_metric = db.get_collection(self.metrics_collection).find_one(
{"pipeline": "sentiment"},
sort=[("timestamp", -1)]
)
if not last_metric:
return {"drift_detected": False, "reason": "no_baseline"}
prev_dist = last_metric["metrics"].get("sentiment_distribution", {})
# Calculate total counts
prev_total = sum(prev_dist.values())
curr_total = sum(current_distribution.values())
if prev_total == 0 or curr_total == 0:
return {"drift_detected": False, "reason": "insufficient_data"}
# Calculate percentage change for each sentiment
changes = {}
for label in ["Positive", "Negative", "Neutral"]:
prev_pct = prev_dist.get(label, 0) / prev_total
curr_pct = current_distribution.get(label, 0) / curr_total
changes[label] = abs(curr_pct - prev_pct)
# Drift if any sentiment changes > 10%
max_change = max(changes.values())
drift_detected = max_change > 0.1
result = {
"drift_detected": drift_detected,
"changes": changes,
"max_change": max_change,
"threshold": 0.1
}
if drift_detected:
logger.warning(f"⚠️ Sentiment drift detected: max_change={max_change:.1%}")
return result
def get_performance_summary(self, pipeline: str, days: int = 7) -> Dict:
"""
Get performance summary for the last N days.
"""
from datetime import timedelta
cutoff = datetime.utcnow() - timedelta(days=days)
metrics = list(db.get_collection(self.metrics_collection).find({
"pipeline": pipeline,
"timestamp": {"$gte": cutoff}
}).sort("timestamp", -1))
if not metrics:
return {"error": "No metrics found"}
# Aggregate
total_runs = len(metrics)
avg_time = np.mean([m["metrics"].get("execution_time", 0) for m in metrics])
return {
"pipeline": pipeline,
"period_days": days,
"total_runs": total_runs,
"avg_execution_time": avg_time,
"last_run": metrics[0]["timestamp"]
}
# Global monitor instance
monitor = PipelineMonitor()
|