Spaces:
Sleeping
Sleeping
Download api/artefacts.py from CloudPulse/ML_classifier: direct link, hf CLI and curl.
- Browser
- Download file 4.63 kB
-
https://huggingface.co/spaces/CloudPulse/ML_classifier/resolve/main/api/artefacts.py
- Command line
-
hf download hf://spaces/CloudPulse/ML_classifier/api/artefacts.py
-
curl -L -o artefacts.py https://huggingface.co/spaces/CloudPulse/ML_classifier/resolve/main/api/artefacts.py
4.63 kB
| """ | |
| 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" | |
| 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, | |
| ) | |