Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,15 +8,25 @@ import tempfile
|
|
| 8 |
# Set a custom directory for Gradio's temporary files
|
| 9 |
os.environ["GRADIO_TEMP"] = tempfile.mkdtemp()
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
# Define required numeric features
|
| 15 |
-
|
| 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",
|
|
@@ -35,35 +45,62 @@ def convert_datetime_features(log_data):
|
|
| 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
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
-
|
|
|
|
|
|
|
| 54 |
if missing_features:
|
| 55 |
-
return f"Missing features
|
| 56 |
|
|
|
|
| 57 |
try:
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 67 |
log_data['Prediction'] = [class_labels.get(pred, 'Unknown Attack') for pred in predictions]
|
| 68 |
|
| 69 |
# Format date for output
|
|
@@ -73,23 +110,39 @@ def detect_intrusion(file):
|
|
| 73 |
output_df = log_data[['date', 'time', 'Prediction']]
|
| 74 |
|
| 75 |
# Save the output to a CSV file for download
|
| 76 |
-
output_file = "
|
| 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=
|
| 84 |
-
inputs=[
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
description=(
|
| 88 |
"""
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
| 93 |
"""
|
| 94 |
)
|
| 95 |
)
|
|
|
|
| 8 |
# Set a custom directory for Gradio's temporary files
|
| 9 |
os.environ["GRADIO_TEMP"] = tempfile.mkdtemp()
|
| 10 |
|
| 11 |
+
# Dictionary of IoT devices and their corresponding model files
|
| 12 |
+
device_models = {
|
| 13 |
+
"Garage Door": "garage_door_model.pkl",
|
| 14 |
+
"GPS Tracker": "gps_tracker_model.pkl",
|
| 15 |
+
"Weather": "weather_model.pkl",
|
| 16 |
+
"Thermostat": "thermostat_model.pkl",
|
| 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",
|
|
|
|
| 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 |
+
rf_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 = rf_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
|
|
|
|
| 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"),
|
| 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 |
)
|