| import pandas as pd |
| import numpy as np |
| import joblib |
| import gradio as gr |
| import os |
| import tempfile |
|
|
| |
| os.environ["GRADIO_TEMP"] = tempfile.mkdtemp() |
|
|
| |
| rf_model = joblib.load('rf_model.pkl') |
|
|
| |
| numeric_features = [ |
| "date_numeric", "time_numeric", "door_state", "sphone_signal", "label" |
| ] |
|
|
| |
| class_labels = { |
| 0: "Normal", |
| 1: "Backdoor", |
| 2: "DDoS", |
| 3: "Injection", |
| 4: "Password Attack", |
| 5: "Ransomware", |
| 6: "Scanning", |
| 7: "XSS", |
| } |
|
|
| def convert_datetime_features(log_data): |
| """Convert date and time into numeric values.""" |
| try: |
| log_data['date'] = pd.to_datetime(log_data['date'], format='%d-%m-%y', errors='coerce') |
| log_data['date_numeric'] = log_data['date'].astype(np.int64) // 10**9 |
|
|
| time_parsed = pd.to_datetime(log_data['time'], format='%H:%M:%S', errors='coerce') |
| log_data['time_numeric'] = (time_parsed.dt.hour * 3600) + (time_parsed.dt.minute * 60) + time_parsed.dt.second |
| except Exception as e: |
| return f"Error processing date/time: {str(e)}" |
| |
| return log_data |
|
|
| def detect_intrusion(file): |
| """Process log file and predict attack type.""" |
| try: |
| log_data = pd.read_csv(file.name) |
| except Exception as e: |
| return f"Error reading file: {str(e)}" |
|
|
| log_data = convert_datetime_features(log_data) |
|
|
| missing_features = [feature for feature in numeric_features if feature not in log_data.columns] |
| if missing_features: |
| return f"Missing features in file: {', '.join(missing_features)}" |
|
|
| try: |
| log_data['door_state'] = log_data['door_state'].astype(str).str.strip().replace({'closed': 0, 'open': 1}) |
| log_data['sphone_signal'] = pd.to_numeric(log_data['sphone_signal'], errors='coerce') |
|
|
| feature_values = log_data[numeric_features].astype(float).values |
| predictions = rf_model.predict(feature_values) |
| except Exception as e: |
| return f"Error during prediction: {str(e)}" |
|
|
| |
| log_data['Prediction'] = [class_labels.get(pred, 'Unknown Attack') for pred in predictions] |
|
|
| |
| log_data['date'] = log_data['date'].dt.strftime('%Y-%m-%d') |
|
|
| |
| output_df = log_data[['date', 'time', 'Prediction']] |
|
|
| |
| output_file = "intrusion_results.csv" |
| output_df.to_csv(output_file, index=False) |
|
|
| return output_df, output_file |
|
|
| |
| iface = gr.Interface( |
| fn=detect_intrusion, |
| inputs=[gr.File(label="Upload Log File (CSV format)")], |
| outputs=[gr.Dataframe(label="Intrusion Detection Results"), gr.File(label="Download Predictions CSV")], |
| title="Intrusion Detection System", |
| description=( |
| """ |
| Upload a CSV log file with the following features: |
| date,time,door_state,sphone_signal,label |
| Example: |
| 26-04-19,13:59:20,1,-85,normal |
| """ |
| ) |
| ) |
|
|
| iface.launch() |