Spaces:
Sleeping
Sleeping
Download webapp/services/inference.py from PeaceAbolisher/Model_Lab_Deployment: direct link, hf CLI and curl.
- Browser
- Download file 12 kB
-
https://huggingface.co/spaces/PeaceAbolisher/Model_Lab_Deployment/resolve/main/webapp/services/inference.py
- Command line
-
hf download hf://spaces/PeaceAbolisher/Model_Lab_Deployment/webapp/services/inference.py
-
curl -L -o inference.py https://huggingface.co/spaces/PeaceAbolisher/Model_Lab_Deployment/resolve/main/webapp/services/inference.py
12 kB
| 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 | |
| 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 | |
| ) | |