NavAI-Guard / app.py
sourize's picture
Update app.py
5580f19 verified
import streamlit as st
import numpy as np
import pandas as pd
import joblib
from tensorflow.keras.models import load_model
# Cache the model so it's loaded only once per session
@st.cache_resource
def load_my_model():
return load_model("autoencoder_model.keras")
# Cache the scaler as well
@st.cache_resource
def load_my_scaler():
return joblib.load("scaler.pkl")
model = load_my_model()
scaler = load_my_scaler()
# Set an anomaly threshold (adjust based on your model calibration)
THRESHOLD = 0.1
st.title("NavAI-Guard : Maritime Anomaly Detection")
st.image("ship.webp")
st.markdown("### Input the following AIS features:")
# Taking inputs from the user
timestamp_str = st.text_input("# Timestamp (Format: DD/MM/YYYY HH:MM:SS)", "27/02/2024 03:42:19")
mmsi = st.number_input("MMSI", value=0.0)
latitude = st.number_input("Latitude", value=0.0)
longitude = st.number_input("Longitude", value=0.0)
sog = st.number_input("SOG", value=0.0)
cog = st.number_input("COG", value=0.0)
heading = st.number_input("Heading", value=0.0)
if st.button("Run Detection"):
try:
# Convert the timestamp to seconds since epoch
timestamp_sec = pd.to_datetime(timestamp_str, format="%d/%m/%Y %H:%M:%S").value / 1e9
except Exception as e:
st.error(f"Invalid Timestamp Format: {e}")
st.stop()
# Create an array from the inputs
input_data = np.array([[timestamp_sec, mmsi, latitude, longitude, sog, cog, heading]])
try:
# Scale the input data
input_scaled = scaler.transform(input_data)
# Reconstruct the input using the autoencoder
reconstructed = model.predict(input_scaled)
# Calculate the reconstruction error (Mean Squared Error)
reconstruction_error = np.mean(np.square(input_scaled - reconstructed))
# Display the result based on the threshold
if reconstruction_error > THRESHOLD:
st.error(f"Anomaly detected, Reconstruction Error = {reconstruction_error:.4f}")
else:
st.success(f"No anomaly detected, Reconstruction Error = {reconstruction_error:.4f}")
except Exception as e:
st.error(f"Error during detection: {e}")