File size: 13,067 Bytes
81e3338
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
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
from dotenv import load_dotenv
from pathlib import Path as _Path
load_dotenv(_Path(__file__).resolve().parent.parent.parent / ".env")
"""
CloudPulse AI service.

Exposes the trained classifiers, anomaly detector, similarity search and Claude
Haiku remediation as a single FastAPI service. The data engineer's pipeline calls
this service; the Lovable dashboard reads the responses through the data engineer's
storage layer.

Endpoints:

    POST /classify     classify one incident with explanation, anomaly score and remediation
    POST /similar      find the top-k most similar past incidents
    GET  /metrics      static evaluation results from notebook 09
    GET  /health       readiness probe
"""
import time
from contextlib import asynccontextmanager
from datetime import datetime
from pathlib import Path

import numpy as np
import pandas as pd
from fastapi import FastAPI, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware

from .artefacts import Artefacts, load_artefacts
from .preprocessing import anonymise, apply_escalation_rule, confidence_label
from anthropic import Anthropic

from .remediation import generate_remediation
from .weekly import build_weekly_report
from .schemas import (
    ClassifyRequest, ClassifyResponse,
    HealthResponse,
    MetricsResponse,
    SimilarRequest, SimilarResponse, SimilarIncident,
    WeeklyRequest, WeeklyResponse,
)

anthropic_client = Anthropic()


# ─────────────────────────────────────────────────────────────────────────────
# Lifespan: load every artefact once at startup
# ─────────────────────────────────────────────────────────────────────────────
artefacts: Artefacts | None = None


@asynccontextmanager
async def lifespan(app: FastAPI):
    global artefacts
    print("Loading artefacts...")
    artefacts = load_artefacts()
    print("Artefacts loaded.")
    yield


app = FastAPI(
    title="CloudPulse AI Service",
    version="1.0.0",
    description="Severity classification, similarity search and remediation generation.",
    lifespan=lifespan,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)


# ─────────────────────────────────────────────────────────────────────────────
# Internal helpers
# ─────────────────────────────────────────────────────────────────────────────
def _predict_3class(text_anonymised: str) -> tuple[str, float]:
    """Predicts the 3-class label and returns (label, probability)."""
    X = artefacts.tfidf.transform([text_anonymised])
    probs = artefacts.classifier_3class.predict_proba(X)[0]

    if artefacts.classifier_3class_label_encoder is not None:
        # XGBoost path with integer labels
        idx     = int(np.argmax(probs))
        label   = artefacts.classifier_3class_label_encoder.inverse_transform([idx])[0]
    else:
        idx   = int(np.argmax(probs))
        label = artefacts.classifier_3class.classes_[idx]

    return str(label), float(probs[idx])


def _predict_binary(text_anonymised: str) -> str:
    X = artefacts.tfidf.transform([text_anonymised])
    pred = artefacts.classifier_binary.predict(X)[0]
    if artefacts.classifier_binary_label_encoder is not None:
        pred = artefacts.classifier_binary_label_encoder.inverse_transform([pred])[0]
    return str(pred)


def _explain(text_anonymised: str, predicted_class: str, top_n: int = 5) -> dict:
    """Returns the top-N TF-IDF terms in this description ranked by their TF-IDF weight.

    A lightweight, model-agnostic explanation. Works for any TF-IDF based classifier
    in the bundle (logreg, svm, xgboost, rf). For a deeper SHAP-based explanation,
    add a separate /explain endpoint that loads the SHAP explainer.
    """
    X = artefacts.tfidf.transform([text_anonymised])

    if artefacts.shap_explainer is not None:
        return artefacts.shap_explainer.explain(
            x_tfidf=X,
            predicted_class=predicted_class,
            top_k=top_n,
        )
    arr   = X.toarray()[0]
    vocab = np.array(artefacts.tfidf.get_feature_names_out())
    idx   = np.argsort(arr)[::-1][:top_n]
    return {
        "top_terms": [
            {"term": str(vocab[i]), "weight": float(arr[i])}
            for i in idx if arr[i] > 0
        ]
    }


def _anomaly_check(req: ClassifyRequest) -> dict:
    """Runs the Isolation Forest on the incident metadata."""
    bundle = artefacts.anomaly_bundle

    row = {
        "description_length"      : len(req.description),
        "resolution_time_minutes" : 0,
        "affected_services_count" : req.affected_services_count or 0,
    }
    impact_col = f"impact_{req.service_impact or 'unknown'}"

    feat = pd.DataFrame([row])
    for col in bundle["feature_columns"]:
        if col not in feat.columns:
            feat[col] = 1 if col == impact_col else 0
    feat = feat[bundle["feature_columns"]]

    scaled = bundle["scaler"].transform(feat)
    score  = float(bundle["model"].decision_function(scaled)[0])
    flag   = int(bundle["model"].predict(scaled)[0])  # -1 = anomaly, 1 = normal

    return {"is_anomaly": flag == -1, "score": score}


# ─────────────────────────────────────────────────────────────────────────────
# /classify
# ─────────────────────────────────────────────────────────────────────────────
@app.post("/classify", response_model=ClassifyResponse)
def classify(
    req: ClassifyRequest,
    include_remediation: bool = Query(
        True,
        description="If false, skip the Claude Haiku call and return faster.",
    ),
):
    """Classifies one incident end to end."""
    started = time.perf_counter()

    text_anonymised = anonymise(req.description)
    if not text_anonymised:
        raise HTTPException(status_code=422, detail="Description anonymised to empty string.")

    ml_label, prob = _predict_3class(text_anonymised)
    binary_label   = _predict_binary(text_anonymised)
    final, escalated, reason = apply_escalation_rule(ml_label, req.original_impact)

    explanation = _explain(text_anonymised, predicted_class=ml_label)
    anomaly     = _anomaly_check(req)

    remediation = None
    if include_remediation:
        remediation = generate_remediation(req.description, final)

    elapsed_ms = int((time.perf_counter() - started) * 1000)

    return ClassifyResponse(
        incident_id        = req.incident_id,
        ml_severity_3class = ml_label,
        final_severity     = final,
        severity_binary    = binary_label,
        confidence         = confidence_label(prob),
        confidence_score   = prob,
        escalated          = escalated,
        escalation_reason  = reason,
        explanation        = explanation,
        anomaly            = anomaly,
        remediation        = remediation,
        processing_ms      = elapsed_ms,
    )


# ─────────────────────────────────────────────────────────────────────────────
# /similar
# ─────────────────────────────────────────────────────────────────────────────
@app.post("/similar", response_model=SimilarResponse)
def similar(req: SimilarRequest):
    """Finds the top-k most similar past incidents using MiniLM embeddings."""
    text_anonymised = anonymise(req.description)
    if not text_anonymised:
        raise HTTPException(status_code=422, detail="Description anonymised to empty string.")

    query_vec = artefacts.minilm_model.encode(
        [text_anonymised],
        normalize_embeddings=True,
    )[0]

    # Embeddings are L2-normalised, so dot product == cosine similarity
    sims = artefacts.minilm_embeddings @ query_vec
    top_idx = np.argsort(sims)[::-1][:req.top_k]

    results = []
    for i in top_idx:
        row = artefacts.minilm_index.iloc[int(i)]
        results.append(SimilarIncident(
            incident_id = str(row["incident_id"]),
            provider    = str(row["provider"]),
            service     = str(row["service"]) if pd.notna(row.get("service")) else None,
            severity    = str(row["severity"]),
            description = str(row["description_raw"])[:500],
            similarity  = float(sims[int(i)]),
        ))

    return SimilarResponse(results=results)


# ─────────────────────────────────────────────────────────────────────────────
# /metrics
# ─────────────────────────────────────────────────────────────────────────────
@app.get("/metrics", response_model=MetricsResponse)
def metrics():
    """Static evaluation results from notebook 09."""
    if not artefacts.metrics:
        raise HTTPException(status_code=503, detail="Metrics not yet computed.")

    return MetricsResponse(
        dataset_size = len(artefacts.minilm_index),
        train_size   = 0,  # filled from results CSV when notebook 09 writes it
        val_size     = 0,
        test_size    = 0,
        **artefacts.metrics,
    )


# ─────────────────────────────────────────────────────────────────────────────
# /health
# ─────────────────────────────────────────────────────────────────────────────
@app.get("/health", response_model=HealthResponse)
def health():
    """Readiness probe for the dashboard and the data engineer's pipeline."""
    loaded = {
        "tfidf"            : artefacts is not None and artefacts.tfidf is not None,
        "classifier_3class": artefacts is not None and artefacts.classifier_3class is not None,
        "classifier_binary": artefacts is not None and artefacts.classifier_binary is not None,
        "anomaly_model"    : artefacts is not None and artefacts.anomaly_bundle is not None,
        "minilm_embeddings": artefacts is not None and artefacts.minilm_embeddings is not None,
    }
    status = "ok" if all(loaded.values()) else "degraded"
    return HealthResponse(
        status           = status,
        artefacts_loaded = loaded,
        timestamp        = datetime.utcnow(),
    )

# ─────────────────────────────────────────────────────────────────────────────
# /weekly
# ─────────────────────────────────────────────────────────────────────────────
@app.post("/weekly", response_model=WeeklyResponse)
def weekly(req: WeeklyRequest):
    """Weekly intelligence pass.

    Aggregates a batch of already-classified incidents over a date range and
    produces a natural-language intelligence report. Mădălina's pipeline calls
    /classify throughout the week, then posts the batch here for the report.

    Hotspot detection and trend deltas are computed deterministically in Python.
    Only the natural-language summary uses Claude Haiku.
    """
    incidents = [inc.model_dump() for inc in req.incidents]
    previous  = (
        [inc.model_dump() for inc in req.previous_week]
        if req.previous_week else None
    )

    report = build_weekly_report(
        incidents       = incidents,
        period_start    = req.period_start,
        period_end      = req.period_end,
        anthropic_client= anthropic_client,
        previous_week   = previous,
    )
    return WeeklyResponse(**report)