1 line
6.1 KiB
JSON
1 line
6.1 KiB
JSON
{"repo": "arun9123/ai-powered-nids", "files": {"app.py": {"b11db0fe2c4967296dcb6c5a010787dd78a2c996": {"t": 1785674394.510285, "n": 5825, "h": "2544fa9de949569f", "c": "import streamlit as st\nimport pandas as pd\nimport numpy as np\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom groq import Groq\nimport os\n\n# --- PAGE SETUP ---\nst.set_page_config(page_title=\"AI-based NIDS\", layout=\"wide\")\n\nst.title(\"AI-Based Network Intrusion Detection System\")\nst.markdown(\"\"\"\n**Student Project**: This system uses **Random Forest** to detect Network attacks and **Groq AI** to explain the packets.\n\"\"\")\n\n# --- CONFIGURATION ---\nDATA_FILE = \"Friday-WorkingHours-Afternoon-DDos.pcap_ISCX.csv\"\n\n# --- SIDEBAR: SETTINGS ---\nst.sidebar.header(\"1. Settings\")\ngroq_api_key = st.sidebar.text_input(\"Groq API Key (starts with gsk_)\", type=\"password\")\nst.sidebar.caption(\"[Get a free key here](https://console.groq.com/keys)\")\n\nst.sidebar.header(\"2. Model Training\")\n\n@st.cache_data\ndef load_data(filepath):\n try:\n df = pd.read_csv(filepath, nrows=15000)\n df.columns = df.columns.str.strip()\n df.replace([np.inf, -np.inf], np.nan, inplace=True)\n df.dropna(inplace=True)\n return df\n except FileNotFoundError:\n return None\n\ndef train_model(df):\n features = ['Flow Duration', 'Total Fwd Packets', 'Total Backward Packets', \n 'Total Length of Fwd Packets', 'Fwd Packet Length Max', \n 'Flow IAT Mean', 'Flow IAT Std', 'Flow Packets/s']\n target = 'Label'\n \n missing_cols = [c for c in features if c not in df.columns]\n if missing_cols:\n st.error(f\"Missing columns in CSV: {missing_cols}\")\n return None, 0, [], None, None\n\n X = df[features]\n y = df[target]\n \n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n \n clf = RandomForestClassifier(n_estimators=10, max_depth=10, random_state=42)\n clf.fit(X_train, y_train)\n \n score = accuracy_score(y_test, clf.predict(X_test))\n return clf, score, features, X_test, y_test\n\n# --- APP LOGIC ---\ndf = load_data(DATA_FILE)\n\nif df is None:\n st.error(f\"Error: File '{DATA_FILE}' not found. Please upload it to the Files tab.\")\n st.stop()\n\nst.sidebar.success(f\"Dataset Loaded: {len(df)} rows\")\n\nif st.sidebar.button(\"Train Model Now\"):\n with st.spinner(\"Training model...\"):\n clf, accuracy, feature_names, X_test, y_test = train_model(df)\n if clf:\n st.session_state['model'] = clf\n st.session_state['features'] = feature_names\n st.session_state['X_test'] = X_test \n st.session_state['y_test'] = y_test\n st.sidebar.success(f\"Training Complete! Accuracy: {accuracy:.2%}\")\n\nst.header(\"3. Threat Analysis Dashboard\")\n\nif 'model' in st.session_state:\n col1, col2 = st.columns(2)\n \n with col1:\n st.subheader(\"Simulation\")\n st.info(\"Pick a random packet from the test data to simulate live traffic.\")\n \n if st.button(\"🎲 Capture Random Packet\"):\n random_idx = np.random.randint(0, len(st.session_state['X_test']))\n packet_data = st.session_state['X_test'].iloc[random_idx]\n actual_label = st.session_state['y_test'].iloc[random_idx]\n \n st.session_state['current_packet'] = packet_data\n st.session_state['actual_label'] = actual_label\n \n if 'current_packet' in st.session_state:\n packet = st.session_state['current_packet']\n \n with col1:\n st.write(\"**Packet Header Info:**\")\n st.dataframe(packet, use_container_width=True)\n\n with col2:\n st.subheader(\"AI Detection Result\")\n prediction = st.session_state['model'].predict([packet])[0]\n \n if prediction == \"BENIGN\":\n st.success(f\" STATUS: **SAFE (BENIGN)**\")\n else:\n st.error(f\"🚨 STATUS: **ATTACK DETECTED ({prediction})**\")\n \n st.caption(f\"Ground Truth Label: {st.session_state['actual_label']}\")\n\n st.markdown(\"---\")\n st.subheader(\" Ask AI Analyst (Groq)\")\n \n if st.button(\"Generate Explanation\"):\n if not groq_api_key:\n st.warning(\" Please enter your Groq API Key in the sidebar first.\")\n else:\n try:\n client = Groq(api_key=groq_api_key)\n \n prompt = f\"\"\"\n You are a cybersecurity analyst. \n A network packet was detected as: {prediction}.\n \n Packet Technical Details:\n {packet.to_string()}\n \n Please explain:\n 1. Why these specific values (like Flow Duration or Packet Length) might indicate {prediction}.\n 2. If it is BENIGN, explain why it looks normal.\n 3. Keep the answer short and simple for a student.\n \"\"\"\n\n with st.spinner(\"Groq is analyzing the packet...\"):\n completion = client.chat.completions.create(\n model=\"llama-3.3-70b-versatile\", # <--- UPDATED MODEL NAME\n messages=[\n {\"role\": \"user\", \"content\": prompt}\n ],\n temperature=0.6,\n )\n st.info(completion.choices[0].message.content)\n \n except Exception as e:\n st.error(f\"API Error: {e}\")\nelse:\n st.info(\" Waiting for model training. Click **'Train Model Now'** in the sidebar.\")"}}}} |