Spaces:
Sleeping
Sleeping
MadalinaCarcea221989 commited on
Commit ·
81e3338
1
Parent(s): 7b56e36
Deploy CloudPulse AI service
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- Dockerfile +43 -0
- api/__init__.py +1 -0
- api/artefacts.py +126 -0
- api/explainer.py +98 -0
- api/main.py +299 -0
- api/preprocessing.py +65 -0
- api/remediation.py +73 -0
- api/schemas.py +176 -0
- api/weekly.py +194 -0
- artefacts/.gitkeep +0 -0
- artefacts/02_features/X_test_tfidf.npz +3 -0
- artefacts/02_features/X_train_tfidf.npz +3 -0
- artefacts/02_features/X_val_tfidf.npz +3 -0
- artefacts/02_features/tfidf_top_terms.png +0 -0
- artefacts/02_features/tfidf_vectoriser.joblib +3 -0
- artefacts/02_features/y_test_3class.npy +3 -0
- artefacts/02_features/y_test_4class.npy +3 -0
- artefacts/02_features/y_test_binary.npy +3 -0
- artefacts/02_features/y_train_3class.npy +3 -0
- artefacts/02_features/y_train_4class.npy +3 -0
- artefacts/02_features/y_train_binary.npy +3 -0
- artefacts/02_features/y_val_3class.npy +3 -0
- artefacts/02_features/y_val_4class.npy +3 -0
- artefacts/02_features/y_val_binary.npy +3 -0
- artefacts/03_logreg/logreg_3class.joblib +3 -0
- artefacts/03_logreg/logreg_3class_confusion_matrix.png +0 -0
- artefacts/03_logreg/logreg_3class_results.json +27 -0
- artefacts/03_logreg/logreg_binary.joblib +3 -0
- artefacts/03_logreg/logreg_binary_confusion_matrix.png +0 -0
- artefacts/03_logreg/logreg_binary_results.json +21 -0
- artefacts/03_logreg/logreg_classification_reports.txt +21 -0
- artefacts/04_xgboost/xgb_3class.joblib +3 -0
- artefacts/04_xgboost/xgb_3class_confusion_matrix.png +0 -0
- artefacts/04_xgboost/xgb_3class_results.json +29 -0
- artefacts/04_xgboost/xgb_binary.joblib +3 -0
- artefacts/04_xgboost/xgb_binary_confusion_matrix.png +0 -0
- artefacts/04_xgboost/xgb_binary_results.json +23 -0
- artefacts/04_xgboost/xgb_classification_reports.txt +21 -0
- artefacts/05_svm/svm_3class.joblib +3 -0
- artefacts/05_svm/svm_3class_confusion_matrix.png +0 -0
- artefacts/05_svm/svm_3class_results.json +27 -0
- artefacts/05_svm/svm_binary.joblib +3 -0
- artefacts/05_svm/svm_binary_confusion_matrix.png +0 -0
- artefacts/05_svm/svm_binary_results.json +21 -0
- artefacts/05_svm/svm_classification_reports.txt +21 -0
- artefacts/06_random_forest/rf_3class.joblib +3 -0
- artefacts/06_random_forest/rf_3class_confusion_matrix.png +0 -0
- artefacts/06_random_forest/rf_3class_results.json +29 -0
- artefacts/06_random_forest/rf_binary.joblib +3 -0
- artefacts/06_random_forest/rf_binary_confusion_matrix.png +0 -0
Dockerfile
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# syntax=docker/dockerfile:1.7
|
| 2 |
+
# ==============================================================================
|
| 3 |
+
# CloudPulse AI Service — Hugging Face Spaces deployment
|
| 4 |
+
# HF Spaces requires the app to listen on port 7860
|
| 5 |
+
# ==============================================================================
|
| 6 |
+
|
| 7 |
+
FROM python:3.12-slim
|
| 8 |
+
|
| 9 |
+
ENV PYTHONDONTWRITEBYTECODE=1 \
|
| 10 |
+
PYTHONUNBUFFERED=1 \
|
| 11 |
+
PIP_NO_CACHE_DIR=1 \
|
| 12 |
+
OMP_NUM_THREADS=2 \
|
| 13 |
+
OPENBLAS_NUM_THREADS=2 \
|
| 14 |
+
MKL_NUM_THREADS=2
|
| 15 |
+
|
| 16 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 17 |
+
build-essential \
|
| 18 |
+
gcc \
|
| 19 |
+
libgomp1 \
|
| 20 |
+
curl \
|
| 21 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 22 |
+
|
| 23 |
+
WORKDIR /app
|
| 24 |
+
|
| 25 |
+
COPY requirements-api.txt .
|
| 26 |
+
RUN pip install --upgrade pip && \
|
| 27 |
+
pip install -r requirements-api.txt
|
| 28 |
+
|
| 29 |
+
# Copy artefacts and API code
|
| 30 |
+
COPY artefacts/ ./artefacts/
|
| 31 |
+
COPY api/ ./api/
|
| 32 |
+
|
| 33 |
+
# HF Spaces runs as root, no need for user creation
|
| 34 |
+
EXPOSE 7860
|
| 35 |
+
|
| 36 |
+
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
|
| 37 |
+
CMD curl --fail --silent http://localhost:7860/health || exit 1
|
| 38 |
+
|
| 39 |
+
CMD ["uvicorn", "api.main:app", \
|
| 40 |
+
"--host", "0.0.0.0", \
|
| 41 |
+
"--port", "7860", \
|
| 42 |
+
"--workers", "1", \
|
| 43 |
+
"--log-level", "info"]
|
api/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""CloudPulse AI inference service."""
|
api/artefacts.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Loads every model and lookup artefact at startup.
|
| 3 |
+
|
| 4 |
+
Single source of truth for which files the API expects. If something is missing,
|
| 5 |
+
fail loud at boot instead of failing per-request later.
|
| 6 |
+
|
| 7 |
+
Reads from per-notebook subfolders under ml/artefacts/:
|
| 8 |
+
02_features/ TF-IDF vectoriser + matrices
|
| 9 |
+
03_logreg/ logreg models
|
| 10 |
+
04_xgboost/ XGBoost models
|
| 11 |
+
05_svm/ SVM models
|
| 12 |
+
06_random_forest/ RF models
|
| 13 |
+
07_minilm/ MiniLM embeddings + index
|
| 14 |
+
08_anomaly/ Isolation Forest bundle
|
| 15 |
+
09_results/ cross-model comparison CSVs
|
| 16 |
+
13_shap/ SHAP TreeExplainer
|
| 17 |
+
"""
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Any
|
| 21 |
+
|
| 22 |
+
import joblib
|
| 23 |
+
import numpy as np
|
| 24 |
+
import pandas as pd
|
| 25 |
+
|
| 26 |
+
from .explainer import SHAPExplainer
|
| 27 |
+
|
| 28 |
+
ARTEFACTS_ROOT = Path(__file__).resolve().parent.parent / "artefacts"
|
| 29 |
+
|
| 30 |
+
FEATURES_DIR = ARTEFACTS_ROOT / "02_features"
|
| 31 |
+
LOGREG_DIR = ARTEFACTS_ROOT / "03_logreg"
|
| 32 |
+
XGBOOST_DIR = ARTEFACTS_ROOT / "04_xgboost"
|
| 33 |
+
SVM_DIR = ARTEFACTS_ROOT / "05_svm"
|
| 34 |
+
RF_DIR = ARTEFACTS_ROOT / "06_random_forest"
|
| 35 |
+
MINILM_DIR = ARTEFACTS_ROOT / "07_minilm"
|
| 36 |
+
ANOMALY_DIR = ARTEFACTS_ROOT / "08_anomaly"
|
| 37 |
+
RESULTS_DIR = ARTEFACTS_ROOT / "09_results"
|
| 38 |
+
SHAP_DIR = ARTEFACTS_ROOT / "13_shap"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@dataclass
|
| 42 |
+
class Artefacts:
|
| 43 |
+
"""All model and lookup artefacts the API needs at runtime."""
|
| 44 |
+
tfidf: Any
|
| 45 |
+
classifier_3class: Any
|
| 46 |
+
classifier_3class_label_encoder: Any
|
| 47 |
+
classifier_binary: Any
|
| 48 |
+
classifier_binary_label_encoder: Any
|
| 49 |
+
anomaly_bundle: dict
|
| 50 |
+
minilm_embeddings: np.ndarray
|
| 51 |
+
minilm_index: pd.DataFrame
|
| 52 |
+
minilm_model: Any
|
| 53 |
+
metrics: dict
|
| 54 |
+
shap_explainer: SHAPExplainer | None
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _load_classifier(path: Path) -> tuple[Any, Any]:
|
| 58 |
+
"""Loads either a bare model or a {model, label_encoder} bundle."""
|
| 59 |
+
obj = joblib.load(path)
|
| 60 |
+
if isinstance(obj, dict) and "model" in obj:
|
| 61 |
+
return obj["model"], obj.get("label_encoder")
|
| 62 |
+
return obj, None
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def load_artefacts() -> Artefacts:
|
| 66 |
+
"""Loads everything the API needs. Raises FileNotFoundError if anything is missing."""
|
| 67 |
+
# Production defaults: XGBoost on both tasks (winner per notebook 09 results)
|
| 68 |
+
best_3class_path = XGBOOST_DIR / "xgb_3class.joblib"
|
| 69 |
+
best_binary_path = XGBOOST_DIR / "xgb_binary.joblib"
|
| 70 |
+
|
| 71 |
+
if not best_3class_path.exists():
|
| 72 |
+
best_3class_path = LOGREG_DIR / "logreg_3class.joblib"
|
| 73 |
+
if not best_binary_path.exists():
|
| 74 |
+
best_binary_path = LOGREG_DIR / "logreg_binary.joblib"
|
| 75 |
+
|
| 76 |
+
tfidf = joblib.load(FEATURES_DIR / "tfidf_vectoriser.joblib")
|
| 77 |
+
clf3, le3 = _load_classifier(best_3class_path)
|
| 78 |
+
clfb, leb = _load_classifier(best_binary_path)
|
| 79 |
+
|
| 80 |
+
anomaly_bundle = joblib.load(ANOMALY_DIR / "anomaly_isoforest.joblib")
|
| 81 |
+
|
| 82 |
+
minilm_embeddings = np.load(MINILM_DIR / "minilm_embeddings.npy")
|
| 83 |
+
minilm_index = pd.read_csv(MINILM_DIR / "minilm_index.csv")
|
| 84 |
+
|
| 85 |
+
# Sentence transformer is loaded lazily here. Heavy import deferred to runtime.
|
| 86 |
+
from sentence_transformers import SentenceTransformer
|
| 87 |
+
minilm_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 88 |
+
|
| 89 |
+
metrics: dict = {}
|
| 90 |
+
if (RESULTS_DIR / "results_3class.csv").exists():
|
| 91 |
+
df3 = pd.read_csv(RESULTS_DIR / "results_3class.csv")
|
| 92 |
+
dfb = pd.read_csv(RESULTS_DIR / "results_binary.csv")
|
| 93 |
+
best3 = df3.iloc[df3["macro_f1"].idxmax()]
|
| 94 |
+
bestb = dfb.iloc[dfb["macro_f1"].idxmax()]
|
| 95 |
+
metrics = {
|
| 96 |
+
"best_3class_model" : best3["model"],
|
| 97 |
+
"best_3class_macro_f1": float(best3["macro_f1"]),
|
| 98 |
+
"best_binary_model" : bestb["model"],
|
| 99 |
+
"best_binary_macro_f1": float(bestb["macro_f1"]),
|
| 100 |
+
"per_class_f1" : {
|
| 101 |
+
"low" : float(best3["low_f1"]),
|
| 102 |
+
"medium": float(best3["medium_f1"]),
|
| 103 |
+
"high" : float(best3["high_f1"]),
|
| 104 |
+
},
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
# SHAP explainer (optional � gracefully missing if notebook 13 not yet run)
|
| 108 |
+
shap_explainer: SHAPExplainer | None = None
|
| 109 |
+
shap_path = SHAP_DIR / "shap_explainer.joblib"
|
| 110 |
+
if shap_path.exists() and le3 is not None:
|
| 111 |
+
vocab = tfidf.get_feature_names_out()
|
| 112 |
+
shap_explainer = SHAPExplainer(shap_path, vocab, le3)
|
| 113 |
+
|
| 114 |
+
return Artefacts(
|
| 115 |
+
tfidf=tfidf,
|
| 116 |
+
classifier_3class=clf3,
|
| 117 |
+
classifier_3class_label_encoder=le3,
|
| 118 |
+
classifier_binary=clfb,
|
| 119 |
+
classifier_binary_label_encoder=leb,
|
| 120 |
+
anomaly_bundle=anomaly_bundle,
|
| 121 |
+
minilm_embeddings=minilm_embeddings,
|
| 122 |
+
minilm_index=minilm_index,
|
| 123 |
+
minilm_model=minilm_model,
|
| 124 |
+
metrics=metrics,
|
| 125 |
+
shap_explainer=shap_explainer,
|
| 126 |
+
)
|
api/explainer.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
CloudPulse — SHAP explainability at inference time.
|
| 3 |
+
|
| 4 |
+
Loads the TreeExplainer trained in notebook 13 and computes per-prediction
|
| 5 |
+
SHAP values when the FastAPI service classifies a new incident.
|
| 6 |
+
|
| 7 |
+
Replaces the previous top-TF-IDF-terms explanation with true Shapley values.
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Any
|
| 13 |
+
|
| 14 |
+
import joblib
|
| 15 |
+
import numpy as np
|
| 16 |
+
import shap
|
| 17 |
+
from scipy import sparse
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class SHAPExplainer:
|
| 21 |
+
"""Wraps a SHAP TreeExplainer for the production XGBoost classifier."""
|
| 22 |
+
|
| 23 |
+
def __init__(self, explainer_path: Path, vocab: np.ndarray, label_encoder: Any):
|
| 24 |
+
self.explainer = joblib.load(explainer_path)
|
| 25 |
+
self.vocab = np.asarray(vocab)
|
| 26 |
+
self.le = label_encoder
|
| 27 |
+
self.classes_ = list(label_encoder.classes_)
|
| 28 |
+
|
| 29 |
+
def explain(self, x_tfidf: sparse.csr_matrix, predicted_class: str, top_k: int = 5) -> dict:
|
| 30 |
+
"""Return the top-k token contributions toward the predicted class.
|
| 31 |
+
|
| 32 |
+
Args:
|
| 33 |
+
x_tfidf : 1×n sparse vector (TF-IDF features for one incident)
|
| 34 |
+
predicted_class: the class label the classifier returned
|
| 35 |
+
top_k : number of top contributions to return
|
| 36 |
+
|
| 37 |
+
Returns:
|
| 38 |
+
{
|
| 39 |
+
"predicted_class": "high",
|
| 40 |
+
"top_contributions": [
|
| 41 |
+
{"token": "authentication", "tfidf_weight": 0.42, "shap_value": 0.18,
|
| 42 |
+
"direction": "toward_high"},
|
| 43 |
+
...
|
| 44 |
+
],
|
| 45 |
+
"expected_value_for_class": 0.34,
|
| 46 |
+
}
|
| 47 |
+
"""
|
| 48 |
+
if predicted_class not in self.classes_:
|
| 49 |
+
return {"error": f"unknown class: {predicted_class}"}
|
| 50 |
+
|
| 51 |
+
cls_idx = self.classes_.index(predicted_class)
|
| 52 |
+
|
| 53 |
+
# SHAP needs dense input. The vector is a single row.
|
| 54 |
+
x_dense = x_tfidf.toarray()
|
| 55 |
+
shap_vals = self.explainer.shap_values(x_dense)
|
| 56 |
+
|
| 57 |
+
# Normalise: SHAP returns either a list of (n, n_features) per class
|
| 58 |
+
# or a 3D array (n, n_features, n_classes) depending on version.
|
| 59 |
+
if isinstance(shap_vals, list):
|
| 60 |
+
sv = shap_vals[cls_idx][0]
|
| 61 |
+
else:
|
| 62 |
+
sv = shap_vals[0, :, cls_idx] if shap_vals.ndim == 3 else shap_vals[0]
|
| 63 |
+
|
| 64 |
+
# Only consider tokens that are actually present in the input
|
| 65 |
+
nonzero = np.nonzero(x_dense[0])[0]
|
| 66 |
+
if len(nonzero) == 0:
|
| 67 |
+
return {
|
| 68 |
+
"predicted_class": predicted_class,
|
| 69 |
+
"top_contributions": [],
|
| 70 |
+
"expected_value_for_class": float(self._expected_for_class(cls_idx)),
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
contributions = [
|
| 74 |
+
(self.vocab[fi], float(x_dense[0, fi]), float(sv[fi]))
|
| 75 |
+
for fi in nonzero
|
| 76 |
+
]
|
| 77 |
+
contributions.sort(key=lambda t: abs(t[2]), reverse=True)
|
| 78 |
+
|
| 79 |
+
top = []
|
| 80 |
+
for token, weight, sv_val in contributions[:top_k]:
|
| 81 |
+
top.append({
|
| 82 |
+
"token" : token,
|
| 83 |
+
"tfidf_weight": round(weight, 4),
|
| 84 |
+
"shap_value" : round(sv_val, 4),
|
| 85 |
+
"direction" : f"toward_{predicted_class}" if sv_val > 0 else f"away_from_{predicted_class}",
|
| 86 |
+
})
|
| 87 |
+
|
| 88 |
+
return {
|
| 89 |
+
"predicted_class" : predicted_class,
|
| 90 |
+
"top_contributions" : top,
|
| 91 |
+
"expected_value_for_class": float(self._expected_for_class(cls_idx)),
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
def _expected_for_class(self, cls_idx: int) -> float:
|
| 95 |
+
ev = self.explainer.expected_value
|
| 96 |
+
if isinstance(ev, (list, tuple, np.ndarray)):
|
| 97 |
+
return float(ev[cls_idx])
|
| 98 |
+
return float(ev)
|
api/main.py
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dotenv import load_dotenv
|
| 2 |
+
from pathlib import Path as _Path
|
| 3 |
+
load_dotenv(_Path(__file__).resolve().parent.parent.parent / ".env")
|
| 4 |
+
"""
|
| 5 |
+
CloudPulse AI service.
|
| 6 |
+
|
| 7 |
+
Exposes the trained classifiers, anomaly detector, similarity search and Claude
|
| 8 |
+
Haiku remediation as a single FastAPI service. The data engineer's pipeline calls
|
| 9 |
+
this service; the Lovable dashboard reads the responses through the data engineer's
|
| 10 |
+
storage layer.
|
| 11 |
+
|
| 12 |
+
Endpoints:
|
| 13 |
+
|
| 14 |
+
POST /classify classify one incident with explanation, anomaly score and remediation
|
| 15 |
+
POST /similar find the top-k most similar past incidents
|
| 16 |
+
GET /metrics static evaluation results from notebook 09
|
| 17 |
+
GET /health readiness probe
|
| 18 |
+
"""
|
| 19 |
+
import time
|
| 20 |
+
from contextlib import asynccontextmanager
|
| 21 |
+
from datetime import datetime
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
import pandas as pd
|
| 26 |
+
from fastapi import FastAPI, HTTPException, Query
|
| 27 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 28 |
+
|
| 29 |
+
from .artefacts import Artefacts, load_artefacts
|
| 30 |
+
from .preprocessing import anonymise, apply_escalation_rule, confidence_label
|
| 31 |
+
from anthropic import Anthropic
|
| 32 |
+
|
| 33 |
+
from .remediation import generate_remediation
|
| 34 |
+
from .weekly import build_weekly_report
|
| 35 |
+
from .schemas import (
|
| 36 |
+
ClassifyRequest, ClassifyResponse,
|
| 37 |
+
HealthResponse,
|
| 38 |
+
MetricsResponse,
|
| 39 |
+
SimilarRequest, SimilarResponse, SimilarIncident,
|
| 40 |
+
WeeklyRequest, WeeklyResponse,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
anthropic_client = Anthropic()
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 47 |
+
# Lifespan: load every artefact once at startup
|
| 48 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 49 |
+
artefacts: Artefacts | None = None
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@asynccontextmanager
|
| 53 |
+
async def lifespan(app: FastAPI):
|
| 54 |
+
global artefacts
|
| 55 |
+
print("Loading artefacts...")
|
| 56 |
+
artefacts = load_artefacts()
|
| 57 |
+
print("Artefacts loaded.")
|
| 58 |
+
yield
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
app = FastAPI(
|
| 62 |
+
title="CloudPulse AI Service",
|
| 63 |
+
version="1.0.0",
|
| 64 |
+
description="Severity classification, similarity search and remediation generation.",
|
| 65 |
+
lifespan=lifespan,
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
app.add_middleware(
|
| 69 |
+
CORSMiddleware,
|
| 70 |
+
allow_origins=["*"],
|
| 71 |
+
allow_methods=["*"],
|
| 72 |
+
allow_headers=["*"],
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 77 |
+
# Internal helpers
|
| 78 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 79 |
+
def _predict_3class(text_anonymised: str) -> tuple[str, float]:
|
| 80 |
+
"""Predicts the 3-class label and returns (label, probability)."""
|
| 81 |
+
X = artefacts.tfidf.transform([text_anonymised])
|
| 82 |
+
probs = artefacts.classifier_3class.predict_proba(X)[0]
|
| 83 |
+
|
| 84 |
+
if artefacts.classifier_3class_label_encoder is not None:
|
| 85 |
+
# XGBoost path with integer labels
|
| 86 |
+
idx = int(np.argmax(probs))
|
| 87 |
+
label = artefacts.classifier_3class_label_encoder.inverse_transform([idx])[0]
|
| 88 |
+
else:
|
| 89 |
+
idx = int(np.argmax(probs))
|
| 90 |
+
label = artefacts.classifier_3class.classes_[idx]
|
| 91 |
+
|
| 92 |
+
return str(label), float(probs[idx])
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _predict_binary(text_anonymised: str) -> str:
|
| 96 |
+
X = artefacts.tfidf.transform([text_anonymised])
|
| 97 |
+
pred = artefacts.classifier_binary.predict(X)[0]
|
| 98 |
+
if artefacts.classifier_binary_label_encoder is not None:
|
| 99 |
+
pred = artefacts.classifier_binary_label_encoder.inverse_transform([pred])[0]
|
| 100 |
+
return str(pred)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _explain(text_anonymised: str, predicted_class: str, top_n: int = 5) -> dict:
|
| 104 |
+
"""Returns the top-N TF-IDF terms in this description ranked by their TF-IDF weight.
|
| 105 |
+
|
| 106 |
+
A lightweight, model-agnostic explanation. Works for any TF-IDF based classifier
|
| 107 |
+
in the bundle (logreg, svm, xgboost, rf). For a deeper SHAP-based explanation,
|
| 108 |
+
add a separate /explain endpoint that loads the SHAP explainer.
|
| 109 |
+
"""
|
| 110 |
+
X = artefacts.tfidf.transform([text_anonymised])
|
| 111 |
+
|
| 112 |
+
if artefacts.shap_explainer is not None:
|
| 113 |
+
return artefacts.shap_explainer.explain(
|
| 114 |
+
x_tfidf=X,
|
| 115 |
+
predicted_class=predicted_class,
|
| 116 |
+
top_k=top_n,
|
| 117 |
+
)
|
| 118 |
+
arr = X.toarray()[0]
|
| 119 |
+
vocab = np.array(artefacts.tfidf.get_feature_names_out())
|
| 120 |
+
idx = np.argsort(arr)[::-1][:top_n]
|
| 121 |
+
return {
|
| 122 |
+
"top_terms": [
|
| 123 |
+
{"term": str(vocab[i]), "weight": float(arr[i])}
|
| 124 |
+
for i in idx if arr[i] > 0
|
| 125 |
+
]
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _anomaly_check(req: ClassifyRequest) -> dict:
|
| 130 |
+
"""Runs the Isolation Forest on the incident metadata."""
|
| 131 |
+
bundle = artefacts.anomaly_bundle
|
| 132 |
+
|
| 133 |
+
row = {
|
| 134 |
+
"description_length" : len(req.description),
|
| 135 |
+
"resolution_time_minutes" : 0,
|
| 136 |
+
"affected_services_count" : req.affected_services_count or 0,
|
| 137 |
+
}
|
| 138 |
+
impact_col = f"impact_{req.service_impact or 'unknown'}"
|
| 139 |
+
|
| 140 |
+
feat = pd.DataFrame([row])
|
| 141 |
+
for col in bundle["feature_columns"]:
|
| 142 |
+
if col not in feat.columns:
|
| 143 |
+
feat[col] = 1 if col == impact_col else 0
|
| 144 |
+
feat = feat[bundle["feature_columns"]]
|
| 145 |
+
|
| 146 |
+
scaled = bundle["scaler"].transform(feat)
|
| 147 |
+
score = float(bundle["model"].decision_function(scaled)[0])
|
| 148 |
+
flag = int(bundle["model"].predict(scaled)[0]) # -1 = anomaly, 1 = normal
|
| 149 |
+
|
| 150 |
+
return {"is_anomaly": flag == -1, "score": score}
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 154 |
+
# /classify
|
| 155 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 156 |
+
@app.post("/classify", response_model=ClassifyResponse)
|
| 157 |
+
def classify(
|
| 158 |
+
req: ClassifyRequest,
|
| 159 |
+
include_remediation: bool = Query(
|
| 160 |
+
True,
|
| 161 |
+
description="If false, skip the Claude Haiku call and return faster.",
|
| 162 |
+
),
|
| 163 |
+
):
|
| 164 |
+
"""Classifies one incident end to end."""
|
| 165 |
+
started = time.perf_counter()
|
| 166 |
+
|
| 167 |
+
text_anonymised = anonymise(req.description)
|
| 168 |
+
if not text_anonymised:
|
| 169 |
+
raise HTTPException(status_code=422, detail="Description anonymised to empty string.")
|
| 170 |
+
|
| 171 |
+
ml_label, prob = _predict_3class(text_anonymised)
|
| 172 |
+
binary_label = _predict_binary(text_anonymised)
|
| 173 |
+
final, escalated, reason = apply_escalation_rule(ml_label, req.original_impact)
|
| 174 |
+
|
| 175 |
+
explanation = _explain(text_anonymised, predicted_class=ml_label)
|
| 176 |
+
anomaly = _anomaly_check(req)
|
| 177 |
+
|
| 178 |
+
remediation = None
|
| 179 |
+
if include_remediation:
|
| 180 |
+
remediation = generate_remediation(req.description, final)
|
| 181 |
+
|
| 182 |
+
elapsed_ms = int((time.perf_counter() - started) * 1000)
|
| 183 |
+
|
| 184 |
+
return ClassifyResponse(
|
| 185 |
+
incident_id = req.incident_id,
|
| 186 |
+
ml_severity_3class = ml_label,
|
| 187 |
+
final_severity = final,
|
| 188 |
+
severity_binary = binary_label,
|
| 189 |
+
confidence = confidence_label(prob),
|
| 190 |
+
confidence_score = prob,
|
| 191 |
+
escalated = escalated,
|
| 192 |
+
escalation_reason = reason,
|
| 193 |
+
explanation = explanation,
|
| 194 |
+
anomaly = anomaly,
|
| 195 |
+
remediation = remediation,
|
| 196 |
+
processing_ms = elapsed_ms,
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 201 |
+
# /similar
|
| 202 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 203 |
+
@app.post("/similar", response_model=SimilarResponse)
|
| 204 |
+
def similar(req: SimilarRequest):
|
| 205 |
+
"""Finds the top-k most similar past incidents using MiniLM embeddings."""
|
| 206 |
+
text_anonymised = anonymise(req.description)
|
| 207 |
+
if not text_anonymised:
|
| 208 |
+
raise HTTPException(status_code=422, detail="Description anonymised to empty string.")
|
| 209 |
+
|
| 210 |
+
query_vec = artefacts.minilm_model.encode(
|
| 211 |
+
[text_anonymised],
|
| 212 |
+
normalize_embeddings=True,
|
| 213 |
+
)[0]
|
| 214 |
+
|
| 215 |
+
# Embeddings are L2-normalised, so dot product == cosine similarity
|
| 216 |
+
sims = artefacts.minilm_embeddings @ query_vec
|
| 217 |
+
top_idx = np.argsort(sims)[::-1][:req.top_k]
|
| 218 |
+
|
| 219 |
+
results = []
|
| 220 |
+
for i in top_idx:
|
| 221 |
+
row = artefacts.minilm_index.iloc[int(i)]
|
| 222 |
+
results.append(SimilarIncident(
|
| 223 |
+
incident_id = str(row["incident_id"]),
|
| 224 |
+
provider = str(row["provider"]),
|
| 225 |
+
service = str(row["service"]) if pd.notna(row.get("service")) else None,
|
| 226 |
+
severity = str(row["severity"]),
|
| 227 |
+
description = str(row["description_raw"])[:500],
|
| 228 |
+
similarity = float(sims[int(i)]),
|
| 229 |
+
))
|
| 230 |
+
|
| 231 |
+
return SimilarResponse(results=results)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 235 |
+
# /metrics
|
| 236 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 237 |
+
@app.get("/metrics", response_model=MetricsResponse)
|
| 238 |
+
def metrics():
|
| 239 |
+
"""Static evaluation results from notebook 09."""
|
| 240 |
+
if not artefacts.metrics:
|
| 241 |
+
raise HTTPException(status_code=503, detail="Metrics not yet computed.")
|
| 242 |
+
|
| 243 |
+
return MetricsResponse(
|
| 244 |
+
dataset_size = len(artefacts.minilm_index),
|
| 245 |
+
train_size = 0, # filled from results CSV when notebook 09 writes it
|
| 246 |
+
val_size = 0,
|
| 247 |
+
test_size = 0,
|
| 248 |
+
**artefacts.metrics,
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 253 |
+
# /health
|
| 254 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 255 |
+
@app.get("/health", response_model=HealthResponse)
|
| 256 |
+
def health():
|
| 257 |
+
"""Readiness probe for the dashboard and the data engineer's pipeline."""
|
| 258 |
+
loaded = {
|
| 259 |
+
"tfidf" : artefacts is not None and artefacts.tfidf is not None,
|
| 260 |
+
"classifier_3class": artefacts is not None and artefacts.classifier_3class is not None,
|
| 261 |
+
"classifier_binary": artefacts is not None and artefacts.classifier_binary is not None,
|
| 262 |
+
"anomaly_model" : artefacts is not None and artefacts.anomaly_bundle is not None,
|
| 263 |
+
"minilm_embeddings": artefacts is not None and artefacts.minilm_embeddings is not None,
|
| 264 |
+
}
|
| 265 |
+
status = "ok" if all(loaded.values()) else "degraded"
|
| 266 |
+
return HealthResponse(
|
| 267 |
+
status = status,
|
| 268 |
+
artefacts_loaded = loaded,
|
| 269 |
+
timestamp = datetime.utcnow(),
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 273 |
+
# /weekly
|
| 274 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 275 |
+
@app.post("/weekly", response_model=WeeklyResponse)
|
| 276 |
+
def weekly(req: WeeklyRequest):
|
| 277 |
+
"""Weekly intelligence pass.
|
| 278 |
+
|
| 279 |
+
Aggregates a batch of already-classified incidents over a date range and
|
| 280 |
+
produces a natural-language intelligence report. Mădălina's pipeline calls
|
| 281 |
+
/classify throughout the week, then posts the batch here for the report.
|
| 282 |
+
|
| 283 |
+
Hotspot detection and trend deltas are computed deterministically in Python.
|
| 284 |
+
Only the natural-language summary uses Claude Haiku.
|
| 285 |
+
"""
|
| 286 |
+
incidents = [inc.model_dump() for inc in req.incidents]
|
| 287 |
+
previous = (
|
| 288 |
+
[inc.model_dump() for inc in req.previous_week]
|
| 289 |
+
if req.previous_week else None
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
report = build_weekly_report(
|
| 293 |
+
incidents = incidents,
|
| 294 |
+
period_start = req.period_start,
|
| 295 |
+
period_end = req.period_end,
|
| 296 |
+
anthropic_client= anthropic_client,
|
| 297 |
+
previous_week = previous,
|
| 298 |
+
)
|
| 299 |
+
return WeeklyResponse(**report)
|
api/preprocessing.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Preprocessing helpers used at inference time.
|
| 3 |
+
|
| 4 |
+
Mirrors exactly what notebook 00 does to the training data, so a description
|
| 5 |
+
arriving from the data engineer's pipeline is anonymised the same way the
|
| 6 |
+
training corpus was.
|
| 7 |
+
"""
|
| 8 |
+
import re
|
| 9 |
+
|
| 10 |
+
URL_PATTERN = re.compile(r"https?://\S+|www\.\S+", flags=re.IGNORECASE)
|
| 11 |
+
|
| 12 |
+
# Same provider list as notebook 00. Kept here so the API can run standalone.
|
| 13 |
+
PROVIDER_VARIANTS = sorted({
|
| 14 |
+
"amazon", "aws", "microsoft azure", "azure", "google cloud", "gcp",
|
| 15 |
+
"cloudflare", "fastly", "datadog", "pagerduty", "twilio", "sendgrid",
|
| 16 |
+
"stripe", "github", "gitlab", "atlassian", "jira", "confluent", "slack",
|
| 17 |
+
"discord", "mongodb", "vercel", "hubspot", "circleci", "typeform",
|
| 18 |
+
"zoom", "digitalocean", "new relic", "shopify", "openai", "intercom",
|
| 19 |
+
"linear", "spotify",
|
| 20 |
+
}, key=len, reverse=True)
|
| 21 |
+
|
| 22 |
+
PROVIDER_PATTERN = re.compile(
|
| 23 |
+
r"\b(" + "|".join(re.escape(p) for p in PROVIDER_VARIANTS) + r")\b",
|
| 24 |
+
flags=re.IGNORECASE,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def anonymise(text: str) -> str:
|
| 29 |
+
"""Replaces URLs and provider names with generic tokens.
|
| 30 |
+
|
| 31 |
+
Identical to the training-time preprocessing in notebook 00. Any change here
|
| 32 |
+
must be mirrored in notebook 00 or the model and inference will diverge.
|
| 33 |
+
"""
|
| 34 |
+
if not isinstance(text, str):
|
| 35 |
+
return ""
|
| 36 |
+
text = URL_PATTERN.sub("URL", text)
|
| 37 |
+
text = PROVIDER_PATTERN.sub("PROVIDER", text)
|
| 38 |
+
text = re.sub(r"\s+", " ", text).strip()
|
| 39 |
+
return text
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def confidence_label(probability: float) -> str:
|
| 43 |
+
"""Bins a predicted probability into a confidence label for the dashboard."""
|
| 44 |
+
if probability >= 0.75:
|
| 45 |
+
return "high"
|
| 46 |
+
if probability >= 0.50:
|
| 47 |
+
return "medium"
|
| 48 |
+
return "low"
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def apply_escalation_rule(
|
| 52 |
+
ml_prediction: str,
|
| 53 |
+
original_impact: str | None,
|
| 54 |
+
) -> tuple[str, bool, str | None]:
|
| 55 |
+
"""The CloudPulse escalation rule.
|
| 56 |
+
|
| 57 |
+
If the classifier predicts 'high' AND the upstream provider tagged the
|
| 58 |
+
incident as 'critical', the final label is upgraded to 'critical'.
|
| 59 |
+
Otherwise the model prediction stands.
|
| 60 |
+
|
| 61 |
+
Returns (final_label, was_escalated, reason).
|
| 62 |
+
"""
|
| 63 |
+
if ml_prediction == "high" and original_impact == "critical":
|
| 64 |
+
return "critical", True, "provider_marked_critical"
|
| 65 |
+
return ml_prediction, False, None
|
api/remediation.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Claude Haiku remediation generator.
|
| 3 |
+
|
| 4 |
+
Same prompt template as notebook 10. Returns a typed RemediationBlock or None
|
| 5 |
+
on failure. The endpoint never blows up on a remediation error — it returns the
|
| 6 |
+
classification result and lets the dashboard show a placeholder.
|
| 7 |
+
"""
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
from typing import Optional
|
| 11 |
+
|
| 12 |
+
from anthropic import Anthropic
|
| 13 |
+
|
| 14 |
+
from .schemas import RemediationBlock
|
| 15 |
+
|
| 16 |
+
REMEDIATION_SYSTEM = """You are a senior site reliability engineer producing concise,
|
| 17 |
+
actionable remediation guidance for cloud infrastructure incidents.
|
| 18 |
+
|
| 19 |
+
Respond ONLY with valid JSON matching this exact schema:
|
| 20 |
+
|
| 21 |
+
{
|
| 22 |
+
"summary": "one or two sentence description of what broke",
|
| 23 |
+
"root_cause_hypothesis": "the most likely root cause given the incident description",
|
| 24 |
+
"immediate_mitigation": ["concrete action 1", "concrete action 2", "concrete action 3"],
|
| 25 |
+
"investigation": ["specific log or metric to check 1", "..."],
|
| 26 |
+
"prevention": ["long-term action 1", "..."]
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
Be concrete. No hedging language. No general SRE advice. Specific to this incident."""
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
_client: Optional[Anthropic] = None
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _get_client() -> Anthropic:
|
| 36 |
+
global _client
|
| 37 |
+
if _client is None:
|
| 38 |
+
_client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
|
| 39 |
+
return _client
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def generate_remediation(
|
| 43 |
+
description: str,
|
| 44 |
+
severity: str,
|
| 45 |
+
model: str = "claude-haiku-4-5-20251001",
|
| 46 |
+
) -> Optional[RemediationBlock]:
|
| 47 |
+
"""Calls Claude Haiku and parses the JSON remediation. Returns None on failure."""
|
| 48 |
+
try:
|
| 49 |
+
client = _get_client()
|
| 50 |
+
response = client.messages.create(
|
| 51 |
+
model=model,
|
| 52 |
+
max_tokens=800,
|
| 53 |
+
system=REMEDIATION_SYSTEM,
|
| 54 |
+
messages=[{
|
| 55 |
+
"role": "user",
|
| 56 |
+
"content": f"Severity: {severity}\nDescription: {description}",
|
| 57 |
+
}],
|
| 58 |
+
)
|
| 59 |
+
text = response.content[0].text.strip()
|
| 60 |
+
|
| 61 |
+
# Strip markdown fences
|
| 62 |
+
if text.startswith("```"):
|
| 63 |
+
text = text.split("```")[1]
|
| 64 |
+
if text.startswith("json"):
|
| 65 |
+
text = text[4:]
|
| 66 |
+
text = text.strip()
|
| 67 |
+
|
| 68 |
+
data = json.loads(text)
|
| 69 |
+
return RemediationBlock(**data)
|
| 70 |
+
except Exception:
|
| 71 |
+
# Caller decides what to do. Failing the whole request because remediation
|
| 72 |
+
# generation hiccuped would make the dashboard worse, not better.
|
| 73 |
+
return None
|
api/schemas.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Pydantic schemas for the CloudPulse AI service.
|
| 3 |
+
|
| 4 |
+
These define the request and response contracts that the data engineer's pipeline
|
| 5 |
+
will conform to. Every endpoint is fully typed, every field is documented.
|
| 6 |
+
"""
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
from typing import Literal, Optional
|
| 9 |
+
|
| 10 |
+
from pydantic import BaseModel, Field
|
| 11 |
+
|
| 12 |
+
# Severity values used across the system
|
| 13 |
+
Severity4Class = Literal["low", "medium", "high", "critical"]
|
| 14 |
+
Severity3Class = Literal["low", "medium", "high"]
|
| 15 |
+
SeverityBinary = Literal["severe", "not_severe"]
|
| 16 |
+
OriginalImpact = Literal["none", "minor", "major", "critical"]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 20 |
+
# /classify
|
| 21 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 22 |
+
class ClassifyRequest(BaseModel):
|
| 23 |
+
"""Incident classification request from the data engineer's pipeline."""
|
| 24 |
+
|
| 25 |
+
incident_id: str = Field(..., description="Unique incident identifier")
|
| 26 |
+
description: str = Field(..., min_length=1, description="Raw incident description text")
|
| 27 |
+
original_impact: Optional[OriginalImpact] = Field(
|
| 28 |
+
None,
|
| 29 |
+
description="Provider's own severity tag from the upstream API. Used by the "
|
| 30 |
+
"escalation rule to upgrade high to critical when applicable.",
|
| 31 |
+
)
|
| 32 |
+
provider: Optional[str] = Field(None, description="Cloud or service provider name")
|
| 33 |
+
service: Optional[str] = Field(None, description="Affected service name")
|
| 34 |
+
affected_services_count: Optional[int] = Field(
|
| 35 |
+
None, ge=0, description="Number of affected services for anomaly detection"
|
| 36 |
+
)
|
| 37 |
+
service_impact: Optional[str] = Field(
|
| 38 |
+
None, description="Type of service impact (compute, ai, platform, storage, network)"
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class RemediationBlock(BaseModel):
|
| 43 |
+
"""Structured remediation generated by Claude Haiku."""
|
| 44 |
+
|
| 45 |
+
summary: str
|
| 46 |
+
root_cause_hypothesis: str
|
| 47 |
+
immediate_mitigation: list[str]
|
| 48 |
+
investigation: list[str]
|
| 49 |
+
prevention: list[str]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class ClassifyResponse(BaseModel):
|
| 53 |
+
"""Full classification response sent back to the pipeline."""
|
| 54 |
+
|
| 55 |
+
incident_id: str
|
| 56 |
+
|
| 57 |
+
ml_severity_3class: Severity3Class = Field(
|
| 58 |
+
..., description="Raw 3-class prediction from the trained classifier"
|
| 59 |
+
)
|
| 60 |
+
final_severity: Severity4Class = Field(
|
| 61 |
+
..., description="Final label after escalation rule. high becomes critical "
|
| 62 |
+
"if original_impact is critical."
|
| 63 |
+
)
|
| 64 |
+
severity_binary: SeverityBinary = Field(
|
| 65 |
+
..., description="Binary classification (severe vs not_severe)"
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
confidence: Literal["high", "medium", "low"] = Field(
|
| 69 |
+
..., description="Confidence label derived from model probability"
|
| 70 |
+
)
|
| 71 |
+
confidence_score: float = Field(
|
| 72 |
+
..., ge=0.0, le=1.0, description="Probability of the predicted class"
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
escalated: bool = Field(
|
| 76 |
+
..., description="True if the rule upgraded the model prediction to critical"
|
| 77 |
+
)
|
| 78 |
+
escalation_reason: Optional[str] = Field(
|
| 79 |
+
None, description="Why the escalation fired (or None)"
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
explanation: dict = Field(
|
| 83 |
+
..., description="Top contributing TF-IDF terms with weights"
|
| 84 |
+
)
|
| 85 |
+
anomaly: dict = Field(
|
| 86 |
+
..., description="Anomaly detection result"
|
| 87 |
+
)
|
| 88 |
+
remediation: Optional[RemediationBlock] = Field(
|
| 89 |
+
None, description="Structured remediation. Returned when ?include_remediation=true"
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
processing_ms: int
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 96 |
+
# /similar
|
| 97 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 98 |
+
class SimilarRequest(BaseModel):
|
| 99 |
+
description: str = Field(..., min_length=1)
|
| 100 |
+
top_k: int = Field(3, ge=1, le=10)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class SimilarIncident(BaseModel):
|
| 104 |
+
incident_id: str
|
| 105 |
+
provider: str
|
| 106 |
+
service: Optional[str]
|
| 107 |
+
severity: str
|
| 108 |
+
description: str
|
| 109 |
+
similarity: float = Field(..., ge=0.0, le=1.0)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class SimilarResponse(BaseModel):
|
| 113 |
+
results: list[SimilarIncident]
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 117 |
+
# /metrics
|
| 118 |
+
# ─────────────────────────────────────────────────���───────────────────────────
|
| 119 |
+
class MetricsResponse(BaseModel):
|
| 120 |
+
"""Static evaluation results loaded from notebook 09."""
|
| 121 |
+
dataset_size: int
|
| 122 |
+
train_size: int
|
| 123 |
+
val_size: int
|
| 124 |
+
test_size: int
|
| 125 |
+
best_3class_model: str
|
| 126 |
+
best_3class_macro_f1: float
|
| 127 |
+
best_binary_model: str
|
| 128 |
+
best_binary_macro_f1: float
|
| 129 |
+
per_class_f1: dict
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 133 |
+
# /health
|
| 134 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 135 |
+
class HealthResponse(BaseModel):
|
| 136 |
+
status: Literal["ok", "degraded"]
|
| 137 |
+
artefacts_loaded: dict[str, bool]
|
| 138 |
+
timestamp: datetime
|
| 139 |
+
|
| 140 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 141 |
+
# /weekly
|
| 142 |
+
# ─────────────────────────────────────────────────────────────────────────────
|
| 143 |
+
class ClassifiedIncidentInput(BaseModel):
|
| 144 |
+
"""Input for an already-classified incident in the weekly batch.
|
| 145 |
+
|
| 146 |
+
Mădălina'\''s pipeline classifies incidents via /classify throughout the week,
|
| 147 |
+
then batches them and posts to /weekly for the natural-language report.
|
| 148 |
+
"""
|
| 149 |
+
incident_id : str
|
| 150 |
+
provider : str
|
| 151 |
+
service : Optional[str] = None
|
| 152 |
+
final_severity: Severity4Class
|
| 153 |
+
description : Optional[str] = None
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class WeeklyRequest(BaseModel):
|
| 157 |
+
"""Weekly intelligence pass request."""
|
| 158 |
+
period_start : str = Field(..., description="ISO date, e.g. 2026-04-27")
|
| 159 |
+
period_end : str = Field(..., description="ISO date, e.g. 2026-05-04")
|
| 160 |
+
incidents : list[ClassifiedIncidentInput]
|
| 161 |
+
previous_week: Optional[list[ClassifiedIncidentInput]] = Field(
|
| 162 |
+
None,
|
| 163 |
+
description="Previous week incidents for week-on-week trend deltas. Optional.",
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class WeeklyResponse(BaseModel):
|
| 168 |
+
"""Weekly intelligence pass response."""
|
| 169 |
+
period_start : str
|
| 170 |
+
period_end : str
|
| 171 |
+
total_incidents: int
|
| 172 |
+
summary : str = Field(..., description="Natural-language report from Claude Haiku")
|
| 173 |
+
aggregation : Optional[dict] = Field(
|
| 174 |
+
None,
|
| 175 |
+
description="Deterministic aggregation: hotspots, severity counts, trend deltas, notable incidents",
|
| 176 |
+
)
|
api/weekly.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
CloudPulse — Weekly Intelligence Pass
|
| 3 |
+
|
| 4 |
+
Aggregates classified incidents over a date range and produces a natural-language
|
| 5 |
+
intelligence report. Powers the `POST /weekly` endpoint.
|
| 6 |
+
|
| 7 |
+
Two input modes:
|
| 8 |
+
1. JSON list of classified incidents (provided by the caller)
|
| 9 |
+
2. SQL query against Mădălina's TimescaleDB (when DATABASE_URL is set)
|
| 10 |
+
|
| 11 |
+
Mode 2 is preferred in production. Mode 1 is the contract Mădălina's pipeline
|
| 12 |
+
uses today: she batches a week's worth of classifications and posts them.
|
| 13 |
+
|
| 14 |
+
The aggregation logic is pure Python; only the natural-language summary uses
|
| 15 |
+
Claude Haiku. Hotspot detection and trend deltas are deterministic.
|
| 16 |
+
"""
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import json
|
| 20 |
+
import os
|
| 21 |
+
from collections import Counter, defaultdict
|
| 22 |
+
from dataclasses import dataclass, field
|
| 23 |
+
from datetime import datetime, timedelta
|
| 24 |
+
from typing import Any
|
| 25 |
+
|
| 26 |
+
from anthropic import Anthropic
|
| 27 |
+
|
| 28 |
+
CLAUDE_MODEL = "claude-haiku-4-5-20251001"
|
| 29 |
+
|
| 30 |
+
SUMMARY_SYSTEM_PROMPT = """You are an SRE intelligence analyst writing a weekly
|
| 31 |
+
incident summary for engineering leadership.
|
| 32 |
+
|
| 33 |
+
You will receive aggregated incident statistics. Produce a concise report with
|
| 34 |
+
these sections:
|
| 35 |
+
|
| 36 |
+
1. **Executive summary** — 2-3 sentences on the week's overall reliability picture.
|
| 37 |
+
2. **Top hotspots** — which providers and services drove the most severe incidents.
|
| 38 |
+
3. **Trend** — how this week compares to the previous week (volume, severity).
|
| 39 |
+
4. **What to watch next week** — 2-3 specific things engineering should monitor.
|
| 40 |
+
|
| 41 |
+
Be concrete. Reference numbers from the data. No hedging language. No generic
|
| 42 |
+
SRE advice. Write as if briefing a CTO."""
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@dataclass
|
| 46 |
+
class WeeklyAggregation:
|
| 47 |
+
"""Pure Python aggregation result. No LLM in here."""
|
| 48 |
+
period_start : str
|
| 49 |
+
period_end : str
|
| 50 |
+
total_incidents: int
|
| 51 |
+
severity_counts: dict
|
| 52 |
+
provider_severity_matrix: dict # provider -> severity -> count
|
| 53 |
+
service_severity_matrix : dict # service -> severity -> count
|
| 54 |
+
top_hotspots_provider : list # [{"provider": ..., "severe_count": ...}]
|
| 55 |
+
top_hotspots_service : list
|
| 56 |
+
severity_trend : dict # week-on-week deltas (if previous week given)
|
| 57 |
+
notable_incidents : list # critical + high incidents, full descriptions
|
| 58 |
+
|
| 59 |
+
def to_dict(self) -> dict:
|
| 60 |
+
return {
|
| 61 |
+
"period_start" : self.period_start,
|
| 62 |
+
"period_end" : self.period_end,
|
| 63 |
+
"total_incidents" : self.total_incidents,
|
| 64 |
+
"severity_counts" : self.severity_counts,
|
| 65 |
+
"provider_severity_matrix": self.provider_severity_matrix,
|
| 66 |
+
"service_severity_matrix" : self.service_severity_matrix,
|
| 67 |
+
"top_hotspots_provider" : self.top_hotspots_provider,
|
| 68 |
+
"top_hotspots_service" : self.top_hotspots_service,
|
| 69 |
+
"severity_trend" : self.severity_trend,
|
| 70 |
+
"notable_incidents" : self.notable_incidents,
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def aggregate(
|
| 75 |
+
incidents : list[dict],
|
| 76 |
+
period_start : str,
|
| 77 |
+
period_end : str,
|
| 78 |
+
previous_week : list[dict] | None = None,
|
| 79 |
+
top_n : int = 5,
|
| 80 |
+
) -> WeeklyAggregation:
|
| 81 |
+
"""Build the aggregation. Pure Python, deterministic, fast."""
|
| 82 |
+
severity_counts = Counter(inc["final_severity"] for inc in incidents)
|
| 83 |
+
|
| 84 |
+
provider_matrix = defaultdict(lambda: defaultdict(int))
|
| 85 |
+
service_matrix = defaultdict(lambda: defaultdict(int))
|
| 86 |
+
for inc in incidents:
|
| 87 |
+
sev = inc["final_severity"]
|
| 88 |
+
provider_matrix[inc.get("provider", "unknown")][sev] += 1
|
| 89 |
+
service_matrix[inc.get("service", "unknown")][sev] += 1
|
| 90 |
+
|
| 91 |
+
# Hotspots: providers/services with most critical+high incidents
|
| 92 |
+
def severe_score(matrix_row):
|
| 93 |
+
return matrix_row.get("critical", 0) * 2 + matrix_row.get("high", 0)
|
| 94 |
+
|
| 95 |
+
top_providers = sorted(
|
| 96 |
+
[(p, severe_score(s), dict(s)) for p, s in provider_matrix.items()],
|
| 97 |
+
key=lambda t: -t[1],
|
| 98 |
+
)[:top_n]
|
| 99 |
+
top_services = sorted(
|
| 100 |
+
[(s, severe_score(sv), dict(sv)) for s, sv in service_matrix.items()],
|
| 101 |
+
key=lambda t: -t[1],
|
| 102 |
+
)[:top_n]
|
| 103 |
+
|
| 104 |
+
top_hotspots_provider = [
|
| 105 |
+
{"provider": p, "severe_score": score, "severity_breakdown": breakdown}
|
| 106 |
+
for p, score, breakdown in top_providers
|
| 107 |
+
]
|
| 108 |
+
top_hotspots_service = [
|
| 109 |
+
{"service": s, "severe_score": score, "severity_breakdown": breakdown}
|
| 110 |
+
for s, score, breakdown in top_services
|
| 111 |
+
]
|
| 112 |
+
|
| 113 |
+
severity_trend: dict = {}
|
| 114 |
+
if previous_week:
|
| 115 |
+
prev_counts = Counter(inc["final_severity"] for inc in previous_week)
|
| 116 |
+
for sev in ["critical", "high", "medium", "low"]:
|
| 117 |
+
curr = severity_counts.get(sev, 0)
|
| 118 |
+
prev = prev_counts.get(sev, 0)
|
| 119 |
+
severity_trend[sev] = {
|
| 120 |
+
"this_week": curr,
|
| 121 |
+
"last_week": prev,
|
| 122 |
+
"delta" : curr - prev,
|
| 123 |
+
"delta_pct": ((curr - prev) / prev * 100) if prev > 0 else None,
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
# Notable incidents: critical and high, capped at 10 to keep prompt size bounded
|
| 127 |
+
notable_incidents = [
|
| 128 |
+
{
|
| 129 |
+
"incident_id" : inc.get("incident_id"),
|
| 130 |
+
"provider" : inc.get("provider"),
|
| 131 |
+
"service" : inc.get("service"),
|
| 132 |
+
"final_severity": inc.get("final_severity"),
|
| 133 |
+
"description" : (inc.get("description") or "")[:300],
|
| 134 |
+
}
|
| 135 |
+
for inc in incidents
|
| 136 |
+
if inc.get("final_severity") in {"critical", "high"}
|
| 137 |
+
][:10]
|
| 138 |
+
|
| 139 |
+
return WeeklyAggregation(
|
| 140 |
+
period_start=period_start,
|
| 141 |
+
period_end=period_end,
|
| 142 |
+
total_incidents=len(incidents),
|
| 143 |
+
severity_counts=dict(severity_counts),
|
| 144 |
+
provider_severity_matrix={p: dict(s) for p, s in provider_matrix.items()},
|
| 145 |
+
service_severity_matrix={s: dict(sv) for s, sv in service_matrix.items()},
|
| 146 |
+
top_hotspots_provider=top_hotspots_provider,
|
| 147 |
+
top_hotspots_service=top_hotspots_service,
|
| 148 |
+
severity_trend=severity_trend,
|
| 149 |
+
notable_incidents=notable_incidents,
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def generate_summary(aggregation: WeeklyAggregation, anthropic_client: Anthropic) -> str:
|
| 154 |
+
"""Pass the aggregation to Claude Haiku and ask for a natural-language report."""
|
| 155 |
+
payload = json.dumps(aggregation.to_dict(), indent=2)
|
| 156 |
+
|
| 157 |
+
response = anthropic_client.messages.create(
|
| 158 |
+
model=CLAUDE_MODEL,
|
| 159 |
+
max_tokens=1500,
|
| 160 |
+
system=SUMMARY_SYSTEM_PROMPT,
|
| 161 |
+
messages=[{
|
| 162 |
+
"role": "user",
|
| 163 |
+
"content": f"Aggregated incident data for the period {aggregation.period_start} to {aggregation.period_end}:\n\n{payload}\n\nWrite the weekly intelligence report.",
|
| 164 |
+
}],
|
| 165 |
+
)
|
| 166 |
+
return response.content[0].text.strip()
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def build_weekly_report(
|
| 170 |
+
incidents : list[dict],
|
| 171 |
+
period_start : str,
|
| 172 |
+
period_end : str,
|
| 173 |
+
anthropic_client: Anthropic,
|
| 174 |
+
previous_week : list[dict] | None = None,
|
| 175 |
+
) -> dict:
|
| 176 |
+
"""Top-level entry point used by the FastAPI endpoint."""
|
| 177 |
+
if not incidents:
|
| 178 |
+
return {
|
| 179 |
+
"period_start" : period_start,
|
| 180 |
+
"period_end" : period_end,
|
| 181 |
+
"total_incidents": 0,
|
| 182 |
+
"summary" : "No incidents in the requested period.",
|
| 183 |
+
"aggregation" : None,
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
agg = aggregate(incidents, period_start, period_end, previous_week=previous_week)
|
| 187 |
+
summary = generate_summary(agg, anthropic_client)
|
| 188 |
+
return {
|
| 189 |
+
"period_start" : period_start,
|
| 190 |
+
"period_end" : period_end,
|
| 191 |
+
"total_incidents": agg.total_incidents,
|
| 192 |
+
"summary" : summary,
|
| 193 |
+
"aggregation" : agg.to_dict(),
|
| 194 |
+
}
|
artefacts/.gitkeep
ADDED
|
File without changes
|
artefacts/02_features/X_test_tfidf.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:86f83ddb75c8cf2172718f3e361ced06404ec5f57e48952228a65adb915a5f10
|
| 3 |
+
size 75985
|
artefacts/02_features/X_train_tfidf.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8689318ed03caa68a4a51c4843ea4be15e127caa2c18d68a3839519616054659
|
| 3 |
+
size 656424
|
artefacts/02_features/X_val_tfidf.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8b4b77e91efc9a6dd4c681636fd15ea0f8d8c0b4cb73e4e5c9b4d6dc931e006e
|
| 3 |
+
size 79758
|
artefacts/02_features/tfidf_top_terms.png
ADDED
|
artefacts/02_features/tfidf_vectoriser.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:808fdd5b0835d6e0d97ab10d1d467301c91d3391b405b5b19ba73bf61846a893
|
| 3 |
+
size 200514
|
artefacts/02_features/y_test_3class.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4cc9e2cb036643470116aa912403da7b25c3f0d4f79b3dd335f11f4f80c41b10
|
| 3 |
+
size 475
|
artefacts/02_features/y_test_4class.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:db687b8844f899859483737e411c20b4f033036a73d27aa02df698f5e1a303f3
|
| 3 |
+
size 484
|
artefacts/02_features/y_test_binary.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:78e90abe09a09b5bfe656bfcd3e061659377a72ace16cfdb363e1d9dffb4016b
|
| 3 |
+
size 477
|
artefacts/02_features/y_train_3class.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:af9c3a2b9695843dba437d4a4c2834ac82608f68674d4403514727bf1d74cc19
|
| 3 |
+
size 1748
|
artefacts/02_features/y_train_4class.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:48503aa914851e7e24131ec1f2b5aa088036f163b0af656bedfb5a2877d4f890
|
| 3 |
+
size 1757
|
artefacts/02_features/y_train_binary.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ec7d2c138d32e79a80fd564f39e102427dff831c6b824a68955bf1bce789f5a3
|
| 3 |
+
size 1750
|
artefacts/02_features/y_val_3class.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:49f4bc2442beb0122260d9cffe90e46f5d4d1655ebda5ae66b08e389ca6284a1
|
| 3 |
+
size 475
|
artefacts/02_features/y_val_4class.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:aba851f61980852b0bfc36b4de40261f55bbe87b65b9e8002c5013219dfa7935
|
| 3 |
+
size 484
|
artefacts/02_features/y_val_binary.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7f905355935b08b369cba789989e3e70b61403bad0df38b1e6a6f13ad323f352
|
| 3 |
+
size 477
|
artefacts/03_logreg/logreg_3class.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:75de992012bc6c9f67cc23f30c8fb29b7b0cec3a54935a8c5f6eb475d5cee768
|
| 3 |
+
size 121039
|
artefacts/03_logreg/logreg_3class_confusion_matrix.png
ADDED
|
artefacts/03_logreg/logreg_3class_results.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"best_params": {
|
| 3 |
+
"C": 5.0
|
| 4 |
+
},
|
| 5 |
+
"val_macro_f1": 0.6843763303533419,
|
| 6 |
+
"test_macro_f1": 0.5944337766398786,
|
| 7 |
+
"per_class": {
|
| 8 |
+
"low": {
|
| 9 |
+
"precision": 0.6818181818181818,
|
| 10 |
+
"recall": 0.7142857142857143,
|
| 11 |
+
"f1": 0.6976744186046512,
|
| 12 |
+
"support": 21
|
| 13 |
+
},
|
| 14 |
+
"medium": {
|
| 15 |
+
"precision": 0.7592592592592593,
|
| 16 |
+
"recall": 0.7454545454545455,
|
| 17 |
+
"f1": 0.7522935779816514,
|
| 18 |
+
"support": 55
|
| 19 |
+
},
|
| 20 |
+
"high": {
|
| 21 |
+
"precision": 0.3333333333333333,
|
| 22 |
+
"recall": 0.3333333333333333,
|
| 23 |
+
"f1": 0.3333333333333333,
|
| 24 |
+
"support": 15
|
| 25 |
+
}
|
| 26 |
+
}
|
| 27 |
+
}
|
artefacts/03_logreg/logreg_binary.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:05989136618d3e49e3ca1a6c9c18cdc248b28189ea5ff7eee8a1f5e8a5359cf0
|
| 3 |
+
size 41023
|
artefacts/03_logreg/logreg_binary_confusion_matrix.png
ADDED
|
artefacts/03_logreg/logreg_binary_results.json
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"best_params": {
|
| 3 |
+
"C": 0.5
|
| 4 |
+
},
|
| 5 |
+
"val_macro_f1": 0.6438024231127679,
|
| 6 |
+
"test_macro_f1": 0.6438024231127679,
|
| 7 |
+
"per_class": {
|
| 8 |
+
"not_severe": {
|
| 9 |
+
"precision": 0.8985507246376812,
|
| 10 |
+
"recall": 0.8157894736842105,
|
| 11 |
+
"f1": 0.8551724137931035,
|
| 12 |
+
"support": 76
|
| 13 |
+
},
|
| 14 |
+
"severe": {
|
| 15 |
+
"precision": 0.36363636363636365,
|
| 16 |
+
"recall": 0.5333333333333333,
|
| 17 |
+
"f1": 0.43243243243243246,
|
| 18 |
+
"support": 15
|
| 19 |
+
}
|
| 20 |
+
}
|
| 21 |
+
}
|
artefacts/03_logreg/logreg_classification_reports.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
=== 3-class ===
|
| 2 |
+
precision recall f1-score support
|
| 3 |
+
|
| 4 |
+
high 0.333 0.333 0.333 15
|
| 5 |
+
low 0.682 0.714 0.698 21
|
| 6 |
+
medium 0.759 0.745 0.752 55
|
| 7 |
+
|
| 8 |
+
accuracy 0.670 91
|
| 9 |
+
macro avg 0.591 0.598 0.594 91
|
| 10 |
+
weighted avg 0.671 0.670 0.671 91
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
=== Binary ===
|
| 14 |
+
precision recall f1-score support
|
| 15 |
+
|
| 16 |
+
not_severe 0.899 0.816 0.855 76
|
| 17 |
+
severe 0.364 0.533 0.432 15
|
| 18 |
+
|
| 19 |
+
accuracy 0.769 91
|
| 20 |
+
macro avg 0.631 0.675 0.644 91
|
| 21 |
+
weighted avg 0.810 0.769 0.785 91
|
artefacts/04_xgboost/xgb_3class.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:907094aae3980c68d68fb6022aabf15e25106291c275777f269497de0b07350c
|
| 3 |
+
size 1777359
|
artefacts/04_xgboost/xgb_3class_confusion_matrix.png
ADDED
|
artefacts/04_xgboost/xgb_3class_results.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"best_params": {
|
| 3 |
+
"n_estimators": 300,
|
| 4 |
+
"max_depth": 8,
|
| 5 |
+
"learning_rate": 0.05
|
| 6 |
+
},
|
| 7 |
+
"val_macro_f1": 0.7196223316912972,
|
| 8 |
+
"test_macro_f1": 0.6366586686354129,
|
| 9 |
+
"per_class": {
|
| 10 |
+
"low": {
|
| 11 |
+
"precision": 0.6818181818181818,
|
| 12 |
+
"recall": 0.7142857142857143,
|
| 13 |
+
"f1": 0.6976744186046512,
|
| 14 |
+
"support": 21
|
| 15 |
+
},
|
| 16 |
+
"medium": {
|
| 17 |
+
"precision": 0.7543859649122807,
|
| 18 |
+
"recall": 0.7818181818181819,
|
| 19 |
+
"f1": 0.7678571428571429,
|
| 20 |
+
"support": 55
|
| 21 |
+
},
|
| 22 |
+
"high": {
|
| 23 |
+
"precision": 0.5,
|
| 24 |
+
"recall": 0.4,
|
| 25 |
+
"f1": 0.4444444444444444,
|
| 26 |
+
"support": 15
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
}
|
artefacts/04_xgboost/xgb_binary.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bd5e6969314a4293a4352b0329de3e55fa289c2bef72613d03265024d1dfaebe
|
| 3 |
+
size 563907
|
artefacts/04_xgboost/xgb_binary_confusion_matrix.png
ADDED
|
artefacts/04_xgboost/xgb_binary_results.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"best_params": {
|
| 3 |
+
"n_estimators": 300,
|
| 4 |
+
"max_depth": 8,
|
| 5 |
+
"learning_rate": 0.05
|
| 6 |
+
},
|
| 7 |
+
"val_macro_f1": 0.7307692307692308,
|
| 8 |
+
"test_macro_f1": 0.6623376623376623,
|
| 9 |
+
"per_class": {
|
| 10 |
+
"not_severe": {
|
| 11 |
+
"precision": 0.8846153846153846,
|
| 12 |
+
"recall": 0.9078947368421053,
|
| 13 |
+
"f1": 0.8961038961038961,
|
| 14 |
+
"support": 76
|
| 15 |
+
},
|
| 16 |
+
"severe": {
|
| 17 |
+
"precision": 0.46153846153846156,
|
| 18 |
+
"recall": 0.4,
|
| 19 |
+
"f1": 0.42857142857142855,
|
| 20 |
+
"support": 15
|
| 21 |
+
}
|
| 22 |
+
}
|
| 23 |
+
}
|
artefacts/04_xgboost/xgb_classification_reports.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
=== 3-class ===
|
| 2 |
+
precision recall f1-score support
|
| 3 |
+
|
| 4 |
+
high 0.500 0.400 0.444 15
|
| 5 |
+
low 0.682 0.714 0.698 21
|
| 6 |
+
medium 0.754 0.782 0.768 55
|
| 7 |
+
|
| 8 |
+
accuracy 0.703 91
|
| 9 |
+
macro avg 0.645 0.632 0.637 91
|
| 10 |
+
weighted avg 0.696 0.703 0.698 91
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
=== Binary ===
|
| 14 |
+
precision recall f1-score support
|
| 15 |
+
|
| 16 |
+
not_severe 0.885 0.908 0.896 76
|
| 17 |
+
severe 0.462 0.400 0.429 15
|
| 18 |
+
|
| 19 |
+
accuracy 0.824 91
|
| 20 |
+
macro avg 0.673 0.654 0.662 91
|
| 21 |
+
weighted avg 0.815 0.824 0.819 91
|
artefacts/05_svm/svm_3class.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7b9ba3c1b9e58149f3422ff1310487d4055fa2538f56b1c1efc302d238328f45
|
| 3 |
+
size 363550
|
artefacts/05_svm/svm_3class_confusion_matrix.png
ADDED
|
artefacts/05_svm/svm_3class_results.json
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"best_params": {
|
| 3 |
+
"C": 1.0
|
| 4 |
+
},
|
| 5 |
+
"val_macro_f1": 0.665079365079365,
|
| 6 |
+
"test_macro_f1": 0.537772795837312,
|
| 7 |
+
"per_class": {
|
| 8 |
+
"low": {
|
| 9 |
+
"precision": 0.75,
|
| 10 |
+
"recall": 0.5714285714285714,
|
| 11 |
+
"f1": 0.6486486486486487,
|
| 12 |
+
"support": 21
|
| 13 |
+
},
|
| 14 |
+
"medium": {
|
| 15 |
+
"precision": 0.6956521739130435,
|
| 16 |
+
"recall": 0.8727272727272727,
|
| 17 |
+
"f1": 0.7741935483870968,
|
| 18 |
+
"support": 55
|
| 19 |
+
},
|
| 20 |
+
"high": {
|
| 21 |
+
"precision": 0.3333333333333333,
|
| 22 |
+
"recall": 0.13333333333333333,
|
| 23 |
+
"f1": 0.19047619047619047,
|
| 24 |
+
"support": 15
|
| 25 |
+
}
|
| 26 |
+
}
|
| 27 |
+
}
|
artefacts/05_svm/svm_binary.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:04c912ca06e73d85611e5193eae51ea845bdb6bf3eb4bae9a624d67cd098dcaf
|
| 3 |
+
size 123165
|
artefacts/05_svm/svm_binary_confusion_matrix.png
ADDED
|
artefacts/05_svm/svm_binary_results.json
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"best_params": {
|
| 3 |
+
"C": 0.5
|
| 4 |
+
},
|
| 5 |
+
"val_macro_f1": 0.6380681818181818,
|
| 6 |
+
"test_macro_f1": 0.5962732919254659,
|
| 7 |
+
"per_class": {
|
| 8 |
+
"not_severe": {
|
| 9 |
+
"precision": 0.8588235294117647,
|
| 10 |
+
"recall": 0.9605263157894737,
|
| 11 |
+
"f1": 0.906832298136646,
|
| 12 |
+
"support": 76
|
| 13 |
+
},
|
| 14 |
+
"severe": {
|
| 15 |
+
"precision": 0.5,
|
| 16 |
+
"recall": 0.2,
|
| 17 |
+
"f1": 0.2857142857142857,
|
| 18 |
+
"support": 15
|
| 19 |
+
}
|
| 20 |
+
}
|
| 21 |
+
}
|
artefacts/05_svm/svm_classification_reports.txt
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
=== 3-class ===
|
| 2 |
+
precision recall f1-score support
|
| 3 |
+
|
| 4 |
+
high 0.333 0.133 0.190 15
|
| 5 |
+
low 0.750 0.571 0.649 21
|
| 6 |
+
medium 0.696 0.873 0.774 55
|
| 7 |
+
|
| 8 |
+
accuracy 0.681 91
|
| 9 |
+
macro avg 0.593 0.526 0.538 91
|
| 10 |
+
weighted avg 0.648 0.681 0.649 91
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
=== Binary ===
|
| 14 |
+
precision recall f1-score support
|
| 15 |
+
|
| 16 |
+
not_severe 0.859 0.961 0.907 76
|
| 17 |
+
severe 0.500 0.200 0.286 15
|
| 18 |
+
|
| 19 |
+
accuracy 0.835 91
|
| 20 |
+
macro avg 0.679 0.580 0.596 91
|
| 21 |
+
weighted avg 0.800 0.835 0.804 91
|
artefacts/06_random_forest/rf_3class.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3b53a2bad5d3caba85b26b80dadd3e8f58822627159cca564ba8f3f44cdc6547
|
| 3 |
+
size 5702545
|
artefacts/06_random_forest/rf_3class_confusion_matrix.png
ADDED
|
artefacts/06_random_forest/rf_3class_results.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"best_params": {
|
| 3 |
+
"n_estimators": 200,
|
| 4 |
+
"max_depth": null,
|
| 5 |
+
"min_samples_split": 2
|
| 6 |
+
},
|
| 7 |
+
"val_macro_f1": 0.6574144997648323,
|
| 8 |
+
"test_macro_f1": 0.6196114146933819,
|
| 9 |
+
"per_class": {
|
| 10 |
+
"low": {
|
| 11 |
+
"precision": 0.8666666666666667,
|
| 12 |
+
"recall": 0.6190476190476191,
|
| 13 |
+
"f1": 0.7222222222222222,
|
| 14 |
+
"support": 21
|
| 15 |
+
},
|
| 16 |
+
"medium": {
|
| 17 |
+
"precision": 0.7313432835820896,
|
| 18 |
+
"recall": 0.8909090909090909,
|
| 19 |
+
"f1": 0.8032786885245902,
|
| 20 |
+
"support": 55
|
| 21 |
+
},
|
| 22 |
+
"high": {
|
| 23 |
+
"precision": 0.4444444444444444,
|
| 24 |
+
"recall": 0.26666666666666666,
|
| 25 |
+
"f1": 0.3333333333333333,
|
| 26 |
+
"support": 15
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
}
|
artefacts/06_random_forest/rf_binary.joblib
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:68ce35a163f5824f29712299d7daed96c0f87c8324b79c8cde53dcb340558ddd
|
| 3 |
+
size 3283865
|
artefacts/06_random_forest/rf_binary_confusion_matrix.png
ADDED
|