Spaces:
Build error
Build error
Download app.py from hareshchander/Smart-Grid-Anomaly-Detector: direct link, hf CLI and curl.
- Browser
- Download file 16.5 kB
-
https://huggingface.co/spaces/hareshchander/Smart-Grid-Anomaly-Detector/resolve/main/app.py
- Command line
-
hf download hf://spaces/hareshchander/Smart-Grid-Anomaly-Detector/app.py
-
curl -L -o app.py https://huggingface.co/spaces/hareshchander/Smart-Grid-Anomaly-Detector/resolve/main/app.py
16.5 kB
| """ | |
| Smart Grid Anomaly Detection System | |
| Complete Gradio Web Application for Hugging Face Deployment | |
| """ | |
| import gradio as gr | |
| import pandas as pd | |
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| import seaborn as sns | |
| from datetime import datetime, timedelta | |
| import warnings | |
| import io | |
| from PIL import Image | |
| warnings.filterwarnings('ignore') | |
| from sklearn.preprocessing import StandardScaler | |
| from sklearn.ensemble import IsolationForest | |
| from sklearn.svm import OneClassSVM | |
| from sklearn.covariance import EllipticEnvelope | |
| from sklearn.decomposition import PCA | |
| from sklearn.feature_selection import VarianceThreshold | |
| from scipy import stats | |
| import plotly.graph_objects as go | |
| from plotly.subplots import make_subplots | |
| plt.style.use('seaborn-v0_8-darkgrid') | |
| sns.set_palette("husl") | |
| def generate_sample_data(duration_days=30): | |
| """Generate realistic sample smart grid data""" | |
| n_samples = duration_days * 96 | |
| start_date = datetime(2024, 1, 1) | |
| timestamps = [start_date + timedelta(minutes=15*i) for i in range(n_samples)] | |
| t = np.arange(n_samples) | |
| daily_pattern = 50 + 30 * np.sin(2 * np.pi * t / 96) | |
| weekly_pattern = 10 * np.sin(2 * np.pi * t / (7 * 96)) | |
| random_variation = np.random.normal(0, 5, n_samples) | |
| power = daily_pattern + weekly_pattern + random_variation | |
| df = pd.DataFrame({ | |
| 'timestamp': timestamps, | |
| 'voltage': 230 + np.random.normal(0, 2, n_samples), | |
| 'current': power / 230 * 1000 + np.random.normal(0, 10, n_samples), | |
| 'frequency': 50 + np.random.normal(0, 0.1, n_samples), | |
| 'power_consumption': power, | |
| 'power_factor': 0.9 + np.random.normal(0, 0.03, n_samples) | |
| }) | |
| n_anomalies = int(0.08 * n_samples) | |
| anomaly_idx = np.random.choice(df.index, n_anomalies, replace=False) | |
| df.loc[anomaly_idx[:n_anomalies//4], 'voltage'] += np.random.choice([-35, 35], n_anomalies//4) | |
| df.loc[anomaly_idx[n_anomalies//4:n_anomalies//2], 'power_consumption'] *= 2.5 | |
| df.loc[anomaly_idx[n_anomalies//2:3*n_anomalies//4], 'frequency'] += np.random.choice([-2, 2], n_anomalies//4) | |
| df.loc[anomaly_idx[3*n_anomalies//4:], 'power_factor'] = 0.6 | |
| return df | |
| def validate_and_preprocess_data(df): | |
| """Validate and preprocess input data""" | |
| column_mapping = { | |
| 'timestamp': ['timestamp', 'time', 'datetime', 'date_time', 'date'], | |
| 'voltage': ['voltage', 'voltage_v', 'volt', 'v'], | |
| 'current': ['current', 'current_a', 'amp', 'i', 'a'], | |
| 'frequency': ['frequency', 'frequency_hz', 'freq', 'hz', 'f'] | |
| } | |
| for standard_name, possible_names in column_mapping.items(): | |
| for col in df.columns: | |
| if col.lower().strip() in possible_names: | |
| df.rename(columns={col: standard_name}, inplace=True) | |
| break | |
| required_cols = ['timestamp', 'voltage', 'current', 'frequency'] | |
| missing_cols = [col for col in required_cols if col not in df.columns] | |
| if missing_cols: | |
| raise ValueError(f"Missing columns: {missing_cols}") | |
| df['timestamp'] = pd.to_datetime(df['timestamp']) | |
| df.set_index('timestamp', inplace=True) | |
| df.sort_index(inplace=True) | |
| if 'power_consumption' not in df.columns: | |
| df['power_consumption'] = (df['voltage'] * df['current']) / 1000 | |
| if 'power_factor' not in df.columns: | |
| df['power_factor'] = 0.9 | |
| initial_missing = df.isnull().sum().sum() | |
| if initial_missing > 0: | |
| df = df.interpolate(method='linear').fillna(method='bfill').fillna(method='ffill') | |
| initial_duplicates = df.index.duplicated().sum() | |
| if initial_duplicates > 0: | |
| df = df[~df.index.duplicated(keep='first')] | |
| return df, initial_missing, initial_duplicates | |
| def engineer_features(df): | |
| """Create features for anomaly detection""" | |
| sensors = ['voltage', 'current', 'frequency', 'power_consumption', 'power_factor'] | |
| window_size = max(12, min(48, len(df) // 240)) | |
| for sensor in sensors: | |
| df[f'{sensor}_rolling_mean'] = df[sensor].rolling(window=window_size).mean() | |
| df[f'{sensor}_rolling_std'] = df[sensor].rolling(window=window_size).std() | |
| df[f'{sensor}_diff'] = df[sensor].diff() | |
| df['hour'] = df.index.hour | |
| df['day_of_week'] = df.index.dayofweek | |
| df['is_weekend'] = (df['day_of_week'] >= 5).astype(int) | |
| df_features = df.dropna() | |
| return df_features, sensors | |
| def detect_anomalies(df_features, contamination=0.05): | |
| """Detect anomalies using ensemble of ML models""" | |
| numeric_cols = df_features.select_dtypes(include=[np.number]).columns.tolist() | |
| X = df_features[numeric_cols] | |
| n_samples, n_features = X.shape | |
| max_features = min(n_samples // 3, 30) | |
| if n_features > max_features: | |
| selector = VarianceThreshold(threshold=0.01) | |
| X_temp = selector.fit_transform(X) | |
| selected_cols = X.columns[selector.get_support()].tolist() | |
| if len(selected_cols) > max_features: | |
| pca = PCA(n_components=max_features, random_state=42) | |
| X_reduced = pca.fit_transform(X[selected_cols]) | |
| X = pd.DataFrame(X_reduced, index=df_features.index) | |
| else: | |
| X = df_features[selected_cols] | |
| scaler = StandardScaler() | |
| X_scaled = scaler.fit_transform(X) | |
| models = { | |
| 'Isolation Forest': IsolationForest(contamination=contamination, random_state=42, n_jobs=-1), | |
| 'One-Class SVM': OneClassSVM(nu=contamination, kernel='rbf', gamma='auto') | |
| } | |
| if n_samples > X.shape[1] * 2: | |
| models['Elliptic Envelope'] = EllipticEnvelope(contamination=contamination, random_state=42) | |
| results = {} | |
| model_info = {} | |
| for name, model in models.items(): | |
| try: | |
| model.fit(X_scaled) | |
| predictions = model.predict(X_scaled) | |
| predictions = (predictions == -1).astype(int) | |
| results[name] = predictions | |
| df_features[f'{name}_prediction'] = predictions | |
| n_detected = predictions.sum() | |
| model_info[name] = {'detected': n_detected, 'rate': (n_detected / len(predictions)) * 100} | |
| except: | |
| df_features[f'{name}_prediction'] = 0 | |
| results[name] = np.zeros(len(X_scaled), dtype=int) | |
| model_info[name] = {'detected': 0, 'rate': 0.0} | |
| sensors = ['voltage', 'current', 'frequency', 'power_consumption', 'power_factor'] | |
| df_features['zscore_anomaly'] = 0 | |
| for sensor in sensors: | |
| z_scores = np.abs(stats.zscore(df_features[sensor])) | |
| df_features['zscore_anomaly'] |= (z_scores > 3).astype(int) | |
| n_zscore = df_features['zscore_anomaly'].sum() | |
| model_info['Z-Score'] = {'detected': n_zscore, 'rate': (n_zscore / len(df_features)) * 100} | |
| successful_models = list(results.keys()) | |
| ensemble_sum = df_features['zscore_anomaly'].copy() | |
| for name in successful_models: | |
| ensemble_sum += df_features[f'{name}_prediction'] | |
| threshold = (len(successful_models) + 1) // 2 + 1 | |
| df_features['ensemble_anomaly'] = (ensemble_sum >= threshold).astype(int) | |
| n_ensemble = df_features['ensemble_anomaly'].sum() | |
| model_info['Ensemble'] = {'detected': n_ensemble, 'rate': (n_ensemble / len(df_features)) * 100} | |
| return df_features, results, sensors, model_info | |
| def create_overview_visualization(df_features, sensors): | |
| """Create time series overview""" | |
| anomaly_mask = df_features['ensemble_anomaly'] == 1 | |
| normal_mask = df_features['ensemble_anomaly'] == 0 | |
| fig, axes = plt.subplots(4, 1, figsize=(16, 12)) | |
| colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A'] | |
| units = ['V', 'A', 'Hz', 'kW'] | |
| for idx, (sensor, color, unit) in enumerate(zip(sensors[:4], colors, units)): | |
| ax = axes[idx] | |
| normal_data = df_features[normal_mask] | |
| ax.plot(normal_data.index, normal_data[sensor], color=color, alpha=0.6, linewidth=1) | |
| ax.fill_between(normal_data.index, normal_data[sensor], alpha=0.15, color=color) | |
| anomaly_data = df_features[anomaly_mask] | |
| if len(anomaly_data) > 0: | |
| ax.scatter(anomaly_data.index, anomaly_data[sensor], color='red', s=50, | |
| alpha=0.8, marker='X', edgecolors='darkred', linewidths=2, zorder=5) | |
| ax.set_ylabel(f'{sensor.title()} ({unit})', fontsize=12, fontweight='bold') | |
| ax.set_title(f'{sensor.replace("_", " ").title()}', fontsize=14, fontweight='bold', color=color) | |
| ax.grid(True, alpha=0.3) | |
| ax.legend(['Normal', 'Anomaly'], loc='upper right') | |
| axes[-1].set_xlabel('Timestamp', fontsize=12, fontweight='bold') | |
| fig.suptitle('Smart Grid Anomaly Detection - Time Series', fontsize=16, fontweight='bold') | |
| plt.tight_layout() | |
| buf = io.BytesIO() | |
| plt.savefig(buf, format='png', dpi=150, bbox_inches='tight') | |
| buf.seek(0) | |
| img = Image.open(buf) | |
| plt.close() | |
| return img | |
| def create_model_comparison(model_info, df_features): | |
| """Create model comparison chart""" | |
| fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 6)) | |
| model_names = list(model_info.keys()) | |
| detection_counts = [info['detected'] for info in model_info.values()] | |
| colors_bar = plt.cm.viridis(np.linspace(0.2, 0.9, len(model_names))) | |
| bars = ax1.bar(model_names, detection_counts, color=colors_bar, edgecolor='black', linewidth=2) | |
| for bar, count in zip(bars, detection_counts): | |
| height = bar.get_height() | |
| ax1.text(bar.get_x() + bar.get_width()/2., height, f'{int(count)}', | |
| ha='center', va='bottom', fontsize=10, fontweight='bold') | |
| ax1.set_ylabel('Anomalies Detected', fontsize=12, fontweight='bold') | |
| ax1.set_title('Model Comparison', fontsize=14, fontweight='bold') | |
| ax1.grid(axis='y', alpha=0.3) | |
| plt.setp(ax1.xaxis.get_majorticklabels(), rotation=20, ha='right') | |
| n_anomalies = df_features['ensemble_anomaly'].sum() | |
| n_normal = len(df_features) - n_anomalies | |
| ax2.pie([n_normal, n_anomalies], labels=['Normal', 'Anomalies'], | |
| colors=['#4ECDC4', '#FF6B6B'], autopct='%1.1f%%', startangle=90) | |
| ax2.set_title('Data Distribution', fontsize=14, fontweight='bold') | |
| plt.tight_layout() | |
| buf = io.BytesIO() | |
| plt.savefig(buf, format='png', dpi=150, bbox_inches='tight') | |
| buf.seek(0) | |
| img = Image.open(buf) | |
| plt.close() | |
| return img | |
| def create_interactive_timeline(df_features, sensors): | |
| """Create interactive timeline""" | |
| anomaly_mask = df_features['ensemble_anomaly'] == 1 | |
| normal_mask = df_features['ensemble_anomaly'] == 0 | |
| fig = make_subplots(rows=len(sensors), cols=1, shared_xaxes=True, | |
| subplot_titles=[s.title() for s in sensors]) | |
| colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#95E1D3'] | |
| for idx, (sensor, color) in enumerate(zip(sensors, colors)): | |
| normal_data = df_features[normal_mask] | |
| fig.add_trace(go.Scatter(x=normal_data.index, y=normal_data[sensor], | |
| mode='lines', name='Normal' if idx == 0 else None, | |
| line=dict(color=color, width=2), showlegend=(idx == 0)), | |
| row=idx+1, col=1) | |
| anomaly_data = df_features[anomaly_mask] | |
| if len(anomaly_data) > 0: | |
| fig.add_trace(go.Scatter(x=anomaly_data.index, y=anomaly_data[sensor], | |
| mode='markers', name='Anomaly' if idx == 0 else None, | |
| marker=dict(color='red', size=8, symbol='x'), | |
| showlegend=(idx == 0)), | |
| row=idx+1, col=1) | |
| fig.update_layout(height=250*len(sensors), title_text="Interactive Timeline", | |
| showlegend=True, hovermode='x unified') | |
| return fig | |
| def process_data(csv_file, use_sample, contamination): | |
| """Main processing function""" | |
| try: | |
| if use_sample or csv_file is None: | |
| df = generate_sample_data(30) | |
| status = "β Generated sample data (30 days)\n" | |
| else: | |
| df = pd.read_csv(csv_file.name) | |
| status = f"β Loaded: {csv_file.name}\n" | |
| df, missing, duplicates = validate_and_preprocess_data(df) | |
| status += f"β Preprocessed {len(df):,} records\n" | |
| status += f"π Range: {df.index.min()} to {df.index.max()}\n\n" | |
| df_features, sensors = engineer_features(df) | |
| status += f"β Features: {df_features.shape}\n\n" | |
| df_features, results, sensors, model_info = detect_anomalies(df_features, contamination) | |
| n_anomalies = df_features['ensemble_anomaly'].sum() | |
| status += f"π― RESULTS:\n" | |
| status += f" Total: {len(df_features):,}\n" | |
| status += f" Anomalies: {n_anomalies:,} ({n_anomalies/len(df_features)*100:.2f}%)\n\n" | |
| for name, info in model_info.items(): | |
| status += f" {name}: {info['detected']} ({info['rate']:.1f}%)\n" | |
| img1 = create_overview_visualization(df_features, sensors) | |
| img2 = create_model_comparison(model_info, df_features) | |
| fig3 = create_interactive_timeline(df_features, sensors) | |
| output_columns = sensors + ['ensemble_anomaly'] | |
| output_df = df_features[output_columns].copy() | |
| output_df.to_csv('results.csv') | |
| if n_anomalies > 0: | |
| summary = df_features[df_features['ensemble_anomaly'] == 1][sensors].head(20) | |
| summary_html = summary.to_html() | |
| else: | |
| summary_html = "<p>No anomalies detected</p>" | |
| return status, img1, img2, fig3, 'results.csv', summary_html | |
| except Exception as e: | |
| error_msg = f"β Error: {str(e)}" | |
| return error_msg, None, None, None, None, None | |
| # Create Gradio Interface | |
| with gr.Blocks(theme=gr.themes.Soft(), title="Smart Grid Anomaly Detection") as demo: | |
| gr.HTML(""" | |
| <div style='text-align: center; padding: 30px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); | |
| border-radius: 15px; margin-bottom: 20px;'> | |
| <h1 style='color: white; margin: 0; font-size: 36px;'>β‘ Smart Grid Anomaly Detection</h1> | |
| <p style='color: white; margin-top: 10px; font-size: 18px;'> | |
| Advanced ML-Powered Time Series Analysis | |
| </p> | |
| </div> | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("### π Input Configuration") | |
| csv_file = gr.File(label="Upload CSV", file_types=[".csv"]) | |
| use_sample = gr.Checkbox(label="Use Sample Data", value=True) | |
| contamination = gr.Slider(0.01, 0.20, value=0.05, step=0.01, | |
| label="Expected Anomaly Rate") | |
| analyze_btn = gr.Button("π Analyze", variant="primary", size="lg") | |
| gr.Markdown(""" | |
| ### π CSV Format | |
| **Required:** | |
| - timestamp | |
| - voltage | |
| - current | |
| - frequency | |
| """) | |
| with gr.Column(scale=2): | |
| gr.Markdown("### π Status") | |
| status_box = gr.Textbox(label="Analysis Status", lines=12) | |
| gr.Markdown("---") | |
| gr.Markdown("## π Results") | |
| with gr.Tabs(): | |
| with gr.Tab("π Time Series"): | |
| img_timeseries = gr.Image(label="Anomaly Detection") | |
| with gr.Tab("π Comparison"): | |
| img_comparison = gr.Image(label="Model Performance") | |
| with gr.Tab("π Interactive"): | |
| plot_interactive = gr.Plot(label="Timeline") | |
| gr.Markdown("---") | |
| with gr.Row(): | |
| with gr.Column(): | |
| gr.Markdown("### π Anomaly Summary") | |
| summary_html = gr.HTML() | |
| with gr.Column(): | |
| gr.Markdown("### πΎ Download") | |
| output_csv = gr.File(label="Results CSV") | |
| analyze_btn.click( | |
| fn=process_data, | |
| inputs=[csv_file, use_sample, contamination], | |
| outputs=[status_box, img_timeseries, img_comparison, plot_interactive, output_csv, summary_html] | |
| ) | |
| gr.HTML(""" | |
| <div style='text-align: center; padding: 20px; margin-top: 20px; background: #f8f9fa; border-radius: 10px;'> | |
| <p style='color: #666;'>π¬ Powered by Machine Learning | Built with Gradio</p> | |
| </div> | |
| """) | |
| if __name__ == "__main__": | |
| demo.launch() |