File size: 3,063 Bytes
d65277f
 
 
 
 
 
 
 
 
 
2f88736
 
d65277f
 
 
2f88736
d65277f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f88736
 
d65277f
 
2f88736
 
 
d65277f
 
2f88736
d65277f
 
 
2f88736
d65277f
 
 
 
 
 
 
 
 
 
 
 
 
2f88736
d65277f
 
 
 
 
 
 
 
 
 
2f88736
d65277f
 
2f88736
d65277f
 
 
 
 
 
 
2f88736
 
 
 
 
 
d65277f
 
2f88736
 
d65277f
2f88736
d65277f
 
 
 
 
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
98
99
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 trained Decision Tree model
decision_tree_model = joblib.load('decision_tree_model.pkl')  # Update path if necessary

# Define required numeric features
numeric_features = [
    "date_numeric", "time_numeric", "latitude", "longitude", "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-%b-%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 GPS tracker 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:
        feature_values = log_data[numeric_features].astype(float).values
        predictions = 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', 'latitude', 'longitude', 'Prediction']]

    # Save the output to a CSV file for download
    output_file = "gps_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 GPS Tracker Log File (CSV format)")],
    outputs=[
        gr.Dataframe(label="Intrusion Detection Results"),
        gr.File(label="Download Predictions CSV")
    ],
    title="GPS Tracker Intrusion Detection System",
    description=(
        """
        Upload a GPS log file with the following features:
        date,time,latitude,longitude,label,type
        Example:
        25-Apr-19,18:31:39,116.521704,132.162504,1,ddos
        """
    )
)

iface.launch()