import streamlit as st import pandas as pd import numpy as np import joblib import json import os import time from datetime import datetime import plotly.express as px from PIL import Image # --------------------------------------------------------- # Smart Base Path Detection # --------------------------------------------------------- APP_ROOT = os.path.dirname(os.path.abspath(__file__)) # Case 1: files are in root of Hugging Face Space if os.path.exists(os.path.join(APP_ROOT, "models")): BASE_DIR = APP_ROOT # Case 2: user uploaded whole WiGuard_App folder into the Space elif os.path.exists(os.path.join(APP_ROOT, "WiGuard_App", "models")): BASE_DIR = os.path.join(APP_ROOT, "WiGuard_App") else: BASE_DIR = APP_ROOT def P(*parts): return os.path.join(BASE_DIR, *parts) # --------------------------------------------------------- # File Paths # --------------------------------------------------------- CICIOT_MODEL_PATH = P("models", "xgboost_wiguard_full.pkl") COMBINED_MODEL_PATH = P("models", "xgboost_combined_ciciot_unsw_binary.pkl") FEATURES_PATH = P("models", "selected_features.pkl") RESULTS_PATH = P("models", "model_results.json") RF_RESULTS_PATH = P("models", "random_forest_results.json") DASHBOARD_DATA_PATH = P("dashboard_data", "dashboard_sample_traffic.csv") # Original CICIoT SHAP outputs SHAP_IMPORTANCE_PATH = P("shap_outputs", "global_shap_feature_importance.csv") SHAP_LOCAL_PATH = P("shap_outputs", "sample_local_explanation.json") SHAP_BAR_IMAGE = P("shap_outputs", "shap_global_bar.png") SHAP_SUMMARY_IMAGE = P("shap_outputs", "shap_summary_beeswarm.png") # Experiment 05 outputs EXP05_COMPARISON_PATH = P("experiment_outputs", "experiment_05_comparison_table.csv") EXP05_SUMMARY_PATH = P("experiment_outputs", "experiment_05c_combined_model_summary.json") UNSW_BINARY_IMBALANCE_PATH = P("experiment_outputs", "unsw_binary_imbalance_summary.csv") UNSW_ATTACK_IMBALANCE_PATH = P("experiment_outputs", "unsw_attack_category_imbalance_summary.csv") EXP05_GRAPH_DIR = P("experiment_outputs", "graphs") EXP05_GRAPHS = { "Experiment 05 Metrics Comparison": os.path.join(EXP05_GRAPH_DIR, "experiment_05_metrics_comparison.png"), "Experiment 05 Accuracy Comparison": os.path.join(EXP05_GRAPH_DIR, "experiment_05_accuracy_comparison.png"), "Direct Transfer vs Combined Model on UNSW-NB15": os.path.join(EXP05_GRAPH_DIR, "experiment_05_direct_transfer_vs_combined_unsw.png"), "Combined Model Confusion Matrix on UNSW-NB15": os.path.join(EXP05_GRAPH_DIR, "experiment_05c_combined_model_unsw_confusion_matrix.png"), "Combined Model Confusion Matrix on CICIoT2023": os.path.join(EXP05_GRAPH_DIR, "experiment_05c_combined_model_ciciot_confusion_matrix.png"), } # Combined model SHAP outputs COMBINED_SHAP_DIR = P("shap_outputs", "combined_model") COMBINED_SHAP_GRAPH_DIR = os.path.join(COMBINED_SHAP_DIR, "graphs") COMBINED_SHAP_UNSW_PATH = os.path.join(COMBINED_SHAP_DIR, "shap_importance_unsw_combined_model.csv") COMBINED_SHAP_CICIOT_PATH = os.path.join(COMBINED_SHAP_DIR, "shap_importance_ciciot_combined_model.csv") COMBINED_SHAP_COMPARE_PATH = os.path.join(COMBINED_SHAP_DIR, "shap_top_feature_comparison_unsw_vs_ciciot.csv") COMBINED_LOCAL_UNSW_PATH = os.path.join(COMBINED_SHAP_DIR, "local_explanation_unsw_sample.json") COMBINED_LOCAL_CICIOT_PATH = os.path.join(COMBINED_SHAP_DIR, "local_explanation_ciciot_sample.json") COMBINED_SHAP_GRAPHS = { "UNSW-NB15 SHAP Bar Plot": os.path.join(COMBINED_SHAP_GRAPH_DIR, "shap_bar_unsw_combined_model.png"), "CICIoT2023 SHAP Bar Plot": os.path.join(COMBINED_SHAP_GRAPH_DIR, "shap_bar_ciciot_combined_model.png"), "UNSW-NB15 SHAP Beeswarm Plot": os.path.join(COMBINED_SHAP_GRAPH_DIR, "shap_beeswarm_unsw_combined_model.png"), "CICIoT2023 SHAP Beeswarm Plot": os.path.join(COMBINED_SHAP_GRAPH_DIR, "shap_beeswarm_ciciot_combined_model.png"), } # --------------------------------------------------------- # Page Configuration # --------------------------------------------------------- st.set_page_config( page_title="WiGuard | Explainable AI IDS", page_icon="๐Ÿ›ก๏ธ", layout="wide" ) # --------------------------------------------------------- # File Paths # --------------------------------------------------------- CICIOT_MODEL_PATH = "models/xgboost_wiguard_full.pkl" COMBINED_MODEL_PATH = "models/xgboost_combined_ciciot_unsw_binary.pkl" FEATURES_PATH = "models/selected_features.pkl" RESULTS_PATH = "models/model_results.json" RF_RESULTS_PATH = "models/random_forest_results.json" DASHBOARD_DATA_PATH = "dashboard_data/dashboard_sample_traffic.csv" # Original CICIoT SHAP outputs SHAP_IMPORTANCE_PATH = "shap_outputs/global_shap_feature_importance.csv" SHAP_LOCAL_PATH = "shap_outputs/sample_local_explanation.json" SHAP_BAR_IMAGE = "shap_outputs/shap_global_bar.png" SHAP_SUMMARY_IMAGE = "shap_outputs/shap_summary_beeswarm.png" # Experiment 05 outputs EXP05_COMPARISON_PATH = "experiment_outputs/experiment_05_comparison_table.csv" EXP05_SUMMARY_PATH = "experiment_outputs/experiment_05c_combined_model_summary.json" UNSW_BINARY_IMBALANCE_PATH = "experiment_outputs/unsw_binary_imbalance_summary.csv" UNSW_ATTACK_IMBALANCE_PATH = "experiment_outputs/unsw_attack_category_imbalance_summary.csv" EXP05_GRAPH_DIR = "experiment_outputs/graphs" EXP05_GRAPHS = { "Experiment 05 Metrics Comparison": f"{EXP05_GRAPH_DIR}/experiment_05_metrics_comparison.png", "Experiment 05 Accuracy Comparison": f"{EXP05_GRAPH_DIR}/experiment_05_accuracy_comparison.png", "Direct Transfer vs Combined Model on UNSW-NB15": f"{EXP05_GRAPH_DIR}/experiment_05_direct_transfer_vs_combined_unsw.png", "Combined Model Confusion Matrix on UNSW-NB15": f"{EXP05_GRAPH_DIR}/experiment_05c_combined_model_unsw_confusion_matrix.png", "Combined Model Confusion Matrix on CICIoT2023": f"{EXP05_GRAPH_DIR}/experiment_05c_combined_model_ciciot_confusion_matrix.png", } # Combined model SHAP outputs COMBINED_SHAP_DIR = "shap_outputs/combined_model" COMBINED_SHAP_GRAPH_DIR = f"{COMBINED_SHAP_DIR}/graphs" COMBINED_SHAP_UNSW_PATH = f"{COMBINED_SHAP_DIR}/shap_importance_unsw_combined_model.csv" COMBINED_SHAP_CICIOT_PATH = f"{COMBINED_SHAP_DIR}/shap_importance_ciciot_combined_model.csv" COMBINED_SHAP_COMPARE_PATH = f"{COMBINED_SHAP_DIR}/shap_top_feature_comparison_unsw_vs_ciciot.csv" COMBINED_LOCAL_UNSW_PATH = f"{COMBINED_SHAP_DIR}/local_explanation_unsw_sample.json" COMBINED_LOCAL_CICIOT_PATH = f"{COMBINED_SHAP_DIR}/local_explanation_ciciot_sample.json" COMBINED_SHAP_GRAPHS = { "UNSW-NB15 SHAP Bar Plot": f"{COMBINED_SHAP_GRAPH_DIR}/shap_bar_unsw_combined_model.png", "CICIoT2023 SHAP Bar Plot": f"{COMBINED_SHAP_GRAPH_DIR}/shap_bar_ciciot_combined_model.png", "UNSW-NB15 SHAP Beeswarm Plot": f"{COMBINED_SHAP_GRAPH_DIR}/shap_beeswarm_unsw_combined_model.png", "CICIoT2023 SHAP Beeswarm Plot": f"{COMBINED_SHAP_GRAPH_DIR}/shap_beeswarm_ciciot_combined_model.png", } # --------------------------------------------------------- # Safe Loading Helpers # --------------------------------------------------------- def file_exists(path): return os.path.exists(path) @st.cache_resource def load_model(path): if os.path.exists(path): return joblib.load(path) return None @st.cache_data def load_pickle_file(path): if os.path.exists(path): return joblib.load(path) return None @st.cache_data def load_json_file(path): if os.path.exists(path): with open(path, "r") as f: return json.load(f) return None @st.cache_data def load_csv_file(path): if os.path.exists(path): return pd.read_csv(path) return None @st.cache_data def load_dashboard_data(): if os.path.exists(DASHBOARD_DATA_PATH): return pd.read_csv(DASHBOARD_DATA_PATH) return pd.DataFrame() # --------------------------------------------------------- # Load Assets # --------------------------------------------------------- ciciot_model = load_model(CICIOT_MODEL_PATH) combined_model = load_model(COMBINED_MODEL_PATH) selected_features = load_pickle_file(FEATURES_PATH) results = load_json_file(RESULTS_PATH) rf_results = load_json_file(RF_RESULTS_PATH) traffic_df = load_dashboard_data() shap_importance_df = load_csv_file(SHAP_IMPORTANCE_PATH) local_explanation = load_json_file(SHAP_LOCAL_PATH) exp05_comparison_df = load_csv_file(EXP05_COMPARISON_PATH) exp05_summary = load_json_file(EXP05_SUMMARY_PATH) unsw_binary_imbalance_df = load_csv_file(UNSW_BINARY_IMBALANCE_PATH) unsw_attack_imbalance_df = load_csv_file(UNSW_ATTACK_IMBALANCE_PATH) combined_shap_unsw_df = load_csv_file(COMBINED_SHAP_UNSW_PATH) combined_shap_ciciot_df = load_csv_file(COMBINED_SHAP_CICIOT_PATH) combined_shap_compare_df = load_csv_file(COMBINED_SHAP_COMPARE_PATH) combined_local_unsw = load_json_file(COMBINED_LOCAL_UNSW_PATH) combined_local_ciciot = load_json_file(COMBINED_LOCAL_CICIOT_PATH) if selected_features is None: selected_features = [] # --------------------------------------------------------- # Helper Functions # --------------------------------------------------------- def get_severity(probability): if probability < 0.25: return "Low", "๐ŸŸข" elif probability < 0.50: return "Medium", "๐ŸŸก" elif probability < 0.75: return "High", "๐ŸŸ " else: return "Critical", "๐Ÿ”ด" def format_percent(x): try: return f"{float(x) * 100:.3f}%" except Exception: return "N/A" def show_image_if_exists(path, caption=None): if os.path.exists(path): st.image(Image.open(path), caption=caption, use_container_width=True) else: st.warning(f"Image not found: {path}") def show_csv_if_exists(df, title=None): if title: st.markdown(title) if df is not None and not df.empty: st.dataframe(df, use_container_width=True) else: st.info("File not found or empty.") def predict_single(row, active_model): if active_model is None: return "Model Missing", 0.0, "Unknown", "โšช" if len(selected_features) == 0: return "Features Missing", 0.0, "Unknown", "โšช" X = pd.DataFrame([row[selected_features].to_dict()]) for col in selected_features: X[col] = pd.to_numeric(X[col], errors="coerce") X = X.fillna(0) X = X[selected_features] X = X.astype(float) prediction = int(active_model.predict(X)[0]) if hasattr(active_model, "predict_proba"): probability = float(active_model.predict_proba(X)[0][1]) else: probability = float(prediction) severity, icon = get_severity(probability) label = "Attack" if prediction == 1 else "Benign" return label, probability, severity, icon def display_confusion_matrix(cm, title, labels=("Benign", "Attack")): fig = px.imshow( cm, text_auto=True, labels=dict(x="Predicted Label", y="Actual Label", color="Count"), x=list(labels), y=list(labels), title=title ) st.plotly_chart(fig, use_container_width=True) # --------------------------------------------------------- # Sidebar # --------------------------------------------------------- st.sidebar.title("๐Ÿ›ก๏ธ WiGuard") st.sidebar.caption("Explainable AI-Based Intrusion Detection System") page = st.sidebar.radio( "Navigation", [ "Home", "Model Performance", "Live Traffic Simulation", "Explainability", "Dataset & Features", "Attack Logs" ] ) st.sidebar.markdown("---") st.sidebar.write("**Models:** XGBoost") st.sidebar.write("**XAI:** SHAP") st.sidebar.write("**Datasets:** CICIoT2023 + UNSW-NB15") st.sidebar.write("**Mode:** Benchmark Traffic Simulation") with st.sidebar.expander("๐Ÿ”Ž File Check"): files_to_check = { "CICIoT model": CICIOT_MODEL_PATH, "Combined model": COMBINED_MODEL_PATH, "Selected features": FEATURES_PATH, "Dashboard data": DASHBOARD_DATA_PATH, "Experiment 05 table": EXP05_COMPARISON_PATH, "Experiment 05 summary": EXP05_SUMMARY_PATH, "Experiment 05 graph folder": EXP05_GRAPH_DIR, "Combined SHAP folder": COMBINED_SHAP_DIR, } st.write("Base directory:") st.code(BASE_DIR) for name, path in files_to_check.items(): if os.path.exists(path): st.success(f"{name}: found") else: st.error(f"{name}: missing") st.code(path) # --------------------------------------------------------- # Home Page # --------------------------------------------------------- if page == "Home": st.title("๐Ÿ›ก๏ธ WiGuard") st.subheader("Explainable AI-Based Network / IoT Intrusion Detection System") st.markdown(""" **WiGuard** is an explainable intrusion detection framework designed to classify network-flow traffic as **Benign** or **Attack** using XGBoost models. The system now includes both the original **CICIoT2023-based model** and a newer **combined CICIoT2023 + UNSW-NB15 model** trained using a shared 44-feature WiGuard representation. SHAP explainability is used to explain model behavior globally and locally. """) col1, col2, col3, col4 = st.columns(4) col1.info("Datasets: CICIoT2023 + UNSW-NB15") col2.info("Models: XGBoost") col3.info("Explainability: SHAP") col4.info("Feature Space: 44 WiGuard Features") st.markdown("### Updated WiGuard Pipeline") st.markdown(""" 1. Load CICIoT2023 and UNSW-NB15 network traffic datasets 2. Clean and preprocess both datasets 3. Map UNSW-NB15 into WiGuard's 44-feature format 4. Train and evaluate CICIoT2023-only, UNSW-specific, and combined models 5. Analyze cross-dataset generalization and domain shift 6. Generate SHAP explanations for original and combined models 7. Display predictions, performance, feature mapping, and explanations in Streamlit """) st.success(""" The combined WiGuard model was trained using samples from both CICIoT2023 and UNSW-NB15. This improves robustness compared to direct zero-shot transfer from one dataset to another. """) st.warning(""" This deployed version uses benchmark test records to simulate real-time traffic. Live Wireshark/tshark packet capture remains a future local extension because raw packets must first be converted into WiGuard-style flow features. """) # --------------------------------------------------------- # Model Performance Page # --------------------------------------------------------- elif page == "Model Performance": st.title("๐Ÿ“Š Model Performance") st.markdown("## 1. Original CICIoT2023 Binary Model") if results is not None and "test" in results: test_results = results["test"] col1, col2, col3, col4, col5 = st.columns(5) col1.metric("Accuracy", format_percent(test_results.get("accuracy"))) col2.metric("Precision", format_percent(test_results.get("precision"))) col3.metric("Recall", format_percent(test_results.get("recall"))) col4.metric("F1 Score", format_percent(test_results.get("f1_score"))) col5.metric("ROC-AUC", format_percent(test_results.get("roc_auc"))) st.markdown("### CICIoT2023 Confusion Matrix") cm = np.array(test_results["confusion_matrix"]) display_confusion_matrix(cm, "Original CICIoT2023 XGBoost Confusion Matrix") st.markdown(f""" - **True Benign:** {cm[0][0]:,} - **False Attack Alerts:** {cm[0][1]:,} - **Missed Attacks:** {cm[1][0]:,} - **Correctly Detected Attacks:** {cm[1][1]:,} """) else: st.warning("Original model results file not found.") st.markdown("---") st.markdown("## 2. Experiment 05: Cross-Dataset and Combined Model Results") if exp05_comparison_df is not None and not exp05_comparison_df.empty: st.dataframe(exp05_comparison_df, use_container_width=True) st.markdown("### Key Interpretation") st.markdown(""" - **05-A Direct Transfer** showed poor generalization because the CICIoT2023-trained model predicted all UNSW-NB15 samples as attacks. - **05-B UNSW-specific model** proved that the mapped UNSW-NB15 44-feature representation is learnable. - **05-C Combined model** performed strongly on both CICIoT2023 and UNSW-NB15, supporting the common feature-space training strategy. """) else: st.warning("Experiment 05 comparison table not found.") st.markdown("### Experiment 05 Graphs") for title, path in EXP05_GRAPHS.items(): with st.expander(title, expanded=False): show_image_if_exists(path, title) st.markdown("---") st.markdown("## 3. Combined Model Summary") if exp05_summary is not None: col1, col2 = st.columns(2) with col1: st.markdown("### Tested on UNSW-NB15") unsw_results = exp05_summary.get("unsw_test_results", {}) st.metric("Accuracy", format_percent(unsw_results.get("accuracy", 0))) st.metric("F1 Score", format_percent(unsw_results.get("f1_score", 0))) st.metric("ROC-AUC", format_percent(unsw_results.get("roc_auc", 0))) with col2: st.markdown("### Tested on CICIoT2023") ciciot_results = exp05_summary.get("ciciot_test_results", {}) st.metric("Accuracy", format_percent(ciciot_results.get("accuracy", 0))) st.metric("F1 Score", format_percent(ciciot_results.get("f1_score", 0))) st.metric("ROC-AUC", format_percent(ciciot_results.get("roc_auc", 0))) with st.expander("View Full Experiment 05-C Summary JSON"): st.json(exp05_summary) else: st.info("Combined model summary JSON not found.") # --------------------------------------------------------- # Live Traffic Simulation Page # --------------------------------------------------------- elif page == "Live Traffic Simulation": st.title("๐Ÿ“ก Live Traffic Simulation") st.markdown(""" This page simulates incoming network-flow records using benchmark test samples. You can choose between the original CICIoT2023 model and the combined CICIoT2023 + UNSW-NB15 model. """) available_models = { "Original CICIoT2023 Binary Model": ciciot_model, "Combined CICIoT2023 + UNSW-NB15 Binary Model": combined_model, } model_choice = st.selectbox( "Select model for prediction", list(available_models.keys()) ) active_model = available_models[model_choice] if active_model is None: st.error(f"Selected model file is missing for: {model_choice}") if traffic_df.empty: st.error("Dashboard sample traffic file not found.") st.stop() max_index = len(traffic_df) - 1 selected_index = st.slider( "Select traffic record index", min_value=0, max_value=max_index, value=0, step=1 ) row = traffic_df.iloc[selected_index] label, probability, severity, icon = predict_single(row, active_model) col1, col2, col3, col4, col5 = st.columns(5) col1.metric("Prediction", label) col2.metric("Attack Probability", f"{probability * 100:.3f}%") col3.metric("Threat Severity", f"{icon} {severity}") col4.metric("Actual Category", str(row.get("attack_category", "Unknown"))) col5.metric("Model Used", model_choice.split(" Binary")[0]) st.markdown("### Traffic Record Features") st.dataframe(row[selected_features].to_frame(name="Value"), use_container_width=True) st.markdown("### Manual Simulation") if st.button("Run Next 10 Records"): logs = [] progress = st.progress(0) total_to_run = min(10, len(traffic_df) - selected_index) for offset, i in enumerate(range(selected_index, selected_index + total_to_run)): current_row = traffic_df.iloc[i] pred_label, prob, sev, sev_icon = predict_single(current_row, active_model) logs.append({ "time": datetime.now().strftime("%H:%M:%S"), "index": i, "model_used": model_choice, "prediction": pred_label, "attack_probability": round(prob * 100, 3), "severity": sev, "actual_category": current_row.get("attack_category", "Unknown") }) progress.progress((offset + 1) / total_to_run) time.sleep(0.1) st.dataframe(pd.DataFrame(logs), use_container_width=True) # --------------------------------------------------------- # Explainability Page # --------------------------------------------------------- elif page == "Explainability": st.title("๐Ÿง  SHAP Explainability") st.markdown(""" SHAP is used to explain how each feature contributes to model predictions. Positive SHAP values generally push predictions toward **Attack**, while negative SHAP values push predictions toward **Benign**. """) tab1, tab2 = st.tabs([ "Original CICIoT2023 Model SHAP", "Combined Model SHAP" ]) with tab1: st.markdown("## Original CICIoT2023 Model Explainability") if shap_importance_df is not None and not shap_importance_df.empty: top_n = st.slider("Number of top original-model features", 5, 20, 10, key="orig_shap_slider") top_shap = shap_importance_df.head(top_n) fig = px.bar( top_shap.sort_values("mean_abs_shap"), x="mean_abs_shap", y="feature", orientation="h", title="Top Global SHAP Features - Original CICIoT2023 Model" ) st.plotly_chart(fig, use_container_width=True) else: st.info("Original SHAP importance CSV not found.") st.markdown("### Saved Original SHAP Plots") col1, col2 = st.columns(2) with col1: show_image_if_exists(SHAP_BAR_IMAGE, "Original Global SHAP Bar Plot") with col2: show_image_if_exists(SHAP_SUMMARY_IMAGE, "Original SHAP Beeswarm Plot") st.markdown("### Original Sample Local Explanation") if local_explanation is not None: st.json(local_explanation) else: st.info("Original local explanation JSON not found.") with tab2: st.markdown("## Combined CICIoT2023 + UNSW-NB15 Model Explainability") st.markdown(""" The combined model was explained separately on CICIoT2023 and UNSW-NB15 samples. This helps show how feature importance changes across datasets. """) subtab1, subtab2, subtab3, subtab4 = st.tabs([ "UNSW SHAP", "CICIoT SHAP", "Feature Comparison", "Local Explanations" ]) with subtab1: st.markdown("### UNSW-NB15 Global SHAP Importance") if combined_shap_unsw_df is not None and not combined_shap_unsw_df.empty: top_n_unsw = st.slider("Top UNSW SHAP features", 5, 20, 10, key="unsw_shap_slider") top_unsw = combined_shap_unsw_df.head(top_n_unsw) fig = px.bar( top_unsw.sort_values("mean_abs_shap"), x="mean_abs_shap", y="feature", orientation="h", title="Combined Model SHAP Importance on UNSW-NB15" ) st.plotly_chart(fig, use_container_width=True) st.dataframe(combined_shap_unsw_df.head(20), use_container_width=True) else: st.info("UNSW combined SHAP CSV not found.") show_image_if_exists(COMBINED_SHAP_GRAPHS["UNSW-NB15 SHAP Bar Plot"], "UNSW-NB15 SHAP Bar Plot") show_image_if_exists(COMBINED_SHAP_GRAPHS["UNSW-NB15 SHAP Beeswarm Plot"], "UNSW-NB15 SHAP Beeswarm Plot") with subtab2: st.markdown("### CICIoT2023 Global SHAP Importance") if combined_shap_ciciot_df is not None and not combined_shap_ciciot_df.empty: top_n_ciciot = st.slider("Top CICIoT SHAP features", 5, 20, 10, key="ciciot_shap_slider") top_ciciot = combined_shap_ciciot_df.head(top_n_ciciot) fig = px.bar( top_ciciot.sort_values("mean_abs_shap"), x="mean_abs_shap", y="feature", orientation="h", title="Combined Model SHAP Importance on CICIoT2023" ) st.plotly_chart(fig, use_container_width=True) st.dataframe(combined_shap_ciciot_df.head(20), use_container_width=True) else: st.info("CICIoT combined SHAP CSV not found.") show_image_if_exists(COMBINED_SHAP_GRAPHS["CICIoT2023 SHAP Bar Plot"], "CICIoT2023 SHAP Bar Plot") show_image_if_exists(COMBINED_SHAP_GRAPHS["CICIoT2023 SHAP Beeswarm Plot"], "CICIoT2023 SHAP Beeswarm Plot") with subtab3: st.markdown("### Top Feature Comparison: UNSW-NB15 vs CICIoT2023") if combined_shap_compare_df is not None and not combined_shap_compare_df.empty: st.dataframe(combined_shap_compare_df, use_container_width=True) st.markdown(""" This comparison shows that some features are important across both datasets, while others are dataset-specific. This supports the domain-shift finding from Experiment 05-A. """) else: st.info("Combined SHAP comparison CSV not found.") with subtab4: st.markdown("### Local Explanation: UNSW-NB15 Sample") if combined_local_unsw is not None: st.json(combined_local_unsw) else: st.info("UNSW local explanation JSON not found.") st.markdown("### Local Explanation: CICIoT2023 Sample") if combined_local_ciciot is not None: st.json(combined_local_ciciot) else: st.info("CICIoT local explanation JSON not found.") # --------------------------------------------------------- # Dataset & Features Page # --------------------------------------------------------- elif page == "Dataset & Features": st.title("๐Ÿงพ Dataset & Features") st.markdown(""" WiGuard uses a shared **44-feature representation** for model training and prediction. CICIoT2023 already contains these selected features, while UNSW-NB15 was mapped into this format for cross-dataset and combined training. """) st.markdown("## Final Selected WiGuard Features") feature_df = pd.DataFrame({"Feature": selected_features}) st.dataframe(feature_df, use_container_width=True) st.markdown("---") st.markdown("## UNSW-NB15 Feature Mapping") mapping_df = pd.DataFrame([ {"WiGuard Feature": "flow_duration", "UNSW-NB15 Mapping": "dur", "Mapping Type": "Direct"}, {"WiGuard Feature": "duration", "UNSW-NB15 Mapping": "dur", "Mapping Type": "Direct"}, {"WiGuard Feature": "rate", "UNSW-NB15 Mapping": "rate", "Mapping Type": "Direct"}, {"WiGuard Feature": "srate", "UNSW-NB15 Mapping": "sload", "Mapping Type": "Approximate"}, {"WiGuard Feature": "drate", "UNSW-NB15 Mapping": "dload", "Mapping Type": "Approximate"}, {"WiGuard Feature": "protocol_type", "UNSW-NB15 Mapping": "encoded proto", "Mapping Type": "Derived"}, {"WiGuard Feature": "tcp", "UNSW-NB15 Mapping": "proto == tcp", "Mapping Type": "Derived"}, {"WiGuard Feature": "udp", "UNSW-NB15 Mapping": "proto == udp", "Mapping Type": "Derived"}, {"WiGuard Feature": "icmp", "UNSW-NB15 Mapping": "proto == icmp", "Mapping Type": "Derived"}, {"WiGuard Feature": "http", "UNSW-NB15 Mapping": "service == http", "Mapping Type": "Derived"}, {"WiGuard Feature": "dns", "UNSW-NB15 Mapping": "service == dns", "Mapping Type": "Derived"}, {"WiGuard Feature": "smtp", "UNSW-NB15 Mapping": "service == smtp", "Mapping Type": "Derived"}, {"WiGuard Feature": "ssh", "UNSW-NB15 Mapping": "service == ssh", "Mapping Type": "Derived"}, {"WiGuard Feature": "tot_sum", "UNSW-NB15 Mapping": "sbytes + dbytes", "Mapping Type": "Derived"}, {"WiGuard Feature": "tot_size", "UNSW-NB15 Mapping": "sbytes + dbytes", "Mapping Type": "Derived"}, {"WiGuard Feature": "number", "UNSW-NB15 Mapping": "spkts + dpkts", "Mapping Type": "Derived"}, {"WiGuard Feature": "avg", "UNSW-NB15 Mapping": "(sbytes + dbytes) / (spkts + dpkts)", "Mapping Type": "Derived"}, {"WiGuard Feature": "iat", "UNSW-NB15 Mapping": "mean(sinpkt, dinpkt)", "Mapping Type": "Approximate"}, {"WiGuard Feature": "header_length", "UNSW-NB15 Mapping": "(spkts + dpkts) ร— 20", "Mapping Type": "Approximate"}, ]) st.dataframe(mapping_df, use_container_width=True) st.info(""" Some CICIoT2023-style features do not have exact equivalents in UNSW-NB15. These were either approximated using similar UNSW-NB15 fields or filled with zero. This is why direct zero-shot transfer performed poorly, while combined training worked better. """) st.markdown("---") st.markdown("## UNSW-NB15 Imbalance Analysis") show_csv_if_exists(unsw_binary_imbalance_df, "### Binary Class Imbalance") show_csv_if_exists(unsw_attack_imbalance_df, "### Attack Category Imbalance") st.markdown("---") st.markdown("## Dashboard Sample Data") if not traffic_df.empty: st.write("Shape:", traffic_df.shape) st.dataframe(traffic_df.head(20), use_container_width=True) else: st.warning("Dashboard sample traffic data not found.") # --------------------------------------------------------- # Attack Logs Page # --------------------------------------------------------- elif page == "Attack Logs": st.title("๐Ÿ“œ Attack Logs") st.markdown(""" This page generates prediction logs from a batch of simulated traffic samples. The logs now include the selected model name. """) available_models = { "Original CICIoT2023 Binary Model": ciciot_model, "Combined CICIoT2023 + UNSW-NB15 Binary Model": combined_model, } model_choice = st.selectbox( "Select model for log generation", list(available_models.keys()), key="logs_model_choice" ) active_model = available_models[model_choice] if traffic_df.empty: st.error("Dashboard sample traffic file not found.") st.stop() batch_size = st.slider("Number of records to process", 10, 500, 50) if st.button("Generate Logs"): sample_batch = traffic_df.sample(n=min(batch_size, len(traffic_df)), random_state=42) logs = [] for idx, row in sample_batch.iterrows(): pred_label, prob, sev, sev_icon = predict_single(row, active_model) logs.append({ "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "record_index": idx, "model_used": model_choice, "prediction": pred_label, "attack_probability": round(prob * 100, 3), "severity": sev, "actual_category": row.get("attack_category", "Unknown") }) logs_df = pd.DataFrame(logs) st.dataframe(logs_df, use_container_width=True) csv = logs_df.to_csv(index=False).encode("utf-8") st.download_button( label="Download Logs as CSV", data=csv, file_name="wiguard_attack_logs.csv", mime="text/csv" )