zarahmer/Load-Forecasting
0
1import gradio as gr2import pandas as pd3from prophet import Prophet4import plotly.graph_objs as go5import plotly.io as pio6pio.renderers.default = 'colab'7 8# Load and prepare data (replace with your own if needed)9df = pd.read_csv("https://raw.githubusercontent.com/jbrownlee/Datasets/master/airline-passengers.csv")10df = df.rename(columns={"Month": "ds", "Passengers": "y"})11df['ds'] = pd.to_datetime(df['ds'])12 13# Train the model once14model = Prophet()15model.fit(df)16 17def forecast_with_plots(months_ahead):18 # Create future dataframe and predict19 future = model.make_future_dataframe(periods=months_ahead, freq='M')20 forecast = model.predict(future)21 22 # Find peak demand in forecast period (last months_ahead rows)23 forecast_period = forecast.tail(months_ahead)24 peak_idx = forecast_period['yhat'].idxmax()25 peak_date = forecast_period.loc[peak_idx, 'ds'].strftime('%Y-%m-%d')26 peak_value = forecast_period.loc[peak_idx, 'yhat']27 28 # Build Plotly figure manually29 fig = go.Figure()30 31 # Original data points32 fig.add_trace(go.Scatter(33 x=df['ds'], y=df['y'],34 mode='markers',35 name='Historical Data',36 marker=dict(color='black')37 ))38 39 # Forecast line40 fig.add_trace(go.Scatter(41 x=forecast['ds'], y=forecast['yhat'],42 mode='lines',43 name='Forecast',44 line=dict(color='blue')45 ))46 47 # Confidence interval area (yhat_lower to yhat_upper)48 fig.add_trace(go.Scatter(49 x=list(forecast['ds']) + list(forecast['ds'][::-1]),50 y=list(forecast['yhat_upper']) + list(forecast['yhat_lower'][::-1]),51 fill='toself',52 fillcolor='rgba(0, 0, 255, 0.2)',53 line=dict(color='rgba(255,255,255,0)'),54 hoverinfo="skip",55 showlegend=True,56 name='Confidence Interval'57 ))58 59 # Highlight peak demand point60 fig.add_trace(go.Scatter(61 x=[peak_date],62 y=[peak_value],63 mode='markers+text',64 marker=dict(color='red', size=12, symbol='star'),65 text=[f"Peak: {peak_date}<br>{peak_value:.1f}"],66 textposition="top center",67 name='Peak Demand'68 ))69 70 fig.update_layout(71 title="Energy Load Forecast",72 xaxis_title="Date",73 yaxis_title="Load",74 hovermode="x unified"75 )76 77 # Return figure and peak info string78 peak_info = f"๐
Peak demand predicted on: {peak_date} with value: {peak_value:.1f}"79 return fig, peak_info80 81# Gradio interface with two outputs: plot and text82iface = gr.Interface(83 fn=forecast_with_plots,84 inputs=gr.Slider(minimum=1, maximum=36, step=1, label="Months Ahead to Forecast"),85 outputs=[gr.Plot(label="Forecast Plot"), gr.Textbox(label="Peak Demand Info")],86 title="Energy Load Forecasting with Prophet",87 description="Select how many months ahead you want to forecast."88)89 90iface.launch()91 