Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,9 +1,9 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import tempfile
|
| 3 |
import pandas as pd
|
| 4 |
-
import
|
|
|
|
| 5 |
import gradio as gr
|
| 6 |
-
|
|
|
|
| 7 |
|
| 8 |
# Set a custom directory for Gradio's temporary files
|
| 9 |
os.environ["GRADIO_TEMP"] = tempfile.mkdtemp()
|
|
@@ -17,159 +17,134 @@ device_models = {
|
|
| 17 |
"Fridge": "fridge_model.pkl"
|
| 18 |
}
|
| 19 |
|
| 20 |
-
# Define
|
| 21 |
device_features = {
|
| 22 |
-
"Fridge": ["date_numeric", "time_numeric", "fridge_temperature", "label"],
|
| 23 |
"Garage Door": ["date_numeric", "time_numeric", "door_state", "sphone_signal", "label"],
|
| 24 |
"GPS Tracker": ["date_numeric", "time_numeric", "latitude", "longitude", "label"],
|
| 25 |
-
"
|
| 26 |
-
"
|
|
|
|
| 27 |
}
|
| 28 |
|
| 29 |
-
#
|
| 30 |
class_labels = {
|
| 31 |
0: "Normal",
|
| 32 |
1: "Backdoor",
|
| 33 |
2: "DDoS",
|
| 34 |
3: "Injection",
|
| 35 |
-
4: "Password",
|
| 36 |
5: "Ransomware",
|
| 37 |
6: "Scanning",
|
| 38 |
-
7: "XSS"
|
| 39 |
}
|
| 40 |
|
| 41 |
-
def convert_datetime_features(
|
| 42 |
-
"""Convert date and time
|
| 43 |
try:
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
for fmt in date_formats:
|
| 52 |
-
try:
|
| 53 |
-
# Attempt to parse dates with the current format
|
| 54 |
-
valid_dates = pd.to_datetime(df['date'], format=fmt, errors='coerce')
|
| 55 |
-
if valid_dates.notna().any():
|
| 56 |
-
df['date_numeric'] = valid_dates.astype('int64') // 10**9
|
| 57 |
-
break
|
| 58 |
-
except Exception:
|
| 59 |
-
continue
|
| 60 |
-
|
| 61 |
-
# Check for unparsed dates
|
| 62 |
-
if df['date_numeric'].isna().any():
|
| 63 |
-
invalid_rows = df[df['date_numeric'].isna()]['date'].to_list()
|
| 64 |
-
raise ValueError(f"Invalid date formats in rows: {invalid_rows[:5]}")
|
| 65 |
-
|
| 66 |
-
# Convert time to seconds since midnight
|
| 67 |
-
df['time'] = pd.to_datetime(df['time'], format='%H:%M:%S', errors='coerce')
|
| 68 |
-
if df['time'].isna().any():
|
| 69 |
-
invalid_times = df[df['time'].isna()]['time'].to_list()
|
| 70 |
-
raise ValueError(f"Invalid time formats in rows: {invalid_times[:5]}")
|
| 71 |
-
df['time_numeric'] = df['time'].dt.hour * 3600 + df['time'].dt.minute * 60 + df['time'].dt.second
|
| 72 |
-
|
| 73 |
-
return df
|
| 74 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
except Exception as e:
|
| 76 |
-
|
| 77 |
|
| 78 |
-
|
| 79 |
try:
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
log_data['door_state'] = log_data['door_state'].
|
| 99 |
-
log_data['sphone_signal'] = log_data['sphone_signal']
|
| 100 |
-
elif
|
| 101 |
log_data['latitude'] = pd.to_numeric(log_data['latitude'], errors='coerce')
|
| 102 |
log_data['longitude'] = pd.to_numeric(log_data['longitude'], errors='coerce')
|
| 103 |
-
elif
|
| 104 |
-
log_data['
|
| 105 |
-
log_data['
|
| 106 |
-
elif
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
# Load the pre-trained model
|
| 118 |
-
try:
|
| 119 |
-
with open(device_models[device_type], "rb") as f:
|
| 120 |
-
model = pickle.load(f)
|
| 121 |
-
except FileNotFoundError:
|
| 122 |
-
error_df = pd.DataFrame({"Error": [f"Model file for {device_type} not found: {device_models[device_type]}"]})
|
| 123 |
-
return error_df, None
|
| 124 |
-
except KeyError:
|
| 125 |
-
error_df = pd.DataFrame({"Error": [f"No model defined for device type: {device_type}"]})
|
| 126 |
-
return error_df, None
|
| 127 |
-
|
| 128 |
-
# Prepare features for prediction (exclude label if present)
|
| 129 |
-
features = [f for f in required_features if f != "label"]
|
| 130 |
-
X = log_data[features]
|
| 131 |
-
|
| 132 |
-
# Make predictions
|
| 133 |
-
predictions = model.predict(X)
|
| 134 |
-
|
| 135 |
-
# Map predictions to class labels
|
| 136 |
-
log_data['Prediction'] = [class_labels.get(pred, "Unknown") for pred in predictions]
|
| 137 |
-
|
| 138 |
-
# Format date for output
|
| 139 |
-
log_data['date'] = log_data['date'].dt.strftime('%Y-%m-%d')
|
| 140 |
-
|
| 141 |
-
# Select output columns
|
| 142 |
-
output_data = log_data[['date', 'time', 'Prediction']]
|
| 143 |
-
|
| 144 |
-
# Save results to CSV
|
| 145 |
-
output_file = f"intrusion_results_{device_type.lower().replace(' ', '_')}.csv"
|
| 146 |
-
output_data.to_csv(output_file, index=False)
|
| 147 |
-
|
| 148 |
-
return output_data, output_file
|
| 149 |
-
|
| 150 |
except Exception as e:
|
| 151 |
-
|
| 152 |
-
return error_df, None
|
| 153 |
|
| 154 |
-
#
|
| 155 |
-
|
| 156 |
-
gr.Markdown("# IoT Intrusion Detection System")
|
| 157 |
-
gr.Markdown("Upload a CSV file and select the device type to detect intrusions.")
|
| 158 |
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
output_file =
|
|
|
|
| 167 |
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
)
|
|
|
|
| 173 |
|
| 174 |
-
|
| 175 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
| 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()
|
|
|
|
| 17 |
"Fridge": "fridge_model.pkl"
|
| 18 |
}
|
| 19 |
|
| 20 |
+
# Define required numeric features for each device
|
| 21 |
device_features = {
|
|
|
|
| 22 |
"Garage Door": ["date_numeric", "time_numeric", "door_state", "sphone_signal", "label"],
|
| 23 |
"GPS Tracker": ["date_numeric", "time_numeric", "latitude", "longitude", "label"],
|
| 24 |
+
"Weather": ["date_numeric", "time_numeric", "temperature", "humidity", "label"],
|
| 25 |
+
"Thermostat": ["date_numeric", "time_numeric", "temp_set", "temp_actual", "label"],
|
| 26 |
+
"Fridge": ["date_numeric", "time_numeric", "temp_inside", "door_open", "label"]
|
| 27 |
}
|
| 28 |
|
| 29 |
+
# Class labels for attack types (assuming same for all devices; adjust if needed)
|
| 30 |
class_labels = {
|
| 31 |
0: "Normal",
|
| 32 |
1: "Backdoor",
|
| 33 |
2: "DDoS",
|
| 34 |
3: "Injection",
|
| 35 |
+
4: "Password Attack",
|
| 36 |
5: "Ransomware",
|
| 37 |
6: "Scanning",
|
| 38 |
+
7: "XSS",
|
| 39 |
}
|
| 40 |
|
| 41 |
+
def convert_datetime_features(log_data):
|
| 42 |
+
"""Convert date and time into numeric values."""
|
| 43 |
try:
|
| 44 |
+
log_data['date'] = pd.to_datetime(log_data['date'], format='%d-%m-%y', errors='coerce')
|
| 45 |
+
log_data['date_numeric'] = log_data['date'].astype(np.int64) // 10**9
|
| 46 |
+
|
| 47 |
+
time_parsed = pd.to_datetime(log_data['time'], format='%H:%M:%S', errors='coerce')
|
| 48 |
+
log_data['time_numeric'] = (time_parsed.dt.hour * 3600) + (time_parsed.dt.minute * 60) + time_parsed.dt.second
|
| 49 |
+
except Exception as e:
|
| 50 |
+
return f"Error processing date/time: {str(e)}", None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
+
return None, log_data
|
| 53 |
+
|
| 54 |
+
def detect_intrusion(device, file):
|
| 55 |
+
"""Process log file and predict attack type based on selected device."""
|
| 56 |
+
# Load the selected device's model
|
| 57 |
+
try:
|
| 58 |
+
model = joblib.load(device_models[device])
|
| 59 |
except Exception as e:
|
| 60 |
+
return f"Error loading model for {device}: {str(e)}", None, None
|
| 61 |
|
| 62 |
+
# Read the uploaded file
|
| 63 |
try:
|
| 64 |
+
log_data = pd.read_csv(file.name)
|
| 65 |
+
except Exception as e:
|
| 66 |
+
return f"Error reading file: {str(e)}", None, None
|
| 67 |
+
|
| 68 |
+
# Convert date and time features
|
| 69 |
+
error, log_data = convert_datetime_features(log_data)
|
| 70 |
+
if error:
|
| 71 |
+
return error, None, None
|
| 72 |
+
|
| 73 |
+
# Get the required features for the selected device
|
| 74 |
+
required_features = device_features[device]
|
| 75 |
+
missing_features = [feature for feature in required_features if feature not in log_data.columns]
|
| 76 |
+
if missing_features:
|
| 77 |
+
return f"Missing features for {device}: {', '.join(missing_features)}", None, None
|
| 78 |
+
|
| 79 |
+
# Preprocess device-specific features
|
| 80 |
+
try:
|
| 81 |
+
if device == "Garage Door":
|
| 82 |
+
log_data['door_state'] = log_data['door_state'].astype(str).str.strip().replace({'closed': 0, 'open': 1})
|
| 83 |
+
log_data['sphone_signal'] = pd.to_numeric(log_data['sphone_signal'], errors='coerce')
|
| 84 |
+
elif device == "GPS Tracker":
|
| 85 |
log_data['latitude'] = pd.to_numeric(log_data['latitude'], errors='coerce')
|
| 86 |
log_data['longitude'] = pd.to_numeric(log_data['longitude'], errors='coerce')
|
| 87 |
+
elif device == "Weather":
|
| 88 |
+
log_data['temperature'] = pd.to_numeric(log_data['temperature'], errors='coerce')
|
| 89 |
+
log_data['humidity'] = pd.to_numeric(log_data['humidity'], errors='coerce')
|
| 90 |
+
elif device == "Thermostat":
|
| 91 |
+
log_data['temp_set'] = pd.to_numeric(log_data['temp_set'], errors='coerce')
|
| 92 |
+
log_data['temp_actual'] = pd.to_numeric(log_data['temp_actual'], errors='coerce')
|
| 93 |
+
elif device == "Fridge":
|
| 94 |
+
log_data['temp_inside'] = pd.to_numeric(log_data['temp_inside'], errors='coerce')
|
| 95 |
+
log_data['door_open'] = log_data['door_open'].astype(str).str.strip().replace({'closed': 0, 'open': 1})
|
| 96 |
+
|
| 97 |
+
# Prepare feature values for prediction
|
| 98 |
+
feature_values = log_data[required_features].astype(float).values
|
| 99 |
+
predictions = model.predict(feature_values)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
except Exception as e:
|
| 101 |
+
return f"Error during prediction for {device}: {str(e)}", None, None
|
|
|
|
| 102 |
|
| 103 |
+
# Map predictions to attack types
|
| 104 |
+
log_data['Prediction'] = [class_labels.get(pred, 'Unknown Attack') for pred in predictions]
|
|
|
|
|
|
|
| 105 |
|
| 106 |
+
# Format date for output
|
| 107 |
+
log_data['date'] = log_data['date'].dt.strftime('%Y-%m-%d')
|
| 108 |
+
|
| 109 |
+
# Select final output columns
|
| 110 |
+
output_df = log_data[['date', 'time', 'Prediction']]
|
| 111 |
+
|
| 112 |
+
# Save the output to a CSV file for download
|
| 113 |
+
output_file = f"intrusion_results_{device.lower().replace(' ', '_')}.csv"
|
| 114 |
+
output_df.to_csv(output_file, index=False)
|
| 115 |
|
| 116 |
+
return None, output_df, output_file
|
| 117 |
+
|
| 118 |
+
# Create Gradio interface
|
| 119 |
+
def gradio_interface(device, file):
|
| 120 |
+
error, df, output_file = detect_intrusion(device, file)
|
| 121 |
+
if error:
|
| 122 |
+
return error, None, None
|
| 123 |
+
return df, df, output_file
|
| 124 |
+
|
| 125 |
+
iface = gr.Interface(
|
| 126 |
+
fn=gradio_interface,
|
| 127 |
+
inputs=[
|
| 128 |
+
gr.Dropdown(choices=list(device_models.keys()), label="Select IoT Device", value="Garage Door"),
|
| 129 |
+
gr.File(label="Upload Log File (CSV format)")
|
| 130 |
+
],
|
| 131 |
+
outputs=[
|
| 132 |
+
gr.Textbox(label="Status/Error Message", visible=False),
|
| 133 |
+
gr.Dataframe(label="Intrusion Detection Results"),
|
| 134 |
+
gr.File(label="Download Predictions CSV")
|
| 135 |
+
],
|
| 136 |
+
title="IoT Intrusion Detection System",
|
| 137 |
+
description=(
|
| 138 |
+
"""
|
| 139 |
+
Select an IoT device and upload a CSV log file with the appropriate features for that device.
|
| 140 |
+
Example features per device:
|
| 141 |
+
- Garage Door: date,time,door_state,sphone_signal,label (e.g., 26-04-19,13:59:20,1,-85,normal)
|
| 142 |
+
- GPS Tracker: date,time,latitude,longitude,label
|
| 143 |
+
- Weather: date,time,temperature,humidity,label
|
| 144 |
+
- Thermostat: date,time,temp_set,temp_actual,label
|
| 145 |
+
- Fridge: date,time,temp_inside,door_open,label
|
| 146 |
+
"""
|
| 147 |
)
|
| 148 |
+
)
|
| 149 |
|
| 150 |
+
iface.launch()
|
|
|