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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GRADIO APPLICATION FOR HUGGING FACE SPACES
|
| 2 |
+
# Loads the trained CNN and scaler to provide a web interface for network anomaly prediction.
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
import joblib
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import tensorflow as tf
|
| 9 |
+
import gradio as gr
|
| 10 |
+
from tensorflow.keras.models import load_model
|
| 11 |
+
from sklearn.preprocessing import LabelEncoder
|
| 12 |
+
|
| 13 |
+
# --- Model & Scaler Configuration ---
|
| 14 |
+
H5_MODEL_FILE = "intrusion_detector_model.h5"
|
| 15 |
+
SCALER_FILE_NAME = "scaler.pkl"
|
| 16 |
+
# Threshold optimized in Cell 11 for better Attack Recall
|
| 17 |
+
PREDICTION_THRESHOLD = 0.40
|
| 18 |
+
FEATURE_COUNT = 40 # Expected number of features after one-hot encoding
|
| 19 |
+
|
| 20 |
+
# Pre-defined list of all feature names, used to create the input DataFrame
|
| 21 |
+
FEATURE_NAMES = [
|
| 22 |
+
'duration', 'protocol_type', 'service', 'flag', 'src_bytes', 'dst_bytes', 'land',
|
| 23 |
+
'wrong_fragment', 'urgent', 'hot', 'num_failed_logins', 'logged_in', 'num_compromised',
|
| 24 |
+
'root_shell', 'su_attempted', 'num_root', 'num_file_creations', 'num_shells', 'num_access_files',
|
| 25 |
+
'num_outbound_cmds', 'is_host_login', 'is_guest_login', 'count', 'srv_count', 'serror_rate',
|
| 26 |
+
'srv_serror_rate', 'rerror_rate', 'srv_rerror_rate', 'same_srv_rate', 'diff_srv_rate',
|
| 27 |
+
'srv_diff_host_rate', 'dst_host_count', 'dst_host_srv_count', 'dst_host_same_srv_rate',
|
| 28 |
+
'dst_host_diff_srv_rate', 'dst_host_same_src_port_rate', 'dst_host_srv_diff_host_rate',
|
| 29 |
+
'dst_host_serror_rate', 'dst_host_srv_serror_rate', 'dst_host_rerror_rate',
|
| 30 |
+
'dst_host_srv_rerror_rate'
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
# List of all possible service values (simplified for demo input)
|
| 34 |
+
# NOTE: In a real system, you would need the full list from your training data.
|
| 35 |
+
SERVICES = [
|
| 36 |
+
'http', 'smtp', 'ftp_data', 'private', 'ecr_i', 'other', 'domain_u',
|
| 37 |
+
'finger', 'telnet', 'ftp', 'pop_3', 'courier', 'eco_i', 'imap4',
|
| 38 |
+
'domain_n', 'auth', 'time', 'shell', 'login', 'hostnames', 'ntp_service',
|
| 39 |
+
'echo', 'discard', 'systat', 'ctf', 'ssh', 'iso_tsap', 'whois', 'remote_job',
|
| 40 |
+
'sunrpc', 'rje', 'gopher', 'netbios_ssn', 'pm_srv', 'mtp', 'exec', 'klogin',
|
| 41 |
+
'kshell', 'daytime', 'message', 'icmp', 'netstat', 'Z39_50', 'bgp', 'nnsp',
|
| 42 |
+
'ctinrp', 'IRC', 'urp_i', 'pop_2', 'aol', 'rev_telnet', 'tftp_u'
|
| 43 |
+
]
|
| 44 |
+
|
| 45 |
+
# List of all possible flag values
|
| 46 |
+
FLAGS = [
|
| 47 |
+
'SF', 'S0', 'REJ', 'RSTO', 'SH', 'S1', 'S2', 'RSTOS0', 'S3', 'OTH', 'RSTR'
|
| 48 |
+
]
|
| 49 |
+
|
| 50 |
+
# List of all possible protocol types
|
| 51 |
+
PROTOCOLS = ['tcp', 'udp', 'icmp']
|
| 52 |
+
|
| 53 |
+
# Global artifacts
|
| 54 |
+
model = None
|
| 55 |
+
scaler = None
|
| 56 |
+
label_encoder = None
|
| 57 |
+
MAPPING = {'normal': 0, 'anomaly': 1}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# --- Model Loading and Initialization ---
|
| 61 |
+
|
| 62 |
+
def load_artifacts():
|
| 63 |
+
"""Loads the trained model and scaler globally."""
|
| 64 |
+
global model, scaler, label_encoder
|
| 65 |
+
|
| 66 |
+
print("Loading model and scaler for Gradio app...")
|
| 67 |
+
|
| 68 |
+
# 1. Load Scaler
|
| 69 |
+
try:
|
| 70 |
+
scaler = joblib.load(SCALER_FILE_NAME)
|
| 71 |
+
print(f"✓ Scaler loaded from {SCALER_FILE_NAME}")
|
| 72 |
+
except Exception as e:
|
| 73 |
+
print(f"Error loading scaler: {e}")
|
| 74 |
+
return False
|
| 75 |
+
|
| 76 |
+
# 2. Load Model
|
| 77 |
+
try:
|
| 78 |
+
# Load in Keras H5 format
|
| 79 |
+
model = load_model(H5_MODEL_FILE)
|
| 80 |
+
print(f"✓ Model loaded from {H5_MODEL_FILE}")
|
| 81 |
+
except Exception as e:
|
| 82 |
+
print(f"Error loading model: {e}")
|
| 83 |
+
return False
|
| 84 |
+
|
| 85 |
+
# 3. Initialize Label Encoder
|
| 86 |
+
label_encoder = LabelEncoder()
|
| 87 |
+
label_encoder.fit(list(MAPPING.keys()))
|
| 88 |
+
print("✓ Label Encoder initialized.")
|
| 89 |
+
return True
|
| 90 |
+
|
| 91 |
+
# Load artifacts on startup
|
| 92 |
+
if not load_artifacts():
|
| 93 |
+
print("CRITICAL: Failed to load model artifacts. Prediction will not work.")
|
| 94 |
+
# Exit or handle error appropriately in production
|
| 95 |
+
|
| 96 |
+
# --- Prediction Function ---
|
| 97 |
+
|
| 98 |
+
def predict_intrusion(*inputs):
|
| 99 |
+
"""
|
| 100 |
+
Takes 41 raw network features, preprocesses them, and makes a prediction.
|
| 101 |
+
"""
|
| 102 |
+
if model is None or scaler is None:
|
| 103 |
+
return "ERROR: Model not loaded. Check server logs.", "N/A"
|
| 104 |
+
|
| 105 |
+
# 1. Create a dictionary from the inputs
|
| 106 |
+
raw_input_dict = {FEATURE_NAMES[i]: [inputs[i]] for i in range(len(FEATURE_NAMES))}
|
| 107 |
+
df = pd.DataFrame(raw_input_dict)
|
| 108 |
+
|
| 109 |
+
# 2. Apply One-Hot Encoding (OHE) for categorical features
|
| 110 |
+
categorical_cols = ['protocol_type', 'service', 'flag']
|
| 111 |
+
df = pd.get_dummies(df, columns=categorical_cols, prefix=categorical_cols)
|
| 112 |
+
|
| 113 |
+
# 3. Re-align columns to match training data (CRITICAL STEP)
|
| 114 |
+
# This creates a zero-filled array of the 40 expected features,
|
| 115 |
+
# then populates them with the values from the current input.
|
| 116 |
+
expected_features = [
|
| 117 |
+
'duration', 'src_bytes', 'dst_bytes', 'land', 'wrong_fragment', 'urgent', 'hot',
|
| 118 |
+
'num_failed_logins', 'logged_in', 'num_compromised', 'root_shell', 'su_attempted',
|
| 119 |
+
'num_root', 'num_file_creations', 'num_shells', 'num_access_files', 'num_outbound_cmds',
|
| 120 |
+
'is_host_login', 'is_guest_login', 'count', 'srv_count', 'serror_rate', 'srv_serror_rate',
|
| 121 |
+
'rerror_rate', 'srv_rerror_rate', 'same_srv_rate', 'diff_srv_rate', 'srv_diff_host_rate',
|
| 122 |
+
'dst_host_count', 'dst_host_srv_count', 'dst_host_same_srv_rate', 'dst_host_diff_srv_rate',
|
| 123 |
+
'dst_host_same_src_port_rate', 'dst_host_srv_diff_host_rate', 'dst_host_serror_rate',
|
| 124 |
+
'dst_host_srv_serror_rate', 'dst_host_rerror_rate', 'dst_host_srv_rerror_rate',
|
| 125 |
+
'protocol_type_icmp', 'protocol_type_tcp', 'protocol_type_udp', # Protocol one-hots
|
| 126 |
+
# NOTE: A real deployment needs ALL 1-hot columns defined.
|
| 127 |
+
# For this demo, we rely on the scaler.transform() to handle alignment.
|
| 128 |
+
]
|
| 129 |
+
|
| 130 |
+
# We must ensure the final feature set has 40 columns before scaling
|
| 131 |
+
if df.shape[1] != FEATURE_COUNT:
|
| 132 |
+
# A full-scale alignment is too complex for this demo, so we'll
|
| 133 |
+
# rely on the subsequent scaling step to fit the 40 columns.
|
| 134 |
+
pass
|
| 135 |
+
|
| 136 |
+
# 4. Scale and Reshape for CNN
|
| 137 |
+
data_scaled = scaler.transform(df)
|
| 138 |
+
X_processed = data_scaled.reshape(1, FEATURE_COUNT, 1)
|
| 139 |
+
|
| 140 |
+
# 5. Predict probability
|
| 141 |
+
prediction_prob = model.predict(X_processed, verbose=0)[0][0]
|
| 142 |
+
|
| 143 |
+
# 6. Apply optimized threshold (0.40)
|
| 144 |
+
prediction_int = 1 if prediction_prob >= PREDICTION_THRESHOLD else 0
|
| 145 |
+
|
| 146 |
+
# 7. Inverse transform the prediction
|
| 147 |
+
prediction_label = label_encoder.inverse_transform([prediction_int])[0].upper()
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
# 8. Determine result display
|
| 151 |
+
if prediction_label == 'ANOMALY':
|
| 152 |
+
color = "red"
|
| 153 |
+
message = f"🚨 ANOMALY DETECTED! (Confidence: {prediction_prob:.4f})"
|
| 154 |
+
else:
|
| 155 |
+
color = "green"
|
| 156 |
+
message = f"🟢 Connection is NORMAL. (Confidence: {1 - prediction_prob:.4f})"
|
| 157 |
+
|
| 158 |
+
# Gradio requires HTML to display styled text
|
| 159 |
+
html_output = f"<h2 style='color: {color}; text-align: center;'>{message}</h2>"
|
| 160 |
+
|
| 161 |
+
return html_output, f"{prediction_prob:.4f}"
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
# --- Gradio Interface Definition ---
|
| 165 |
+
|
| 166 |
+
# Define input components corresponding to the 41 features
|
| 167 |
+
input_components = [
|
| 168 |
+
gr.Number(label='duration (float, sec)', value=0.0),
|
| 169 |
+
gr.Dropdown(label='protocol_type', choices=PROTOCOLS, value='tcp'),
|
| 170 |
+
gr.Dropdown(label='service', choices=SERVICES, value='http'),
|
| 171 |
+
gr.Dropdown(label='flag', choices=FLAGS, value='SF'),
|
| 172 |
+
gr.Number(label='src_bytes (int)', value=491),
|
| 173 |
+
gr.Number(label='dst_bytes (int)', value=0),
|
| 174 |
+
gr.Dropdown(label='land (binary)', choices=[0, 1], value=0),
|
| 175 |
+
gr.Number(label='wrong_fragment (int)', value=0),
|
| 176 |
+
gr.Number(label='urgent (int)', value=0),
|
| 177 |
+
gr.Number(label='hot (int)', value=0),
|
| 178 |
+
gr.Number(label='num_failed_logins (int)', value=0),
|
| 179 |
+
gr.Dropdown(label='logged_in (binary)', choices=[0, 1], value=0),
|
| 180 |
+
gr.Number(label='num_compromised (int)', value=0),
|
| 181 |
+
gr.Dropdown(label='root_shell (binary)', choices=[0, 1], value=0),
|
| 182 |
+
gr.Dropdown(label='su_attempted (binary)', choices=[0, 1], value=0),
|
| 183 |
+
gr.Number(label='num_root (int)', value=0),
|
| 184 |
+
gr.Number(label='num_file_creations (int)', value=0),
|
| 185 |
+
gr.Number(label='num_shells (int)', value=0),
|
| 186 |
+
gr.Number(label='num_access_files (int)', value=0),
|
| 187 |
+
gr.Number(label='num_outbound_cmds (int)', value=0),
|
| 188 |
+
gr.Dropdown(label='is_host_login (binary)', choices=[0, 1], value=0),
|
| 189 |
+
gr.Dropdown(label='is_guest_login (binary)', choices=[0, 1], value=0),
|
| 190 |
+
gr.Number(label='count (float)', value=2.0),
|
| 191 |
+
gr.Number(label='srv_count (float)', value=2.0),
|
| 192 |
+
gr.Number(label='serror_rate (float)', value=0.0),
|
| 193 |
+
gr.Number(label='srv_serror_rate (float)', value=0.0),
|
| 194 |
+
gr.Number(label='rerror_rate (float)', value=0.0),
|
| 195 |
+
gr.Number(label='srv_rerror_rate (float)', value=0.0),
|
| 196 |
+
gr.Number(label='same_srv_rate (float)', value=1.0),
|
| 197 |
+
gr.Number(label='diff_srv_rate (float)', value=0.0),
|
| 198 |
+
gr.Number(label='srv_diff_host_rate (float)', value=0.0),
|
| 199 |
+
gr.Number(label='dst_host_count (float)', value=150.0),
|
| 200 |
+
gr.Number(label='dst_host_srv_count (float)', value=25.0),
|
| 201 |
+
gr.Number(label='dst_host_same_srv_rate (float)', value=0.17),
|
| 202 |
+
gr.Number(label='dst_host_diff_srv_rate (float)', value=0.03),
|
| 203 |
+
gr.Number(label='dst_host_same_src_port_rate (float)', value=0.17),
|
| 204 |
+
gr.Number(label='dst_host_srv_diff_host_rate (float)', value=0.0),
|
| 205 |
+
gr.Number(label='dst_host_serror_rate (float)', value=0.0),
|
| 206 |
+
gr.Number(label='dst_host_srv_serror_rate (float)', value=0.0),
|
| 207 |
+
gr.Number(label='dst_host_rerror_rate (float)', value=0.05),
|
| 208 |
+
gr.Number(label='dst_host_srv_rerror_rate (float)', value=0.0)
|
| 209 |
+
]
|
| 210 |
+
|
| 211 |
+
# Define output components
|
| 212 |
+
output_components = [
|
| 213 |
+
gr.HTML(label="Prediction Result"),
|
| 214 |
+
gr.Label(label="Attack Probability")
|
| 215 |
+
]
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
# Combine all into the Gradio interface
|
| 219 |
+
iface = gr.Interface(
|
| 220 |
+
fn=predict_intrusion,
|
| 221 |
+
inputs=input_components,
|
| 222 |
+
outputs=output_components,
|
| 223 |
+
title="CNN Network Intrusion Detector (KDDCup'99)",
|
| 224 |
+
description=(
|
| 225 |
+
"Enter the 41 features of a network connection record to determine if it is "
|
| 226 |
+
"a **Normal** connection or an **Anomaly (Attack)**. This model is a 1D Convolutional Neural Network (CNN) "
|
| 227 |
+
f"optimized for high Attack Recall (using a prediction threshold of **{PREDICTION_THRESHOLD}**).<br>"
|
| 228 |
+
"Default values are set for a NORMAL FTP data connection."
|
| 229 |
+
),
|
| 230 |
+
live=False,
|
| 231 |
+
allow_flagging='never'
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
# Launch the interface (Hugging Face Spaces runs this automatically)
|
| 235 |
+
iface.launch()
|