import pandas as pd import numpy as np import pickle import os import xgboost # Fonction pour charger le modèle directement depuis le fichier local def load_model(): try: # Charger le modèle depuis le fichier local model_path = os.path.join(os.path.dirname(__file__), "xgboots_regressor.pkl") if os.path.exists(model_path): with open(model_path, "rb") as f: model = pickle.load(f) return model else: raise FileNotFoundError(f"Le fichier modèle '{model_path}' n'a pas été trouvé.") except Exception as e: raise ValueError(f"Erreur lors du chargement du modèle: {str(e)}") def predict_price(model, input_df, with_confidence_interval=False, confidence_level=0.95, error_margin=0.15): try: # Make prediction prediction = model.predict(input_df) predicted_price = float(prediction[0]) if with_confidence_interval: # Map confidence levels to z-scores z_scores = { 0.50: 0.674, 0.80: 1.282, 0.90: 1.645, 0.95: 1.96, 0.99: 2.576, 0.999: 3.291 } # Get the appropriate z-score (default to 95% if not found) z_score = z_scores.get(confidence_level, 1.96) # Calculate the margin of error margin = predicted_price * error_margin # Calculate the bounds of the confidence interval lower_bound = max(0, predicted_price - (z_score * margin)) upper_bound = predicted_price + (z_score * margin) return predicted_price, lower_bound, upper_bound else: return predicted_price except Exception as e: raise ValueError(f"Failed to make prediction: {str(e)}")