SilverDragon9 commited on
Commit
0c115c5
·
verified ·
1 Parent(s): 73db1d3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -133
app.py CHANGED
@@ -1,9 +1,9 @@
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,159 +17,134 @@ device_models = {
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 with flexible format handling."""
43
  try:
44
- # Copy dataframe to avoid modifying original
45
- df = df.copy()
46
-
47
- # Try multiple date formats
48
- date_formats = ['%d-%b-%y', '%d-%m-%y', '%Y-%m-%d']
49
- df['date_numeric'] = pd.Series(index=df.index, dtype='float64')
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
- raise ValueError(f"Error converting date/time: {str(e)}")
77
 
78
- def detect_intrusion(file, device_type="Fridge"):
79
  try:
80
- # Read the input CSV file
81
- if isinstance(file, str):
82
- log_data = pd.read_csv(file)
83
- else:
84
- log_data = pd.read_csv(file.name)
85
-
86
- # Validate device type
87
- if device_type not in device_features:
88
- error_df = pd.DataFrame({"Error": [f"Unsupported device type: {device_type}"]})
89
- return error_df, None
90
-
91
- # Convert date and time to numeric features
92
- log_data = convert_datetime_features(log_data)
93
-
94
- # Preprocess features based on device type
95
- if device_type == "Fridge":
96
- log_data['fridge_temperature'] = pd.to_numeric(log_data['fridge_temperature'], errors='coerce')
97
- elif device_type == "Garage Door":
98
- log_data['door_state'] = log_data['door_state'].map({'closed': 0, 'open': 1})
99
- log_data['sphone_signal'] = log_data['sphone_signal'].astype(int)
100
- elif device_type == "GPS Tracker":
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 device_type == "Thermostat":
104
- log_data['current_temp'] = pd.to_numeric(log_data['current_temp'], errors='coerce')
105
- log_data['thermostat_status'] = log_data['thermostat_status'].astype(int)
106
- elif device_type == "Weather":
107
- for col in ['temperature', 'pressure', 'humidity']:
108
- log_data[col] = pd.to_numeric(log_data[col], errors='coerce')
109
-
110
- # Select relevant features
111
- required_features = device_features[device_type]
112
- missing_features = [f for f in required_features if f not in log_data.columns]
113
- if missing_features:
114
- error_df = pd.DataFrame({"Error": [f"Missing features for {device_type}: {', '.join(missing_features)}"]})
115
- return error_df, None
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
- error_df = pd.DataFrame({"Error": [f"Error processing file: {str(e)}"]})
152
- return error_df, None
153
 
154
- # Create Gradio interface
155
- with gr.Blocks() as demo:
156
- gr.Markdown("# IoT Intrusion Detection System")
157
- gr.Markdown("Upload a CSV file and select the device type to detect intrusions.")
158
 
159
- with gr.Row():
160
- file_input = gr.File(label="Upload CSV File")
161
- device_type = gr.Dropdown(choices=list(device_features.keys()), label="Device Type", value="Fridge")
162
-
163
- submit_button = gr.Button("Detect Intrusions")
164
-
165
- output_table = gr.Dataframe(label="Detection Results")
166
- output_file = gr.File(label="Download Results CSV")
 
167
 
168
- submit_button.click(
169
- fn=detect_intrusion,
170
- inputs=[file_input, device_type],
171
- outputs=[output_table, output_file]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  )
 
173
 
174
- # Launch the interface
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()