libbeyfox commited on
Commit
b8f9f43
·
verified ·
1 Parent(s): cb87e0b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -47
app.py CHANGED
@@ -4,7 +4,7 @@ import tempfile
4
  import os
5
  from datetime import datetime
6
  import numpy as np
7
- import MLForecast
8
 
9
  from statsforecast import StatsForecast
10
  from statsforecast.models import (
@@ -28,7 +28,41 @@ from utilsforecast.losses import *
28
  from mlforecast import MLForecast
29
  from lightgbm import LGBMRegressor
30
 
31
- #Function to generate and return a plot for validation results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  def create_forecast_plot(forecast_df, original_df, title="Forecasting Results", horizon=None, freq='D'):
33
  plt.figure(figsize=(12, 7))
34
  unique_ids = forecast_df['unique_id'].unique()
@@ -88,22 +122,6 @@ def create_forecast_plot(forecast_df, original_df, title="Forecasting Results",
88
 
89
  return fig
90
 
91
-
92
-
93
- # Foundation Models
94
- try:
95
- from chronos import ChronosPipeline
96
- import torch
97
- CHRONOS_AVAILABLE = True
98
- except:
99
- CHRONOS_AVAILABLE = False
100
-
101
- try:
102
- from uni2ts.model.moirai import MoiraiForecast
103
- MOIRAI_AVAILABLE = True
104
- except:
105
- MOIRAI_AVAILABLE = False
106
-
107
  # Function to load and process uploaded CSV
108
  def load_data(file):
109
  if file is None:
@@ -125,28 +143,6 @@ def load_data(file):
125
  return df, "Data loaded successfully!"
126
  except Exception as e:
127
  return None, f"Error loading data: {str(e)}"
128
-
129
-
130
- # Helper function to calculate date offset based on frequency and horizon
131
- def calculate_date_offset(freq, horizon):
132
- """Calculate a timedelta based on frequency code and horizon"""
133
- if freq == 'H':
134
- return pd.Timedelta(hours=horizon)
135
- elif freq == 'D':
136
- return pd.Timedelta(days=horizon)
137
- elif freq == 'B':
138
- return pd.Timedelta(days=int(horizon * 1.4))
139
- elif freq == 'WS':
140
- return pd.Timedelta(weeks=horizon)
141
- elif freq == 'MS':
142
- return pd.Timedelta(days=horizon * 30)
143
- elif freq == 'QS':
144
- return pd.Timedelta(days=horizon * 90)
145
- elif freq == 'YS':
146
- return pd.Timedelta(days=horizon * 365)
147
- else:
148
- return pd.Timedelta(days=horizon)
149
-
150
 
151
  # Main forecasting function
152
  def run_forecast(
@@ -170,9 +166,6 @@ def run_forecast(
170
  # Prepare data - only required columns for models without predictors
171
  df_basic = df[['unique_id', 'ds', 'y']].copy()
172
 
173
- # For models that need predictors, prepare full feature set
174
- # (This would be expanded based on your feature engineering)
175
-
176
  # Initialize models list
177
  models = []
178
  models_need_predictors = []
@@ -220,7 +213,7 @@ def run_forecast(
220
  if models_need_predictors:
221
  sf_pred = StatsForecast(models=models_need_predictors, freq=frequency, n_jobs=-1)
222
  cv_df_pred = sf_pred.cross_validation(
223
- df=df_basic, # Use df with predictors when implemented
224
  h=int(h),
225
  step_size=int(step_size),
226
  n_windows=int(num_windows)
@@ -235,7 +228,6 @@ def run_forecast(
235
  return None, None, None, None, None, [], "No models selected"
236
 
237
  else: # Fixed Window
238
- # Similar logic for fixed window
239
  # Split data
240
  train_df = []
241
  for uid in df_basic['unique_id'].unique():
@@ -396,8 +388,6 @@ def run_forecast(
396
  error_msg = f"Error: {str(e)}\n\n{traceback.format_exc()}"
397
  return None, None, None, None, None, [], error_msg
398
 
399
-
400
-
401
  # Gradio Interface
402
  with gr.Blocks(title="Duke Energy Forecasting App") as app:
403
  gr.Markdown("""
 
4
  import os
5
  from datetime import datetime
6
  import numpy as np
7
+ import matplotlib.pyplot as plt
8
 
9
  from statsforecast import StatsForecast
10
  from statsforecast.models import (
 
28
  from mlforecast import MLForecast
29
  from lightgbm import LGBMRegressor
30
 
31
+ # Foundation Models
32
+ try:
33
+ from chronos import ChronosPipeline
34
+ import torch
35
+ CHRONOS_AVAILABLE = True
36
+ except:
37
+ CHRONOS_AVAILABLE = False
38
+
39
+ try:
40
+ from uni2ts.model.moirai import MoiraiForecast
41
+ MOIRAI_AVAILABLE = True
42
+ except:
43
+ MOIRAI_AVAILABLE = False
44
+
45
+ # Helper function to calculate date offset based on frequency and horizon
46
+ def calculate_date_offset(freq, horizon):
47
+ """Calculate a timedelta based on frequency code and horizon"""
48
+ if freq == 'H':
49
+ return pd.Timedelta(hours=horizon)
50
+ elif freq == 'D':
51
+ return pd.Timedelta(days=horizon)
52
+ elif freq == 'B':
53
+ return pd.Timedelta(days=int(horizon * 1.4))
54
+ elif freq == 'WS':
55
+ return pd.Timedelta(weeks=horizon)
56
+ elif freq == 'MS':
57
+ return pd.Timedelta(days=horizon * 30)
58
+ elif freq == 'QS':
59
+ return pd.Timedelta(days=horizon * 90)
60
+ elif freq == 'YS':
61
+ return pd.Timedelta(days=horizon * 365)
62
+ else:
63
+ return pd.Timedelta(days=horizon)
64
+
65
+ # Function to generate and return a plot for validation results
66
  def create_forecast_plot(forecast_df, original_df, title="Forecasting Results", horizon=None, freq='D'):
67
  plt.figure(figsize=(12, 7))
68
  unique_ids = forecast_df['unique_id'].unique()
 
122
 
123
  return fig
124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  # Function to load and process uploaded CSV
126
  def load_data(file):
127
  if file is None:
 
143
  return df, "Data loaded successfully!"
144
  except Exception as e:
145
  return None, f"Error loading data: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
 
147
  # Main forecasting function
148
  def run_forecast(
 
166
  # Prepare data - only required columns for models without predictors
167
  df_basic = df[['unique_id', 'ds', 'y']].copy()
168
 
 
 
 
169
  # Initialize models list
170
  models = []
171
  models_need_predictors = []
 
213
  if models_need_predictors:
214
  sf_pred = StatsForecast(models=models_need_predictors, freq=frequency, n_jobs=-1)
215
  cv_df_pred = sf_pred.cross_validation(
216
+ df=df_basic,
217
  h=int(h),
218
  step_size=int(step_size),
219
  n_windows=int(num_windows)
 
228
  return None, None, None, None, None, [], "No models selected"
229
 
230
  else: # Fixed Window
 
231
  # Split data
232
  train_df = []
233
  for uid in df_basic['unique_id'].unique():
 
388
  error_msg = f"Error: {str(e)}\n\n{traceback.format_exc()}"
389
  return None, None, None, None, None, [], error_msg
390
 
 
 
391
  # Gradio Interface
392
  with gr.Blocks(title="Duke Energy Forecasting App") as app:
393
  gr.Markdown("""