BIproject / app.py
Asembris
cluster pred5
e4fba33
Raw History Blame Contribute Delete
73.4 kB
from fastapi import FastAPI, HTTPException import joblib import numpy as np import pandas as pd from pydantic import BaseModel from typing import Optional, Union, List, Dict import os import pickle import time from datetime import datetime from sklearn.pipeline import Pipeline from sklearn.compose import ColumnTransformer from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler, OneHotEncoder # Prometheus metrics from prometheus_fastapi_instrumentator import Instrumentator from prometheus_client import Counter, Histogram, Gauge # === SQLAlchemy for Supabase Persistence === from sqlalchemy import create_engine, text from sqlalchemy.pool import QueuePool # === OpenAI for Explainable AI === from openai import OpenAI # ================================================= # DATABASE CONFIGURATION # ================================================= # Get the connection string from environment variable (set in Hugging Face Secrets) DATABASE_URL = os.environ.get("DATABASE_URL") # Create the engine only if DATABASE_URL is set db_engine = None if DATABASE_URL: try: db_engine = create_engine( DATABASE_URL, poolclass=QueuePool, pool_size=5, max_overflow=10, pool_timeout=30, pool_recycle=1800 # Recycle connections every 30 minutes ) print("✓ Database engine created successfully") except Exception as e: print(f"✗ Failed to create database engine: {e}") else: print("⚠ DATABASE_URL not set. Logging will be disabled.") # ================================================= app = FastAPI( title="Charity Prediction API", description="Predict employee_class, income_other_sources, donation_range, gross_income, and income_donations using ML models" ) # Initialize Prometheus instrumentator (adds /metrics endpoint automatically) instrumentator = Instrumentator( should_group_status_codes=False, should_ignore_untemplated=True, should_instrument_requests_inprogress=True, excluded_handlers=["/metrics"], inprogress_labels=True, ) # Instrument the app and expose /metrics endpoint (must be done at module level, not in startup) instrumentator.instrument(app).expose(app, endpoint="/metrics") # Custom ML metrics ml_predictions_total = Counter( "ml_predictions_total", "Total number of ML predictions", ["model_name", "model_type", "status"] ) ml_prediction_latency = Histogram( "ml_prediction_latency_seconds", "ML prediction latency in seconds", ["model_name", "model_type"], buckets=[0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0] ) ml_models_loaded = Gauge( "ml_models_loaded_total", "Number of ML models currently loaded" ) # ================================================= # NEW: Database-Backed Logging Function # ================================================= def log_prediction(model_name: str, model_type: str, latency: float, status: str, result: str = None): """Log a prediction to Supabase database""" if db_engine is None: return # Silently skip if no DB configured try: with db_engine.connect() as conn: conn.execute( text(""" INSERT INTO monitoring_logs (model_name, model_type, latency_ms, status, result) VALUES (:model_name, :model_type, :latency_ms, :status, :result) """), { "model_name": model_name, "model_type": model_type, "latency_ms": round(latency * 1000, 2), "status": status, "result": result[:500] if result else None # Truncate long results } ) conn.commit() except Exception as e: print(f"DB Log Error: {e}") # Don't crash prediction on logging failure # ================================================= # Store loaded models and preprocessing objects # ================================================= models = {} label_encoders = None scaler = None seif_preprocessor = None stacking_base_models = {} stacking_meta_learner = None kmeans_pipeline = None # KMeans clustering pipeline # ================================================= # OpenAI Client for XAI # ================================================= OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY") openai_client = None if OPENAI_API_KEY: try: openai_client = OpenAI(api_key=OPENAI_API_KEY) print("✓ OpenAI client initialized for XAI") except Exception as e: print(f"✗ Failed to initialize OpenAI client: {e}") else: print("⚠ OPENAI_API_KEY not set. XAI explanations will be disabled.") # ================================================= # XAI Helper Functions # ================================================= # ================================================= # XAI Helper Functions # ================================================= def get_feature_importance(model, feature_names: list, features_df: pd.DataFrame, top_k: int = 5) -> List[Dict]: """ Calculate feature importance using model's built-in feature_importances_ or coefficients. For KMeans, calculates alignment with cluster centroid (SHAP-like heuristic). Returns top K features with their importance scores. """ try: # 1. Handle KMeans Pipeline specifically is_kmeans = False kmeans_model = None scaler_step = None if hasattr(model, 'named_steps'): if 'kmeans' in model.named_steps: is_kmeans = True kmeans_model = model.named_steps['kmeans'] scaler_step = model.named_steps.get('scaler') # Assuming standard scaler elif 'model' in model.named_steps and hasattr(model.named_steps['model'], 'cluster_centers_'): is_kmeans = True kmeans_model = model.named_steps['model'] scaler_step = model.named_steps.get('scaler') if is_kmeans and kmeans_model: # KMeans "Feature Importance" = Contribution to cluster assignment # Heuristic: (x_scaled * cluster_center_scaled) # This measures how much the feature pulls the point towards the centroid # Predict cluster to know which centroid to compare against # (Note: features_df passed here is just 1 row usually) # First transform input if scaler exists X_input = features_df.values if scaler_step: X_scaled = scaler_step.transform(features_df) else: X_scaled = X_input cluster_idx = kmeans_model.predict(X_scaled)[0] center = kmeans_model.cluster_centers_[cluster_idx] # Calculate alignment score: value * center_value (works well for StandardScaler data) # High +ve means this feature value strongly matches the cluster characteristic importances = X_scaled[0] * center # Match lengths importances = importances[:len(feature_names)] feature_values = features_df.iloc[0].to_dict() importance_list = [] for i in range(len(feature_names)): if i >= len(importances): break name = feature_names[i] imp = float(importances[i]) val = list(feature_values.values())[i] importance_list.append({ "feature": name, "importance": imp, "value": val }) # Sort by absolute importance (magnitude of contribution) importance_list.sort(key=lambda x: abs(x["importance"]), reverse=True) return importance_list[:top_k] # 2. Handle Standard Supervised Models (Tree/Linear) # Handle sklearn Pipeline - extract the actual model actual_model = model if hasattr(model, 'named_steps'): for step_name in ['model', 'classifier', 'regressor', 'estimator', 'xgboost']: if step_name in model.named_steps: actual_model = model.named_steps[step_name] break else: actual_model = model.steps[-1][1] # Get feature importances if hasattr(actual_model, 'feature_importances_'): importances = actual_model.feature_importances_ elif hasattr(actual_model, 'coef_'): importances = np.abs(actual_model.coef_).flatten() else: return [] feature_values = features_df.iloc[0].to_dict() min_len = min(len(feature_names), len(importances)) importance_list = [] for i in range(min_len): name = feature_names[i] imp = importances[i] if i < len(importances) else 0 val = list(feature_values.values())[i] if i < len(feature_values) else 0 importance_list.append({ "feature": name, "importance": float(imp), "value": float(val) if isinstance(val, (int, float, np.number)) else str(val) }) importance_list.sort(key=lambda x: x["importance"], reverse=True) return importance_list[:top_k] except Exception as e: print(f"Feature importance error: {e}") return [] def generate_explanation(prediction: str, model_type: str, target_name: str, top_features: List[Dict], language: str = "fr") -> str: """ Generate a natural language explanation using GPT-4o-mini. """ if not openai_client or not top_features: return None try: features_text = "\n".join([ f"- {f['feature']}: {f['value']} (significance: {f['importance']:.3f})" for f in top_features ]) lang_instruction = "Réponds en français." if language == "fr" else "Respond in English." # Customize prompt for Clustering if "cluster" in model_type.lower() or "kmeans" in model_type.lower(): prompt = f"""You are a data analyst helper. KMeans Clustering Classification: {prediction} Data Context: French Non-profit Associations Key characteristic factors for this assignment: {features_text} {lang_instruction} Explain why this association falls into this cluster based on the factors above. Keep it simple, concise (2-3 sentences), and professional. Avoid technical jargon like 'centroid' or 'dot product'.""" else: # Standard prompt for regression/classification prompt = f"""Tu es un assistant d'analyse de données. Un modèle ML ({model_type}) a prédit: {prediction} Cible: {target_name} Les facteurs influents: {features_text} {lang_instruction} Explique cette prédiction en 2-3 phrases simples pour un manager non-technique.""" response = openai_client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": prompt}], max_tokens=200, temperature=0.7 ) return response.choices[0].message.content.strip() except Exception as e: print(f"XAI explanation error: {e}") return None # ================================================= # Clustering Schema # ================================================= class ClusteringInput(BaseModel): latitude: float longitude: float age_association: float delay_declaration: float code_officiel_commune: str code_officiel_departement: str code_officiel_region: str obj1_family_c: str has_obj2: int est_active: int dirigeant_type: str @app.post("/clustering/predict") def predict_cluster(data: ClusteringInput): """ Predict the cluster for a new association (requires all 11 features). """ if kmeans_pipeline is None: raise HTTPException(status_code=503, detail="Clustering model not loaded") try: # Prepare input features matching training data names exactly # Encoding mappings family_map = {"sports": 0, "culture": 1, "social": 2, "education": 3} dirigeant_map = {"personne_physique": 0, "personne_morale": 1} def safe_int(val): try: return int(val) except: return 0 features = pd.DataFrame([{ "latitude": float(data.latitude), "longitude": float(data.longitude), "age_association": float(data.age_association), "delay_declaration": float(data.delay_declaration), "Code Officiel Commune Siège": safe_int(data.code_officiel_commune), "Code Officiel Département": safe_int(data.code_officiel_departement), "Code Officiel EPCI": safe_int(data.code_officiel_region), "obj1_family_clean": family_map.get(data.obj1_family_c, 0), "has_obj2": int(data.has_obj2), "est_active": int(data.est_active), "dirigeant_type_bin": dirigeant_map.get(data.dirigeant_type, 0) }]) # Predict cluster cluster = int(kmeans_pipeline.predict(features)[0]) cluster_label = "Cluster A" if cluster == 0 else "Cluster B" # Generate XAI Explanation feature_names = features.columns.tolist() top_features = get_feature_importance(kmeans_pipeline, feature_names, features, top_k=5) explanation = generate_explanation( prediction=cluster_label, model_type="KMeans Clustering", target_name="Cluster Assignment", top_features=top_features ) return { "predicted_cluster": cluster, "cluster_label": cluster_label, "message": f"Cette association appartient au {cluster_label}", "top_features": top_features, "explanation": explanation } except Exception as e: raise HTTPException(status_code=400, detail=f"Prediction error: {str(e)}") # ================================================= # Pydantic Schemas (UNCHANGED from original) # ================================================= class ClassificationInput(BaseModel): surplus_deficit: float cash_at_hand: float start_season: str end_season: str gross_income_schools: float gross_expenditure_schools: float volunteer_class_reduced: str income_government: float income_other_public_bodies: float income_philanthropic_orgs: float income_donations: float income_trading_commercial: float income_other_sources: float income_bequests: float gross_income: float gross_expenditure: float other_assets: float total_assets: float net_assets_liabilities: float total_liabilities: float arts_culture: int charity_sector_support: int community_development: int education_youth: int environment_animals: int health_welfare: int international_aid: int poverty_housing: int religion: int class RegressionInput(BaseModel): surplus_deficit: float cash_at_hand: float start_season: str end_season: str gross_income_schools: float gross_expenditure_schools: float volunteer_class_reduced: str number_employees_class_reduced: str income_government: float income_other_public_bodies: float income_philanthropic_orgs: float income_donations: float income_trading_commercial: float income_bequests: float gross_income: float gross_expenditure: float other_assets: float total_assets: float net_assets_liabilities: float total_liabilities: float arts_culture: int charity_sector_support: int community_development: int education_youth: int environment_animals: int health_welfare: int international_aid: int poverty_housing: int religion: int class BinaryClassificationInput(BaseModel): surplus_deficit: float cash_at_hand: float start_season: int end_season: int gross_income_schools: float gross_expenditure_schools: float volunteer_class_reduced: int number_employees_class_reduced: int income_government: float income_other_public_bodies: float income_philanthropic_orgs: float income_trading_commercial: float income_other_sources: float income_bequests: float gross_income: float gross_expenditure: float other_assets: float total_assets: float net_assets_liabilities: float total_liabilities: float arts_culture: int charity_sector_support: int community_development: int education_youth: int environment_animals: int health_welfare: int international_aid: int poverty_housing: int religion: int class FeatureImportance(BaseModel): feature: str importance: float value: Union[float, str] class ClassificationOutput(BaseModel): model: str predicted_class: str prediction_confidence: Optional[float] = None all_probabilities: Optional[dict] = None top_features: Optional[List[FeatureImportance]] = None explanation: Optional[str] = None class RegressionOutput(BaseModel): model: str predicted_value: float target_name: str top_features: Optional[List[FeatureImportance]] = None explanation: Optional[str] = None class XGBoostInput(BaseModel): surplus_deficit: float cash_at_hand: float start_season: str end_season: str gross_income_schools: float gross_expenditure_schools: float volunteer_class_reduced: str number_employees_class_reduced: str income_government: float income_other_public_bodies: float income_philanthropic_orgs: float income_donations: float income_trading_commercial: float income_other_sources: float income_bequests: float gross_expenditure: float other_assets: float total_assets: float net_assets_liabilities: float total_liabilities: float arts_culture: int charity_sector_support: int community_development: int education_youth: int environment_animals: int health_welfare: int international_aid: int poverty_housing: int religion: int class SeifInput(BaseModel): surplus_deficit: float cash_at_hand: float start_season: str end_season: str gross_income_schools: float gross_expenditure_schools: float volunteer_class_reduced: str number_employees_class_reduced: str income_government: float income_other_public_bodies: float income_philanthropic_orgs: float income_trading_commercial: float income_other_sources: float income_bequests: float gross_income: float gross_expenditure: float other_assets: float total_assets: float net_assets_liabilities: float total_liabilities: float arts_culture: int charity_sector_support: int community_development: int education_youth: int environment_animals: int health_welfare: int international_aid: int poverty_housing: int religion: int class StackingInput(BaseModel): surplus_deficit: float cash_at_hand: float start_season: int end_season: int gross_income_schools: float gross_expenditure_schools: float number_employees_class_reduced: int income_government: float income_other_public_bodies: float income_philanthropic_orgs: float income_donations: float income_trading_commercial: float income_other_sources: float income_bequests: float gross_income: float gross_expenditure: float other_assets: float total_assets: float net_assets_liabilities: float total_liabilities: float arts_culture: int charity_sector_support: int community_development: int education_youth: int environment_animals: int health_welfare: int international_aid: int poverty_housing: int religion: int class ClusteringInput(BaseModel): """Input features for KMeans clustering prediction.""" latitude: float longitude: float age_association: float delay_declaration: float code_officiel_commune: str code_officiel_departement: str code_officiel_region: str obj1_family_c: str has_obj2: int est_active: int dirigeant_type: str # ================================================= # Load models at startup (UNCHANGED) # ================================================= @app.on_event("startup") async def load_models(): global label_encoders, scaler model_files = { "randomforest": {"file": "models/yassine.pkl", "type": "classification"}, "regression_other_sources": {"file": "models/omar.pkl", "type": "regression"}, "donation_range": {"file": "models/adam.pkl", "type": "binary_classification"}, "xgboost_gross_income": {"file": "models/xgb_model.pkl", "type": "xgboost_regression"}, "xgboost_donations": {"file": "models/seif.pkl", "type": "xgboost_donations"}, "stacking_volunteer": {"file": "models/stacking_lr.pkl", "type": "stacking"}, } for model_name, model_info in model_files.items(): model_file = model_info["file"] if os.path.exists(model_file): try: models[model_name] = { "model": joblib.load(model_file), "type": model_info["type"] } print(f"✓ Loaded {model_name} ({model_info['type']}) from {model_file}") except Exception as e: print(f"✗ Failed to load {model_name}: {e}") else: print(f"⚠ Model file {model_file} not found") if os.path.exists("models/label_encoders.pkl"): try: with open("models/label_encoders.pkl", "rb") as f: label_encoders = pickle.load(f) print(f"✓ Loaded label_encoders.pkl with {len(label_encoders)} encoders") except Exception as e: print(f"✗ Failed to load label_encoders: {e}") if os.path.exists("models/scaler.pkl"): try: with open("models/scaler.pkl", "rb") as f: scaler = pickle.load(f) print(f"✓ Loaded scaler.pkl (StandardScaler)") except Exception as e: print(f"✗ Failed to load scaler: {e}") global stacking_base_models, stacking_meta_learner stacking_base_files = { "xgb_single": "models/xgb_single_model0.pkl", "knn_optionA": "models/knn_optiona.pkl", "knn_tuned": "models/knn_tuned.pkl", "adaboost_weighted": "models/adaboost_weighted.pkl", } for base_name, base_file in stacking_base_files.items(): if os.path.exists(base_file): try: stacking_base_models[base_name] = joblib.load(base_file) print(f"✓ Loaded stacking base model: {base_name}") except Exception as e: print(f"✗ Failed to load stacking base {base_name}: {e}") else: print(f"⚠ Stacking base model {base_file} not found") if "stacking_volunteer" in models: stacking_meta_learner = models["stacking_volunteer"]["model"] print(f"✓ Stacking meta-learner ready with {len(stacking_base_models)} base models") # Load KMeans clustering pipeline global kmeans_pipeline kmeans_file = "models/kmeans_pipeline.joblib" if os.path.exists(kmeans_file): try: kmeans_pipeline = joblib.load(kmeans_file) print(f"✓ Loaded KMeans clustering pipeline") except Exception as e: print(f"✗ Failed to load KMeans pipeline: {e}") kmeans_pipeline = None else: print(f"⚠ KMeans pipeline {kmeans_file} not found") kmeans_pipeline = None ml_models_loaded.set(len(models) + len(stacking_base_models) + (1 if kmeans_pipeline else 0)) print(f"✓ Prometheus metrics enabled at /metrics") # ================================================= # API Endpoints # ================================================= @app.get("/") def read_root(): model_info = {name: info["type"] for name, info in models.items()} return { "message": "Charity Prediction API is running", "available_models": model_info, "total_models": len(models), "database_connected": db_engine is not None, "classification_models": [k for k, v in models.items() if v["type"] == "classification"], "binary_classification_models": [k for k, v in models.items() if v["type"] == "binary_classification"], "regression_models": [k for k, v in models.items() if v["type"] == "regression"], "xgboost_models": [k for k, v in models.items() if v["type"] in ["xgboost_regression", "xgboost_donations"]], "stacking_models": [k for k, v in models.items() if v["type"] == "stacking"], "stacking_base_models_loaded": list(stacking_base_models.keys()) } @app.get("/models") def list_models(): return {"models": {name: info["type"] for name, info in models.items()}} # ================================================= # NEW: Database-Backed /stats Endpoint # ================================================= @app.get("/stats") def get_stats(): """Get prediction statistics from database""" if db_engine is None: return { "total_predictions": 0, "total_errors": 0, "avg_latency_ms": 0, "by_model": [], "models_loaded": len(models), "database_connected": False } try: with db_engine.connect() as conn: # Aggregate stats result = conn.execute(text(""" SELECT COUNT(*) as total, SUM(CASE WHEN status = 'error' THEN 1 ELSE 0 END) as errors, AVG(latency_ms) as avg_latency FROM monitoring_logs """)) row = result.fetchone() total = row[0] or 0 errors = row[1] or 0 avg_latency = row[2] or 0 # Per-model stats model_result = conn.execute(text(""" SELECT model_name, COUNT(*) as predictions, SUM(CASE WHEN status = 'error' THEN 1 ELSE 0 END) as errors, AVG(latency_ms) as avg_latency FROM monitoring_logs GROUP BY model_name ORDER BY predictions DESC """)) by_model = [] for row in model_result: by_model.append({ "model": row[0], "predictions": row[1], "errors": row[2] or 0, "avg_latency_ms": round(row[3] or 0, 2) }) return { "total_predictions": total, "total_errors": errors, "avg_latency_ms": round(avg_latency, 2), "by_model": by_model, "models_loaded": len(models), "database_connected": True } except Exception as e: return { "total_predictions": 0, "total_errors": 0, "avg_latency_ms": 0, "by_model": [], "models_loaded": len(models), "database_connected": False, "error": str(e) } # ================================================= # NEW: Database-Backed /logs Endpoint # ================================================= @app.get("/logs") def get_logs(limit: int = 20): """Get recent prediction logs from database""" if db_engine is None: return {"logs": [], "total_in_memory": 0, "database_connected": False} try: with db_engine.connect() as conn: result = conn.execute(text(""" SELECT timestamp, model_name, model_type, latency_ms, status, result FROM monitoring_logs ORDER BY timestamp DESC LIMIT :limit """), {"limit": limit}) logs = [] for row in result: logs.append({ "timestamp": row[0].isoformat() if row[0] else None, "model_name": row[1], "model_type": row[2], "latency_ms": row[3], "status": row[4], "result": row[5] }) # Get total count count_result = conn.execute(text("SELECT COUNT(*) FROM monitoring_logs")) total = count_result.fetchone()[0] return { "logs": logs, "total_in_memory": total, "database_connected": True } except Exception as e: return {"logs": [], "total_in_memory": 0, "database_connected": False, "error": str(e)} # ================================================= # Feature Preparation Functions (UNCHANGED) # ================================================= def prepare_classification_features(data: ClassificationInput) -> pd.DataFrame: features = { 'Surplus / (Deficit) for the Period': data.surplus_deficit, 'Cash at Hand and in Bank': data.cash_at_hand, 'start_season': data.start_season, 'end_season': data.end_season, 'Gross Income (Schools) class': data.gross_income_schools, 'Gross Expenditure (Schools) class': data.gross_expenditure_schools, 'volunteer_class_reduced': data.volunteer_class_reduced, 'Income: Government or Local Authorities_log': data.income_government, 'Income: Other Public Bodies_log': data.income_other_public_bodies, 'Income: Philantrophic Organisations_log': data.income_philanthropic_orgs, 'Income: Donations_log': data.income_donations, 'Income: Trading and Commercial Activities_log': data.income_trading_commercial, 'Income: Other Sources_log': data.income_other_sources, 'Income: Bequests_log': data.income_bequests, 'Gross Income_log': data.gross_income, 'Gross Expenditure_log': data.gross_expenditure, 'Other Assets_log': data.other_assets, 'Total Assets_log': data.total_assets, 'Net Assets / (Liabilities)_log': data.net_assets_liabilities, 'Total Liabilities_log': data.total_liabilities, 'Arts & Culture': data.arts_culture, 'Charity & Sector Support': data.charity_sector_support, 'Community & Development': data.community_development, 'Education & Youth': data.education_youth, 'Environment & Animals': data.environment_animals, 'Health & Welfare': data.health_welfare, 'International Aid': data.international_aid, 'Poverty & Housing': data.poverty_housing, 'Religion': data.religion } return pd.DataFrame([features]) def prepare_regression_features(data: RegressionInput) -> pd.DataFrame: features = { 'Surplus / (Deficit) for the Period': data.surplus_deficit, 'Cash at Hand and in Bank': data.cash_at_hand, 'start_season': data.start_season, 'end_season': data.end_season, 'Gross Income (Schools) class': data.gross_income_schools, 'Gross Expenditure (Schools) class': data.gross_expenditure_schools, 'volunteer_class_reduced': data.volunteer_class_reduced, 'Number_Employees_class_reduced': data.number_employees_class_reduced, 'Income: Government or Local Authorities_log': data.income_government, 'Income: Other Public Bodies_log': data.income_other_public_bodies, 'Income: Philantrophic Organisations_log': data.income_philanthropic_orgs, 'Income: Donations_log': data.income_donations, 'Income: Trading and Commercial Activities_log': data.income_trading_commercial, 'Income: Bequests_log': data.income_bequests, 'Gross Income_log': data.gross_income, 'Gross Expenditure_log': data.gross_expenditure, 'Other Assets_log': data.other_assets, 'Total Assets_log': data.total_assets, 'Net Assets / (Liabilities)_log': data.net_assets_liabilities, 'Total Liabilities_log': data.total_liabilities, 'Arts & Culture': data.arts_culture, 'Charity & Sector Support': data.charity_sector_support, 'Community & Development': data.community_development, 'Education & Youth': data.education_youth, 'Environment & Animals': data.environment_animals, 'Health & Welfare': data.health_welfare, 'International Aid': data.international_aid, 'Poverty & Housing': data.poverty_housing, 'Religion': data.religion } return pd.DataFrame([features]) def prepare_binary_classification_features(data: BinaryClassificationInput) -> pd.DataFrame: features = { 'Surplus / (Deficit) for the Period': data.surplus_deficit, 'Cash at Hand and in Bank': data.cash_at_hand, 'start_season': data.start_season, 'end_season': data.end_season, 'Gross Income (Schools) class': data.gross_income_schools, 'Gross Expenditure (Schools) class': data.gross_expenditure_schools, 'volunteer_class_reduced': data.volunteer_class_reduced, 'Number_Employees_class_reduced': data.number_employees_class_reduced, 'Income: Government or Local Authorities_log': data.income_government, 'Income: Other Public Bodies_log': data.income_other_public_bodies, 'Income: Philantrophic Organisations_log': data.income_philanthropic_orgs, 'Income: Trading and Commercial Activities_log': data.income_trading_commercial, 'Income: Other Sources_log': data.income_other_sources, 'Income: Bequests_log': data.income_bequests, 'Gross Income_log': data.gross_income, 'Gross Expenditure_log': data.gross_expenditure, 'Other Assets_log': data.other_assets, 'Total Assets_log': data.total_assets, 'Net Assets / (Liabilities)_log': data.net_assets_liabilities, 'Total Liabilities_log': data.total_liabilities, 'Arts & Culture': data.arts_culture, 'Charity & Sector Support': data.charity_sector_support, 'Community & Development': data.community_development, 'Education & Youth': data.education_youth, 'Environment & Animals': data.environment_animals, 'Health & Welfare': data.health_welfare, 'International Aid': data.international_aid, 'Poverty & Housing': data.poverty_housing, 'Religion': data.religion } return pd.DataFrame([features]) def prepare_xgboost_features(data: XGBoostInput) -> pd.DataFrame: global label_encoders, scaler features = { 'Surplus / (Deficit) for the Period': data.surplus_deficit, 'Cash at Hand and in Bank': data.cash_at_hand, 'start_season': data.start_season, 'end_season': data.end_season, 'Gross Income (Schools) class': data.gross_income_schools, 'Gross Expenditure (Schools) class': data.gross_expenditure_schools, 'volunteer_class_reduced': data.volunteer_class_reduced, 'Number_Employees_class_reduced': data.number_employees_class_reduced, 'Income: Government or Local Authorities_log': data.income_government, 'Income: Other Public Bodies_log': data.income_other_public_bodies, 'Income: Philantrophic Organisations_log': data.income_philanthropic_orgs, 'Income: Donations_log': data.income_donations, 'Income: Trading and Commercial Activities_log': data.income_trading_commercial, 'Income: Other Sources_log': data.income_other_sources, 'Income: Bequests_log': data.income_bequests, 'Gross Expenditure_log': data.gross_expenditure, 'Other Assets_log': data.other_assets, 'Total Assets_log': data.total_assets, 'Net Assets / (Liabilities)_log': data.net_assets_liabilities, 'Total Liabilities_log': data.total_liabilities, 'Arts & Culture': data.arts_culture, 'Charity & Sector Support': data.charity_sector_support, 'Community & Development': data.community_development, 'Education & Youth': data.education_youth, 'Environment & Animals': data.environment_animals, 'Health & Welfare': data.health_welfare, 'International Aid': data.international_aid, 'Poverty & Housing': data.poverty_housing, 'Religion': data.religion } df = pd.DataFrame([features]) if label_encoders: for col, le in label_encoders.items(): if col in df.columns: try: df[col] = le.transform(df[col].astype(str)) except ValueError: df[col] = 0 for col in df.columns: df[col] = pd.to_numeric(df[col], errors='coerce') if scaler: df_scaled = pd.DataFrame( scaler.transform(df), columns=df.columns, index=df.index ) return df_scaled return df def prepare_seif_features(data: SeifInput) -> np.ndarray: season_map = {'autumn': 0, 'spring': 1, 'summer': 2, 'winter': 3} class_map = {'A_NONE': 0, 'B_SMALL': 1, 'C_MEDIUM': 2, 'D_LARGE': 3} features = [ data.surplus_deficit, data.cash_at_hand, season_map.get(data.start_season, 0), season_map.get(data.end_season, 0), data.gross_income_schools, data.gross_expenditure_schools, class_map.get(data.volunteer_class_reduced, 0), class_map.get(data.number_employees_class_reduced, 0), data.income_government, data.income_other_public_bodies, data.income_philanthropic_orgs, data.income_trading_commercial, data.income_other_sources, data.income_bequests, data.gross_income, data.gross_expenditure, data.other_assets, data.total_assets, data.net_assets_liabilities, data.total_liabilities, data.arts_culture, data.charity_sector_support, data.community_development, data.education_youth, data.environment_animals, data.health_welfare, data.international_aid, data.poverty_housing, data.religion ] return np.array([features]) def prepare_stacking_features(data: StackingInput) -> np.ndarray: features = [ data.surplus_deficit, data.cash_at_hand, data.start_season, data.end_season, data.gross_income_schools, data.gross_expenditure_schools, data.number_employees_class_reduced, data.income_government, data.income_other_public_bodies, data.income_philanthropic_orgs, data.income_donations, data.income_trading_commercial, data.income_other_sources, data.income_bequests, data.gross_income, data.gross_expenditure, data.other_assets, data.total_assets, data.net_assets_liabilities, data.total_liabilities, data.arts_culture, data.charity_sector_support, data.community_development, data.education_youth, data.environment_animals, data.health_welfare, data.international_aid, data.poverty_housing, data.religion ] return np.array([features]) def build_meta_features_inference(X: np.ndarray) -> np.ndarray: global stacking_base_models base_model_order = ["xgb_single", "knn_optionA", "knn_tuned", "adaboost_weighted"] probas = [] for model_name in base_model_order: if model_name in stacking_base_models: model = stacking_base_models[model_name] try: proba = model.predict_proba(X) probas.append(proba) except Exception as e: raise ValueError(f"Base model {model_name} failed: {str(e)}") else: raise ValueError(f"Base model {model_name} not loaded") X_meta = np.concatenate(probas, axis=1) return X_meta # ================================================= # Prediction Endpoints (UNCHANGED except log_prediction uses DB now) # ================================================= @app.post("/predict/{model_name}", response_model=ClassificationOutput) def predict_classification(model_name: str, data: ClassificationInput): if model_name not in models: raise HTTPException( status_code=404, detail=f"Model '{model_name}' not found. Available: {list(models.keys())}" ) if models[model_name]["type"] != "classification": raise HTTPException( status_code=400, detail=f"Model '{model_name}' is a {models[model_name]['type']} model. Use /predict_regression endpoint." ) start_time = time.time() try: features_df = prepare_classification_features(data) model = models[model_name]["model"] prediction = model.predict(features_df)[0] try: probabilities = model.predict_proba(features_df)[0] if hasattr(model, 'classes_'): prob_dict = {str(cls): float(prob) for cls, prob in zip(model.classes_, probabilities)} max_prob = float(max(probabilities)) else: prob_dict = None max_prob = None except: prob_dict = None max_prob = None # XAI: Get feature importance feature_names = list(features_df.columns) top_features = get_feature_importance(model, feature_names, features_df, top_k=5) # XAI: Generate natural language explanation explanation = generate_explanation( prediction=str(prediction), model_type="Classification (RandomForest)", target_name="Employee Class", top_features=top_features ) latency = time.time() - start_time ml_predictions_total.labels(model_name=model_name, model_type="classification", status="success").inc() ml_prediction_latency.labels(model_name=model_name, model_type="classification").observe(latency) log_prediction(model_name, "classification", latency, "success", str(prediction)) return { "model": model_name, "predicted_class": str(prediction), "prediction_confidence": max_prob, "all_probabilities": prob_dict, "top_features": top_features if top_features else None, "explanation": explanation } except Exception as e: latency = time.time() - start_time ml_predictions_total.labels(model_name=model_name, model_type="classification", status="error").inc() log_prediction(model_name, "classification", latency, "error", str(e)) raise HTTPException(status_code=400, detail=f"Prediction error: {str(e)}") @app.post("/predict_regression/{model_name}", response_model=RegressionOutput) def predict_regression(model_name: str, data: RegressionInput): if model_name not in models: raise HTTPException( status_code=404, detail=f"Model '{model_name}' not found. Available: {list(models.keys())}" ) if models[model_name]["type"] != "regression": raise HTTPException( status_code=400, detail=f"Model '{model_name}' is a {models[model_name]['type']} model. Use /predict endpoint." ) start_time = time.time() try: features_df = prepare_regression_features(data) model = models[model_name]["model"] prediction = model.predict(features_df)[0] # XAI: Get feature importance feature_names = list(features_df.columns) top_features = get_feature_importance(model, feature_names, features_df, top_k=5) # XAI: Generate natural language explanation explanation = generate_explanation( prediction=f"{prediction:.4f}", model_type="Regression", target_name="Income: Other Sources", top_features=top_features ) latency = time.time() - start_time ml_predictions_total.labels(model_name=model_name, model_type="regression", status="success").inc() ml_prediction_latency.labels(model_name=model_name, model_type="regression").observe(latency) log_prediction(model_name, "regression", latency, "success", f"{prediction:.4f}") return { "model": model_name, "predicted_value": float(prediction), "target_name": "Income: Other Sources_log", "top_features": top_features if top_features else None, "explanation": explanation } except Exception as e: latency = time.time() - start_time ml_predictions_total.labels(model_name=model_name, model_type="regression", status="error").inc() log_prediction(model_name, "regression", latency, "error", str(e)) raise HTTPException(status_code=400, detail=f"Prediction error: {str(e)}") @app.post("/predict_binary/{model_name}", response_model=ClassificationOutput) def predict_binary_classification(model_name: str, data: BinaryClassificationInput): if model_name not in models: raise HTTPException( status_code=404, detail=f"Model '{model_name}' not found. Available: {list(models.keys())}" ) if models[model_name]["type"] != "binary_classification": raise HTTPException( status_code=400, detail=f"Model '{model_name}' is a {models[model_name]['type']} model. Use appropriate endpoint." ) start_time = time.time() try: features_df = prepare_binary_classification_features(data) model = models[model_name]["model"] prediction = model.predict(features_df)[0] try: probabilities = model.predict_proba(features_df)[0] if hasattr(model, 'classes_'): prob_dict = {str(cls): float(prob) for cls, prob in zip(model.classes_, probabilities)} max_prob = float(max(probabilities)) else: prob_dict = None max_prob = None except: prob_dict = None max_prob = None # XAI: Get feature importance feature_names = list(features_df.columns) top_features = get_feature_importance(model, feature_names, features_df, top_k=5) # XAI: Generate natural language explanation explanation = generate_explanation( prediction=str(prediction), model_type="Binary Classification (RandomForest)", target_name="Donation Range", top_features=top_features ) latency = time.time() - start_time ml_predictions_total.labels(model_name=model_name, model_type="binary_classification", status="success").inc() ml_prediction_latency.labels(model_name=model_name, model_type="binary_classification").observe(latency) log_prediction(model_name, "binary_classification", latency, "success", str(prediction)) return { "model": model_name, "predicted_class": str(prediction), "prediction_confidence": max_prob, "all_probabilities": prob_dict, "top_features": top_features if top_features else None, "explanation": explanation } except Exception as e: latency = time.time() - start_time ml_predictions_total.labels(model_name=model_name, model_type="binary_classification", status="error").inc() log_prediction(model_name, "binary_classification", latency, "error", str(e)) raise HTTPException(status_code=400, detail=f"Prediction error: {str(e)}") @app.post("/predict_xgboost/{model_name}", response_model=RegressionOutput) def predict_xgboost(model_name: str, data: XGBoostInput): if model_name not in models: raise HTTPException( status_code=404, detail=f"Model '{model_name}' not found. Available: {list(models.keys())}" ) if models[model_name]["type"] != "xgboost_regression": raise HTTPException( status_code=400, detail=f"Model '{model_name}' is a {models[model_name]['type']} model. Use appropriate endpoint." ) if label_encoders is None or scaler is None: raise HTTPException( status_code=500, detail="Preprocessing components (label_encoders or scaler) not loaded" ) start_time = time.time() try: features_df = prepare_xgboost_features(data) model = models[model_name]["model"] prediction = model.predict(features_df)[0] # XAI: Get feature importance feature_names = list(features_df.columns) top_features = get_feature_importance(model, feature_names, features_df, top_k=5) # XAI: Generate natural language explanation explanation = generate_explanation( prediction=f"{prediction:.4f}", model_type="XGBoost Regression", target_name="Gross Income", top_features=top_features ) latency = time.time() - start_time ml_predictions_total.labels(model_name=model_name, model_type="xgboost_regression", status="success").inc() ml_prediction_latency.labels(model_name=model_name, model_type="xgboost_regression").observe(latency) log_prediction(model_name, "xgboost_regression", latency, "success", f"{prediction:.4f}") return { "model": model_name, "predicted_value": float(prediction), "target_name": "Gross Income_log", "top_features": top_features if top_features else None, "explanation": explanation } except Exception as e: latency = time.time() - start_time ml_predictions_total.labels(model_name=model_name, model_type="xgboost_regression", status="error").inc() log_prediction(model_name, "xgboost_regression", latency, "error", str(e)) raise HTTPException(status_code=400, detail=f"Prediction error: {str(e)}") @app.post("/predict_donations/{model_name}", response_model=RegressionOutput) def predict_donations(model_name: str, data: SeifInput): if model_name not in models: raise HTTPException( status_code=404, detail=f"Model '{model_name}' not found. Available: {list(models.keys())}" ) if models[model_name]["type"] != "xgboost_donations": raise HTTPException( status_code=400, detail=f"Model '{model_name}' is a {models[model_name]['type']} model. Use /predict_donations/xgboost_donations" ) start_time = time.time() try: features = prepare_seif_features(data) model = models[model_name]["model"] prediction = model.predict(features)[0] # XAI: Feature names for SeifInput seif_feature_names = [ "surplus_deficit", "cash_at_hand", "start_season", "end_season", "gross_income_schools", "gross_expenditure_schools", "volunteer_class", "employees_class", "income_government", "income_other_public", "income_philanthropic", "income_trading", "income_other_sources", "income_bequests", "gross_income", "gross_expenditure", "other_assets", "total_assets", "net_assets_liabilities", "total_liabilities", "arts_culture", "charity_support", "community_dev", "education_youth", "environment_animals", "health_welfare", "international_aid", "poverty_housing", "religion" ] # Get feature importance top_features = [] if hasattr(model, 'feature_importances_'): importances = model.feature_importances_ for i, (name, imp) in enumerate(zip(seif_feature_names, importances)): if i < len(features[0]): top_features.append({ "feature": name, "importance": float(imp), "value": float(features[0][i]) }) top_features.sort(key=lambda x: x["importance"], reverse=True) top_features = top_features[:5] # XAI: Generate natural language explanation explanation = generate_explanation( prediction=f"{prediction:.4f}", model_type="XGBoost Regression", target_name="Income: Donations", top_features=top_features ) latency = time.time() - start_time ml_predictions_total.labels(model_name=model_name, model_type="xgboost_donations", status="success").inc() ml_prediction_latency.labels(model_name=model_name, model_type="xgboost_donations").observe(latency) log_prediction(model_name, "xgboost_donations", latency, "success", f"{prediction:.4f}") return { "model": model_name, "predicted_value": float(prediction), "target_name": "Income: Donations_log", "top_features": top_features if top_features else None, "explanation": explanation } except Exception as e: latency = time.time() - start_time ml_predictions_total.labels(model_name=model_name, model_type="xgboost_donations", status="error").inc() log_prediction(model_name, "xgboost_donations", latency, "error", str(e)) raise HTTPException(status_code=400, detail=f"Prediction error: {str(e)}") @app.post("/predict_stacking/{model_name}", response_model=ClassificationOutput) def predict_stacking(model_name: str, data: StackingInput): global stacking_meta_learner if model_name not in models: raise HTTPException( status_code=404, detail=f"Model '{model_name}' not found. Available: {list(models.keys())}" ) if models[model_name]["type"] != "stacking": raise HTTPException( status_code=400, detail=f"Model '{model_name}' is a {models[model_name]['type']} model. Use /predict_stacking/stacking_volunteer" ) if stacking_meta_learner is None: raise HTTPException( status_code=500, detail="Stacking meta-learner not loaded" ) if len(stacking_base_models) < 4: raise HTTPException( status_code=500, detail=f"Not all base models loaded. Have: {list(stacking_base_models.keys())}" ) start_time = time.time() try: X = prepare_stacking_features(data) X_meta = build_meta_features_inference(X) prediction = stacking_meta_learner.predict(X_meta)[0] class_labels = ["A_NONE", "B_SMALL", "C_MEDIUM", "D_LARGE"] prob_dict = None max_prob = None if hasattr(stacking_meta_learner, 'predict_proba'): proba = stacking_meta_learner.predict_proba(X_meta)[0] prob_dict = {class_labels[i]: float(proba[i]) for i in range(len(proba))} max_prob = float(max(proba)) # XAI: Feature names for stacking input stacking_feature_names = [ "surplus_deficit", "cash_at_hand", "start_season", "end_season", "gross_income_schools", "gross_expenditure_schools", "employees_class", "income_government", "income_other_public", "income_philanthropic", "income_donations", "income_trading", "income_other_sources", "income_bequests", "gross_income", "gross_expenditure", "other_assets", "total_assets", "net_assets_liabilities", "total_liabilities", "arts_culture", "charity_support", "community_dev", "education_youth", "environment_animals", "health_welfare", "international_aid", "poverty_housing", "religion" ] # For stacking, use meta-learner coefficients if available top_features = [] if hasattr(stacking_meta_learner, 'coef_'): # Meta-learner has coefficients over base model outputs base_model_names = ["XGBoost", "KNN_A", "KNN_tuned", "AdaBoost"] coefs = np.abs(stacking_meta_learner.coef_).flatten() # Average coefficients per base model (4 classes each = 16 total) importance_values = [] for i, name in enumerate(base_model_names): if i*4 < len(coefs): avg_imp = float(np.mean(coefs[i*4:(i+1)*4])) importance_values.append((name, avg_imp)) # Calculate percentage contributions total_imp = sum(imp for _, imp in importance_values) if importance_values else 1 for name, avg_imp in importance_values: pct = (avg_imp / total_imp) * 100 if total_imp > 0 else 0 top_features.append({ "feature": f"Base: {name}", "importance": avg_imp, "value": f"{pct:.1f}%" # Show percentage contribution }) top_features.sort(key=lambda x: x["importance"], reverse=True) # XAI: Generate natural language explanation explanation = generate_explanation( prediction=class_labels[int(prediction)], model_type="Stacking Ensemble (XGBoost + KNN + AdaBoost)", target_name="Volunteer Classification", top_features=top_features if top_features else None ) latency = time.time() - start_time ml_predictions_total.labels(model_name=model_name, model_type="stacking", status="success").inc() ml_prediction_latency.labels(model_name=model_name, model_type="stacking").observe(latency) log_prediction(model_name, "stacking", latency, "success", class_labels[int(prediction)]) return { "model": model_name, "predicted_class": class_labels[int(prediction)], "prediction_confidence": max_prob, "all_probabilities": prob_dict, "top_features": top_features if top_features else None, "explanation": explanation } except Exception as e: latency = time.time() - start_time ml_predictions_total.labels(model_name=model_name, model_type="stacking", status="error").inc() log_prediction(model_name, "stacking", latency, "error", str(e)) raise HTTPException(status_code=400, detail=f"Prediction error: {str(e)}") @app.get("/health") def health(): return { "status": "healthy", "models_loaded": len(models), "label_encoders_loaded": label_encoders is not None, "scaler_loaded": scaler is not None, "stacking_base_models": len(stacking_base_models), "stacking_meta_learner_ready": stacking_meta_learner is not None, "database_connected": db_engine is not None } @app.get("/example/classification") def example_classification(): return { "endpoint": "/predict/randomforest", "method": "POST", "example_input": { "surplus_deficit": -137699000.0, "cash_at_hand": 331570000.0, "start_season": "winter", "end_season": "winter", "gross_income_schools": 0, "gross_expenditure_schools": 0, "volunteer_class_reduced": "D_LARGE", "income_government": 23.879876, "income_other_public_bodies": 17.300344, "income_philanthropic_orgs": 15.320921, "income_donations": 16.220201, "income_trading_commercial": 19.731279, "income_other_sources": 19.996591, "income_bequests": 0.0, "gross_income": 23.917578, "gross_expenditure": 23.923207, "other_assets": 22.73303, "total_assets": 22.777331, "net_assets_liabilities": 22.229597, "total_liabilities": 21.913968, "arts_culture": 0, "charity_sector_support": 0, "community_development": 0, "education_youth": 0, "environment_animals": 0, "health_welfare": 1, "international_aid": 0, "poverty_housing": 0, "religion": 0 } } @app.get("/example/regression") def example_regression(): return { "endpoint": "/predict_regression/regression_other_sources", "method": "POST", "target": "Income: Other Sources_log", "example_input": { "surplus_deficit": -137699000.0, "cash_at_hand": 331570000.0, "start_season": "winter", "end_season": "winter", "gross_income_schools": 0, "gross_expenditure_schools": 0, "volunteer_class_reduced": "D_LARGE", "number_employees_class_reduced": "D_LARGE", "income_government": 23.8799, "income_other_public_bodies": 17.3003, "income_philanthropic_orgs": 15.3209, "income_donations": 16.2202, "income_trading_commercial": 19.7313, "income_bequests": 0.0, "gross_income": 23.9176, "gross_expenditure": 23.9232, "other_assets": 22.7339, "total_assets": 22.7773, "net_assets_liabilities": 22.2296, "total_liabilities": 21.9140, "arts_culture": 0, "charity_sector_support": 0, "community_development": 0, "education_youth": 0, "environment_animals": 0, "health_welfare": 1, "international_aid": 0, "poverty_housing": 0, "religion": 0 } } @app.get("/example/binary_classification") def example_binary_classification(): return { "endpoint": "/predict_binary/donation_range", "method": "POST", "target": "donation_range (binary)", "model_info": "RandomForestClassifier(class_weight='balanced', n_estimators=200)", "encoding_info": { "start_season": "winter=0, spring=1, summer=2, autumn=3", "end_season": "winter=0, spring=1, summer=2, autumn=3", "volunteer_class_reduced": "A_NONE=0, B_SMALL=1, C_MEDIUM=2, D_LARGE=3", "number_employees_class_reduced": "A_NONE=0, B_SMALL=1, C_MEDIUM=2, D_LARGE=3" }, "example_input": { "surplus_deficit": -137699000.0, "cash_at_hand": 331570000.0, "start_season": 0, "end_season": 0, "gross_income_schools": 0, "gross_expenditure_schools": 0, "volunteer_class_reduced": 3, "number_employees_class_reduced": 3, "income_government": 23.8799, "income_other_public_bodies": 17.3003, "income_philanthropic_orgs": 15.3209, "income_trading_commercial": 19.7313, "income_other_sources": 19.9966, "income_bequests": 0.0, "gross_income": 23.9176, "gross_expenditure": 23.9232, "other_assets": 22.7339, "total_assets": 22.7773, "net_assets_liabilities": 22.2296, "total_liabilities": 21.9140, "arts_culture": 0, "charity_sector_support": 0, "community_development": 0, "education_youth": 0, "environment_animals": 0, "health_welfare": 1, "international_aid": 0, "poverty_housing": 0, "religion": 0 } } @app.get("/example/xgboost") def example_xgboost(): return { "endpoint": "/predict_xgboost/xgboost_gross_income", "method": "POST", "target": "Gross Income_log", "model_info": "XGBoostRegressor with StandardScaler + LabelEncoders", "note": "Categorical columns are automatically encoded, all features are scaled", "example_input": { "surplus_deficit": -137699000.0, "cash_at_hand": 331570000.0, "start_season": "winter", "end_season": "winter", "gross_income_schools": 0, "gross_expenditure_schools": 0, "volunteer_class_reduced": "D_LARGE", "number_employees_class_reduced": "D_LARGE", "income_government": 23.8799, "income_other_public_bodies": 17.3003, "income_philanthropic_orgs": 15.3209, "income_donations": 16.2202, "income_trading_commercial": 19.7313, "income_other_sources": 19.9966, "income_bequests": 0.0, "gross_expenditure": 23.9232, "other_assets": 22.7339, "total_assets": 22.7773, "net_assets_liabilities": 22.2296, "total_liabilities": 21.9140, "arts_culture": 0, "charity_sector_support": 0, "community_development": 0, "education_youth": 0, "environment_animals": 0, "health_welfare": 1, "international_aid": 0, "poverty_housing": 0, "religion": 0 } } @app.get("/example/donations") def example_donations(): return { "endpoint": "/predict_donations/xgboost_donations", "method": "POST", "target": "Income: Donations_log", "model_info": "XGBoostRegressor with dynamic ColumnTransformer (StandardScaler + OneHotEncoder)", "note": "Uses fit_transform on inference - for production, save and load preprocessor", "example_input": { "surplus_deficit": -137699000.0, "cash_at_hand": 331570000.0, "start_season": "winter", "end_season": "winter", "gross_income_schools": 0, "gross_expenditure_schools": 0, "volunteer_class_reduced": "D_LARGE", "number_employees_class_reduced": "D_LARGE", "income_government": 23.8799, "income_other_public_bodies": 17.3003, "income_philanthropic_orgs": 15.3209, "income_trading_commercial": 19.7313, "income_other_sources": 19.9966, "income_bequests": 0.0, "gross_income": 23.9176, "gross_expenditure": 23.9232, "other_assets": 22.7339, "total_assets": 22.7773, "net_assets_liabilities": 22.2296, "total_liabilities": 21.9140, "arts_culture": 0, "charity_sector_support": 0, "community_development": 0, "education_youth": 0, "environment_animals": 0, "health_welfare": 1, "international_aid": 0, "poverty_housing": 0, "religion": 0 } } @app.get("/example/stacking") def example_stacking(): return { "endpoint": "/predict_stacking/stacking_volunteer", "method": "POST", "target": "volunteer_class_reduced (4 classes: A_NONE, B_SMALL, C_MEDIUM, D_LARGE)", "model_info": "Stacking Ensemble: XGBoost + KNN + AdaBoost → LogisticRegression meta-learner", "note": "Input uses label-encoded integers (start_season: 0-3, end_season: 0-3, number_employees: 0-3)", "example_input": { "surplus_deficit": -137699000.0, "cash_at_hand": 331570000.0, "start_season": 3, "end_season": 3, "gross_income_schools": 0, "gross_expenditure_schools": 0, "number_employees_class_reduced": 3, "income_government": 23.879876, "income_other_public_bodies": 17.300344, "income_philanthropic_orgs": 15.320921, "income_donations": 16.220201, "income_trading_commercial": 19.731279, "income_other_sources": 19.996591, "income_bequests": 0.0, "gross_income": 23.917578, "gross_expenditure": 23.923207, "other_assets": 22.73389, "total_assets": 22.777331, "net_assets_liabilities": 22.229597, "total_liabilities": 21.913968, "arts_culture": 0, "charity_sector_support": 0, "community_development": 0, "education_youth": 0, "environment_animals": 0, "health_welfare": 1, "international_aid": 0, "poverty_housing": 0, "religion": 0 } } # ================================================= # Clustering Endpoints # ================================================= @app.get("/clustering/data") def get_clustering_data(per_cluster: int = 400): """ Fetch a balanced sample of association data for 3D cluster visualization. Returns 250 points per cluster (500 total) for fast loading. """ if db_engine is None: raise HTTPException(status_code=503, detail="Database not connected") try: with db_engine.connect() as conn: # Simplified query - only essential columns for 2D plot result = conn.execute(text(""" (SELECT "PC1", "PC2", "cluster", "age_association" FROM "associations-rna" WHERE "cluster" = 0 LIMIT :per_cluster) UNION ALL (SELECT "PC1", "PC2", "cluster", "age_association" FROM "associations-rna" WHERE "cluster" = 1 LIMIT :per_cluster) """), {"per_cluster": per_cluster}) rows = result.fetchall() data = [] for row in rows: data.append({ "pc1": float(row[0]) if row[0] is not None else 0, "pc2": float(row[1]) if row[1] is not None else 0, "cluster": int(row[2]) if row[2] is not None else 0, "age": float(row[3]) if row[3] is not None else 0 }) return { "total_points": len(data), "per_cluster": per_cluster, "data": data } except Exception as e: raise HTTPException(status_code=500, detail=f"Database query failed: {str(e)}") @app.post("/clustering/predict") def predict_cluster(data: ClusteringInput): """ Predict which cluster a new association belongs to using KMeans pipeline. """ if kmeans_pipeline is None: raise HTTPException(status_code=503, detail="KMeans model not loaded") try: # Prepare input features in the same order as training # The pipeline expects: Latitude, Longitude, age_association, delay_declaration, # plus encoded categorical features # Prepare input features matching training data names exactly # Prepare input features matching training data names exactly # Based on user error log: # Encoding mappings family_map = { "sports": 0, "culture": 1, "social": 2, "education": 3 } dirigeant_map = { "personne_physique": 0, "personne_morale": 1 } # Safe conversion for Code Officiel def safe_int(val): try: return int(val) except: return 0 features = pd.DataFrame([{ "latitude": float(data.latitude), "longitude": float(data.longitude), "age_association": float(data.age_association), "delay_declaration": float(data.delay_declaration), "Code Officiel Commune Siège": safe_int(data.code_officiel_commune), "Code Officiel Département": safe_int(data.code_officiel_departement), "Code Officiel EPCI": safe_int(data.code_officiel_region), # Mapping Region input to EPCI slot "obj1_family_clean": family_map.get(data.obj1_family_c, 0), # Default to 0 (sports) "has_obj2": int(data.has_obj2), "est_active": int(data.est_active), "dirigeant_type_bin": dirigeant_map.get(data.dirigeant_type, 0) # Default to 0 }]) # Predict cluster cluster = int(kmeans_pipeline.predict(features)[0]) return { "predicted_cluster": cluster, "cluster_label": "Cluster A" if cluster == 0 else "Cluster B", "message": f"Cette association appartient au {('Cluster A' if cluster == 0 else 'Cluster B')}" } except Exception as e: raise HTTPException(status_code=400, detail=f"Prediction error: {str(e)}")
from fastapi import FastAPI, HTTPException
import joblib
import numpy as np
import pandas as pd
from pydantic import BaseModel
from typing import Optional, Union, List, Dict
import os
import pickle
import time
from datetime import datetime
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
# Prometheus metrics
from prometheus_fastapi_instrumentator import Instrumentator
from prometheus_client import Counter, Histogram, Gauge
# === SQLAlchemy for Supabase Persistence ===
from sqlalchemy import create_engine, text
from sqlalchemy.pool import QueuePool
# === OpenAI for Explainable AI ===
from openai import OpenAI
# =================================================
# DATABASE CONFIGURATION
# =================================================
# Get the connection string from environment variable (set in Hugging Face Secrets)
DATABASE_URL = os.environ.get("DATABASE_URL")
# Create the engine only if DATABASE_URL is set
db_engine = None
if DATABASE_URL:
try:
db_engine = create_engine(
DATABASE_URL,
poolclass=QueuePool,
pool_size=5,
max_overflow=10,
pool_timeout=30,
pool_recycle=1800 # Recycle connections every 30 minutes
)
print("✓ Database engine created successfully")
except Exception as e:
print(f"✗ Failed to create database engine: {e}")
else:
print("⚠ DATABASE_URL not set. Logging will be disabled.")
# =================================================
app = FastAPI(
title="Charity Prediction API",
description="Predict employee_class, income_other_sources, donation_range, gross_income, and income_donations using ML models"
)
# Initialize Prometheus instrumentator (adds /metrics endpoint automatically)
instrumentator = Instrumentator(
should_group_status_codes=False,
should_ignore_untemplated=True,
should_instrument_requests_inprogress=True,
excluded_handlers=["/metrics"],
inprogress_labels=True,
)
# Instrument the app and expose /metrics endpoint (must be done at module level, not in startup)
instrumentator.instrument(app).expose(app, endpoint="/metrics")
# Custom ML metrics
ml_predictions_total = Counter(
"ml_predictions_total",
"Total number of ML predictions",
["model_name", "model_type", "status"]
)
ml_prediction_latency = Histogram(
"ml_prediction_latency_seconds",
"ML prediction latency in seconds",
["model_name", "model_type"],
buckets=[0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0]
)
ml_models_loaded = Gauge(
"ml_models_loaded_total",
"Number of ML models currently loaded"
)
# =================================================
# NEW: Database-Backed Logging Function
# =================================================
def log_prediction(model_name: str, model_type: str, latency: float, status: str, result: str = None):
"""Log a prediction to Supabase database"""
if db_engine is None:
return # Silently skip if no DB configured
try:
with db_engine.connect() as conn:
conn.execute(
text("""