Rename app.py to Sniffer_AI(GPS Tracker Dataset).py
Browse files- Sniffer_AI(GPS Tracker Dataset).py +97 -0
- app.py +0 -64
Sniffer_AI(GPS Tracker Dataset).py
ADDED
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pandas as pd
|
2 |
+
import numpy as np
|
3 |
+
import joblib
|
4 |
+
import gradio as gr
|
5 |
+
import os
|
6 |
+
import tempfile
|
7 |
+
|
8 |
+
# Set a custom directory for Gradio's temporary files
|
9 |
+
os.environ["GRADIO_TEMP"] = tempfile.mkdtemp()
|
10 |
+
|
11 |
+
# Load the saved Random Forest model
|
12 |
+
rf_model = joblib.load('rf_model.pkl') # Ensure the correct model path
|
13 |
+
|
14 |
+
# Define required numeric features
|
15 |
+
numeric_features = [
|
16 |
+
"date_numeric", "time_numeric", "door_state", "sphone_signal", "label"
|
17 |
+
]
|
18 |
+
|
19 |
+
# Class labels for attack types
|
20 |
+
class_labels = {
|
21 |
+
0: "Normal",
|
22 |
+
1: "Backdoor",
|
23 |
+
2: "DDoS",
|
24 |
+
3: "Injection",
|
25 |
+
4: "Password Attack",
|
26 |
+
5: "Ransomware",
|
27 |
+
6: "Scanning",
|
28 |
+
7: "XSS",
|
29 |
+
}
|
30 |
+
|
31 |
+
def convert_datetime_features(log_data):
|
32 |
+
"""Convert date and time into numeric values."""
|
33 |
+
try:
|
34 |
+
log_data['date'] = pd.to_datetime(log_data['date'], format='%d-%m-%y', errors='coerce')
|
35 |
+
log_data['date_numeric'] = log_data['date'].astype(np.int64) // 10**9
|
36 |
+
|
37 |
+
time_parsed = pd.to_datetime(log_data['time'], format='%H:%M:%S', errors='coerce')
|
38 |
+
log_data['time_numeric'] = (time_parsed.dt.hour * 3600) + (time_parsed.dt.minute * 60) + time_parsed.dt.second
|
39 |
+
except Exception as e:
|
40 |
+
return f"Error processing date/time: {str(e)}"
|
41 |
+
|
42 |
+
return log_data
|
43 |
+
|
44 |
+
def detect_intrusion(file):
|
45 |
+
"""Process log file and predict attack type."""
|
46 |
+
try:
|
47 |
+
log_data = pd.read_csv(file.name)
|
48 |
+
except Exception as e:
|
49 |
+
return f"Error reading file: {str(e)}"
|
50 |
+
|
51 |
+
log_data = convert_datetime_features(log_data)
|
52 |
+
|
53 |
+
missing_features = [feature for feature in numeric_features if feature not in log_data.columns]
|
54 |
+
if missing_features:
|
55 |
+
return f"Missing features in file: {', '.join(missing_features)}"
|
56 |
+
|
57 |
+
try:
|
58 |
+
log_data['door_state'] = log_data['door_state'].astype(str).str.strip().replace({'closed': 0, 'open': 1})
|
59 |
+
log_data['sphone_signal'] = pd.to_numeric(log_data['sphone_signal'], errors='coerce')
|
60 |
+
|
61 |
+
feature_values = log_data[numeric_features].astype(float).values
|
62 |
+
predictions = rf_model.predict(feature_values)
|
63 |
+
except Exception as e:
|
64 |
+
return f"Error during prediction: {str(e)}"
|
65 |
+
|
66 |
+
# Map predictions to specific attack types
|
67 |
+
log_data['Prediction'] = [class_labels.get(pred, 'Unknown Attack') for pred in predictions]
|
68 |
+
|
69 |
+
# Format date for output
|
70 |
+
log_data['date'] = log_data['date'].dt.strftime('%Y-%m-%d')
|
71 |
+
|
72 |
+
# Select final output columns
|
73 |
+
output_df = log_data[['date', 'time', 'Prediction']]
|
74 |
+
|
75 |
+
# Save the output to a CSV file for download
|
76 |
+
output_file = "intrusion_results.csv"
|
77 |
+
output_df.to_csv(output_file, index=False)
|
78 |
+
|
79 |
+
return output_df, output_file
|
80 |
+
|
81 |
+
# Create Gradio interface
|
82 |
+
iface = gr.Interface(
|
83 |
+
fn=detect_intrusion,
|
84 |
+
inputs=[gr.File(label="Upload Log File (CSV format)")],
|
85 |
+
outputs=[gr.Dataframe(label="Intrusion Detection Results"), gr.File(label="Download Predictions CSV")],
|
86 |
+
title="Intrusion Detection System",
|
87 |
+
description=(
|
88 |
+
"""
|
89 |
+
Upload a CSV log file with the following features:
|
90 |
+
date,time,door_state,sphone_signal,label
|
91 |
+
Example:
|
92 |
+
26-04-19,13:59:20,1,-85,normal
|
93 |
+
"""
|
94 |
+
)
|
95 |
+
)
|
96 |
+
|
97 |
+
iface.launch()
|
app.py
DELETED
@@ -1,64 +0,0 @@
|
|
1 |
-
import gradio as gr
|
2 |
-
import joblib
|
3 |
-
import requests
|
4 |
-
import os
|
5 |
-
|
6 |
-
from sklearn.ensemble import RandomForestClassifier, BaggingClassifier, AdaBoostClassifier
|
7 |
-
from sklearn.tree import DecisionTreeClassifier
|
8 |
-
|
9 |
-
|
10 |
-
# Load the saved models
|
11 |
-
rf_model = joblib.load('rf_model.pkl')
|
12 |
-
dt_model = joblib.load('decision_tree_model.pkl')
|
13 |
-
bagging_model = joblib.load('model_bagging.pkl')
|
14 |
-
ada_model = joblib.load('model_adaboost.pkl')
|
15 |
-
|
16 |
-
class_labels = {
|
17 |
-
0: "normal",
|
18 |
-
1: "backdoor",
|
19 |
-
2: "ddos",
|
20 |
-
3: "dos",
|
21 |
-
4: "injection",
|
22 |
-
5: "password",
|
23 |
-
6: "ransomware",
|
24 |
-
7: "scanning",
|
25 |
-
8: "xss",
|
26 |
-
9: "mitm"
|
27 |
-
}
|
28 |
-
|
29 |
-
def detect_intrusion(features, model_choice="Random Forest"):
|
30 |
-
# Convert the input string (comma-separated values) into a list of floats
|
31 |
-
features = [list(map(float, features.split(",")))]
|
32 |
-
|
33 |
-
# Choose the model based on user selection
|
34 |
-
if model_choice == "Random Forest":
|
35 |
-
model = rf_model
|
36 |
-
elif model_choice == "Decision Tree":
|
37 |
-
model = decision_tree_model
|
38 |
-
elif model_choice == "Bagging Classifier":
|
39 |
-
model = model_bagging
|
40 |
-
elif model_choice == "AdaBoost Classifier":
|
41 |
-
model = model_adaboost
|
42 |
-
else:
|
43 |
-
return "Invalid model choice!"
|
44 |
-
|
45 |
-
# Predict the class (multi-class classification)
|
46 |
-
prediction = model.predict(features)
|
47 |
-
predicted_class = prediction[0] # Get the predicted class (an integer between 0-8)
|
48 |
-
|
49 |
-
# Return the human-readable class description
|
50 |
-
if predicted_class == 0:
|
51 |
-
return "No Intrusion Detected"
|
52 |
-
else:
|
53 |
-
return f"Intrusion Detected: {class_labels.get(predicted_class, 'Unknown Attack')}"
|
54 |
-
|
55 |
-
# Create a Gradio interface
|
56 |
-
iface = gr.Interface(fn=detect_intrusion,
|
57 |
-
inputs=[gr.Textbox(label="Input Features (comma-separated)"),
|
58 |
-
gr.Dropdown(choices=["Random Forest", "Decision Tree", "Bagging Classifier", "AdaBoost Classifier"], label="Select Model")],
|
59 |
-
outputs="text",
|
60 |
-
title="Intrusion Detection System",
|
61 |
-
description="Enter features in the format: feature1, feature2, feature3...")
|
62 |
-
|
63 |
-
# Launch the interface locally for testing
|
64 |
-
iface.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|