AutoSense-Demo / pages /engine.py
Bmoussaouali
Deploy AutoSense anomaly detection app
5a3b83f
Raw History Blame Contribute Delete
6.57 kB
import os
import sys
import json
import dash
from dash import html, dcc, callback, Input, Output, State
import dash_bootstrap_components as dbc
import plotly.graph_objects as go
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from model_loader import detect_anomaly, get_metadata
dash.register_page(__name__, path="/engine", name="Anomaly Engine")
META = get_metadata()
FEATURES = META["feature_columns"]
FMIN = META["feature_min"]
FMAX = META["feature_max"]
UNITS = {"coolant_temp": "C", "manifold_pressure": "kPa", "rpm": "RPM", "speed": "km/h",
"intake_temp": "C", "mass_air_flow": "g/s", "throttle_pos": "%",
"ambient_temp": "C", "accel_pedal": "%"}
# Presets are derived from real data and verified against the loaded model
# (see the diagnostics in the final-model workflow). Healthy passes; the two
# fault presets genuinely cross the threshold.
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "presets.json")) as _f:
_PRESETS = json.load(_f)
HEALTHY_PRESET = _PRESETS["healthy"]
COOLANT_FAULT_PRESET = _PRESETS["coolant"]
INTAKE_FAULT_PRESET = _PRESETS["intake"]
DARK = dict(paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)",
font=dict(color="#cfcfcf"), margin=dict(l=20, r=20, t=30, b=20))
def slider_row(feature, idx):
lo, hi = FMIN[idx], FMAX[idx]
step = max(round((hi - lo) / 100, 2), 0.1)
return html.Div([
html.Div([
html.Label(feature, className="text-white fw-bold"),
html.Span(id=f"val-{feature}", className="text-info float-end"),
]),
dcc.Slider(
id=f"slider-{feature}", min=lo, max=hi, step=step,
value=HEALTHY_PRESET[feature],
marks={lo: f"{lo:.0f}", hi: f"{hi:.0f}"},
tooltip={"placement": "bottom", "always_visible": False},
className="sensor-slider",
),
html.Small(UNITS[feature], className="text-muted"),
], className="mb-3")
layout = html.Div([
html.Div([
html.H1("Anomaly Engine", className="text-white fw-bold mb-2"),
html.P("Adjust the engine sensors and watch the autoencoder judge whether the reading "
"fits healthy driving.", className="lead text-info"),
], className="mb-4"),
dbc.Row([
dbc.Col([
dbc.Card(dbc.CardBody([
html.Div([
html.H4("Sensor inputs", className="text-white mb-0 d-inline"),
html.Div([
dbc.Button("Healthy", id="preset-healthy", size="sm",
color="success", outline=True, className="me-1"),
dbc.Button("Coolant fault", id="preset-coolant", size="sm",
color="danger", outline=True, className="me-1"),
dbc.Button("Intake fault", id="preset-intake", size="sm",
color="danger", outline=True),
], className="float-end"),
], className="mb-4"),
html.Div([slider_row(f, i) for i, f in enumerate(FEATURES)]),
]), className="modern-card"),
], md=6, className="mb-4"),
dbc.Col([
dbc.Card(dbc.CardBody([
html.H4("Verdict", className="text-white mb-3"),
html.Div(id="verdict-status", className="text-center mb-3"),
html.Div(id="verdict-gauge"),
html.Hr(style={"borderColor": "rgba(255,255,255,0.1)"}),
html.H6("Sensors contributing most to the error", className="text-white mb-2"),
html.Div(id="verdict-sensors"),
]), className="modern-card"),
], md=6, className="mb-4"),
]),
])
@callback(
[Output(f"slider-{f}", "value") for f in FEATURES],
[Input("preset-healthy", "n_clicks"),
Input("preset-coolant", "n_clicks"),
Input("preset-intake", "n_clicks")],
prevent_initial_call=True,
)
def apply_preset(h, c, i):
trig = dash.callback_context.triggered[0]["prop_id"]
if "coolant" in trig:
preset = COOLANT_FAULT_PRESET
elif "intake" in trig:
preset = INTAKE_FAULT_PRESET
else:
preset = HEALTHY_PRESET
return [preset[f] for f in FEATURES]
@callback(
[Output(f"val-{f}", "children") for f in FEATURES],
[Input(f"slider-{f}", "value") for f in FEATURES],
)
def show_values(*values):
return [f"{v:.1f} {UNITS[f]}" for f, v in zip(FEATURES, values)]
@callback(
[Output("verdict-status", "children"),
Output("verdict-gauge", "children"),
Output("verdict-sensors", "children")],
[Input(f"slider-{f}", "value") for f in FEATURES],
)
def run_detection(*values):
reading = {f: v for f, v in zip(FEATURES, values)}
result = detect_anomaly(reading)
if result["is_anomaly"]:
status = html.Div([
html.I(className="bi bi-exclamation-triangle-fill fs-1 status-anomaly"),
html.H2("ANOMALY", className="status-anomaly fw-bold mt-2"),
html.P(f"{result['ratio']:.1f}x above threshold", className="text-muted"),
])
bar_color = "#e24b4a"
else:
status = html.Div([
html.I(className="bi bi-check-circle-fill fs-1 status-normal"),
html.H2("HEALTHY", className="status-normal fw-bold mt-2"),
html.P(f"{result['ratio']:.0%} of threshold", className="text-muted"),
])
bar_color = "#2fe0a5"
gauge = go.Figure(go.Indicator(
mode="gauge+number",
value=result["score"],
number={"valueformat": ".4f", "font": {"color": "#fff"}},
gauge={
"axis": {"range": [0, max(result["threshold"] * 3, result["score"] * 1.2)],
"tickcolor": "#888"},
"bar": {"color": bar_color},
"threshold": {"line": {"color": "red", "width": 3},
"value": result["threshold"]},
"bgcolor": "rgba(0,0,0,0)",
},
))
gauge.update_layout(height=220, **DARK)
sensors = html.Div([
html.Div([
html.Span(s["sensor"], className="text-light"),
html.Span(f"{s['error']:.4f}", className="text-info float-end"),
dbc.Progress(value=min(s["error"] / max(result["top_sensors"][0]["error"], 1e-6) * 100, 100),
color="info", className="mb-2", style={"height": "6px"}),
]) for s in result["top_sensors"]
])
return status, dcc.Graph(figure=gauge, config={"displayModeBar": False}), sensors