SilverDragon9 commited on
Commit
d254296
·
verified ·
1 Parent(s): 619bf90

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -109
app.py CHANGED
@@ -1,9 +1,9 @@
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,134 +17,131 @@ device_models = {
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()
 
 
 
 
 
 
1
  import os
2
  import tempfile
3
+ import pandas as pd
4
+ import pickle
5
+ import gradio as gr
6
+ from datetime import datetime
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 the device-specific features
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
+ "Thermostat": ["date_numeric", "time_numeric", "current_temp", "thermostat_status", "label"],
26
+ "Weather": ["date_numeric", "time_numeric", "temperature", "pressure", "humidity", "label"]
 
27
  }
28
 
29
+ # Define class labels for attack types
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(df):
42
+ """Convert date and time to numeric features."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  try:
44
+ # Convert date to datetime and then to Unix timestamp
45
+ df['date'] = pd.to_datetime(df['date'], format='%d-%b-%y')
46
+ df['date_numeric'] = df['date'].astype('int64') // 10**9
47
+
48
+ # Convert time to seconds since midnight
49
+ df['time'] = pd.to_datetime(df['time'], format='%H:%M:%S')
50
+ df['time_numeric'] = df['time'].dt.hour * 3600 + df['time'].dt.minute * 60 + df['time'].dt.second
51
  except Exception as e:
52
+ raise ValueError(f"Error converting date/time: {str(e)}")
53
+ return df
 
 
 
 
 
 
 
 
 
 
54
 
55
+ def detect_intrusion(file, device_type="Fridge"):
56
  try:
57
+ # Read the input CSV file
58
+ if isinstance(file, str):
59
+ log_data = pd.read_csv(file)
60
+ else:
61
+ log_data = pd.read_csv(file.name)
62
+
63
+ # Validate device type
64
+ if device_type not in device_features:
65
+ return f"Unsupported device type: {device_type}"
66
+
67
+ # Convert date and time to numeric features
68
+ log_data = convert_datetime_features(log_data)
69
+
70
+ # Preprocess features based on device type
71
+ if device_type == "Fridge":
72
+ log_data['fridge_temperature'] = pd.to_numeric(log_data['fridge_temperature'], errors='coerce')
73
+ elif device_type == "Garage Door":
74
+ log_data['door_state'] = log_data['door_state'].map({'closed': 0, 'open': 1})
75
+ log_data['sphone_signal'] = log_data['sphone_signal'].astype(int)
76
+ elif device_type == "GPS Tracker":
77
  log_data['latitude'] = pd.to_numeric(log_data['latitude'], errors='coerce')
78
  log_data['longitude'] = pd.to_numeric(log_data['longitude'], errors='coerce')
79
+ elif device_type == "Thermostat":
80
+ log_data['current_temp'] = pd.to_numeric(log_data['current_temp'], errors='coerce')
81
+ log_data['thermostat_status'] = log_data['thermostat_status'].astype(int)
82
+ elif device_type == "Weather":
83
+ for col in ['temperature', 'pressure', 'humidity']:
84
+ log_data[col] = pd.to_numeric(log_data[col], errors='coerce')
85
+
86
+ # Select relevant features
87
+ required_features = device_features[device_type]
88
+ missing_features = [f for f in required_features if f not in log_data.columns]
89
+ if missing_features:
90
+ return f"Missing features for {device_type}: {', '.join(missing_features)}"
91
+
92
+ # Load the pre-trained model
93
+ try:
94
+ with open(device_models[device_type], "rb") as f:
95
+ model = pickle.load(f)
96
+ except FileNotFoundError:
97
+ return f"Model file for {device_type} not found: {device_models[device_type]}"
98
+ except KeyError:
99
+ return f"No model defined for device type: {device_type}"
100
+
101
+ # Prepare features for prediction (exclude label if present)
102
+ features = [f for f in required_features if f != "label"]
103
+ X = log_data[features]
104
+
105
+ # Make predictions
106
+ predictions = model.predict(X)
107
+
108
+ # Map predictions to class labels
109
+ log_data['Prediction'] = [class_labels.get(pred, "Unknown") for pred in predictions]
110
+
111
+ # Format date for output
112
+ log_data['date'] = log_data['date'].dt.strftime('%Y-%m-%d')
113
+
114
+ # Select output columns
115
+ output_data = log_data[['date', 'time', 'Prediction']]
116
+
117
+ # Save results to CSV
118
+ output_file = f"intrusion_results_{device_type.lower().replace(' ', '_')}.csv"
119
+ output_data.to_csv(output_file, index=False)
120
+
121
+ return output_data, output_file
122
 
123
+ except Exception as e:
124
+ return f"Error processing file: {str(e)}"
125
 
126
+ # Create Gradio interface
127
+ with gr.Blocks() as demo:
128
+ gr.Markdown("# IoT Intrusion Detection System")
129
+ gr.Markdown("Upload a CSV file and select the device type to detect intrusions.")
130
 
131
+ with gr.Row():
132
+ file_input = gr.File(label="Upload CSV File")
133
+ device_type = gr.Dropdown(choices=list(device_features.keys()), label="Device Type", value="Fridge")
134
+
135
+ submit_button = gr.Button("Detect Intrusions")
136
+
137
+ output_table = gr.Dataframe(label="Detection Results")
138
+ output_file = gr.File(label="Download Results CSV")
139
 
140
+ submit_button.click(
141
+ fn=detect_intrusion,
142
+ inputs=[file_input, device_type],
143
+ outputs=[output_table, output_file]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  )
 
145
 
146
+ # Launch the interface
147
+ demo.launch()