File size: 11,981 Bytes
e50f22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
from __future__ import annotations

import io, os, uuid
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple
import re
import joblib
import numpy as np
import pandas as pd
from django.conf import settings
from sklearn.metrics import f1_score, roc_auc_score
from sklearn.inspection import permutation_importance

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

try:
    import shap
    _SHAP_OK = True
except Exception:
    _SHAP_OK = False


@dataclass
class InferenceResult:
    error: Optional[str] = None
    predictions: Optional[List[Tuple[str, int]]] = None
    test_f1: Optional[float] = None
    test_auc: Optional[float] = None
    val_f1: Optional[float] = None
    val_auc: Optional[float] = None
    shap_url: Optional[str] = None
    explain_type: Optional[str] = None
    summary: Optional[Dict[str, Any]] = None     



def _pretty_feature_names(names: List[str]) -> List[str]:
    out = []
    for n in names:
        s = str(n)
        # strip ColumnTransformer prefixes
        s = re.sub(r'^(num|cat)_{1,2}', '', s)
        out.append(s if len(s) <= 40 else s[:37] + '…')
    return out


def _read_model(upload):
    if hasattr(upload, "read"):
        data = upload.read()
        return joblib.load(io.BytesIO(data))
    return joblib.load(upload)


def _coerce_numeric(df: pd.DataFrame) -> pd.DataFrame:
    out = df.copy()
    for c in out.columns:
        if out[c].dtype == object:
            coerced = pd.to_numeric(out[c], errors="coerce")
            if coerced.notna().sum() > 0:
                out[c] = coerced
    return out


def _media_plot_paths(run_id: str, tag: str) -> Tuple[str, str]:
    rel_dir = "inference_runs"
    abs_dir = os.path.join(settings.MEDIA_ROOT, rel_dir)
    os.makedirs(abs_dir, exist_ok=True)
    abs_path = os.path.join(abs_dir, f"{run_id}_{tag}.svg")  # ← SVG
    url = settings.MEDIA_URL + f"{rel_dir}/{run_id}_{tag}.svg"
    return abs_path, url


def _try_shap(model, X: pd.DataFrame, feature_names: List[str], run_id: str) -> Tuple[Optional[str], Optional[List[Tuple[str, float]]]]:
    if not _SHAP_OK:
        return None, None
    try:
        bg = X.sample(min(50, len(X)), random_state=0)
        ev = X.sample(min(200, len(X)), random_state=1)

        try:
            exp = shap.Explainer(model, bg)
            sv = exp(ev)
            shap.summary_plot(sv, features=ev, feature_names=feature_names, plot_type="bar", show=False)
            # mean absolute shap per feature
            vals = np.abs(sv.values).mean(0)
        except Exception:
            def _f(A):
                df = pd.DataFrame(A, columns=feature_names)
                if hasattr(model, "predict_proba"):
                    return model.predict_proba(df)[:, 1]
                return model.predict(df)
            kexp = shap.KernelExplainer(_f, bg)
            sv = kexp.shap_values(ev, nsamples=100)
            shap.summary_plot(sv, ev, feature_names=feature_names, plot_type="bar", show=False)
            vals = np.abs(sv).mean(0)  # kernel returns ndarray

        plt.tight_layout()
        plt.gcf().set_size_inches(8, 5)                     # ← baseline size
        abs_path, url = _media_plot_paths(run_id, "shap")
        plt.savefig(abs_path, format="svg", bbox_inches="tight")
        plt.close()


        importances = [(str(f), float(v)) for f, v in zip(feature_names, vals)]
        return url, importances
    except Exception:
        try: plt.close()
        except Exception: pass
        return None, None



def _try_perm(model, X: pd.DataFrame, y: pd.Series, feature_names: List[str], run_id: str) -> Tuple[Optional[str], Optional[List[Tuple[str, float]]]]:
    try:
        res = permutation_importance(model, X, y, n_repeats=10, random_state=0, scoring="roc_auc")
        imps = pd.Series(res.importances_mean, index=feature_names).fillna(0.0)
        top = imps.sort_values().tail(25)

        plt.figure(figsize=(10, 6), dpi=140)
        cols = ["tab:red" if v < 0 else "tab:green" for v in top.values]
        plt.barh(top.index, top.values, color=cols, alpha=0.9)
        plt.axvline(0, linestyle="--", linewidth=1, alpha=0.6)
        plt.title("Permutation importance")
        plt.xlabel("Ξ” ROC AUC when permuted")
        plt.tight_layout()

        abs_path, url = _media_plot_paths(run_id, "perm")
        plt.savefig(abs_path, format="svg", bbox_inches="tight")
        plt.close()

        importances = [(str(f), float(s)) for f, s in zip(feature_names, res.importances_mean)]
        return url, importances
    except Exception:
        try: plt.close()
        except Exception: pass
        return None, None


def _normalize_artifact(obj: Any) -> Dict[str, Any]:
    """
    Normalize different saved shapes into a common dict:
      keys: model, preprocessor|scaler (optional), selector (optional),
            pre_features (optional), final_features (optional),
            val_auc/val_f1/test_auc/test_f1 (optional)
    """
    # A) New/modern artifact (dict with "model")
    if isinstance(obj, dict) and "model" in obj:
        return {
            "model": obj["model"],
            "preprocessor": obj.get("preprocessor"),
            "scaler": obj.get("scaler"),
            "selector": obj.get("selector"),
            "pre_features": obj.get("pre_selection_feature_names"),
            "final_features": obj.get("final_feature_names"),
            "val_auc": obj.get("val_auc"),
            "val_f1": obj.get("val_f1"),
            "test_auc": obj.get("test_auc"),
            "test_f1": obj.get("test_f1"),
        }

    # B) Older scripts (dict with model + scaler and possibly selector + feature lists)
    if isinstance(obj, dict) and "model" in obj and ("scaler" in obj or "preprocessor" in obj):
        return {
            "model": obj["model"],
            "preprocessor": obj.get("preprocessor"),
            "scaler": obj.get("scaler"),
            "selector": obj.get("selector"),
            "pre_features": obj.get("pre_selection_feature_names"),
            "final_features": obj.get("final_feature_names") or obj.get("feature_names"),
            "val_auc": obj.get("val_auc"),
            "val_f1": obj.get("val_f1"),
            "test_auc": obj.get("test_auc"),
            "test_f1": obj.get("test_f1"),
        }

    # C) Plain sklearn Pipeline or bare estimator
    if hasattr(obj, "predict") and hasattr(obj, "fit"):
        return {
            "model": obj,
            "preprocessor": None,
            "scaler": None,
            "selector": None,
            "pre_features": None,
            "final_features": list(getattr(obj, "feature_names_in_", [])) or None,
            "val_auc": None, "val_f1": None, "test_auc": None, "test_f1": None,
        }

    raise ValueError("Unrecognized model file format")


def run_inference(model_file, test_file) -> InferenceResult:
    # Load model/artifact
    try:
        obj = _read_model(model_file)
    except Exception as e:
        return InferenceResult(error=f"Could not load model file: {e}")

    try:
        art = _normalize_artifact(obj)
    except Exception as e:
        return InferenceResult(error=f"Uploaded model file is not a recognized artifact: {e}")

    # Load test CSV
    try:
        df = pd.read_csv(test_file) if hasattr(test_file, "read") else pd.read_csv(str(test_file))
    except Exception as e:
        return InferenceResult(error=f"Could not read test data: {e}")

    y = df["healthy"].astype(int).reset_index(drop=True) if "healthy" in df.columns else None
    X = df.drop(columns=["healthy"]) if "healthy" in df.columns else df
    X = _coerce_numeric(X)

    model        = art["model"]
    preprocessor = art.get("preprocessor")
    scaler       = art.get("scaler")
    selector     = art.get("selector")
    pre_feats    = art.get("pre_features")
    final_feats  = art.get("final_features")

    # ── Preprocess (A: reindex to training columns before transform) ───────────
    try:
        if preprocessor is not None:
            # Columns the ColumnTransformer saw during fit (raw, before OHE/scale)
            raw_cols = list(getattr(preprocessor, "feature_names_in_", []))
            if raw_cols:
                # Drop extras like `sample_id`; add any missing cols as NaN for imputers
                X_raw = X.reindex(columns=raw_cols, fill_value=np.nan)
            else:
                X_raw = X  # fallback if sklearn version lacks feature_names_in_
            Xp_arr = preprocessor.transform(X_raw)
            names = preprocessor.get_feature_names_out().tolist()
            Xp = pd.DataFrame(Xp_arr, columns=names).astype(np.float32)

        elif scaler is not None:
            # If an older artifact saved a bare scaler, align to its training columns too
            raw_cols = list(getattr(scaler, "feature_names_in_", []))
            X_raw = X.reindex(columns=raw_cols, fill_value=np.nan) if raw_cols else X
            if not hasattr(scaler, "n_features_in_"):
                try:
                    scaler.fit(X_raw)
                except Exception:
                    pass
            Xp = pd.DataFrame(scaler.transform(X_raw), columns=X_raw.columns).astype(np.float32)

        else:
            Xp = X.copy()

        # Feature selection / alignment
        if selector is not None and pre_feats is not None:
            X_aligned = Xp.reindex(columns=pre_feats, fill_value=0.0)
            X_final_arr = selector.transform(X_aligned)
            Xf = pd.DataFrame(X_final_arr, columns=final_feats)
        elif final_feats is not None:
            Xf = Xp.reindex(columns=final_feats, fill_value=0.0)
        elif hasattr(model, "feature_names_in_"):
            needs = list(model.feature_names_in_)
            Xf = Xp.reindex(columns=needs, fill_value=0.0)
            final_feats = needs
        else:
            Xf = Xp
            final_feats = Xf.columns.tolist()
    except Exception as e:
        return InferenceResult(error=f"Preprocessing/feature selection failed: {e}")

    # Clean labels for plots/links (drop num__/cat__ prefixes)
    pretty_feats = _pretty_feature_names(final_feats)


    # Predict
    try:
        y_pred = model.predict(Xf)
    except Exception as e:
        return InferenceResult(error=f"Model prediction failed: {e}")

    # Metrics (optional)
    test_f1 = test_auc = None
    if y is not None and len(y) == len(y_pred):
        try:
            test_f1 = float(f1_score(y, y_pred))
        except Exception:
            test_f1 = None
        try:
            if hasattr(model, "predict_proba"):
                test_auc = float(roc_auc_score(y, model.predict_proba(Xf)[:, 1]))
        except Exception:
            test_auc = None

    # Explainability
    run_id = uuid.uuid4().hex
    summary = None

    shap_url, shap_importances = _try_shap(model, Xf, pretty_feats, run_id)
    explain_type = "shap" if shap_url else None

    if shap_url:
        summary = {"explain_type": "shap", "shap_importance": shap_importances}
    elif y is not None:
        perm_url, perm_importances = _try_perm(model, Xf, y, pretty_feats, run_id)
        if perm_url:
            shap_url = perm_url
            explain_type = "permutation"
            summary = {"explain_type": "permutation", "permutation_importance": perm_importances}


    # Preview (show sample_id if present)
    n = min(25, len(df))
    row_ids = (
        df["sample_id"].astype(str).tolist()[:n]
        if "sample_id" in df.columns else [str(i) for i in range(n)]
    )
    preds_head = list(zip(row_ids, [int(y_pred[i]) for i in range(n)]))

    return InferenceResult(
    error=None,
    predictions=preds_head,
    test_f1=test_f1,
    test_auc=test_auc,
    val_f1=(None if art.get("val_f1") is None else float(art["val_f1"])),
    val_auc=(None if art.get("val_auc") is None else float(art["val_auc"])),
    shap_url=shap_url,
    explain_type=explain_type,
    summary=summary,  #make sure the new summary is returned
)