Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990import streamlit as stimport pandas as pdimport pickleimport joblib# Load model artifacts@st.cache_resourcedef load_model_artifacts():with open('features_to_drop.pkl', 'rb') as f:features_to_drop = pickle.load(f)with open('category_encodings.pkl', 'rb') as f:category_encodings = pickle.load(f)model = joblib.load('xgb_model.pkl')return features_to_drop, category_encodings, model# Preprocessing functiondef preprocess_input(df, features_to_drop, category_encodings):df = df.copy()drop_cols = list(features_to_drop.intersection(df.columns))df.drop(columns=drop_cols, inplace=True, errors='ignore')for col, cats in category_encodings.items():if col in df.columns:df[col] = df[col].astype(str)df[col] = pd.Categorical(df[col], categories=cats)df[col] = df[col].cat.codesdf = df.fillna(0)return df# UI layoutst.set_page_config("IDS - Selected Features Input", layout="wide")st.title("Intrusion Detection System (IDS) - Manual Test Input")st.markdown("Enter selected features for a single row of network flow data:")with st.form("selected_input_form"):col1, col2 = st.columns(2)with col1:dur = st.number_input("Duration of Flow (`dur`)", min_value=0.0, step=0.001)proto = st.selectbox("Protocol (`proto`)", ["tcp", "udp", "icmp", "-"])service = st.text_input("Service (`service`)", value="-")state = st.selectbox("State (`state`)", ["CON", "INT", "FIN", "REQ", "-"])sbytes = st.number_input("Source Bytes (`sbytes`)", min_value=0)spkts = st.number_input("Source Packets (`spkts`)", min_value=0)sttl = st.number_input("Source TTL (`sttl`)", min_value=0)sload = st.number_input("Source Load (`sload`)", min_value=0.0)with col2:dbytes = st.number_input("Destination Bytes (`dbytes`)", min_value=0)dpkts = st.number_input("Destination Packets (`dpkts`)", min_value=0)sloss = st.number_input("Source Packet Loss (`sloss`)", min_value=0)swin = st.number_input("Source TCP Window Size (`swin`)", min_value=0)trans_depth = st.number_input("Transaction Depth (`trans_depth`)", min_value=0)ct_flw_http_mthd = st.text_input("HTTP Method (`ct_flw_http_mthd`)", value="-")is_ftp_login = st.selectbox("Is FTP Login (`is_ftp_login`)", [0, 1])attack_cat = st.text_input("(Optional) Ground Truth Label (`attack_cat`)", value="")submitted = st.form_submit_button("Run IDS Prediction")if submitted:user_input = pd.DataFrame([{"dur": dur,"proto": proto,"service": service,"state": state,"sbytes": sbytes,"dbytes": dbytes,"spkts": spkts,"dpkts": dpkts,"sttl": sttl,"sload": sload,"sloss": sloss,"swin": swin,"trans_depth": trans_depth,"ct_flw_http_mthd": ct_flw_http_mthd,"is_ftp_login": is_ftp_login,"attack_cat": attack_cat}])features_to_drop, category_encodings, model = load_model_artifacts()processed_input = preprocess_input(user_input, features_to_drop, category_encodings)if processed_input is not None:prediction = model.predict(processed_input)[0]st.success(f"Prediction: {prediction}")st.markdown("""- **13** → Normal Traffic- **Other values** → Intrusion Category""")else:st.error("Preprocessing failed. Please check your input.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051import streamlit as stimport pandas as pdimport numpy as npimport joblibimport pickle# ---------------------------# Load trained model and metadata# ---------------------------model = joblib.load('xgb_model.pkl')with open('features_to_drop.pkl', 'rb') as f:features_to_drop = pickle.load(f)with open('category_encodings.pkl', 'rb') as f:category_encodings = pickle.load(f)# ---------------------------# App UI# ---------------------------st.title("🚨 Intrusion Detection In Networks")st.markdown("Paste a single row of preprocessed NB15 features (comma-separated) below to predict the intrusion type.")user_input = st.text_area("Input (1 row from NB15_combined_preprocessed.csv):", height=150)if st.button("Predict"):try:# Convert user input string into a DataFramerow = [x.strip() for x in user_input.strip().split(",")]input_df = pd.DataFrame([row])# Load a sample row to get correct column names and data typessample_df = pd.read_csv('NB15_combined_preprocessed.csv', nrows=1)columns = sample_df.drop('attack_cat', axis=1).columns.tolist()# Ensure correct number of columnsif len(row) != len(columns):st.error(f"Expected {len(columns)} values, but got {len(row)}.")else:input_df.columns = columns# Convert to appropriate typesinput_df = input_df.apply(pd.to_numeric, errors='coerce')# Drop high-correlation featuresinput_df = input_df.drop(columns=features_to_drop, errors='ignore')# Predictprediction = model.predict(input_df)[0]st.success(f"🛡️ Predicted Intrusion Category: **{prediction}**")except Exception as e:st.error(f"⚠️ Error processing input: {e}")
app.py+47-86