Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from sklearn.preprocessing import StandardScaler
|
| 4 |
+
from sklearn.svm import OneClassSVM
|
| 5 |
+
|
| 6 |
+
# Function to detect theft and provide insights
|
| 7 |
+
def detect_theft_from_file(uploaded_file):
|
| 8 |
+
# Determine the file type and read it
|
| 9 |
+
if uploaded_file.name.endswith('.csv'):
|
| 10 |
+
df = pd.read_csv(uploaded_file.name)
|
| 11 |
+
elif uploaded_file.name.endswith(('.xlsx', '.xls')):
|
| 12 |
+
df = pd.read_excel(uploaded_file.name)
|
| 13 |
+
else:
|
| 14 |
+
return "Unsupported file format. Please upload a CSV or Excel file."
|
| 15 |
+
|
| 16 |
+
# Ensure required format (Consumer ID + 12 months + optional Last Year)
|
| 17 |
+
if len(df.columns) < 13:
|
| 18 |
+
return "The file must have at least 13 columns: 'Consumer ID', 12 months (e.g., Jan-Dec), and optionally 'Last Year Avg'."
|
| 19 |
+
|
| 20 |
+
feature_columns = df.columns[1:13] # 12 months
|
| 21 |
+
data = df[feature_columns].values
|
| 22 |
+
|
| 23 |
+
# Normalize the data
|
| 24 |
+
scaler = StandardScaler()
|
| 25 |
+
data_scaled = scaler.fit_transform(data)
|
| 26 |
+
|
| 27 |
+
# One-Class SVM model
|
| 28 |
+
model = OneClassSVM(nu=0.1, kernel='rbf', gamma='scale')
|
| 29 |
+
model.fit(data_scaled)
|
| 30 |
+
|
| 31 |
+
# Predict anomalies
|
| 32 |
+
predictions = model.predict(data_scaled)
|
| 33 |
+
|
| 34 |
+
# Add Reasons and Tips
|
| 35 |
+
reasons = []
|
| 36 |
+
tips = []
|
| 37 |
+
for i, pred in enumerate(predictions):
|
| 38 |
+
if pred == -1: # Theft detected
|
| 39 |
+
current_pattern = data[i]
|
| 40 |
+
if 'Last Year Avg' in df.columns:
|
| 41 |
+
last_year_avg = df['Last Year Avg'].iloc[i]
|
| 42 |
+
if current_pattern.mean() < 0.5 * last_year_avg:
|
| 43 |
+
reasons.append("Unusual drop compared to last year's average.")
|
| 44 |
+
elif current_pattern.mean() > 1.5 * last_year_avg:
|
| 45 |
+
reasons.append("Unusual rise compared to last year's average.")
|
| 46 |
+
else:
|
| 47 |
+
reasons.append("Irregular monthly pattern detected.")
|
| 48 |
+
else:
|
| 49 |
+
reasons.append("Irregular monthly pattern detected.")
|
| 50 |
+
|
| 51 |
+
tips.append(
|
| 52 |
+
"1. Inspect the meter physically for tampering.\n"
|
| 53 |
+
"2. Compare with neighborhood usage for similar consumption patterns.\n"
|
| 54 |
+
"3. Check if there are bypass connections or rewiring."
|
| 55 |
+
)
|
| 56 |
+
else: # No theft detected
|
| 57 |
+
reasons.append("No irregularities detected.")
|
| 58 |
+
tips.append("No action required.")
|
| 59 |
+
|
| 60 |
+
# Results
|
| 61 |
+
df['Anomaly'] = ['Theft' if pred == -1 else 'No Theft' for pred in predictions]
|
| 62 |
+
df['Reason'] = reasons
|
| 63 |
+
df['Tips'] = tips
|
| 64 |
+
return df[['Consumer ID', 'Anomaly', 'Reason', 'Tips']]
|
| 65 |
+
|
| 66 |
+
# Function for manual input detection
|
| 67 |
+
def detect_theft_from_manual_input(consumer_id, *monthly_kwh):
|
| 68 |
+
# Create a DataFrame from manual input
|
| 69 |
+
df = pd.DataFrame(
|
| 70 |
+
{
|
| 71 |
+
'Consumer ID': [consumer_id],
|
| 72 |
+
**{f'Month {i+1}': [monthly_kwh[i]] for i in range(12)},
|
| 73 |
+
}
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
# Normalize the data
|
| 77 |
+
data = df.iloc[:, 1:].values # Select monthly data
|
| 78 |
+
scaler = StandardScaler()
|
| 79 |
+
data_scaled = scaler.fit_transform(data)
|
| 80 |
+
|
| 81 |
+
# One-Class SVM model
|
| 82 |
+
model = OneClassSVM(nu=0.1, kernel='rbf', gamma='scale')
|
| 83 |
+
model.fit(data_scaled)
|
| 84 |
+
|
| 85 |
+
# Predict anomaly
|
| 86 |
+
prediction = model.predict(data_scaled)
|
| 87 |
+
|
| 88 |
+
# Add Reason and Tips
|
| 89 |
+
if prediction[0] == -1: # Theft detected
|
| 90 |
+
reason = "Irregular monthly pattern detected."
|
| 91 |
+
tips = (
|
| 92 |
+
"1. Inspect the meter physically for tampering.\n"
|
| 93 |
+
"2. Compare with neighborhood usage for similar consumption patterns.\n"
|
| 94 |
+
"3. Check if there are bypass connections or rewiring."
|
| 95 |
+
)
|
| 96 |
+
else:
|
| 97 |
+
reason = "No irregularities detected."
|
| 98 |
+
tips = "No action required."
|
| 99 |
+
|
| 100 |
+
df['Anomaly'] = ['Theft' if prediction[0] == -1 else 'No Theft']
|
| 101 |
+
df['Reason'] = [reason]
|
| 102 |
+
df['Tips'] = [tips]
|
| 103 |
+
return df[['Consumer ID', 'Anomaly', 'Reason', 'Tips']]
|
| 104 |
+
|
| 105 |
+
# Gradio Interface
|
| 106 |
+
file_interface = gr.Interface(
|
| 107 |
+
fn=detect_theft_from_file,
|
| 108 |
+
inputs=gr.File(label="Upload Meter Data File (CSV, XLSX, XLS)"),
|
| 109 |
+
outputs=gr.Dataframe(label="Meter Theft Detection")
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
manual_input_interface = gr.Interface(
|
| 113 |
+
fn=detect_theft_from_manual_input,
|
| 114 |
+
inputs=[
|
| 115 |
+
gr.Textbox(label="Consumer ID", placeholder="Enter Consumer ID"),
|
| 116 |
+
*[gr.Number(label=f"Month {i+1} kWh") for i in range(12)],
|
| 117 |
+
],
|
| 118 |
+
outputs=gr.Dataframe(label="Meter Theft Detection")
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
# Combine interfaces
|
| 122 |
+
iface = gr.TabbedInterface(
|
| 123 |
+
interface_list=[file_interface, manual_input_interface],
|
| 124 |
+
tab_names=["Upload File", "Manual Input"]
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
# Launch the Gradio app
|
| 128 |
+
iface.launch()
|