Sniffer.AI / Sniffer_AI(GPS Tracker Dataset).py
SilverDragon9's picture
Update Sniffer_AI(GPS Tracker Dataset).py
2f88736 verified
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()