File size: 1,803 Bytes
5a3b83f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
model_loader.py
---------------
Loads the production artifacts saved by Notebook 3 and exposes the single
detect_anomaly function the pages call. Mirrors the function tested at the end
of 3-Final_Model.ipynb.
"""

import os
import json
import numpy as np
import pandas as pd
import joblib
from tensorflow import keras

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
MODEL_DIR = os.path.join(BASE_DIR, "models")

_model = None
_scaler = None
_metadata = None


def _load():
    global _model, _scaler, _metadata
    if _model is None:
        _model = keras.models.load_model(os.path.join(MODEL_DIR, "autoencoder_model.keras"))
        _scaler = joblib.load(os.path.join(MODEL_DIR, "scaler.pkl"))
        with open(os.path.join(MODEL_DIR, "metadata.json")) as f:
            _metadata = json.load(f)
    return _model, _scaler, _metadata


def get_metadata():
    _, _, meta = _load()
    return meta


def detect_anomaly(reading):
    """
    reading: dict mapping each sensor name to a value.
    Returns dict with is_anomaly, score, threshold, ratio, top_sensors.
    """
    model, scaler, meta = _load()
    feature_cols = meta["feature_columns"]
    threshold = meta["threshold"]

    x = pd.DataFrame([[reading[c] for c in feature_cols]], columns=feature_cols)
    x_scaled = scaler.transform(x)
    recon = model.predict(x_scaled, verbose=0)

    per_sensor = ((x_scaled - recon) ** 2)[0]
    score = float(per_sensor.mean())

    ranked = sorted(zip(feature_cols, per_sensor.tolist()),
                    key=lambda t: t[1], reverse=True)

    return {
        "is_anomaly": bool(score > threshold),
        "score": score,
        "threshold": threshold,
        "ratio": score / threshold,
        "top_sensors": [{"sensor": s, "error": round(e, 6)} for s, e in ranked[:3]],
    }