import joblib import os from pathlib import Path import numpy as np from huggingface_hub import hf_hub_download MODEL_REPO = "perachon/credit-scoring-model" MODEL_FILE = "lightgbm_api_pipeline.pkl" def get_model_path() -> Path: # Chemin vers le pipeline entraîné en local # model_path = Path("models/lightgbm_api_pipeline.pkl") # Pipeline entraîné versionné sur Hugging Face model_path = hf_hub_download( repo_id="perachon/credit-scoring-model", filename="lightgbm_api_pipeline.pkl" ) return joblib.load(model_path) def load_model(): """ Télécharge et charge le modèle depuis Hugging Face Hub. Le fichier est mis en cache automatiquement par huggingface_hub. """ local_model_path = os.getenv("MODEL_PATH") if local_model_path: local_path = Path(local_model_path) if not local_path.exists(): raise FileNotFoundError(f"MODEL_PATH défini mais introuvable: {local_path}") return joblib.load(local_path) model_path = hf_hub_download( repo_id=MODEL_REPO, filename=MODEL_FILE ) model = joblib.load(model_path) return model def predict_proba(model, X): """ Retourne la probabilité de défaut pour un DataFrame X. """ proba = model.predict_proba(X) # Sécurité : certaines implémentations renvoient (n,1) if proba.shape[1] == 1: return np.zeros(len(proba)) return proba[:, 1]