Wiguard-AI / app.py
A1mal's picture
Upload app.py
fbf75ec verified
Raw History Blame Contribute Delete
4.9 kB
import streamlit as st
import pandas as pd
import numpy as np
import time
import matplotlib.pyplot as plt
from src.capture import LiveCaptureModule, SimulatedCaptureModule
from src.features import FeatureExtractor
from src.model import WiGuardModel
from src.utils import initialize_dummy_models, check_dependencies
from loguru import logger
# Page Config
st.set_page_config(
page_title="WiGuard AI - IDS",
page_icon="🛡️",
layout="wide"
)
# Initialize Session State
if 'history' not in st.session_state:
st.session_state.history = pd.DataFrame(columns=['Time', 'Score', 'Threshold', 'Label'])
if 'running' not in st.session_state:
st.session_state.running = False
# Sidebar
st.sidebar.title("🛡️ WiGuard AI")
st.sidebar.markdown("---")
mode = st.sidebar.selectbox("Capture Mode", ["Simulation (Demo)", "Live Traffic (tshark)"])
interface = st.sidebar.text_input("Wireless Interface", value="en0")
st.sidebar.markdown("---")
# Load Models
@st.cache_resource
def load_ids_model():
model = WiGuardModel()
if not model.load_models():
initialize_dummy_models()
model.load_models()
return model
@st.cache_resource
def get_capture_module(mode, interface):
if mode == "Live Traffic (tshark)":
if not check_dependencies():
st.error("Error: 'tshark' not found on system. Falling back to Simulation.")
return SimulatedCaptureModule()
return LiveCaptureModule(interface=interface)
return SimulatedCaptureModule()
ids_model = load_ids_model()
extractor = FeatureExtractor()
capture = get_capture_module(mode, interface)
# Main UI
st.title("Wi-Fi Intrusion Detection System")
st.caption("Real-Time Privacy-Preserving Network Monitoring")
# Metrics Container
col1, col2, col3, col4 = st.columns(4)
metric_score = col1.empty()
metric_threshold = col2.empty()
metric_status = col3.empty()
metric_pcount = col4.empty()
# Layout for Charts
chart_col, data_col = st.columns([2, 1])
with chart_col:
chart_placeholder = st.empty()
alert_placeholder = st.empty()
with data_col:
st.subheader("System Logs & Alerts")
log_placeholder = st.empty()
# Control Buttons
if st.button("Start System" if not st.session_state.running else "Stop System"):
st.session_state.running = not st.session_state.running
if st.session_state.running:
st.toast("WiGuard AI is now monitoring traffic...")
# Main Loop
if st.session_state.running:
while st.session_state.running:
# 1. Capture Data
df_packet_window = capture.get_window_data()
# 2. Feature Extraction
features = extractor.extract(df_packet_window)
if features is not None:
# 3. Inference
result = ids_model.predict(features)
# 4. Update History
new_row = {
'Time': time.strftime('%H:%M:%S'),
'Score': result['anomaly_score'],
'Threshold': result['threshold'],
'Label': result['label']
}
st.session_state.history = pd.concat([st.session_state.history, pd.DataFrame([new_row])]).tail(30)
# 5. UI Updates
metric_score.metric("Anomaly Score", f"{result['anomaly_score']:.3f}")
metric_threshold.metric("Adaptive Threshold", f"{result['threshold']:.3f}")
status_color = "normal"
if result['is_anomaly']:
status_color = "inverse"
alert_placeholder.warning(f"⚠️ {result['label']} Detected!")
else:
alert_placeholder.empty()
metric_status.metric("Classification", result['label'])
metric_pcount.metric("Packets/Window", len(df_packet_window))
# Render Chart
fig, ax = plt.subplots(figsize=(10, 4))
ax.plot(st.session_state.history['Time'], st.session_state.history['Score'], label='Anomaly Score', color='#3b82f6', linewidth=2)
ax.axhline(y=result['threshold'], color='#ef4444', linestyle='--', label='Adaptive Threshold')
ax.set_ylim(0, 1.1)
ax.set_title("Real-Time Threat Level")
ax.legend()
plt.xticks(rotation=45)
chart_placeholder.pyplot(fig)
plt.close(fig)
# Feature Inspection
with st.expander("Inspect Raw Features"):
st.table(features)
# Heartbeat
time.sleep(1)
if not st.session_state.running:
break
else:
st.info("Click 'Start System' to begin real-time monitoring.")
st.image("https://images.unsplash.com/photo-1550751827-4bd374c3f58b?auto=format&fit=crop&q=80&w=1000", caption="WiGuard AI Protected Environment")
# Footer
st.markdown("---")
st.markdown("Developed for Academic Evaluation | WiGuard AI Project 2026")