import pickle import json import numpy as np import pandas as pd class ACPredictor: def __init__(self, model_path="ac_model.pkl"): with open(model_path, "rb") as f: self.model = pickle.load(f) self.features = [ 'month_tmax_mean', 'month_tmax_max', 'month_tmin', 'month_tmean', 'month_rh', 'month_precip', 'month_hi', 'month_hi_max', 'month_apparent_max', 'month_apparent_mean', 'month_days_above_30', 'month_days_above_32', 'month_days_hi_above_32', 'month' ] def predict(self, current_month_data): """ current_month_data: dict with monthly weather summary Returns: {'ac_needed': 0/1, 'confidence': float, 'reasoning': str} """ X = np.array([[current_month_data.get(f, 0) for f in self.features]]) pred = self.model.predict(X)[0] proba = self.model.predict_proba(X)[0] confidence = proba[pred] reasoning = [] if current_month_data.get('month_tmax_mean', 0) > 31: reasoning.append(f"High avg max temp: {current_month_data['month_tmax_mean']:.1f}C") if current_month_data.get('month_hi', 0) > 32: reasoning.append(f"High heat index: {current_month_data['month_hi']:.1f}C") if current_month_data.get('month_precip', 0) < 40: reasoning.append(f"Low rainfall: {current_month_data['month_precip']:.1f}mm") if current_month_data.get('month_days_above_30', 0) > 15: reasoning.append(f"Many hot days: {current_month_data['month_days_above_30']:.0f} days >30C") return { 'ac_needed': int(pred), 'confidence': float(confidence), 'reasoning': "; ".join(reasoning) if reasoning else "Moderate conditions", 'prob_no_ac': float(proba[0]), 'prob_ac': float(proba[1]) }