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