TANVEERMAKHDOOM commited on
Commit
1bfb5eb
·
verified ·
1 Parent(s): d57bfd7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -0
app.py CHANGED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import numpy as np
4
+ from sklearn.ensemble import IsolationForest
5
+
6
+ def generate_sample_data():
7
+ # Simulate 200 time points of energy consumption
8
+ rng = np.random.default_rng(seed=42)
9
+ normal_consumption = rng.normal(loc=100, scale=10, size=200)
10
+
11
+ # Inject anomalies (potential theft) - unusually low or high consumption spikes
12
+ anomalies = rng.choice([50, 200], size=10) # Very low or very high
13
+ anomaly_indices = rng.choice(range(200), size=10, replace=False)
14
+ normal_consumption[anomaly_indices] = anomalies
15
+
16
+ df = pd.DataFrame({
17
+ 'timestamp': pd.date_range(start='2025-01-01', periods=200, freq='H'),
18
+ 'consumption': normal_consumption
19
+ })
20
+ return df
21
+
22
+ def detect_energy_theft(file=None, use_sample=False):
23
+ if use_sample:
24
+ df = generate_sample_data()
25
+ else:
26
+ try:
27
+ df = pd.read_csv(file.name)
28
+ except Exception as e:
29
+ return f"Error reading file: {e}"
30
+
31
+ if 'consumption' not in df.columns:
32
+ return "CSV must have a 'consumption' column."
33
+
34
+ X = df[['consumption']].values
35
+
36
+ model = IsolationForest(contamination=0.05, random_state=42)
37
+ model.fit(X)
38
+
39
+ df['anomaly_score'] = model.decision_function(X)
40
+ df['anomaly'] = model.predict(X)
41
+ df['theft_detected'] = df['anomaly'] == -1
42
+
43
+ suspicious = df[df['theft_detected'] == True][['timestamp', 'consumption', 'anomaly_score']]
44
+ if suspicious.empty:
45
+ return "No energy theft anomalies detected."
46
+ else:
47
+ return suspicious
48
+
49
+ # Gradio UI
50
+ with gr.Blocks() as demo:
51
+ gr.Markdown("# Energy Theft Detection")
52
+ gr.Markdown("Upload CSV with 'consumption' column or use sample data to detect anomalies.")
53
+
54
+ with gr.Row():
55
+ file_input = gr.File(label="Upload your CSV file", file_types=['.csv'])
56
+ sample_btn = gr.Button("Use Sample Data")
57
+
58
+ output = gr.Dataframe(headers=["timestamp", "consumption", "anomaly_score"], label="Suspicious Anomalies Detected")
59
+
60
+ def on_file_submit(file):
61
+ return detect_energy_theft(file=file, use_sample=False)
62
+
63
+ def on_sample_click():
64
+ return detect_energy_theft(use_sample=True)
65
+
66
+ file_input.change(on_file_submit, inputs=file_input, outputs=output)
67
+ sample_btn.click(on_sample_click, outputs=output)
68
+
69
+ if __name__ == "__main__":
70
+ demo.launch()