# GRADIO APPLICATION FOR HUGGING FACE SPACES # Loads the trained CNN and scaler to provide a web interface for network anomaly prediction. #int import os import joblib import numpy as np import pandas as pd import tensorflow as tf import gradio as gr from tensorflow.keras.models import load_model from sklearn.preprocessing import LabelEncoder # --- Model & Scaler Configuration --- H5_MODEL_FILE = "intrusion_detector_model.h5" SCALER_FILE_NAME = "scaler.pkl" # Threshold optimized in Cell 11 for better Attack Recall PREDICTION_THRESHOLD = 0.40 FEATURE_COUNT = 40 # Pre-defined list of all feature names (41 raw features) FEATURE_NAMES = [ 'duration', 'protocol_type', 'service', 'flag', 'src_bytes', 'dst_bytes', 'land', 'wrong_fragment', 'urgent', 'hot', 'num_failed_logins', 'logged_in', 'num_compromised', 'root_shell', 'su_attempted', 'num_root', 'num_file_creations', 'num_shells', 'num_access_files', 'num_outbound_cmds', 'is_host_login', 'is_guest_login', 'count', 'srv_count', 'serror_rate', 'srv_serror_rate', 'rerror_rate', 'srv_rerror_rate', 'same_srv_rate', 'diff_srv_rate', 'srv_diff_host_rate', 'dst_host_count', 'dst_host_srv_count', 'dst_host_same_srv_rate', 'dst_host_diff_srv_rate', 'dst_host_same_src_port_rate', 'dst_host_srv_diff_host_rate', 'dst_host_serror_rate', 'dst_host_srv_serror_rate', 'dst_host_rerror_rate', 'dst_host_srv_rerror_rate' ] # List of all possible service values (Must be comprehensive for correct OHE alignment) SERVICES = [ 'http', 'smtp', 'ftp_data', 'private', 'ecr_i', 'other', 'domain_u', 'finger', 'telnet', 'ftp', 'pop_3', 'courier', 'eco_i', 'imap4', 'domain_n', 'auth', 'time', 'shell', 'login', 'hostnames', 'ntp_service', 'echo', 'discard', 'systat', 'ctf', 'ssh', 'iso_tsap', 'whois', 'remote_job', 'sunrpc', 'rje', 'gopher', 'netbios_ssn', 'pm_srv', 'mtp', 'exec', 'klogin', 'kshell', 'daytime', 'message', 'icmp', 'netstat', 'Z39_50', 'bgp', 'nnsp', 'ctinrp', 'IRC', 'urp_i', 'pop_2', 'aol', 'rev_telnet', 'tftp_u' ] # List of all possible flag values FLAGS = [ 'SF', 'S0', 'REJ', 'RSTO', 'SH', 'S1', 'S2', 'RSTOS0', 'S3', 'OTH', 'RSTR' ] # List of all possible protocol types PROTOCOLS = ['tcp', 'udp', 'icmp'] # --- Define ALL Expected OHE Columns --- PROTOCOL_OHE = [f'protocol_type_{p}' for p in PROTOCOLS] FLAG_OHE = [f'flag_{f}' for f in FLAGS] SERVICE_OHE = [f'service_{s}' for s in SERVICES] NUMERICAL_BINARY_COLS = [ 'duration', 'src_bytes', 'dst_bytes', 'land', 'wrong_fragment', 'urgent', 'hot', 'num_failed_logins', 'logged_in', 'num_compromised', 'root_shell', 'su_attempted', 'num_root', 'num_file_creations', 'num_shells', 'num_access_files', 'num_outbound_cmds', 'is_host_login', 'is_guest_login', 'count', 'srv_count', 'serror_rate', 'srv_serror_rate', 'rerror_rate', 'srv_rerror_rate', 'same_srv_rate', 'diff_srv_rate', 'srv_diff_host_rate', 'dst_host_count', 'dst_host_srv_count', 'dst_host_same_srv_rate', 'dst_host_diff_srv_rate', 'dst_host_same_src_port_rate', 'dst_host_srv_diff_host_rate', 'dst_host_serror_rate', 'dst_host_srv_serror_rate', 'dst_host_rerror_rate', 'dst_host_srv_rerror_rate' ] MASTER_OHE_COLUMNS = NUMERICAL_BINARY_COLS + PROTOCOL_OHE + SERVICE_OHE + FLAG_OHE # Global artifacts model = None scaler = None label_encoder = None MAPPING = {'normal': 0, 'anomaly': 1} # --- Model Loading and Initialization (CRITICAL STEP) --- def load_artifacts(): """Loads the trained model and scaler globally.""" global model, scaler, label_encoder print("--- Starting Artifact Loading ---") # Check for file existence first if not os.path.exists(SCALER_FILE_NAME) or not os.path.exists(H5_MODEL_FILE): print(f"CRITICAL ERROR: One or both files are missing in the current directory:") print(f" Expected Scaler: {SCALER_FILE_NAME} (Exists: {os.path.exists(SCALER_FILE_NAME)})") print(f" Expected Model: {H5_MODEL_FILE} (Exists: {os.path.exists(H5_MODEL_FILE)})") print("Please ensure both files are uploaded to the root of your Hugging Face Space.") return False # 1. Load Scaler try: scaler = joblib.load(SCALER_FILE_NAME) print(f"✓ Scaler loaded from {SCALER_FILE_NAME}") except Exception as e: print(f"Error loading scaler. Check file format or compatibility: {e}") return False # 2. Load Model try: # Load in Keras H5 format # Setting compile=False often helps with deployment stability model = load_model(H5_MODEL_FILE, compile=False) print(f"✓ Model loaded from {H5_MODEL_FILE}") except Exception as e: print(f"Error loading model. Check Keras version compatibility: {e}") return False # 3. Initialize Label Encoder label_encoder = LabelEncoder() label_encoder.fit(list(MAPPING.keys())) print("✓ Label Encoder initialized.") print("--- Artifact Loading Complete ---") return True # Load artifacts on startup if not load_artifacts(): # If loading failed, the prediction function will return the error message pass # --- Prediction Function (Same as before) --- def predict_intrusion(*inputs): """ Takes 41 raw network features, preprocesses them, and makes a prediction. """ if model is None or scaler is None: return "