Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -39,18 +39,41 @@ class_labels = {
|
|
| 39 |
}
|
| 40 |
|
| 41 |
def convert_datetime_features(df):
|
| 42 |
-
"""Convert date and time to numeric features."""
|
| 43 |
try:
|
| 44 |
-
#
|
| 45 |
-
df
|
| 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:
|
|
@@ -62,7 +85,8 @@ def detect_intrusion(file, device_type="Fridge"):
|
|
| 62 |
|
| 63 |
# Validate device type
|
| 64 |
if device_type not in device_features:
|
| 65 |
-
|
|
|
|
| 66 |
|
| 67 |
# Convert date and time to numeric features
|
| 68 |
log_data = convert_datetime_features(log_data)
|
|
@@ -87,16 +111,19 @@ def detect_intrusion(file, device_type="Fridge"):
|
|
| 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 |
-
|
|
|
|
| 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 |
-
|
|
|
|
| 98 |
except KeyError:
|
| 99 |
-
|
|
|
|
| 100 |
|
| 101 |
# Prepare features for prediction (exclude label if present)
|
| 102 |
features = [f for f in required_features if f != "label"]
|
|
@@ -121,7 +148,8 @@ def detect_intrusion(file, device_type="Fridge"):
|
|
| 121 |
return output_data, output_file
|
| 122 |
|
| 123 |
except Exception as e:
|
| 124 |
-
|
|
|
|
| 125 |
|
| 126 |
# Create Gradio interface
|
| 127 |
with gr.Blocks() as demo:
|
|
|
|
| 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:
|
|
|
|
| 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)
|
|
|
|
| 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"]
|
|
|
|
| 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:
|