AutoSense-Demo / model_loader.py
Bmoussaouali
Deploy AutoSense anomaly detection app
5a3b83f
Raw History Blame Contribute Delete
1.8 kB
"""
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]],
}