Aditya Das Gupta commited on
Update app.py
Browse files10 unmodified lines1112131415161718192021222324252627282930313233343536373839401 unmodified line424344454647484950515253545556575859606162636465666768697071722 unmodified lines757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451 unmodified line14714814915015115215315415515615715810 unmodified lines# --- Configuration Constants ---SCALER_PATH = 'scaler.joblib'KMEANS_MODEL_PATH = 'kmeans.joblib'# NOTE: For visualization, this app assumes a pre-trained PCA model is saved.# If you don't have one, you would train it on your data and save it:# pca = PCA(n_components=2).fit(scaled_data)# joblib.dump(pca, 'pca.joblib')PCA_MODEL_PATH = 'pca.joblib'# Define human-readable labels and visual icons for each cluster.# Icons are from placehold.co for demonstration purposes.CLUSTER_VISUALS = {0: {"label": "Voltage Swell","icon": "https://placehold.co/100x100/F87171/FFFFFF?text=Swell&font=roboto"},1: {"label": "Voltage Sag with Harmonics","icon": "https://placehold.co/100x100/FBBF24/FFFFFF?text=Sag&font=roboto"},2: {"label": "Normal Operation","icon": "https://placehold.co/100x100/34D399/FFFFFF?text=Normal&font=roboto"},3: {"label": "Severe Distortion","icon": "https://placehold.co/100x100/60A5FA/FFFFFF?text=Distortion&font=roboto"}}1 unmodified linetry:scaler = joblib.load(SCALER_PATH)kmeans = joblib.load(KMEANS_MODEL_PATH)# Load the PCA model for visualization.# If pca.joblib doesn't exist, we'll create a dummy one for demonstration.try:pca = joblib.load(PCA_MODEL_PATH)except FileNotFoundError:print("Warning: 'pca.joblib' not found. Using a dummy PCA for visualization.")# Create a dummy PCA if not found. In a real scenario, this file must exist.pca = PCA(n_components=2)# We need to fit it with dummy data that has the same number of features as the scaler.dummy_data = np.random.rand(10, scaler.n_features_in_)pca.fit(dummy_data)except FileNotFoundError as e:print(f"Error: Required model file not found at '{e.filename}'.")print("Please ensure 'scaler.joblib', 'kmeans.joblib', and 'pca.joblib' are in the same directory.")sys.exit(1)# --- Prediction and Visualization Function ---def classify_and_visualize(rms: float, thd: float, peak_voltage: float, crest_factor: float):"""Predicts the disturbance type and generates a 2D visualization of the result.Returns:tuple: A tuple containing the predicted label (str), a matplotlib plot,and an HTML string for the representative icon."""# 1. Predictioninput_data = pd.DataFrame({2 unmodified lines})scaled_input = scaler.transform(input_data)prediction = kmeans.predict(scaled_input)[0]result_label = CLUSTER_VISUALS.get(prediction, {}).get("label", "Unknown Cluster")icon_url = CLUSTER_VISUALS.get(prediction, {}).get("icon", "")icon_html = f"<div style='display:flex; justify-content:center; align-items:center; height:100%;'><img src='{icon_url}' alt='{result_label}' style='border-radius: 10px;'></div>"# 2. Visualization# Transform cluster centers and the new data point to 2D using PCAcluster_centers_2d = pca.transform(scaler.transform(kmeans.cluster_centers_))input_point_2d = pca.transform(scaled_input)# Create the plotfig, ax = plt.subplots(figsize=(6, 5))scatter = ax.scatter(cluster_centers_2d[:, 0], cluster_centers_2d[:, 1],c=range(len(cluster_centers_2d)), cmap='viridis', s=200, marker='X', label='Cluster Centers')ax.scatter(input_point_2d[:, 0], input_point_2d[:, 1],c='red', s=150, marker='*', label='Your Input', edgecolors='black')# Add labels to cluster centersfor i, center in enumerate(cluster_centers_2d):label = CLUSTER_VISUALS.get(i, {}).get("label", f"Cluster {i}")ax.text(center[0] + 0.05, center[1] + 0.05, label, fontsize=9)ax.set_title("Data Point vs. Cluster Centers (PCA View)")ax.set_xlabel("Principal Component 1")ax.set_ylabel("Principal Component 2")ax.grid(True, linestyle='--', alpha=0.6)ax.legend()plt.tight_layout()return result_label, fig, icon_html# --- Gradio Interface Definition ---with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as iface:gr.Markdown("# Power Quality Disturbance Classifier\n""Enter the features of an electrical signal to classify the disturbance type and visualize its relationship to learned clusters.")with gr.Row():with gr.Column(scale=1):gr.Markdown("### Input Features")rms_input = gr.Number(label="RMS Voltage")thd_input = gr.Number(label="Total Harmonic Distortion (THD)")peak_input = gr.Number(label="Peak Voltage")crest_input = gr.Number(label="Crest Factor")submit_btn = gr.Button("Classify", variant="primary")gr.Examples(examples=[[0.70, 0.09, 1.06, 1.51],[0.94, 0.19, 1.63, 1.75],[0.49, 0.45, 0.99, 2.04],],inputs=[rms_input, thd_input, peak_input, crest_input])with gr.Column(scale=2):gr.Markdown("### Classification Result")with gr.Row():with gr.Column(scale=1):result_icon = gr.HTML(label="Visual Indicator")with gr.Column(scale=2):result_label_output = gr.Textbox(label="Predicted Disturbance Type")plot_output = gr.Plot(label="Cluster Visualization")submit_btn.click(fn=classify_and_visualize,1 unmodified lineoutputs=[result_label_output, plot_output, result_icon])gr.Markdown("--- \n""**About this App:** This demonstration uses a K-Means clustering model to categorize power quality events. ""The plot visualizes the data in a 2D space created using Principal Component Analysis (PCA) for easier interpretation.")# --- Application Entry Point ---if __name__ == "__main__":iface.launch()10 unmodified lines1112131415161718192021222324252627282930313233343536373839404142434445464748495051521 unmodified line545556575859606162636465666768697071727374752 unmodified lines787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571 unmodified line15916016116216316410 unmodified lines# --- Configuration Constants ---SCALER_PATH = 'scaler.joblib'KMEANS_MODEL_PATH = 'kmeans.joblib'PCA_MODEL_PATH = 'pca.joblib'# --- Visual Assets and Labels ---# Using embedded SVGs for clean, scalable icons.CLUSTER_VISUALS = {0: {"label": "Voltage Swell","color": "#F87171", # Red"icon": """<svg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"><rect width="100" height="100" rx="15" fill="#F87171"/><path d="M10 50 Q 30 10, 50 50 T 90 50" stroke="white" stroke-width="5" fill="none" stroke-linecap="round"/></svg>"""},1: {"label": "Voltage Sag with Harmonics","color": "#FBBF24", # Amber"icon": """<svg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"><rect width="100" height="100" rx="15" fill="#FBBF24"/><path d="M10 50 Q 30 90, 50 50 T 90 50" stroke="white" stroke-width="5" fill="none" stroke-linecap="round"/></svg>"""},2: {"label": "Normal Operation","color": "#34D399", # Green"icon": """<svg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"><rect width="100" height="100" rx="15" fill="#34D399"/><path d="M10 50 Q 30 30, 50 50 T 90 50" stroke="white" stroke-width="5" fill="none" stroke-linecap="round"/></svg>"""},3: {"label": "Severe Distortion","color": "#60A5FA", # Blue"icon": """<svg width="100" height="100" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"><rect width="100" height="100" rx="15" fill="#60A5FA"/><path d="M10 50 l10-15 l10 25 l10-30 l10 20 l10-25 l10 15 l10-5 l10 15" stroke="white" stroke-width="5" fill="none" stroke-linecap="round" stroke-linejoin="round"/></svg>"""}}1 unmodified linetry:scaler = joblib.load(SCALER_PATH)kmeans = joblib.load(KMEANS_MODEL_PATH)try:pca = joblib.load(PCA_MODEL_PATH)except FileNotFoundError:print("Warning: 'pca.joblib' not found. A dummy PCA model will be created.")pca = PCA(n_components=2)dummy_data = np.random.rand(10, scaler.n_features_in_)pca.fit(dummy_data)except FileNotFoundError as e:print(f"Error: Required model file not found at '{e.filename}'.")print("Please ensure 'scaler.joblib' and 'kmeans.joblib' are present.")sys.exit(1)# --- Prediction and Visualization Function ---def classify_and_visualize(rms: float, thd: float, peak_voltage: float, crest_factor: float):"""Predicts disturbance type and generates a 2D visualization."""# 1. Predictioninput_data = pd.DataFrame({2 unmodified lines})scaled_input = scaler.transform(input_data)prediction = kmeans.predict(scaled_input)[0]result_info = CLUSTER_VISUALS.get(prediction, {})result_label = result_info.get("label", "Unknown Cluster")icon_html = f"<div style='display:flex; justify-content:center; align-items:center; height:100%;'>{result_info.get('icon', '')}</div>"# 2. Visualizationplt.style.use('seaborn-v0_8-whitegrid')fig, ax = plt.subplots(figsize=(6, 5))# Transform data for plottingcluster_centers_2d = pca.transform(kmeans.cluster_centers_)input_point_2d = pca.transform(scaled_input)# Plot cluster centerscolors = [CLUSTER_VISUALS.get(i, {}).get("color", "#808080") for i in range(len(cluster_centers_2d))]ax.scatter(cluster_centers_2d[:, 0], cluster_centers_2d[:, 1],c=colors, s=250, marker='X', label='Cluster Centers', edgecolors='black', linewidth=1)# Plot user's input pointax.scatter(input_point_2d[:, 0], input_point_2d[:, 1],c=CLUSTER_VISUALS.get(prediction, {}).get("color", "red"), s=200, marker='*', label='Your Input', edgecolors='white', linewidth=1.5)# Aestheticsax.set_title("Data Point vs. Cluster Centers (PCA View)", fontsize=14, weight='bold')ax.set_xlabel("Principal Component 1", fontsize=10)ax.set_ylabel("Principal Component 2", fontsize=10)ax.grid(True, which='both', linestyle='--', linewidth=0.5)ax.spines['top'].set_visible(False)ax.spines['right'].set_visible(False)ax.tick_params(labelsize=9)ax.legend(fontsize=10, frameon=True, fancybox=True, shadow=True, framealpha=0.9)plt.tight_layout()return result_label, fig, icon_html# --- Gradio Interface Definition ---with gr.Blocks(theme=gr.themes.Glass(primary_hue="blue", secondary_hue="sky")) as iface:gr.Markdown("<h1 style='text-align: center; margin-bottom: 1rem'>Power Quality Disturbance Classifier</h1>""<p style='text-align: center; font-size: 1rem;'>An intelligent tool to classify electrical disturbances and visualize the results in real-time.</p>")with gr.Row():with gr.Column(scale=2):with gr.Box():gr.Markdown("<h3 style='margin-bottom: 1rem; text-align: center;'>Input Features</h3>")rms_input = gr.Number(label="RMS Voltage")thd_input = gr.Number(label="Total Harmonic Distortion (THD)")peak_input = gr.Number(label="Peak Voltage")crest_input = gr.Number(label="Crest Factor")submit_btn = gr.Button("Analyze Signal", variant="primary", scale=2)with gr.Column(scale=3):with gr.Box():gr.Markdown("<h3 style='margin-bottom: 1rem; text-align: center;'>Classification Result</h3>")with gr.Row():with gr.Column(scale=1):result_icon = gr.HTML(label="Visual Indicator")with gr.Column(scale=2):result_label_output = gr.Textbox(label="Predicted Disturbance Type", interactive=False)plot_output = gr.Plot(label="Cluster Visualization")gr.Examples(examples=[[0.70, 0.09, 1.06, 1.51],[0.94, 0.19, 1.63, 1.75],[0.49, 0.45, 0.99, 2.04],],inputs=[rms_input, thd_input, peak_input, crest_input],label="Sample Inputs")submit_btn.click(fn=classify_and_visualize,1 unmodified lineoutputs=[result_label_output, plot_output, result_icon])# --- Application Entry Point ---if __name__ == "__main__":iface.launch()
app.py+82-76