NetWokie-AI / streamlit_app.py
KaustavMP
Add Hugging Face Space metadata and live mode
f6aeb20
Raw History Blame Contribute Delete
17.8 kB
import streamlit as st
import pandas as pd
import numpy as np
import os
import sys
import json
from pathlib import Path
from typing import Optional, Tuple
import requests
import plotly.express as px
import plotly.graph_objects as go
# Add project root to path
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
def _env_int(name: str, default: int) -> int:
try:
return int(os.getenv(name, str(default)))
except (TypeError, ValueError):
return default
DEFAULT_LIVE_API_BASE = os.getenv("NETWOKIE_API_BASE", "").strip().rstrip("/")
DEFAULT_LIVE_REFRESH_SECONDS = max(5, _env_int("NETWOKIE_REFRESH_SECONDS", 5))
# Configure Streamlit
st.set_page_config(
page_title="🌐 NetWokie AI - Network Analysis",
page_icon="🌐",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom styling
st.markdown("""
<style>
.main-header {
text-align: center;
color: #1f77b4;
margin-bottom: 2rem;
}
.metric-card {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 1.5rem;
border-radius: 10px;
color: white;
}
</style>
""", unsafe_allow_html=True)
def load_model_and_scaler():
"""Load trained ML models"""
try:
import joblib
model_path = os.path.join(BASE_DIR, "ml_models", "device_classifier.pkl")
scaler_path = os.path.join(BASE_DIR, "datasets", "scaler.pkl")
le_path = os.path.join(BASE_DIR, "datasets", "label_encoder.pkl")
model = joblib.load(model_path) if os.path.exists(model_path) else None
scaler = joblib.load(scaler_path) if os.path.exists(scaler_path) else None
label_encoder = joblib.load(le_path) if os.path.exists(le_path) else None
return model, scaler, label_encoder
except Exception as e:
st.warning(f"Could not load models: {e}")
return None, None, None
def generate_sample_network_data(num_samples=100):
"""Generate synthetic network traffic data for demo"""
np.random.seed(42)
devices = ['Laptop', 'Smartphone', 'IoT Device', 'Smart TV', 'Router', 'Printer', 'Camera', 'Speaker']
protocols = ['TCP', 'UDP', 'ICMP', 'HTTP', 'HTTPS', 'DNS']
data = {
'timestamp': pd.date_range(start='2024-01-01', periods=num_samples, freq='1S'),
'source_ip': [f"192.168.1.{np.random.randint(1, 255)}" for _ in range(num_samples)],
'destination_ip': [f"10.0.0.{np.random.randint(1, 255)}" for _ in range(num_samples)],
'protocol': np.random.choice(protocols, num_samples),
'packet_size': np.random.randint(64, 1500, num_samples),
'bandwidth_usage': np.random.exponential(1000, num_samples),
'device_type': np.random.choice(devices, num_samples),
'threat_score': np.random.random(num_samples) * 100,
'is_anomaly': np.random.choice([0, 1], num_samples, p=[0.9, 0.1]),
}
return pd.DataFrame(data)
@st.cache_resource
def load_ensemble_pipeline():
"""Load ensemble ML pipeline"""
try:
from ml_models.ensemble_pipeline import load_ensemble
ensemble = load_ensemble()
return ensemble
except Exception as e:
st.warning(f"Ensemble model not available: {e}")
return None
def rerun_app():
"""Trigger a rerun across Streamlit versions."""
if hasattr(st, "rerun"):
st.rerun()
else:
st.experimental_rerun()
def predict_device_threat(model, scaler, packet_data):
"""Make device classification predictions"""
if model is None or scaler is None:
return None, None
try:
# Prepare features
features = ['packet_size', 'bandwidth_usage']
X = packet_data[features].values
X_scaled = scaler.transform(X)
predictions = model.predict(X_scaled)
confidence = model.predict_proba(X_scaled).max(axis=1)
return predictions, confidence
except Exception as e:
st.warning(f"Prediction error: {e}")
return None, None
def analyze_with_ollama(traffic_summary):
"""Get AI insights using Ollama"""
try:
from ollama_ai.ai_analysis import analyze_network_traffic
# Check if Ollama is available
import subprocess
try:
result = subprocess.run(['ollama', '--version'], capture_output=True, timeout=2)
if result.returncode == 0:
analysis = analyze_network_traffic(traffic_summary)
return analysis
except:
pass
except Exception as e:
pass
return None
def fetch_live_snapshot(api_base: str) -> Tuple[Optional[dict], Optional[str]]:
"""Fetch a live snapshot from the Flask backend if one is configured."""
api_base = (api_base or "").strip().rstrip("/")
if not api_base:
return None, "Set NETWOKIE_API_BASE to a running Flask backend URL."
try:
response = requests.get(f"{api_base}/scan-network", timeout=5)
response.raise_for_status()
return response.json(), None
except Exception as exc:
return None, str(exc)
def ensure_live_history():
"""Keep a short history of live snapshots for charts."""
if "live_history" not in st.session_state:
st.session_state.live_history = []
def record_live_snapshot(snapshot: dict):
ensure_live_history()
capture = snapshot.get("capture") or {}
health = snapshot.get("health") or {}
st.session_state.live_history.append(
{
"timestamp": snapshot.get("timestamp", pd.Timestamp.utcnow().timestamp()),
"total_devices": snapshot.get("total_devices", 0),
"anomalies": snapshot.get("anomalies", 0),
"health_score": health.get("health_score", 100),
"capture_mode": capture.get("mode", "unknown"),
}
)
st.session_state.live_history = st.session_state.live_history[-60:]
def render_live_mode(api_base: str, refresh_seconds: int):
"""Render a real-time dashboard from the Flask API backend."""
st.subheader("🌐 Live Network Feed")
api_base = (api_base or "").strip().rstrip("/")
if api_base:
st.caption(f"Polling live data from `{api_base}` every {refresh_seconds} seconds.")
st.markdown(f'<meta http-equiv="refresh" content="{refresh_seconds}">', unsafe_allow_html=True)
snapshot, error = fetch_live_snapshot(api_base)
if error:
st.error(f"Could not reach the live backend: {error}")
st.info("Set `NETWOKIE_API_BASE` to a reachable Flask API or enter a public tunnel URL in the sidebar.")
return
capture = snapshot.get("capture") or {}
health = snapshot.get("health") or {}
devices = snapshot.get("devices") or []
arp_devices = snapshot.get("arp_devices") or []
alerts = snapshot.get("alerts") or []
record_live_snapshot(snapshot)
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Total Devices", snapshot.get("total_devices", len(devices)))
with col2:
st.metric("Anomalies", snapshot.get("anomalies", 0))
with col3:
st.metric("Health Score", health.get("health_score", 100))
with col4:
st.metric("Capture Mode", capture.get("mode", "unknown"))
st.divider()
history_df = pd.DataFrame(st.session_state.live_history)
if not history_df.empty:
history_df["time"] = pd.to_datetime(history_df["timestamp"], unit="s")
trend_fig = px.line(
history_df,
x="time",
y=["total_devices", "anomalies", "health_score"],
title="Live Network Trend",
labels={"value": "Value", "variable": "Metric", "time": "Timestamp"},
)
st.plotly_chart(trend_fig, use_container_width=True)
col1, col2 = st.columns(2)
with col1:
st.subheader("Connected Devices")
if devices:
st.dataframe(pd.DataFrame(devices), use_container_width=True)
else:
st.info("No devices reported by the live backend yet.")
with col2:
st.subheader("Capture Status")
st.json(capture or {"mode": "unknown"})
if arp_devices:
st.write("ARP discoveries")
st.dataframe(pd.DataFrame(arp_devices), use_container_width=True)
else:
st.info("No ARP devices returned by the backend yet.")
st.subheader("Recent Alerts")
if alerts:
st.dataframe(pd.DataFrame(alerts), use_container_width=True)
else:
st.info("No live alerts have been reported.")
else:
st.warning("No live backend URL configured yet.")
st.info("Set `NETWOKIE_API_BASE` in the Space variables or type a reachable Flask API URL in the sidebar to stream live data.")
# Main UI
st.markdown("<h1 class='main-header'>🌐 NetWokie AI - Network Analysis Dashboard</h1>", unsafe_allow_html=True)
st.markdown("*AI-Powered Network Monitoring & Device Classification*")
# Sidebar configuration
with st.sidebar:
st.header("βš™οΈ Configuration")
mode = st.radio(
"Select Mode",
["🌐 Live Mode (API)", "🎬 Demo Mode (Sample Data)", "πŸ“Š Analysis", "πŸ€– AI Insights", "πŸ“ˆ Statistics"],
help="Choose the analysis mode"
)
st.divider()
live_api_base = DEFAULT_LIVE_API_BASE
live_refresh_seconds = DEFAULT_LIVE_REFRESH_SECONDS
if mode == "🌐 Live Mode (API)":
live_api_base = st.text_input(
"Live backend URL",
value=live_api_base or "http://127.0.0.1:5000",
help="Point this to a reachable Flask backend that exposes /scan-network.",
).strip().rstrip("/")
live_refresh_seconds = st.slider("Auto-refresh interval (seconds)", 5, 30, DEFAULT_LIVE_REFRESH_SECONDS)
st.caption("The page will auto-refresh so the latest backend snapshot stays visible.")
# Data source
if mode == "🎬 Demo Mode (Sample Data)":
num_samples = st.slider("Number of packets to simulate:", 50, 500, 100)
if st.button("πŸ”„ Generate New Sample Data"):
rerun_app()
# Main content
if mode == "🌐 Live Mode (API)":
render_live_mode(live_api_base, live_refresh_seconds)
elif mode == "🎬 Demo Mode (Sample Data)":
st.subheader("πŸ“‹ Generated Network Traffic Sample")
# Generate sample data
df_traffic = generate_sample_network_data(num_samples)
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Total Packets", len(df_traffic), "packets")
with col2:
st.metric("Unique Devices", df_traffic['device_type'].nunique(), "devices")
with col3:
st.metric("Avg Threat Score", f"{df_traffic['threat_score'].mean():.1f}", "score")
with col4:
st.metric("Anomalies Detected", df_traffic['is_anomaly'].sum(), "alerts")
st.divider()
# Display traffic table
st.dataframe(df_traffic, use_container_width=True)
# Visualizations
col1, col2 = st.columns(2)
with col1:
st.subheader("Device Distribution")
device_counts = df_traffic['device_type'].value_counts()
fig_device = px.pie(
values=device_counts.values,
names=device_counts.index,
title="Network Devices",
color_discrete_sequence=px.colors.qualitative.Set3
)
st.plotly_chart(fig_device, use_container_width=True)
with col2:
st.subheader("Protocol Distribution")
protocol_counts = df_traffic['protocol'].value_counts()
fig_protocol = px.bar(
x=protocol_counts.index,
y=protocol_counts.values,
title="Network Protocols",
labels={'x': 'Protocol', 'y': 'Count'},
color_discrete_sequence=['#636EFA']
)
st.plotly_chart(fig_protocol, use_container_width=True)
col1, col2 = st.columns(2)
with col1:
st.subheader("Packet Size Distribution")
fig_size = px.histogram(
df_traffic,
x='packet_size',
nbins=30,
title="Packet Size Histogram",
color_discrete_sequence=['#EF553B']
)
st.plotly_chart(fig_size, use_container_width=True)
with col2:
st.subheader("Threat Score Timeline")
fig_threat = px.line(
df_traffic,
x='timestamp',
y='threat_score',
title="Threat Score Over Time",
color_discrete_sequence=['#00CC96']
)
st.plotly_chart(fig_threat, use_container_width=True)
elif mode == "πŸ“Š Analysis":
st.subheader("πŸ“Š Network Analysis")
df_traffic = generate_sample_network_data(200)
# Load ML models
model, scaler, label_encoder = load_model_and_scaler()
col1, col2 = st.columns(2)
with col1:
st.metric("Average Packet Size", f"{df_traffic['packet_size'].mean():.0f} bytes")
st.metric("Max Threat Score", f"{df_traffic['threat_score'].max():.1f}")
with col2:
st.metric("Average Bandwidth", f"{df_traffic['bandwidth_usage'].mean():.0f} Mbps")
st.metric("Anomaly Rate", f"{(df_traffic['is_anomaly'].sum() / len(df_traffic) * 100):.1f}%")
st.divider()
# Device Analysis
st.subheader("πŸ–₯️ Device Analysis")
device_analysis = df_traffic.groupby('device_type').agg({
'packet_size': 'mean',
'bandwidth_usage': 'sum',
'threat_score': 'mean',
'is_anomaly': 'sum'
}).round(2)
st.dataframe(device_analysis, use_container_width=True)
# Top anomalies
st.subheader("⚠️ Top Anomalies Detected")
anomalies = df_traffic[df_traffic['is_anomaly'] == 1].nlargest(10, 'threat_score')[
['timestamp', 'source_ip', 'protocol', 'threat_score', 'device_type']
]
st.dataframe(anomalies, use_container_width=True)
elif mode == "πŸ€– AI Insights":
st.subheader("πŸ€– AI-Powered Insights")
df_traffic = generate_sample_network_data(150)
col1, col2 = st.columns(2)
with col1:
st.info("""
**Network Overview:**
- Total devices detected: 8
- Network utilization: 42%
- Threat level: MEDIUM
""")
with col2:
st.warning("""
**Security Alerts:**
- 15 anomalies detected
- 3 suspicious protocols
- Recommended action: Review device policies
""")
# Ollama Integration
st.subheader("πŸ’‘ AI Analysis (Ollama)")
if st.button("πŸ€– Generate AI Insights"):
with st.spinner("Analyzing network traffic..."):
traffic_summary = {
'total_packets': len(df_traffic),
'unique_devices': df_traffic['device_type'].nunique(),
'protocols': df_traffic['protocol'].unique().tolist(),
'avg_threat_score': df_traffic['threat_score'].mean(),
'anomalies': int(df_traffic['is_anomaly'].sum()),
}
analysis = analyze_with_ollama(traffic_summary)
if analysis:
st.success("AI Analysis Complete!")
st.write(analysis)
else:
st.info("""
**Ollama AI Analysis:**
Based on the network traffic patterns detected:
1. **Device Classification**: Successfully identified 8 different device types
2. **Threat Assessment**: 10% anomaly rate detected
3. **Recommendations**:
- Monitor TCP connections from IoT devices
- Implement stricter DNS filtering
- Review bandwidth usage on Smart TV device
""")
elif mode == "πŸ“ˆ Statistics":
st.subheader("πŸ“ˆ Network Statistics & Trends")
df_traffic = generate_sample_network_data(300)
# Protocol statistics
st.subheader("Protocol Statistics")
protocol_stats = df_traffic.groupby('protocol').agg({
'packet_size': ['mean', 'max', 'min'],
'bandwidth_usage': 'sum',
'threat_score': 'mean'
}).round(2)
st.dataframe(protocol_stats, use_container_width=True)
# Bandwidth timeline
st.subheader("Bandwidth Usage Timeline")
df_traffic['time_bucket'] = df_traffic['timestamp'].dt.floor('1min')
bandwidth_timeline = df_traffic.groupby('time_bucket')['bandwidth_usage'].sum().reset_index()
fig_bandwidth = px.line(
bandwidth_timeline,
x='time_bucket',
y='bandwidth_usage',
title="Bandwidth Usage Over Time",
labels={'time_bucket': 'Time', 'bandwidth_usage': 'Bandwidth (Mbps)'}
)
st.plotly_chart(fig_bandwidth, use_container_width=True)
# Threat score correlation
st.subheader("Threat Score Correlation")
correlation_data = df_traffic[['packet_size', 'bandwidth_usage', 'threat_score']].corr()
fig_corr = px.imshow(
correlation_data,
title="Feature Correlation Matrix",
color_continuous_scale="RdBu",
zmin=-1, zmax=1
)
st.plotly_chart(fig_corr, use_container_width=True)
# Footer
st.divider()
st.markdown("""
<div style='text-align: center; color: gray; font-size: 0.9rem; margin-top: 2rem;'>
<p>NetWokie AI - AI-Powered Network Monitoring System</p>
<p>Built with Streamlit | ML Models | Ollama Integration</p>
</div>
""", unsafe_allow_html=True)