File size: 3,145 Bytes
827f213
 
552f626
827f213
122faa5
827f213
122faa5
827f213
 
552f626
827f213
 
552f626
827f213
 
b3e393a
9a09d32
 
827f213
552f626
827f213
 
 
 
 
 
 
 
552f626
 
827f213
 
 
 
 
 
 
b3e393a
827f213
 
 
 
9a09d32
58ce0c9
827f213
9a09d32
827f213
58ce0c9
 
9a09d32
827f213
 
 
58ce0c9
 
552f626
827f213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a09d32
827f213
9a09d32
827f213
9a09d32
58ce0c9
827f213
 
9a09d32
827f213
 
 
58ce0c9
827f213
 
 
 
9a09d32
552f626
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import pandas as pd
import numpy as np
import joblib
import gradio as gr
import os
import tempfile

# Set a custom directory for Gradio's temporary files
os.environ["GRADIO_TEMP"] = tempfile.mkdtemp()

# Load the saved Random Forest model
rf_model = joblib.load('rf_model.pkl')  # Ensure the correct model path

# Define required numeric features
numeric_features = [
    "date_numeric", "time_numeric", "door_state", "sphone_signal", "label"
]

# Class labels for attack types
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)}"

    # Map predictions to specific attack types
    log_data['Prediction'] = [class_labels.get(pred, 'Unknown Attack') for pred in predictions]

    # Format date for output
    log_data['date'] = log_data['date'].dt.strftime('%Y-%m-%d')

    # Select final output columns
    output_df = log_data[['date', 'time', 'Prediction']]

    # Save the output to a CSV file for download
    output_file = "intrusion_results.csv"
    output_df.to_csv(output_file, index=False)

    return output_df, output_file

# Create Gradio interface
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()