File size: 1,460 Bytes
cc3cf41
 
 
 
56aba02
 
 
 
cc3cf41
 
 
56aba02
 
 
 
 
 
 
 
 
 
 
cc3cf41
 
 
56aba02
 
cc3cf41
0ad7b2b
 
 
 
 
 
 
56aba02
 
 
 
 
 
 
cc3cf41
 
 
 
 
 
 
 
 
 
 
 
 
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
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]