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(""" """, 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'', 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("
NetWokie AI - AI-Powered Network Monitoring System
Built with Streamlit | ML Models | Ollama Integration