# Online Python - IDE, Editor, Compiler, Interpreter import gradio as gr import pandas as pd import numpy as np import pickle import matplotlib.pyplot as plt from sklearn.ensemble import IsolationForest # Load trained model with open("trained_model.pkl", "rb") as f: model = pickle.load(f) # Load dataset df = pd.read_csv("Electric_Production.csv") df["DATE"] = pd.to_datetime(df["DATE"]) df.set_index("DATE", inplace=True) df = df.asfreq("MS") df["Lag_1"] = df["Value"].shift(1) df["Lag_2"] = df["Value"].shift(2) df["Month"] = df.index.month df["Year"] = df.index.year df.dropna(inplace=True) # Fit Isolation Forest for anomaly detection df["Timestamp"] = df.index.astype(np.int64) // 10**9 X_anom = df[["Timestamp", "Value"]] iso_forest = IsolationForest(contamination=0.02, random_state=42) df["Anomaly"] = iso_forest.fit_predict(X_anom) # Prediction function def forecast_electricity(lag1, lag2, month, year): input_df = pd.DataFrame([[lag1, lag2, month, year]], columns=["Lag_1", "Lag_2", "Month", "Year"]) prediction = model.predict(input_df)[0] return f"🔮 Predicted Electricity Production: {prediction:.2f}" # Plot function def show_anomaly_plot(): plt.figure(figsize=(10, 4)) plt.plot(df.index, df["Value"], label="Electricity Production", color="blue") anomalies = df[df["Anomaly"] == -1] plt.scatter(anomalies.index, anomalies["Value"], color="red", label="Anomalies", s=30) plt.xlabel("Date") plt.ylabel("Electricity Production") plt.title("Anomaly Detection") plt.legend() plt.grid(True) plt.tight_layout() plt.savefig("anomaly_plot.png") return "anomaly_plot.png" # Gradio UI with gr.Blocks() as demo: gr.Markdown("## ⚡ Powecast-AI: Electricity Forecasting and Anomaly Detection") with gr.Row(): with gr.Column(): lag1 = gr.Number(label="Lag 1 (Previous Month)") lag2 = gr.Number(label="Lag 2 (Two Months Ago)") month = gr.Number(label="Month (1-12)") year = gr.Number(label="Year (e.g. 2025)") predict_btn = gr.Button("Predict") prediction_output = gr.Textbox(label="Forecast Output") with gr.Column(): plot_btn = gr.Button("Show Anomaly Plot") plot_output = gr.Image() predict_btn.click(forecast_electricity, inputs=[lag1, lag2, month, year], outputs=prediction_output) plot_btn.click(show_anomaly_plot, outputs=plot_output) # Launch the app demo.launch()