File size: 4,634 Bytes
81e3338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
"""
Loads every model and lookup artefact at startup.

Single source of truth for which files the API expects. If something is missing,
fail loud at boot instead of failing per-request later.

Reads from per-notebook subfolders under ml/artefacts/:
  02_features/       TF-IDF vectoriser + matrices
  03_logreg/         logreg models
  04_xgboost/        XGBoost models
  05_svm/            SVM models
  06_random_forest/  RF models
  07_minilm/         MiniLM embeddings + index
  08_anomaly/        Isolation Forest bundle
  09_results/        cross-model comparison CSVs
  13_shap/           SHAP TreeExplainer
"""
from dataclasses import dataclass
from pathlib import Path
from typing import Any

import joblib
import numpy as np
import pandas as pd

from .explainer import SHAPExplainer

ARTEFACTS_ROOT = Path(__file__).resolve().parent.parent / "artefacts"

FEATURES_DIR  = ARTEFACTS_ROOT / "02_features"
LOGREG_DIR    = ARTEFACTS_ROOT / "03_logreg"
XGBOOST_DIR   = ARTEFACTS_ROOT / "04_xgboost"
SVM_DIR       = ARTEFACTS_ROOT / "05_svm"
RF_DIR        = ARTEFACTS_ROOT / "06_random_forest"
MINILM_DIR    = ARTEFACTS_ROOT / "07_minilm"
ANOMALY_DIR   = ARTEFACTS_ROOT / "08_anomaly"
RESULTS_DIR   = ARTEFACTS_ROOT / "09_results"
SHAP_DIR      = ARTEFACTS_ROOT / "13_shap"


@dataclass
class Artefacts:
    """All model and lookup artefacts the API needs at runtime."""
    tfidf: Any
    classifier_3class: Any
    classifier_3class_label_encoder: Any
    classifier_binary: Any
    classifier_binary_label_encoder: Any
    anomaly_bundle: dict
    minilm_embeddings: np.ndarray
    minilm_index: pd.DataFrame
    minilm_model: Any
    metrics: dict
    shap_explainer: SHAPExplainer | None


def _load_classifier(path: Path) -> tuple[Any, Any]:
    """Loads either a bare model or a {model, label_encoder} bundle."""
    obj = joblib.load(path)
    if isinstance(obj, dict) and "model" in obj:
        return obj["model"], obj.get("label_encoder")
    return obj, None


def load_artefacts() -> Artefacts:
    """Loads everything the API needs. Raises FileNotFoundError if anything is missing."""
    # Production defaults: XGBoost on both tasks (winner per notebook 09 results)
    best_3class_path = XGBOOST_DIR / "xgb_3class.joblib"
    best_binary_path = XGBOOST_DIR / "xgb_binary.joblib"

    if not best_3class_path.exists():
        best_3class_path = LOGREG_DIR / "logreg_3class.joblib"
    if not best_binary_path.exists():
        best_binary_path = LOGREG_DIR / "logreg_binary.joblib"

    tfidf      = joblib.load(FEATURES_DIR / "tfidf_vectoriser.joblib")
    clf3, le3  = _load_classifier(best_3class_path)
    clfb, leb  = _load_classifier(best_binary_path)

    anomaly_bundle = joblib.load(ANOMALY_DIR / "anomaly_isoforest.joblib")

    minilm_embeddings = np.load(MINILM_DIR / "minilm_embeddings.npy")
    minilm_index      = pd.read_csv(MINILM_DIR / "minilm_index.csv")

    # Sentence transformer is loaded lazily here. Heavy import deferred to runtime.
    from sentence_transformers import SentenceTransformer
    minilm_model = SentenceTransformer("all-MiniLM-L6-v2")

    metrics: dict = {}
    if (RESULTS_DIR / "results_3class.csv").exists():
        df3   = pd.read_csv(RESULTS_DIR / "results_3class.csv")
        dfb   = pd.read_csv(RESULTS_DIR / "results_binary.csv")
        best3 = df3.iloc[df3["macro_f1"].idxmax()]
        bestb = dfb.iloc[dfb["macro_f1"].idxmax()]
        metrics = {
            "best_3class_model"   : best3["model"],
            "best_3class_macro_f1": float(best3["macro_f1"]),
            "best_binary_model"   : bestb["model"],
            "best_binary_macro_f1": float(bestb["macro_f1"]),
            "per_class_f1"        : {
                "low"   : float(best3["low_f1"]),
                "medium": float(best3["medium_f1"]),
                "high"  : float(best3["high_f1"]),
            },
        }

    # SHAP explainer (optional � gracefully missing if notebook 13 not yet run)
    shap_explainer: SHAPExplainer | None = None
    shap_path = SHAP_DIR / "shap_explainer.joblib"
    if shap_path.exists() and le3 is not None:
        vocab          = tfidf.get_feature_names_out()
        shap_explainer = SHAPExplainer(shap_path, vocab, le3)

    return Artefacts(
        tfidf=tfidf,
        classifier_3class=clf3,
        classifier_3class_label_encoder=le3,
        classifier_binary=clfb,
        classifier_binary_label_encoder=leb,
        anomaly_bundle=anomaly_bundle,
        minilm_embeddings=minilm_embeddings,
        minilm_index=minilm_index,
        minilm_model=minilm_model,
        metrics=metrics,
        shap_explainer=shap_explainer,
    )