Spaces:
Sleeping
Sleeping
Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# anomaly-engine/main.py
|
| 2 |
+
from fastapi import FastAPI
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
import numpy as np
|
| 5 |
+
from sklearn.ensemble import IsolationForest
|
| 6 |
+
import uvicorn
|
| 7 |
+
|
| 8 |
+
app = FastAPI(title="Omni-Node ML Engine")
|
| 9 |
+
|
| 10 |
+
# Train a baseline Isolation Forest for unsupervised anomaly detection
|
| 11 |
+
# Simulating baseline normal metrics: [CPU Load (%), Memory (GB), Latency (ms)]
|
| 12 |
+
baseline_data = np.random.normal(loc=[45.0, 16.0, 120.0], scale=[5.0, 2.0, 15.0], size=(1000, 3))
|
| 13 |
+
clf = IsolationForest(n_estimators=100, contamination=0.05, random_state=42)
|
| 14 |
+
clf.fit(baseline_data)
|
| 15 |
+
|
| 16 |
+
class TelemetryPayload(BaseModel):
|
| 17 |
+
component_id: str
|
| 18 |
+
cpu_load: float
|
| 19 |
+
memory_usage: float
|
| 20 |
+
api_latency: float
|
| 21 |
+
|
| 22 |
+
@app.post("/api/v1/analyze")
|
| 23 |
+
async def analyze_telemetry(data: TelemetryPayload):
|
| 24 |
+
# Format incoming telemetry into a 2D array
|
| 25 |
+
current_state = np.array([[data.cpu_load, data.memory_usage, data.api_latency]])
|
| 26 |
+
|
| 27 |
+
# Predict: 1 for normal, -1 for anomaly
|
| 28 |
+
prediction = clf.predict(current_state)[0]
|
| 29 |
+
score = clf.decision_function(current_state)[0]
|
| 30 |
+
|
| 31 |
+
is_critical = bool(prediction == -1)
|
| 32 |
+
|
| 33 |
+
return {
|
| 34 |
+
"component_id": data.component_id,
|
| 35 |
+
"is_critical": is_critical,
|
| 36 |
+
"anomaly_score": round(float(score), 4),
|
| 37 |
+
"status": "REQUIRES_REMEDIATION" if is_critical else "NOMINAL"
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
if __name__ == "__main__":
|
| 41 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|